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