2 # The RBN connection system
4 # Copyright (c) 2020 Dirk Koopman G1TLH
21 use Math::Round qw(nearest);
23 use Time::HiRes qw(gettimeofday);
51 our @ISA = qw(DXChannel);
53 our $startup_delay = 5*60; # don't send anything out until this timer has expired
54 # this is to allow the feed to "warm up" with duplicates
55 # so that the "big rush" doesn't happen.
57 our $minspottime = 60*60; # the time between respots of a callsign - if a call is
58 # still being spotted (on the same freq) and it has been
59 # spotted before, it's spotted again after this time
60 # until the next minspottime has passed.
62 our $beacontime = 5*60; # same as minspottime, but for beacons (and shorter)
64 our $dwelltime = 10; # the amount of time to wait for duplicates before issuing
65 # a spot to the user (no doubt waiting with bated breath).
67 our $filterdef = $Spot::filterdef; # we use the same filter as the Spot system. Can't think why :-).
69 my $spots; # the GLOBAL spot cache
71 my %runtime; # how long each channel has been running
73 our $cachefn = localdata('rbn_cache');
74 our $cache_valid = 4*60; # The cache file is considered valid if it is not more than this old
77 my $noinrush = 0; # override the inrushpreventor if set
86 if (defined $DB::VERSION) {
94 my $self = DXChannel::alloc(@_);
96 # routing, this must go out here to prevent race condx
103 $self->{nouser} = {};
105 $self->{noraw10} = 0;
106 $self->{nospot10} = 0;
107 $self->{nouser10} = {};
108 $self->{norbn10} = 0;
109 $self->{nospothour} = 0;
110 $self->{nouserhour} = {};
111 $self->{norbnhour} = 0;
112 $self->{norawhour} = 0;
114 $self->{lasttime} = $main::systime;
115 $self->{minspottime} = $minspottime;
116 $self->{beacontime} = $beacontime;
117 $self->{showstats} = 0;
118 $self->{pingint} = 0;
119 $self->{nopings} = 0;
126 my ($self, $line, $sort) = @_;
127 my $user = $self->{user};
128 my $call = $self->{call};
129 my $name = $user->{name};
132 my $host = $self->{conn}->peerhost;
134 $self->{hostname} = $host;
136 $self->{name} = $name ? $name : $call;
137 $self->state('prompt'); # a bit of room for further expansion, passwords etc
138 $self->{lang} = $user->lang || $main::lang || 'en';
139 if ($line =~ /host=/) {
140 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
141 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
143 ($h) = $line =~ /host=([\da..fA..F:]+)/;
144 $line =~ s/\s*host=[\da..fA..F:]+// if $h;
148 $self->{hostname} = $h;
151 $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
152 $self->{consort} = $line; # save the connection type
154 LogDbg('DXCommand', "$call connected from $self->{hostname}");
156 # set some necessary flags on the user if they are connecting
157 $self->{registered} = 1;
158 # sort out privilege reduction
163 $nossid =~ s/-\d+$//;
165 $self->{inrbnfilter} = Filter::read_in('rbn', $call, 1)
166 || Filter::read_in('rbn', 'node_default', 1);
168 # clean up qra locators
169 my $qra = $user->qra;
170 $qra = undef if ($qra && !DXBearing::is_qra($qra));
172 my $lat = $user->lat;
173 my $long = $user->long;
174 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);
177 # if we have been running and stopped for a while
178 # if the cache is warm enough don't operate the inrush preventor
179 $self->{inrushpreventor} = exists $runtime{$call} && $runtime{$call} > $startup_delay || $noinrush ? 0 : $main::systime + $startup_delay;
180 dbg("RBN: noinrush: $noinrush, setting inrushpreventor on $self->{call} to $self->{inrushpreventor}");
183 my @queue; # the queue of spots ready to send
190 # my $spots = $self->{spot};
192 # remove leading and trailing spaces
199 my $tim = $main::systime;
202 dbg "RBN:RAW,$line" if isdbg('rbnraw');
203 return unless $line=~/^DX\s+de/;
205 my (undef, undef, $origin, $qrg, $call, $mode, $s, $m, $spd, $u, $sort, $t, $tx) = split /[:\s]+/, $line;
207 # fix up FT8 spots from 7001
208 $t = $u, $u = '' if !$t && is_ztime($u);
209 $t = $sort, $sort = '' if !$t && is_ztime($sort);
210 my $qra = $spd, $spd = '' if is_qra($spd);
213 # is this anything like a callsign?
214 unless (is_callsign($call)) {
215 dbg("RBN: ERROR $call from $origin on $qrg is invalid, dumped");
219 $origin =~ s/\-(?:\d{1,2}\-)?\#$//; # get rid of all the crap we aren't interested in
225 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');
229 ++$self->{norawhour};
235 # fix up times for things like 'NXDXF B' etc
236 if ($tx && is_ztime($t)) {
245 if ($sort && $sort eq 'NCDXF') {
249 if ($sort && $sort eq 'BEACON') {
252 if ($mode =~ /^PSK/) {
255 if ($mode eq 'RTTY') {
259 # The main de-duping key is [call, $frequency], but we probe a bit around that frequency to find a
260 # range of concurrent frequencies that might be in play.
262 # The key to this is deducing the true callsign by "majority voting" (the greater the number of spotters
263 # the more effective this is) together with some lexical analsys probably in conjuction with DXSpider
264 # 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)
265 # and some heuristical "Kwalitee" rating given distance from the zone centres of spotter, recipient user
266 # and spotted. A map can be generated once per user and spotter as they are essentially mostly static.
267 # The spotted will only get a coarse position unless other info is available. Programs that parse
268 # DX bulletins and the online data online databases could be be used and then cached.
270 # Obviously users have to opt in to receiving RBN spots and other users will simply be passed over and
273 # Clearly this will only work in the 'mojo' branch of DXSpider where it is possible to pass off external
274 # data requests to ephemeral or semi resident forked processes that do any grunt work and the main
275 # process to just the standard "message passing" which has been shown to be able to sustain over 5000
276 # per second (limited by the test program's output and network speed, rather than DXSpider's handling).
278 my $nqrg = nearest(1, $qrg); # normalised to nearest Khz
279 # my $nqrg = nearest_even($qrg); # normalised to nearest Khz
280 my $sp = "$call|$nqrg"; # hopefully the skimmers will be calibrated at least this well!
281 my $spp = sprintf("$call|%d", $nqrg+1); # but, clearly, my hopes are rudely dashed
282 my $spm = sprintf("$call|%d", $nqrg-1); # in BOTH directions!
285 my $spot = $spots->{$sp};
286 $spot = $spots->{$spp}, $sp = $spp, dbg(qq{RBN: SPP using $spp for $sp}) if isdbg('rbn') && !$spot && exists $spots->{$spp};
287 $spot = $spots->{$spm}, $sp = $spm, dbg(qq{RBN: SPM using $spm for $sp}) if isdbg('rbn') && !$spot && exists $spots->{$spm};
290 # if we have one and there is only one slot and that slot's time isn't expired for respot then return
292 if ($spot && ref $spot) {
294 unless ($self->{minspottime} > 0 && $tim - $spot->[0] >= $self->{minspottime}) {
295 dbg("RBN: key: '$sp' call: $call qrg: $qrg DUPE \@ ". atime(int $spot->[0])) if isdbg('rbn');
299 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $spot->[0])) if isdbg('rbn');
300 undef $spot; # it's about to be recreated (in one place)
304 # otherwise we have a spot being built up at the moment
306 dbg("RBN: key '$sp' = '$spot' not ref");
310 # here we either have an existing spot record buildup on the go, or we need to create the first one
312 $spots->{$sp} = $spot = [$main::systime];
313 dbg("RBN: key: '$sp' call: $call qrg: $qrg NEW" . ($respot ? ' RESPOT' : '')) if isdbg('rbn');
316 # add me to the display queue unless we are waiting for initial in rush to finish
317 return unless $noinrush || $self->{inrushpreventor} < $main::systime;
319 # build up a new record and store it in the buildup
320 # deal with the unix time
321 my ($hh,$mm) = $t =~ /(\d\d)(\d\d)Z$/;
322 my $utz = $hh*3600 + $mm*60 + $main::systime_daystart; # possible issue with late spot from previous day
323 $utz -= 86400 if $utz > $tim+3600; # too far ahead, drag it back one day
325 # create record and add into the buildup
326 my $r = [$origin, nearest(.1, $qrg), $call, $mode, $s, $t, $utz, $respot, $u];
327 my @s = Spot::prepare($r->[RQrg], $r->[RCall], $r->[RUtz], '', $r->[ROrigin]);
329 dbg("RBN: ERROR invalid prefix/callsign $call from $origin-# on $qrg, dumped");
333 if ($self->{inrbnfilter}) {
334 my ($want, undef) = $self->{inrbnfilter}->it($s);
337 $r->[RSpotData] = \@s;
339 push @{$self->{queue}}, $sp if @$spot == 1; # queue the KEY (not the record)
341 dbg("RBN: key: '$sp' ADD RECORD call: $call qrg: $qrg origin: $origin") if isdbg('rbn');
345 # At this point we run the queue to see if anything can be sent onwards to the punter
346 my $now = $main::systime;
348 # now run the waiting queue which just contains KEYS ($call|$qrg)
349 foreach $sp (@{$self->{queue}}) {
350 my $cand = $spots->{$sp};
351 unless ($cand && $cand->[0]) {
352 dbg "RBN Cand " . ($cand ? 'def' : 'undef') . " [0] " . ($cand->[0] ? 'def' : 'undef') . " dwell $dwelltime";
355 if ($now >= $cand->[0] + $dwelltime ) {
356 # we have a candidate, create qualitee value(s);
357 unless (@$cand > 1) {
358 dbg "RBN: QUEUE key '$sp' MISSING RECORDS " . dd($cand) if isdbg 'rbn';
359 shift @{$self->{queue}};
362 my $savedtime = shift @$cand; # save the start time
364 my $quality = @$cand;
365 $quality = 9 if $quality > 9;
366 $quality = "Q:$quality";
367 if (isdbg('progress')) {
368 my $s = "RBN: SPOT key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] $quality";
369 $s .= " route: $self->{call}";
373 send_dx_spot($self, $quality, $cand);
375 # clear out the data and make this now just "spotted", but no further action required until respot time
376 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
378 $spots->{$sp} = [$savedtime];
379 shift @{$self->{queue}};
381 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $spot->[0] + $dwelltime - $now) if isdbg 'rbnqueue';
385 dbg "RBN:DATA,$line" if isdbg('rbn');
389 # we should get the spot record minus the time, so just an array of record (arrays)
398 ++$self->{norbnhour};
400 # $r = [$origin, $qrg, $call, $mode, $s, $utz, $respot];
402 my $mode = $spot->[0]->[3]; # as all the modes will be the same;
404 my @dxchan = DXChannel::get_all();
406 foreach my $dxchan (@dxchan) {
407 next unless $dxchan->is_user;
408 my $user = $dxchan->{user};
409 next unless $user && $user->wantrbn;
411 # does this user want this sort of spot at all?
413 ++$want if $user->wantbeacon && $mode =~ /^BCN|DXF/;
414 ++$want if $user->wantcw && $mode =~ /^CW/;
415 ++$want if $user->wantrtty && $mode =~ /^RTT/;
416 ++$want if $user->wantpsk && $mode =~ /^PSK|FSK|MSK/;
417 ++$want if $user->wantft && $mode =~ /^FT/;
419 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",
426 )) if isdbg('rbnll');
428 # send one spot to one user out of the ones that we have
429 $self->dx_spot($dxchan, $quality, $spot) if $want;
439 my $call = $dxchan->{call};
442 my $strength = 100; # because it could if we talk about FTx
450 ++$self->{nousers}->{$call};
451 ++$self->{nousers10}->{$call};
452 ++$self->{nousershour}->{$call};
455 my $rf = $dxchan->{rbnfilter} || $dxchan->{spotsfilter};
456 foreach my $r (@$spot) {
457 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
458 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
460 my $comment = sprintf "%-3s %2ddB $quality", $r->[RMode], $r->[RStrength];
461 $respot = 1 if $r->[Respot];
462 $qra = $r->[RQra] if !$qra && $r->[RQra] && is_qra($r->[RQra]);
464 my $s = $r->[RSpotData]; # the prepared spot
465 $s->[SComment] = $comment; # apply new generated comment
468 ++$zone{$s->[SZone]}; # save the spotter's zone
469 ++$qrg{$s->[SQrg]}; # and the qrg
472 # save the lowest strength one
473 if ($r->[RStrength] < $strength) {
474 $strength = $r->[RStrength];
476 dbg("RBN: STRENGTH spot: $s->[SCall] qrg: $s->[SQrg] origin: $s->[SOrigin] dB: $r->[RStrength] < $strength") if isdbg 'rbnll';
480 my ($want, undef) = $rf->it($s);
481 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';
489 $saver = $filtered; # if nothing passed the filter's lips then $saver == $filtered == undef !
494 # create a zone list of spotters
495 delete $zone{$saver->[SZone]}; # remove this spotter's zone (leaving all the other zones)
496 my $z = join ',', sort {$a <=> $b} keys %zone;
498 # determine the most likely qrg and then set it
502 while (my ($k, $v) = each %qrg) {
503 $fk = $k, $mv = $v if $v > $mv;
506 $saver->[SQrg] = $fk;
507 $saver->[SComment] .= '*' if $c > 1;
508 $saver->[SComment] .= '+' if $respot;
509 $saver->[SComment] .= " Z:$z" if $z;
511 dbg("RBN: SENDING to $call spot: $saver->[SCall] qrg: $saver->[SQrg] origin: $saver->[SOrigin] $saver->[SComment]") if isdbg 'rbnll';
512 if ($dxchan->{ve7cc}) {
513 my $call = $saver->[SOrigin];
514 $saver->[SOrigin] .= '-#';
515 $buf = VE7CC::dx_spot($dxchan, @$saver);
516 $saver->[SOrigin] = $call;
518 my $call = $saver->[SOrigin];
519 $saver->[SOrigin] = substr($call, 0, 6);
520 $saver->[SOrigin] .= '-#';
521 $buf = $dxchan->format_dx_spot(@$saver);
522 $saver->[SOrigin] = $call;
525 $dxchan->local_send('N', $buf);
529 ++$self->{nospothour};
532 my $user = DXUser::get_current($saver->[SCall]) || DXUser->new($saver->[SCall]);
533 unless ($user->qra && is_qra($user->qra)) {
535 dbg("RBN: update qra on $saver->[SCall] to $qra");
545 foreach my $dxchan (DXChannel::get_all()) {
546 next unless $dxchan->is_rbn;
547 dbg "RBN:STATS minute $dxchan->{call} raw: $dxchan->{noraw} sent: $dxchan->{norbn} delivered: $dxchan->{nospot} users: " . scalar keys %{$dxchan->{nousers}} if isdbg('rbnstats');
548 if ($dxchan->{noraw} == 0 && $dxchan->{lasttime} > 60) {
549 LogDbg('RBN', "RBN: no input from $dxchan->{call}, disconnecting");
552 $dxchan->{noraw} = $dxchan->{norbn} = $dxchan->{nospot} = 0; $dxchan->{nousers} = {};
553 $runtime{$dxchan->{call}} += 60;
556 # save the spot cache
557 write_cache() unless $main::systime + $startup_delay < $main::systime;;
564 while (my ($k,$v) = each %{$spots}) {
565 if ($main::systime - $v->[0] > $minspottime*2) {
573 dbg "RBN:STATS spot cache remain: $count removed: $removed"; # if isdbg('rbn');
574 foreach my $dxchan (DXChannel::get_all()) {
575 next unless $dxchan->is_rbn;
576 dbg "RBN:STATS 10-minute $dxchan->{call} raw: $dxchan->{noraw10} sent: $dxchan->{norbn10} delivered: $dxchan->{nospot10} users: " . scalar keys %{$dxchan->{nousers10}};
577 $dxchan->{noraw10} = $dxchan->{norbn10} = $dxchan->{nospot10} = 0; $dxchan->{nousers10} = {};
583 foreach my $dxchan (DXChannel::get_all()) {
584 next unless $dxchan->is_rbn;
585 dbg "RBN:STATS hour $dxchan->{call} raw: $dxchan->{norawhour} sent: $dxchan->{norbnhour} delivered: $dxchan->{nospothour} users: " . scalar keys %{$dxchan->{nousershour}};
586 $dxchan->{norawhour} = $dxchan->{norbnhour} = $dxchan->{nospothour} = 0; $dxchan->{nousershour} = {};
597 my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
598 my $s = $json->encode($spots);
606 my $mt = (stat($cachefn))[9];
607 my $t = $main::systime - $mt || 1;
609 if ($t < $cache_valid) {
610 dbg("RBN:check_cache '$cachefn' spot cache exists, created $p ago and not too old");
611 my $fh = IO::File->new($cachefn);
616 dbg("RBN:check_cache cache read size " . length $s);
619 dbg("RBN:check_cache file read error $!");
623 eval {$spots = $json->decode($s)};
624 if ($spots && ref $spots) {
625 dbg("RBN:check_cache spot cache restored");
629 dbg("RBN::checkcache error decoding $@");
631 my $d = difft($main::systime-$cache_valid);
632 dbg("RBN::checkcache '$cachefn' created $p ago is too old (> $d), ignored");
635 dbg("RBN:check_cache '$cachefn' spot cache not present");