2 # The RBN connection system
4 # Copyright (c) 2020 Dirk Koopman G1TLH
19 use Math::Round qw(nearest);
21 use Time::HiRes qw(clock_gettime CLOCK_REALTIME);
26 our @ISA = qw(DXChannel);
28 our $startup_delay = 5*60; # don't send anything out until this timer has expired
29 # this is to allow the feed to "warm up" with duplicates
30 # so that the "big rush" doesn't happen.
32 our $minspottime = 60*60; # the time between respots of a callsign - if a call is
33 # still being spotted (on the same freq) and it has been
34 # spotted before, it's spotted again after this time
35 # until the next minspottime has passed.
37 our $beacontime = 5*60; # same as minspottime, but for beacons (and shorter)
39 our $dwelltime = 10; # the amount of time to wait for duplicates before issuing
40 # a spot to the user (no doubt waiting with bated breath).
42 our $filterdef = $Spot::filterdef; # we use the same filter as the Spot system. Can't think why :-).
44 my $spots; # the GLOBAL spot cache
46 my %runtime; # how long each channel has been running
48 our $cachefn = localdata('rbn_cache');
49 our $cache_valid = 4*60; # The cache file is considered valid if it is not more than this old
52 my $noinrush = 0; # override the inrushpreventor if set
61 if (defined $DB::VERSION) {
69 my $self = DXChannel::alloc(@_);
71 # routing, this must go out here to prevent race condx
81 $self->{nospot10} = 0;
82 $self->{nouser10} = {};
84 $self->{nospothour} = 0;
85 $self->{nouserhour} = {};
86 $self->{norbnhour} = 0;
87 $self->{norawhour} = 0;
89 $self->{lasttime} = $main::systime;
90 $self->{minspottime} = $minspottime;
91 $self->{beacontime} = $beacontime;
92 $self->{showstats} = 0;
101 my ($self, $line, $sort) = @_;
102 my $user = $self->{user};
103 my $call = $self->{call};
104 my $name = $user->{name};
107 my $host = $self->{conn}->peerhost;
109 $self->{hostname} = $host;
111 $self->{name} = $name ? $name : $call;
112 $self->state('prompt'); # a bit of room for further expansion, passwords etc
113 $self->{lang} = $user->lang || $main::lang || 'en';
114 if ($line =~ /host=/) {
115 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
116 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
118 ($h) = $line =~ /host=([\da..fA..F:]+)/;
119 $line =~ s/\s*host=[\da..fA..F:]+// if $h;
123 $self->{hostname} = $h;
126 $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
127 $self->{consort} = $line; # save the connection type
129 LogDbg('DXCommand', "$call connected from $self->{hostname}");
131 # set some necessary flags on the user if they are connecting
132 $self->{registered} = 1;
133 # sort out privilege reduction
138 $nossid =~ s/-\d+$//;
140 $self->{inrbnfilter} = Filter::read_in('rbn', $call, 1)
141 || Filter::read_in('rbn', 'node_default', 1);
143 # clean up qra locators
144 my $qra = $user->qra;
145 $qra = undef if ($qra && !DXBearing::is_qra($qra));
147 my $lat = $user->lat;
148 my $long = $user->long;
149 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);
152 # if we have been running and stopped for a while
153 # if the cache is warm enough don't operate the inrush preventor
154 $self->{inrushpreventor} = exists $runtime{$call} && $runtime{$call} > $startup_delay || $noinrush ? 0 : $main::systime + $startup_delay;
155 dbg("RBN: noinrush: $noinrush, setting inrushpreventor on $self->{call} to $self->{inrushpreventor}");
158 my @queue; # the queue of spots ready to send
165 # my $spots = $self->{spot};
167 # save this for them's that need it
170 # remove leading and trailing spaces
177 my $tim = $main::systime;
180 dbg "RBN:RAW,$line" if isdbg('rbnraw');
181 return unless $line=~/^DX\s+de/;
183 my (undef, undef, $origin, $qrg, $call, $mode, $s, $m, $spd, $u, $sort, $t, $tx) = split /[:\s]+/, $line;
185 # fix up FT8 spots from 7001
186 $t = $u, $u = '' if !$t && is_ztime($u);
187 $t = $sort, $sort = '' if !$t && is_ztime($sort);
188 my $qra = $spd, $spd = '' if is_qra($spd);
191 # is this anything like a callsign?
192 unless (is_callsign($call)) {
193 dbg("RBN: ERROR $call from $origin on $qrg is invalid, dumped");
197 $origin =~ s/\-(?:\d{1,2}\-)?\#$//; # get rid of all the crap we aren't interested in
203 dbg qq{RBN:input decode 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');
207 ++$self->{norawhour};
213 # fix up times for things like 'NXDXF B' etc
214 if ($tx && is_ztime($t)) {
223 if ($sort && $sort eq 'NCDXF') {
227 if ($sort && $sort eq 'BEACON') {
230 if ($mode =~ /^PSK/) {
233 if ($mode eq 'RTTY') {
237 # The main de-duping key is [call, $frequency], but we probe a bit around that frequency to find a
238 # range of concurrent frequencies that might be in play.
240 # The key to this is deducing the true callsign by "majority voting" (the greater the number of spotters
241 # the more effective this is) together with some lexical analsys probably in conjuction with DXSpider
242 # 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)
243 # and some heuristical "Kwalitee" rating given distance from the zone centres of spotter, recipient user
244 # and spotted. A map can be generated once per user and spotter as they are essentially mostly static.
245 # The spotted will only get a coarse position unless other info is available. Programs that parse
246 # DX bulletins and the online data online databases could be be used and then cached.
248 # Obviously users have to opt in to receiving RBN spots and other users will simply be passed over and
251 # Clearly this will only work in the 'mojo' branch of DXSpider where it is possible to pass off external
252 # data requests to ephemeral or semi resident forked processes that do any grunt work and the main
253 # process to just the standard "message passing" which has been shown to be able to sustain over 5000
254 # per second (limited by the test program's output and network speed, rather than DXSpider's handling).
256 my $nqrg = nearest(1, $qrg); # normalised to nearest Khz
257 my $sp = "$call|$nqrg"; # hopefully the skimmers will be calibrated at least this well!
258 my $spp = sprintf("$call|%d", $nqrg+1); # but, clearly, my hopes are rudely dashed
259 my $spm = sprintf("$call|%d", $nqrg-1); # in BOTH directions!
262 my $spot = $spots->{$sp};
263 $spot = $spots->{$spp}, $sp = $spp, dbg(qq{RBN: SPP using $spp for $sp}) if isdbg('rbn') && !$spot && exists $spots->{$spp};
264 $spot = $spots->{$spm}, $sp = $spm, dbg(qq{RBN: SPM using $spm for $sp}) if isdbg('rbn') && !$spot && exists $spots->{$spm};
267 # if we have one and there is only one slot and that slot's time isn't expired for respot then return
269 if ($spot && ref $spot) {
271 unless ($self->{minspottime} > 0 && $tim - $spot->[0] >= $self->{minspottime}) {
272 dbg("RBN: key: '$sp' call: $call qrg: $qrg DUPE \@ ". atime(int $spot->[0])) if isdbg('rbn');
276 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $spot->[0])) if isdbg('rbn');
277 undef $spot; # it's about to be recreated (in one place)
281 # otherwise we have a spot being built up at the moment
283 dbg("RBN: key '$sp' = '$spot' not ref");
287 # here we either have an existing spot record buildup on the go, or we need to create the first one
289 $spots->{$sp} = $spot = [clock_gettime(CLOCK_REALTIME)];;
290 dbg("RBN: key: '$sp' call: $call qrg: $qrg NEW" . ($respot ? ' RESPOT' : '')) if isdbg('rbn');
293 # add me to the display queue unless we are waiting for initial in rush to finish
294 return unless $noinrush || $self->{inrushpreventor} < $main::systime;
296 # build up a new record and store it in the buildup
297 # deal with the unix time
298 my ($hh,$mm) = $t =~ /(\d\d)(\d\d)Z$/;
299 my $utz = $hh*3600 + $mm*60 + $main::systime_daystart; # possible issue with late spot from previous day
300 $utz -= 86400 if $utz > $tim+3600; # too far ahead, drag it back one day
302 # create record and add into the buildup
303 my $r = [$origin, nearest(.1, $qrg), $call, $mode, $s, $t, $utz, $respot, $u];
304 my @s = Spot::prepare($r->[1], $r->[2], $r->[6], '', $r->[0]);
306 dbg("RBN: ERROR invalid prefix/callsign $call from $origin-# on $qrg, dumped");
310 if ($self->{inrbnfilter}) {
311 my ($want, undef) = $self->{inrbnfilter}->it($s);
316 push @{$self->{queue}}, $sp if @$spot == 1; # queue the KEY (not the record)
318 dbg("RBN: key: '$sp' ADD RECORD call: $call qrg: $qrg origin: $origin") if isdbg('rbn');
322 # At this point we run the queue to see if anything can be sent onwards to the punter
323 my $now = clock_gettime(CLOCK_REALTIME);
325 # now run the waiting queue which just contains KEYS ($call|$qrg)
326 foreach $sp (@{$self->{queue}}) {
327 my $cand = $spots->{$sp};
328 unless ($cand && $cand->[0]) {
329 dbg "RBN Cand " . ($cand ? 'def' : 'undef') . " [0] " . ($cand->[0] ? 'def' : 'undef') . " dwell $dwelltime";
332 if ($now >= $cand->[0] + $dwelltime ) {
333 # we have a candidate, create qualitee value(s);
334 unless (@$cand > 1) {
335 dbg "RBN: QUEUE key '$sp' MISSING RECORDS " . dd($cand) if isdbg 'rbn';
336 shift @{$self->{queue}};
339 my $savedtime = shift @$cand; # save the start time
341 my $quality = @$cand;
342 $quality = 9 if $quality > 9;
343 $quality = "Q:$quality";
344 if (isdbg('progress')) {
345 my $s = "RBN: SPOT key: '$sp' = $r->[2] on $r->[1] by $r->[0] \@ $r->[5] $quality";
346 $s .= " route: $self->{call}";
350 send_dx_spot($self, $quality, $cand);
352 # clear out the data and make this now just "spotted", but no further action required until respot time
353 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
355 $spots->{$sp} = [$savedtime];
356 shift @{$self->{queue}};
358 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $spot->[0] + $dwelltime - $now) if isdbg 'rbnqueue';
362 dbg "RBN:DATA,$line" if isdbg('rbn');
368 foreach my $dxchan (DXChannel::get_all()) {
369 next unless $dxchan->is_rbn;
370 dbg "RBN:STATS minute $dxchan->{call} raw: $dxchan->{noraw} sent: $dxchan->{norbn} delivered: $dxchan->{nospot} users: " . scalar keys %{$dxchan->{nousers}} if isdbg('rbnstats');
371 if ($dxchan->{noraw} == 0 && $dxchan->{lasttime} > 60) {
372 LogDbg('RBN', "RBN: no input from $dxchan->{call}, disconnecting");
375 $dxchan->{noraw} = $dxchan->{norbn} = $dxchan->{nospot} = 0; $dxchan->{nousers} = {};
376 $runtime{$dxchan->{call}} += 60;
379 # save the spot cache
380 write_cache() unless $main::systime + $startup_delay < $main::systime;;
387 while (my ($k,$v) = each %{$spots}) {
388 if ($main::systime - $v->[0] > $minspottime*2) {
396 dbg "RBN:STATS spot cache remain: $count removed: $removed"; # if isdbg('rbn');
397 foreach my $dxchan (DXChannel::get_all()) {
398 next unless $dxchan->is_rbn;
399 dbg "RBN:STATS 10-minute $dxchan->{call} raw: $dxchan->{noraw10} sent: $dxchan->{norbn10} delivered: $dxchan->{nospot10} users: " . scalar keys %{$dxchan->{nousers10}};
400 $dxchan->{noraw10} = $dxchan->{norbn10} = $dxchan->{nospot10} = 0; $dxchan->{nousers10} = {};
406 foreach my $dxchan (DXChannel::get_all()) {
407 next unless $dxchan->is_rbn;
408 dbg "RBN:STATS hour $dxchan->{call} raw: $dxchan->{norawhour} sent: $dxchan->{norbnhour} delivered: $dxchan->{nospothour} users: " . scalar keys %{$dxchan->{nousershour}};
409 $dxchan->{norawhour} = $dxchan->{norbnhour} = $dxchan->{nospothour} = 0; $dxchan->{nousershour} = {};
413 # we should get the spot record minus the time, so just an array of record (arrays)
422 ++$self->{norbnhour};
424 # $r = [$origin, $qrg, $call, $mode, $s, $utz, $respot];
426 my $mode = $spot->[0]->[3]; # as all the modes will be the same;
428 my @dxchan = DXChannel::get_all();
430 foreach my $dxchan (@dxchan) {
431 next unless $dxchan->is_user;
432 my $user = $dxchan->{user};
433 next unless $user && $user->wantrbn;
435 # does this user want this sort of spot at all?
437 ++$want if $user->wantbeacon && $mode =~ /^BCN|DXF/;
438 ++$want if $user->wantcw && $mode =~ /^CW/;
439 ++$want if $user->wantrtty && $mode =~ /^RTT/;
440 ++$want if $user->wantpsk && $mode =~ /^PSK|FSK|MSK/;
441 ++$want if $user->wantft && $mode =~ /^FT/;
443 dbg(sprintf("RBN: spot selection for $dxchan->{call} mode: '$mode' want: $want flags rbn:%d ft:%d bcn:%d cw:%d psk:%d rtty:%d",
450 )) if isdbg('rbnll');
452 # send one spot to one user out of the ones that we have
453 $self->dx_spot($dxchan, $quality, $spot) if $want;
463 my $call = $dxchan->{call};
466 my $strength = 100; # because it could if we talk about FTx
474 ++$self->{nousers}->{$call};
475 ++$self->{nousers10}->{$call};
476 ++$self->{nousershour}->{$call};
478 foreach my $r (@$spot) {
479 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
480 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
482 my $comment = sprintf "%-3s %2ddB $quality", $r->[3], $r->[4];
483 $respot = 1 if $r->[7];
484 $qra = $r->[8] if !$qra && $r->[8] && is_qra($r->[8]);
486 my $s = $r->[9]; # the prepared spot
487 $s->[3] = $comment; # apply new generated comment
490 ++$zone{$s->[11]}; # save the spotter's zone
491 ++$qrg{$s->[0]}; # and the qrg
495 my $rf = $dxchan->{rbnfilter} || $dxchan->{spotsfilter};
497 ($want, undef) = $rf->it($s);
500 dbg("RBN: FILTERED call: $s->[1] qrg: $s->[0] origin: $s->[4] dB: $r->[4]") if isdbg 'rbn';
504 # save the lowest strength one
505 if ($r->[4] < $strength) {
508 dbg("RBN: STRENGTH call: $s->[1] qrg: $s->[0] origin: $s->[4] dB: $r->[4]") if isdbg 'rbn';
514 # create a zone list of spotters
515 delete $zone{$saver->[11]}; # remove this spotter's zone (leaving all the other zones)
516 my $z = join ',', sort {$a <=> $b} keys %zone;
518 # determine the most likely qrg and then set it
522 while (my ($k, $v) = each %qrg) {
523 $fk = $k, $mv = $v if $v > $mv;
527 $saver->[3] .= '*' if $c > 1;
528 $saver->[3] .= '+' if $respot;
529 $saver->[3] .= " Z:$z" if $z;
531 dbg("RBN: SENDING call: $saver->[1] qrg: $saver->[0] origin: $saver->[4] $saver->[3]") if isdbg 'rbn';
532 if ($dxchan->{ve7cc}) {
533 my $call = $saver->[4];
535 $buf = VE7CC::dx_spot($dxchan, @$saver);
538 my $call = $saver->[4];
539 $saver->[4] = substr($call, 0, 6);
541 $buf = $dxchan->format_dx_spot(@$saver);
545 $dxchan->local_send('N', $buf);
549 ++$self->{nospothour};
552 my $user = DXUser::get_current($saver->[1]) || DXUser->new($saver->[1]);
553 unless ($user->qra && is_qra($user->qra)) {
555 dbg("RBN: update qra on $saver->[1] to $qra");
569 my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
570 my $s = $json->encode($spots);
578 my $mt = (stat($cachefn))[9];
579 my $t = $main::systime - $mt || 1;
581 if ($t < $cache_valid) {
582 dbg("RBN:check_cache '$cachefn' spot cache exists, created $p ago and not too old");
583 my $fh = IO::File->new($cachefn);
588 dbg("RBN:check_cache cache read size " . length $s);
591 dbg("RBN:check_cache file read error $!");
595 eval {$spots = $json->decode($s)};
596 if ($spots && ref $spots) {
597 dbg("RBN:check_cache spot cache restored");
601 dbg("RBN::checkcache error decoding $@");
603 my $d = difft($main::systime-$cache_valid);
604 dbg("RBN::checkcache '$cachefn' created $p ago is too old (> $d), ignored");
607 dbg("RBN:check_cache '$cachefn' spot cache not present");