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