increase rbn connection startup delay
[spider.git] / perl / RBN.pm
1 #
2 # The RBN connection system
3 #
4 # Copyright (c) 2020 Dirk Koopman G1TLH
5 #
6
7 use warnings;
8 use strict;
9
10 package RBN;
11
12 use 5.10.1;
13
14 use DXUtil;
15 use DXDebug;
16 use DXLog;
17 use DXUser;
18 use DXChannel;
19 use Math::Round qw(nearest);
20 use Date::Parse;
21 use Time::HiRes qw(clock_gettime CLOCK_REALTIME);
22
23 our @ISA = qw(DXChannel);
24
25 our $startup_delay = 10*60;             # don't send anything out until this timer has expired
26                                 # this is to allow the feed to "warm up" with duplicates
27                                 # so that the "big rush" doesn't happen.
28
29 our $minspottime = 60*60;               # the time between respots of a callsign - if a call is
30                                 # still being spotted (on the same freq) and it has been
31                                 # spotted before, it's spotted again after this time
32                                 # until the next minspottime has passed.
33
34 our $dwelltime = 6;                     # the amount of time to wait for duplicates before issuing
35                                 # a spot to the user (no doubt waiting with bated breath).
36
37
38 sub new 
39 {
40         my $self = DXChannel::alloc(@_);
41
42         # routing, this must go out here to prevent race condx
43         my $pkg = shift;
44         my $call = shift;
45
46         DXProt::_add_thingy($main::routeroot, [$call, 0, 0, 1, undef, undef, $self->hostname], );
47         $self->{d} = {};
48         $self->{spot} = {};
49         $self->{last} = 0;
50         $self->{noraw} = 0;
51         $self->{nospot} = 0;
52         $self->{norbn} = 0;
53         $self->{sort} = 'N';
54         $self->{lasttime} = $main::systime;
55         $self->{minspottime} = $minspottime;
56         $self->{showstats} = 0;
57
58         return $self;
59 }
60
61 sub start
62
63         my ($self, $line, $sort) = @_;
64         my $user = $self->{user};
65         my $call = $self->{call};
66         my $name = $user->{name};
67         my $dref = $self->{d};
68         my $spotref = $self->{spot};
69                 
70         # log it
71         my $host = $self->{conn}->peerhost;
72         $host ||= "unknown";
73         $self->{hostname} = $host;
74
75         $self->{name} = $name ? $name : $call;
76         $self->state('prompt');         # a bit of room for further expansion, passwords etc
77         $self->{lang} = $user->lang || $main::lang || 'en';
78         if ($line =~ /host=/) {
79                 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
80                 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
81                 unless ($h) {
82                         ($h) = $line =~ /host=([\da..fA..F:]+)/;
83                         $line =~ s/\s*host=[\da..fA..F:]+// if $h;
84                 }
85                 $self->{hostname} = $h if $h;
86         }
87         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
88         $self->{consort} = $line;       # save the connection type
89
90         LogDbg('DXCommand', "$call connected from $self->{hostname}");
91
92         # set some necessary flags on the user if they are connecting
93         $self->{registered} = 1;
94         # sort out privilege reduction
95         $self->{priv} = 0;
96
97         # get the filters
98         my $nossid = $call;
99         $nossid =~ s/-\d+$//;
100         
101         $self->{spotsfilter} = Filter::read_in('spots', $call, 0) 
102                 || Filter::read_in('spots', $nossid, 0)
103                         || Filter::read_in('spots', 'user_default', 0);
104
105         # clean up qra locators
106         my $qra = $user->qra;
107         $qra = undef if ($qra && !DXBearing::is_qra($qra));
108         unless ($qra) {
109                 my $lat = $user->lat;
110                 my $long = $user->long;
111                 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);  
112         }
113
114         # start inrush timer
115         $self->{inrushpreventor} = $main::systime + $startup_delay;
116 }
117
118 my @queue;                                              # the queue of spots ready to send
119
120 sub normal
121 {
122         my $self = shift;
123         my $line = shift;
124         my @ans;
125         my $spots = $self->{spot};
126         
127         # save this for them's that need it
128         my $rawline = $line;
129         
130         # remove leading and trailing spaces
131         chomp $line;
132         $line =~ s/^\s*//;
133         $line =~ s/\s*$//;
134
135         # add base RBN
136
137         my $tim = $main::systime;
138
139         # parse line
140         dbg "RBN:RAW,$line" if isdbg('rbnraw');
141         return unless $line=~/^DX\s+de/;
142
143         my (undef, undef, $origin, $qrg, $call, $mode, $s, $m, $spd, $u, $sort, $t, $tx) = split /[:\s]+/, $line;
144
145         # fix up FT8 spots from 7001
146         $t = $u, $u = '' if !$t && is_ztime($u);
147         $t = $sort, $sort = '' if !$t && is_ztime($sort);
148         my $qra = $spd, $spd = '' if is_qra($spd);
149         $u = $qra if $qra;
150
151         $origin =~ s/\-(?:\d{1,2}\-)?\#$//; # get rid of all the crap we aren't interested in
152
153
154         $sort ||= '';
155         $tx ||= '';
156         $qra ||= '';
157     dbg qq{or:$origin qr:$qrg ca:$call mo:$mode s:$s m:$m sp:$spd u:$u sort:$sort t:$t tx:$tx qra:$qra} if isdbg('rbn');
158
159         
160         my $b;
161         
162         if ($t || $tx) {
163
164                 # fix up times for things like 'NXDXF B' etc
165                 if ($tx && is_ztime($t)) {
166                         if (is_ztime($tx)) {
167                                 $b = $t;
168                                 $t = $tx;
169                         } else {
170                                 dbg "RBN:ERR,$line";
171                                 return (0);
172                         }
173                 }
174                 if ($sort && $sort eq 'NCDXF') {
175                         $mode = 'DXF';
176                         $t = $tx;
177                 }
178                 if ($sort && $sort eq 'BEACON') {
179                         $mode = 'BCN';
180                 }
181                 if ($mode =~ /^PSK/) {
182                         $mode = 'PSK';
183                 }
184                 if ($mode eq 'RTTY') {
185                         $mode = 'RTT';
186                 }
187
188                 # The main de-duping key is [call, $frequency], but we probe a bit around that frequency to find a
189                 # range of concurrent frequencies that might be in play. 
190
191                 # The key to this is deducing the true callsign by "majority voting" (the greater the number of spotters
192         # the more effective this is) together with some lexical analsys probably in conjuction with DXSpider
193                 # data sources (for singleton spots) to then generate a "centre" from and to zone (whatever that will mean if it isn't the usual one)
194                 # and some heuristical "Kwalitee" rating given distance from the zone centres of spotter, recipient user
195         # and spotted. A map can be generated once per user and spotter as they are essentially mostly static. 
196                 # The spotted will only get a coarse position unless other info is available. Programs that parse 
197                 # DX bulletins and the online data online databases could be be used and then cached. 
198
199                 # Obviously users have to opt in to receiving RBN spots and other users will simply be passed over and
200                 # ignored.
201
202                 # Clearly this will only work in the 'mojo' branch of DXSpider where it is possible to pass off external
203                 # data requests to ephemeral or semi resident forked processes that do any grunt work and the main
204                 # process to just the standard "message passing" which has been shown to be able to sustain over 5000 
205                 # per second (limited by the test program's output and network speed, rather than DXSpider's handling).
206
207                 my $nqrg = nearest(1, $qrg);  # normalised to nearest Khz
208                 my $sp = "$call|$nqrg";           # hopefully the skimmers will be calibrated at least this well!
209                 my $spp = sprintf("$call|%d", $nqrg+1); # but, clearly, my hopes are rudely dashed
210                 my $spm = sprintf("$call|%d", $nqrg-1); # in BOTH directions!
211
212                 # do we have it?
213                 my $spot = $spots->{$sp};
214                 $spot = $spots->{$spp}, $sp = $spp, dbg('SPP') if !$spot && exists $spots->{$spp};
215                 $spot = $spots->{$spm}, $sp = $spm, dbg('SPM') if !$spot && exists $spots->{$spm};
216                 
217
218                 # if we have one and there is only one slot and that slot's time isn't expired for respot then return
219                 my $respot = 0;
220                 if ($spot && ref $spot) {
221                         if (@$spot == 1) {
222                                 unless ($self->{minspottime} > 0 && $tim - $spot->[0] >= $self->{minspottime}) {
223                                         dbg("RBN: key: '$sp' call: $call qrg: $qrg DUPE \@ ". atime(int $spot->[0])) if isdbg('rbn');
224                                         return;
225                                 }
226                                 
227                                 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $spot->[0])) if isdbg('rbn');
228                                 ++$respot;
229                         }
230                 } elsif ($spot) {
231                         dbg("RBN: key '$sp' = '$spot' not ref");
232                         return;
233                 }
234
235                 # here we either have an existing spot record buildup on the go, or we need to create the first one
236                 unless ($spot) {
237                         $spot = [clock_gettime(CLOCK_REALTIME)];
238                         $spots->{$sp} = $spot;
239                         dbg("RBN: key: '$sp' call: $call qrg: $qrg NEW") if isdbg('rbn');
240                 }
241
242                 # add me to the display queue unless we are waiting for initial in rush to finish
243                 return unless $self->{inrushpreventor} < $main::systime;
244                 push @{$self->{queue}}, $sp if @$spot == 1; # queue the KEY (not the record)
245
246                 # build up a new record and store it in the buildup
247                 # deal with the unix time
248                 my ($hh,$mm) = $t =~ /(\d\d)(\d\d)Z$/;
249                 my $utz = $hh*3600 + $mm*60 + $main::systime_daystart; # possible issue with late spot from previous day
250                 $utz -= 86400 if $utz > $tim+3600;                                         # too far ahead, drag it back one day
251
252                 # create record and add into the buildup
253                 my $r = [$origin, nearest(.1, $qrg), $call, $mode, $s, $t, $utz, $respot, $u];
254                 dbg("RBN: key: '$sp' ADD RECORD call: $call qrg: $qrg origin: $origin") if isdbg('rbn');
255
256                 push @$spot, $r;
257
258                 # At this point we run the queue to see if anything can be sent onwards to the punter
259                 my $now = clock_gettime(CLOCK_REALTIME);
260
261                 # now run the waiting queue which just contains KEYS ($call|$qrg)
262                 foreach $sp (@{$self->{queue}}) {
263                         my $cand = $spots->{$sp};
264                         unless ($cand && $cand->[0]) {
265                                 dbg "RBN Cand " . ($cand ? 'def' : 'undef') . " [0] " . ($cand->[0] ? 'def' : 'undef') . " dwell $dwelltime";
266                                 next;
267                         } 
268                         if ($now >= $cand->[0] + $dwelltime ) {
269                                 # we have a candidate, create qualitee value(s);
270                                 unless (@$cand > 1) {
271                                         dbg "RBN: QUEUE key '$sp' MISSING RECORDS " . dd($cand) if isdbg 'rbn';
272                                         shift @{$self->{queue}};
273                                         next;
274                                 }
275                                 my $savedtime = shift @$cand; # save the start time
276                                 my $r = $cand->[0];
277                                 my $quality = @$cand;
278                                 $quality = 9 if $quality > 9;
279                                 $quality = "Q:$quality";
280                                 if (isdbg('progress')) {
281                                         my $s = "RBN: SPOT key: '$sp' = $r->[2] on $r->[1] \@ $r->[5] $quality";
282                                         $s .=  " route: $self->{call}";
283                                         dbg($s);
284                                 }
285                                 
286                                 send_dx_spot($self, $quality, $cand);
287                                 
288                                 # clear out the data and make this now just "spotted", but no further action required until respot time
289                                 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
290                                 
291                                 $spots->{$sp} = [$savedtime];
292                                 shift @{$self->{queue}};
293                         } else {
294                                 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $spot->[0] + $dwelltime - $now) if isdbg 'rbnqueue'; 
295                         }
296                 }
297                 
298
299         } else {
300                 dbg "RBN:DATA,$line" if isdbg('rbn');
301         }
302
303         #       # periodic clearing out of the two caches
304         if (($tim % 60 == 0 && $tim > $self->{last}) || ($self->{last} && $tim >= $self->{last} + 60)) {
305                 my $count = 0;
306                 my $removed = 0;
307                 while (my ($k,$v) = each %{$spots}) {
308                         if ($tim - $v->[0] > $self->{minspottime}*2) {
309                                 delete $spots->{$k};
310                                 ++$removed;
311                         }
312                         else {
313                                 ++$count;
314                         }
315                 }
316                 dbg "RBN:ADMIN,spot cache: $removed removed $count remain"; # if isdbg('rbn');
317                 dbg "RBN:" . join(',', "STAT", $self->{noraw}, $self->{norbn}, $self->{nospot}) if $self->{showstats};
318                 $self->{noraw} = $self->{norbn} = $self->{nospot} = 0;
319                 $self->{last} = int($tim / 60) * 60;
320         }
321 }
322
323
324
325 #       }
326 # }
327
328 # we should get the spot record minus the time, so just an array of record (arrays)
329 sub send_dx_spot
330 {
331         my $self = shift;
332         my $quality = shift;
333         my $spot = shift;
334
335         # $r = [$origin, $qrg, $call, $mode, $s, $utz, $respot];
336
337         my $mode = $spot->[0]->[3]; # as all the modes will be the same;
338         
339         my @dxchan = DXChannel::get_all();
340
341         foreach my $dxchan (@dxchan) {
342                 next unless $dxchan->is_user;
343                 my $user = $dxchan->{user};
344                 next unless $user &&  $user->wantrbn;
345
346                 # does this user want this sort of spot at all?
347                 my $want = 0;
348                 ++$want if $user->wantbeacon && $mode =~ /^BCN|DXF/;
349                 ++$want if $user->wantcw && $mode =~ /^CW/;
350                 ++$want if $user->wantrtty && $mode =~ /^RTT/;
351                 ++$want if $user->wantpsk && $mode =~ /^PSK/;
352                 ++$want if $user->wantcw && $mode =~ /^CW/;
353                 ++$want if $user->wantft && $mode =~ /^FT/;
354                 ++$want unless $want;   # send everything if nothing is selected.
355
356                 next unless $want;
357
358                 # send one spot to one user out of the ones that we have
359                 $self->dx_spot($dxchan, $quality, $spot) if $want;
360         }
361 }
362
363 sub dx_spot
364 {
365         my $self = shift;
366         my $dxchan = shift;
367         my $quality = shift;
368         my $spot = shift;
369
370         my $strength = 100;             # because it could if we talk about FTx
371         my $saver;
372
373         my %zone;
374         my %qrg;
375         my $respot;
376         
377         
378         foreach my $r (@$spot) {
379                 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
380                 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
381
382                 my $comment = sprintf "%-3s %2ddB $quality", $r->[3], $r->[4];
383                 my @s =  Spot::prepare($r->[1], $r->[2], $r->[6], $comment, $r->[0]);
384                 $respot = 1 if $r->[7];
385                 ++$zone{$s[11]};                # save the spotter's zone
386                 ++$qrg{$s[0]};                  # and the qrg
387                 
388                 
389                 # save the highest strength one
390                 if ($r->[4] < $strength) {
391                         $strength = $r->[4];
392                         $saver = \@s;
393                         dbg("RBN: STRENGTH call: $s[1] qrg: $s[0] origin: $s[4] dB: $r->[4]") if isdbg 'rbn';
394                 }
395  
396                 my $filter = 0;
397
398                 if ($dxchan->{rbnfilter}) {
399                         ($filter, undef) = $dxchan->{rbnfilter}->it(\@s);
400                         next unless $filter;
401                         $saver = \@s;
402                         dbg("RBN: FILTERED call: $s[1] qrg: $s[0] origin: $s[4] dB: $r->[4]") if isdbg 'rbn';
403                         last;
404                 }
405
406         }
407
408         if ($saver) {
409                 my $buf;
410                 # create a zone list of spotters
411                 delete $zone{$saver->[11]};  # remove this spotter's zone (leaving all the other zones)
412                 my $z = join ',', sort {$a <=> $b} keys %zone;
413
414                 # determine the most likely qrg and then set it
415                 my $mv = 0;
416                 my $fk;
417                 my $c = 0;
418                 while (my ($k, $v) = each %qrg) {
419                         $fk = $k, $mv = $v if $v > $mv;
420                         ++$c;
421                 }
422                 $saver->[0] = $fk;
423                 $saver->[3] .= '*' if $c > 1;
424                 $saver->[3] .= '+' if $respot;
425                 $saver->[3] .= " Z:$z" if $z;
426                 
427                 dbg("RBN: SENDING call: $saver->[1] qrg: $saver->[0] origin: $saver->[4] $saver->[3]") if isdbg 'rbn';
428                 if ($dxchan->{ve7cc}) {
429                         $buf = VE7CC::dx_spot($dxchan, @$saver);
430                 } else {
431                         $buf = $dxchan->format_dx_spot(@$saver);
432                 }
433                 $buf =~ s/^DX/RB/;
434                 $dxchan->local_send('N', $buf);
435
436                 if ($saver->[8] && is_qra($saver->[8])) {
437                         my $user = DXUser::get_current($s[1]) || DXUser::new($s[1]);
438                         $user->qra($saver->[8]) unless $user->qra;
439                         $user->lastseen($main::systime);
440                 }
441         }
442 }
443
444 1;