2 # The RBN connection system
4 # Copyright (c) 2020 Dirk Koopman G1TLH
21 use Math::Round qw(nearest);
23 use Time::HiRes qw(gettimeofday);
40 # at least one whole spot per cache entry is necessary
51 SQra => 15, # i.e. extra after the IP address
55 # Standard Cache entries
56 # key Spot|normalised freq
58 CTime => 0, # time of latest spot in a tranch
59 CQual => 1, # Qualitee
60 CSpot => 3, # the Spot::Prepare data for this spot
61 CSkims => 3, # the list of skimmers (hcalls) is [[...]...]
68 SKTime =>0, # last time seen
71 SKSpot =>3, # the Spot::Prepare data for this skimmer
75 our $CACHE_VERSION = 2;
77 our @ISA = qw(DXChannel);
79 our $startup_delay = 5*60; # don't send anything out until this timer has expired
80 # this is to allow the feed to "warm up" with duplicates
81 # so that the "big rush" doesn't happen.
83 our $minspottime = 60*60; # the time between respots of a callsign - if a call is
84 # still being spotted (on the same freq) and it has been
85 # spotted before, it's spotted again after this time
86 # until the next minspottime has passed.
88 our $beacontime = 5*60; # same as minspottime, but for beacons (and shorter)
90 our $dwelltime = 10; # the amount of time to wait for duplicates before issuing
91 # a spot to the user (no doubt waiting with bated breath).
93 our $filterdef = $Spot::filterdef; # we use the same filter as the Spot system. Can't think why :-).
95 my $spots; # the GLOBAL spot cache
97 my %runtime; # how long each channel has been running
99 our $cachefn = localdata('rbn_cache');
100 our $cache_valid = 4*60; # The cache file is considered valid if it is not more than this old
103 my $noinrush = 0; # override the inrushpreventor if set
112 if (defined $DB::VERSION) {
120 my $self = DXChannel::alloc(@_);
122 # routing, this must go out here to prevent race condx
129 $self->{nouser} = {};
131 $self->{noraw10} = 0;
132 $self->{nospot10} = 0;
133 $self->{nouser10} = {};
134 $self->{norbn10} = 0;
135 $self->{nospothour} = 0;
136 $self->{nouserhour} = {};
137 $self->{norbnhour} = 0;
138 $self->{norawhour} = 0;
140 $self->{lasttime} = $main::systime;
141 $self->{minspottime} = $minspottime;
142 $self->{beacontime} = $beacontime;
143 $self->{showstats} = 0;
144 $self->{pingint} = 0;
145 $self->{nopings} = 0;
152 my ($self, $line, $sort) = @_;
153 my $user = $self->{user};
154 my $call = $self->{call};
155 my $name = $user->{name};
158 my $host = $self->{conn}->peerhost;
160 $self->{hostname} = $host;
162 $self->{name} = $name ? $name : $call;
163 $self->state('prompt'); # a bit of room for further expansion, passwords etc
164 $self->{lang} = $user->lang || $main::lang || 'en';
165 if ($line =~ /host=/) {
166 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
167 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
169 ($h) = $line =~ /host=([\da..fA..F:]+)/;
170 $line =~ s/\s*host=[\da..fA..F:]+// if $h;
174 $self->{hostname} = $h;
177 $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
178 $self->{consort} = $line; # save the connection type
180 LogDbg('DXCommand', "$call connected from $self->{hostname}");
182 # set some necessary flags on the user if they are connecting
183 $self->{registered} = 1;
184 # sort out privilege reduction
189 $nossid =~ s/-\d+$//;
191 $self->{inrbnfilter} = Filter::read_in('rbn', $call, 1)
192 || Filter::read_in('rbn', 'node_default', 1);
194 # clean up qra locators
195 my $qra = $user->qra;
196 $qra = undef if ($qra && !DXBearing::is_qra($qra));
198 my $lat = $user->lat;
199 my $long = $user->long;
200 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);
203 # if we have been running and stopped for a while
204 # if the cache is warm enough don't operate the inrush preventor
205 $self->{inrushpreventor} = exists $runtime{$call} && $runtime{$call} > $startup_delay || $noinrush ? 0 : $main::systime + $startup_delay;
206 dbg("RBN: noinrush: $noinrush, setting inrushpreventor on $self->{call} to $self->{inrushpreventor}");
209 my @queue; # the queue of spots ready to send
216 # my $spots = $self->{spot};
218 # remove leading and trailing spaces
225 my $tim = $main::systime;
228 dbg "RBN:RAW,$line" if isdbg('rbnraw');
229 return unless $line=~/^DX\s+de/;
231 my (undef, undef, $origin, $qrg, $call, $mode, $s, $m, $spd, $u, $sort, $t, $tx) = split /[:\s]+/, $line;
233 # fix up FT8 spots from 7001
234 $t = $u, $u = '' if !$t && is_ztime($u);
235 $t = $sort, $sort = '' if !$t && is_ztime($sort);
236 my $qra = $spd, $spd = '' if is_qra($spd);
239 # is this anything like a callsign?
240 unless (is_callsign($call)) {
241 dbg("RBN: ERROR $call from $origin on $qrg is invalid, dumped");
245 $origin =~ s/\-(?:\d{1,2}\-)?\#$//; # get rid of all the crap we aren't interested in
251 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');
255 ++$self->{norawhour};
261 # fix up times for things like 'NXDXF B' etc
262 if ($tx && is_ztime($t)) {
271 if ($sort && $sort eq 'NCDXF') {
275 if ($sort && $sort eq 'BEACON') {
278 if ($mode =~ /^PSK/) {
281 if ($mode eq 'RTTY') {
285 # The main de-duping key is [call, $frequency], but we probe a bit around that frequency to find a
286 # range of concurrent frequencies that might be in play.
288 # The key to this is deducing the true callsign by "majority voting" (the greater the number of spotters
289 # the more effective this is) together with some lexical analsys probably in conjuction with DXSpider
290 # 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)
291 # and some heuristical "Kwalitee" rating given distance from the zone centres of spotter, recipient user
292 # and spotted. A map can be generated once per user and spotter as they are essentially mostly static.
293 # The spotted will only get a coarse position unless other info is available. Programs that parse
294 # DX bulletins and the online data online databases could be be used and then cached.
296 # Obviously users have to opt in to receiving RBN spots and other users will simply be passed over and
299 # Clearly this will only work in the 'mojo' branch of DXSpider where it is possible to pass off external
300 # data requests to ephemeral or semi resident forked processes that do any grunt work and the main
301 # process to just the standard "message passing" which has been shown to be able to sustain over 5000
302 # per second (limited by the test program's output and network speed, rather than DXSpider's handling).
304 my $nqrg = nearest(5, $qrg*10); # normalised to nearest .5 Khz (but multipled by 10 to get an integer)
305 # my $nqrg = nearest_even($qrg); # normalised to nearest Khz
306 my $sp = "$call|$nqrg"; # hopefully the skimmers will be calibrated at least this well!
307 my $spp = sprintf("$call|%d", $nqrg+1); # but, clearly, my hopes are rudely dashed
308 my $spm = sprintf("$call|%d", $nqrg-1); # in BOTH directions!
311 my $cand = $spots->{$sp};
312 $cand = $spots->{$spp}, $sp = $spp, dbg(qq{RBN: SPP using $spp for $sp}) if isdbg('rbn') && !$cand && exists $spots->{$spp};
313 $cand = $spots->{$spm}, $sp = $spm, dbg(qq{RBN: SPM using $spm for $sp}) if isdbg('rbn') && !$cand && exists $spots->{$spm};
315 # if we have one and there is only one slot and that slot's time isn't expired for respot then return
317 if ($cand && ref $cand) {
318 if (@$cand <= CEMPTY) {
319 unless ($self->{minspottime} > 0 && $tim - $cand->[0] >= $self->{minspottime}) {
320 dbg("RBN: key: '$sp' call: $call qrg: $qrg DUPE \@ ". atime(int $cand->[0])) if isdbg('rbn');
324 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $cand->[0])) if isdbg('rbn');
325 undef $cand; # it's about to be recreated (in one place)
329 # otherwise we have a spot being built up at the moment
331 dbg("RBN: key '$sp' = '$cand' not ref");
335 # here we either have an existing spot record buildup on the go, or we need to create the first one
337 $spots->{$sp} = $cand = [$main::systime, 0, 0];
338 dbg("RBN: key: '$sp' call: $call qrg: $qrg NEW" . ($respot ? ' RESPOT' : '')) if isdbg('rbn');
341 # add me to the display queue unless we are waiting for initial in rush to finish
342 return unless $noinrush || $self->{inrushpreventor} < $main::systime;
344 # build up a new record and store it in the buildup
345 # deal with the unix time
346 my ($hh,$mm) = $t =~ /(\d\d)(\d\d)Z$/;
347 my $utz = $hh*3600 + $mm*60 + $main::systime_daystart; # possible issue with late spot from previous day
348 $utz -= 86400 if $utz > $tim+3600; # too far ahead, drag it back one day
350 # create record and add into the buildup
351 my $r = [$origin, nearest(.1, $qrg), $call, $mode, $s, $t, $utz, $respot, $u];
352 unless ($cand->[CSpot]) {
353 my @s = Spot::prepare($r->[RQrg], $r->[RCall], $r->[RUtz], '', $r->[ROrigin]);
355 dbg("RBN: ERROR invalid prefix/callsign $call from $origin-# on $qrg, dumped");
358 $cand->[CSpot] = \@s;
361 if ($self->{inrbnfilter}) {
362 my ($want, undef) = $self->{inrbnfilter}->it($s);
366 # add/set up the skimmer record
367 my $skimkey = "SK|$origin";
368 my $skim = $spots->{$skimkey};
370 my $ur = DXUser::get($origin);
371 $spots->{$skimkey} = [$main::systime, 0, 0, $s->[SODxcc], $s->[SOItu], $s->[SOZone], $s->[SOState], ($ur ? $ur->qra : undef) ];
376 push @{$self->{queue}}, $sp if @$cand == 1; # queue the KEY (not the record)
378 dbg("RBN: key: '$sp' ADD RECORD call: $call qrg: $qrg origin: $origin") if isdbg('rbn');
382 # At this point we run the queue to see if anything can be sent onwards to the punter
383 my $now = $main::systime;
385 # now run the waiting queue which just contains KEYS ($call|$qrg)
386 foreach $sp (@{$self->{queue}}) {
387 my $cand = $spots->{$sp};
388 unless ($cand && $cand->[0]) {
389 dbg "RBN Cand " . ($cand ? 'def' : 'undef') . " [0] " . ($cand->[0] ? 'def' : 'undef') . " dwell $dwelltime";
392 if ($now >= $cand->[CTime] + $dwelltime ) {
393 # we have a candidate, create qualitee value(s);
394 unless (@$cand > CEMPTY) {
395 dbg "RBN: QUEUE key '$sp' MISSING RECORDS " . dd($cand) if isdbg 'rbn';
396 shift @{$self->{queue}};
399 my $savedtime = shift @$cand; # save the start time
401 my $quality = @$cand;
402 $quality = 9 if $quality > 9;
403 $quality = "Q:$quality";
404 if (isdbg('progress')) {
405 my $s = "RBN: SPOT key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] $quality";
406 $s .= " route: $self->{call}";
410 send_dx_spot($self, $quality, $cand);
412 # clear out the data and make this now just "spotted", but no further action required until respot time
413 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
415 $spots->{$sp} = [$savedtime];
416 shift @{$self->{queue}};
418 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $cand->[0] + $dwelltime - $now) if isdbg 'rbnqueue';
422 dbg "RBN:DATA,$line" if isdbg('rbn');
426 # we should get the spot record minus the time, so just an array of record (arrays)
435 ++$self->{norbnhour};
437 # $r = [$origin, $qrg, $call, $mode, $s, $utz, $respot];
439 my $mode = $cand->[0]->[3]; # as all the modes will be the same;
441 my @dxchan = DXChannel::get_all();
443 foreach my $dxchan (@dxchan) {
444 next unless $dxchan->is_user;
445 my $user = $dxchan->{user};
446 next unless $user && $user->wantrbn;
448 # does this user want this sort of spot at all?
450 ++$want if $user->wantbeacon && $mode =~ /^BCN|DXF/;
451 ++$want if $user->wantcw && $mode =~ /^CW/;
452 ++$want if $user->wantrtty && $mode =~ /^RTT/;
453 ++$want if $user->wantpsk && $mode =~ /^PSK|FSK|MSK/;
454 ++$want if $user->wantft && $mode =~ /^FT/;
456 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",
463 )) if isdbg('rbnll');
465 # send one spot to one user out of the ones that we have
466 $self->dx_spot($dxchan, $quality, $cand) if $want;
476 my $call = $dxchan->{call};
479 my $strength = 100; # because it could if we talk about FTx
487 ++$self->{nousers}->{$call};
488 ++$self->{nousers10}->{$call};
489 ++$self->{nousershour}->{$call};
492 my $rf = $dxchan->{rbnfilter} || $dxchan->{spotsfilter};
493 foreach my $r (@$cand) {
494 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
495 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
497 my $comment = sprintf "%-3s %2ddB $quality", $r->[RMode], $r->[RStrength];
498 $respot = 1 if $r->[Respot];
499 $qra = $r->[RQra] if !$qra && $r->[RQra] && is_qra($r->[RQra]);
501 my $s = $r->[RSpotData]; # the prepared spot
502 $s->[SComment] = $comment; # apply new generated comment
505 ++$zone{$s->[SZone]}; # save the spotter's zone
506 ++$qrg{$s->[SQrg]}; # and the qrg
509 # save the lowest strength one
510 if ($r->[RStrength] < $strength) {
511 $strength = $r->[RStrength];
513 dbg("RBN: STRENGTH spot: $s->[SCall] qrg: $s->[SQrg] origin: $s->[SOrigin] dB: $r->[RStrength] < $strength") if isdbg 'rbnll';
517 my ($want, undef) = $rf->it($s);
518 dbg("RBN: FILTERING for $call spot: $s->[SCall] qrg: $s->[SQrg] origin: $s->[SOrigin] dB: $r->[RStrength] com: '$s->[SComment]' want: " . ($want ? 'YES':'NO')) if isdbg 'rbnll';
526 $saver = $filtered; # if nothing passed the filter's lips then $saver == $filtered == undef !
531 # create a zone list of spotters
532 delete $zone{$saver->[SZone]}; # remove this spotter's zone (leaving all the other zones)
533 my $z = join ',', sort {$a <=> $b} keys %zone;
535 # determine the most likely qrg and then set it
539 while (my ($k, $v) = each %qrg) {
540 $fk = $k, $mv = $v if $v > $mv;
543 $saver->[SQrg] = $fk;
544 $saver->[SComment] .= '*' if $c > 1;
545 $saver->[SComment] .= '+' if $respot;
546 $saver->[SComment] .= " Z:$z" if $z;
548 dbg("RBN: SENDING to $call spot: $saver->[SCall] qrg: $saver->[SQrg] origin: $saver->[SOrigin] $saver->[SComment]") if isdbg 'rbnll';
549 if ($dxchan->{ve7cc}) {
550 my $call = $saver->[SOrigin];
551 $saver->[SOrigin] .= '-#';
552 $buf = VE7CC::dx_spot($dxchan, @$saver);
553 $saver->[SOrigin] = $call;
555 my $call = $saver->[SOrigin];
556 $saver->[SOrigin] = substr($call, 0, 6);
557 $saver->[SOrigin] .= '-#';
558 $buf = $dxchan->format_dx_spot(@$saver);
559 $saver->[SOrigin] = $call;
562 $dxchan->local_send('N', $buf);
566 ++$self->{nospothour};
569 my $user = DXUser::get_current($saver->[SCall]) || DXUser->new($saver->[SCall]);
570 unless ($user->qra && is_qra($user->qra)) {
572 dbg("RBN: update qra on $saver->[SCall] to $qra");
582 foreach my $dxchan (DXChannel::get_all()) {
583 next unless $dxchan->is_rbn;
584 dbg "RBN:STATS minute $dxchan->{call} raw: $dxchan->{noraw} sent: $dxchan->{norbn} delivered: $dxchan->{nospot} users: " . scalar keys %{$dxchan->{nousers}} if isdbg('rbnstats');
585 if ($dxchan->{noraw} == 0 && $dxchan->{lasttime} > 60) {
586 LogDbg('RBN', "RBN: no input from $dxchan->{call}, disconnecting");
589 $dxchan->{noraw} = $dxchan->{norbn} = $dxchan->{nospot} = 0; $dxchan->{nousers} = {};
590 $runtime{$dxchan->{call}} += 60;
593 # save the spot cache
594 write_cache() unless $main::systime + $startup_delay < $main::systime;;
601 while (my ($k,$v) = each %{$spots}) {
602 if ($main::systime - $v->[0] > $minspottime*2) {
610 dbg "RBN:STATS spot cache remain: $count removed: $removed"; # if isdbg('rbn');
611 foreach my $dxchan (DXChannel::get_all()) {
612 next unless $dxchan->is_rbn;
613 dbg "RBN:STATS 10-minute $dxchan->{call} raw: $dxchan->{noraw10} sent: $dxchan->{norbn10} delivered: $dxchan->{nospot10} users: " . scalar keys %{$dxchan->{nousers10}};
614 $dxchan->{noraw10} = $dxchan->{norbn10} = $dxchan->{nospot10} = 0; $dxchan->{nousers10} = {};
620 foreach my $dxchan (DXChannel::get_all()) {
621 next unless $dxchan->is_rbn;
622 dbg "RBN:STATS hour $dxchan->{call} raw: $dxchan->{norawhour} sent: $dxchan->{norbnhour} delivered: $dxchan->{nospothour} users: " . scalar keys %{$dxchan->{nousershour}};
623 $dxchan->{norawhour} = $dxchan->{norbnhour} = $dxchan->{nospothour} = 0; $dxchan->{nousershour} = {};
634 my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
635 $spots->{version} = $CACHE_VERSION;
636 my $s = $json->encode($spots);
644 my $mt = (stat($cachefn))[9];
645 my $t = $main::systime - $mt || 1;
647 if ($t < $cache_valid) {
648 dbg("RBN:check_cache '$cachefn' spot cache exists, created $p ago and not too old");
649 my $fh = IO::File->new($cachefn);
654 dbg("RBN:check_cache cache read size " . length $s);
657 dbg("RBN:check_cache file read error $!");
661 eval {$spots = $json->decode($s)};
662 if ($spots && ref $spots) {
663 my $version = $spots->{version} || 0;
664 unless ($version != $CACHE_VERSION) {
665 # wrong version number
666 dbg("RBN:check_cache version number mismatch got: $version want: $CACHE_VERSION, reseting");
670 dbg("RBN:check_cache spot cache restored");
674 dbg("RBN::checkcache error decoding $@");
676 my $d = difft($main::systime-$cache_valid);
677 dbg("RBN::checkcache '$cachefn' created $p ago is too old (> $d), ignored");
680 dbg("RBN:check_cache '$cachefn' spot cache not present");