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