c968d4c8d56cc4f6f0c01b4ee5c8567837a01e35
[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 lib qw {.};
15
16 use DXDebug;
17 use DXUtil;
18 use DXLog;
19 use DXUser;
20 use DXChannel;
21 use Math::Round qw(nearest nearest_floor);
22 use Date::Parse;
23 use Time::HiRes qw(gettimeofday);
24 use Spot;
25 use DXJSON;
26 use IO::File;
27
28 use constant {
29                           ROrigin => 0,
30                           RQrg => 1,
31                           RCall => 2,
32                           RMode => 3,
33                           RStrength => 4,
34                           RTime => 5,
35                           RUtz => 6,
36                           Respot => 7,
37                           RQra => 8,
38                           RSpotData => 9,
39                          };
40
41 use constant {
42                           SQrg => 0,
43                           SCall => 1,
44                           STime => 2,
45                           SComment => 3,
46                           SOrigin => 4,
47                           SZone => 11,
48                          };
49 use constant {
50                           OQual => 0,
51                           OAvediff => 1,
52                           OSpare => 2,
53                           ODiff => 3,
54                          };
55 use constant {
56                           CTime => 0,
57                           CQual => 1,
58                           CData => 2,
59                          };
60
61 use constant {
62                           DScore => 0,
63                           DGood => 1,
64                           DBad => 2,
65                           DLastin => 3,
66                           DEviants => 4,
67                          };
68
69
70 our $DATA_VERSION = 1;
71
72 our @ISA = qw(DXChannel);
73
74 our $startup_delay = 5*60;              # don't send anything out until this timer has expired
75                                 # this is to allow the feed to "warm up" with duplicates
76                                 # so that the "big rush" doesn't happen.
77
78 our $minspottime = 30*60;               # the time between respots of a callsign - if a call is
79                                 # still being spotted (on the same freq) and it has been
80                                 # spotted before, it's spotted again after this time
81                                 # until the next minspottime has passed.
82
83 our $beacontime = 5*60;                 # same as minspottime, but for beacons (and shorter)
84
85 our $dwelltime = 10;                    # the amount of time to wait for duplicates before issuing
86                                 # a spot to the user (no doubt waiting with bated breath).
87
88 our $filterdef = $Spot::filterdef; # we use the same filter as the Spot system. Can't think why :-).
89
90 my $spots;                                              # the GLOBAL spot cache
91
92 my %runtime;                                    # how long each channel has been running
93
94 our $cachefn = localdata('rbn_cache');
95 our $cache_valid = 4*60;                # The cache file is considered valid if it is not more than this old
96
97 our $maxqrgdiff = 10;                   # the maximum
98 our $minqual = 2;                               # the minimum quality we will accept for output
99
100 my $json;
101 my $noinrush = 0;                               # override the inrushpreventor if set
102 our $maxdeviants = 5;                   # the number of deviant QRGs to record for skimmer records
103
104 sub init
105 {
106         $json = DXJSON->new;
107         if (check_cache()) {
108                 $noinrush = 1;
109         } else {
110                 $spots = {VERSION=>$DATA_VERSION};
111         }
112         if (defined $DB::VERSION) {
113                 $noinrush = 1;
114                 $json->indent(1);
115         }
116         
117 }
118
119 sub new 
120 {
121         my $self = DXChannel::alloc(@_);
122
123         # routing, this must go out here to prevent race condx
124         my $pkg = shift;
125         my $call = shift;
126
127         $self->{last} = 0;
128         $self->{noraw} = 0;
129         $self->{nospot} = 0;
130         $self->{nouser} = {};
131         $self->{norbn} = 0;
132         $self->{noraw10} = 0;
133         $self->{nospot10} = 0;
134         $self->{nouser10} = {};
135         $self->{norbn10} = 0;
136         $self->{nospothour} = 0;
137         $self->{nouserhour} = {};
138         $self->{norbnhour} = 0;
139         $self->{norawhour} = 0;
140         $self->{sort} = 'N';
141         $self->{lasttime} = $main::systime;
142         $self->{minspottime} = $minspottime;
143         $self->{beacontime} = $beacontime;
144         $self->{showstats} = 0;
145         $self->{pingint} = 0;
146         $self->{nopings} = 0;
147         $self->{queue} = {};
148
149         return $self;
150 }
151
152 sub start
153
154         my ($self, $line, $sort) = @_;
155         my $user = $self->{user};
156         my $call = $self->{call};
157         my $name = $user->{name};
158                 
159         # log it
160         my $host = $self->{conn}->peerhost;
161         $host ||= "unknown";
162         $self->{hostname} = $host;
163
164         $self->{name} = $name ? $name : $call;
165         $self->state('prompt');         # a bit of room for further expansion, passwords etc
166         $self->{lang} = $user->lang || $main::lang || 'en';
167         if ($line =~ /host=/) {
168                 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
169                 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
170                 unless ($h) {
171                         ($h) = $line =~ /host=([\da..fA..F:]+)/;
172                         $line =~ s/\s*host=[\da..fA..F:]+// if $h;
173                 }
174                 if ($h) {
175                         $h =~ s/^::ffff://;
176                         $self->{hostname} = $h;
177                 }
178         }
179         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
180         $self->{consort} = $line;       # save the connection type
181
182         LogDbg('DXCommand', "$call connected from $self->{hostname}");
183
184         # set some necessary flags on the user if they are connecting
185         $self->{registered} = 1;
186         # sort out privilege reduction
187         $self->{priv} = 0;
188
189         # get the filters
190         my $nossid = $call;
191         $nossid =~ s/-\d+$//;
192
193         $self->{inrbnfilter} = Filter::read_in('rbn', $call, 1) 
194                 || Filter::read_in('rbn', 'node_default', 1);
195         
196         # clean up qra locators
197         my $qra = $user->qra;
198         $qra = undef if ($qra && !DXBearing::is_qra($qra));
199         unless ($qra) {
200                 my $lat = $user->lat;
201                 my $long = $user->long;
202                 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);  
203         }
204
205         # if we have been running and stopped for a while 
206         # if the cache is warm enough don't operate the inrush preventor
207         $self->{inrushpreventor} = exists $runtime{$call} && $runtime{$call} > $startup_delay || $noinrush ?  0 : $main::systime + $startup_delay;
208         dbg("RBN: noinrush: $noinrush, setting inrushpreventor on $self->{call} to $self->{inrushpreventor}");
209 }
210
211 my @queue;                                              # the queue of spots ready to send
212
213 sub normal
214 {
215         my $self = shift;
216         my $line = shift;
217         my @ans;
218 #       my $spots = $self->{spot};
219         
220         # remove leading and trailing spaces
221         chomp $line;
222         $line =~ s/^\s*//;
223         $line =~ s/\s*$//;
224
225         # add base RBN
226
227         my $now = $main::systime;
228
229         # parse line
230         dbg "RBN:RAW,$line" if isdbg('rbnraw');
231         return unless $line=~/^DX\s+de/;
232
233         my (undef, undef, $origin, $qrg, $call, $mode, $s, $m, $spd, $u, $sort, $t, $tx) = split /[:\s]+/, $line;
234
235         # fix up FT8 spots from 7001
236         $t = $u, $u = '' if !$t && is_ztime($u);
237         $t = $sort, $sort = '' if !$t && is_ztime($sort);
238         my $qra = $spd, $spd = '' if is_qra($spd);
239         $u = $qra if $qra;
240
241         # is this anything like a callsign?
242         unless (is_callsign($call)) {
243                 dbg("RBN: ERROR $call from $origin on $qrg is invalid, dumped");
244                 return;
245         }
246
247         $origin =~ s/\-(?:\d{1,2}\-)?\#$//; # get rid of all the crap we aren't interested in
248
249
250         $sort ||= '';
251         $tx ||= '';
252         $qra ||= '';
253     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');
254
255         ++$self->{noraw};
256         ++$self->{noraw10};
257         ++$self->{norawhour};
258         
259         my $b;
260         
261         if ($t || $tx) {
262
263                 # fix up times for things like 'NXDXF B' etc
264                 if ($tx && is_ztime($t)) {
265                         if (is_ztime($tx)) {
266                                 $b = $t;
267                                 $t = $tx;
268                         } else {
269                                 dbg "RBN:ERR,$line";
270                                 return (0);
271                         }
272                 }
273                 if ($sort && $sort eq 'NCDXF') {
274                         $mode = 'DXF';
275                         $t = $tx;
276                 }
277                 if ($sort && $sort eq 'BEACON') {
278                         $mode = 'BCN';
279                 }
280                 if ($mode =~ /^PSK/) {
281                         $mode = 'PSK';
282                 }
283                 if ($mode eq 'RTTY') {
284                         $mode = 'RTT';
285                 }
286
287                 # The main de-duping key is [call, $frequency], but we probe a bit around that frequency to find a
288                 # range of concurrent frequencies that might be in play. 
289
290                 # The key to this is deducing the true callsign by "majority voting" (the greater the number of spotters
291         # the more effective this is) together with some lexical analsys probably in conjuction with DXSpider
292                 # 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)
293                 # and some heuristical "Kwalitee" rating given distance from the zone centres of spotter, recipient user
294         # and spotted. A map can be generated once per user and spotter as they are essentially mostly static. 
295                 # The spotted will only get a coarse position unless other info is available. Programs that parse 
296                 # DX bulletins and the online data online databases could be be used and then cached. 
297
298                 # Obviously users have to opt in to receiving RBN spots and other users will simply be passed over and
299                 # ignored.
300
301                 # Clearly this will only work in the 'mojo' branch of DXSpider where it is possible to pass off external
302                 # data requests to ephemeral or semi resident forked processes that do any grunt work and the main
303                 # process to just the standard "message passing" which has been shown to be able to sustain over 5000 
304                 # per second (limited by the test program's output and network speed, rather than DXSpider's handling).
305
306                 my $search = 5;
307                 my $nqrg = nearest(1, $qrg * 10);  # normalised to nearest Khz
308                 my $sp = "$call|$nqrg";           # hopefully the skimmers will be calibrated at least this well!
309
310                 # find it?
311                 my $cand = $spots->{$sp};
312                 unless ($cand) {
313                         my ($i, $new);
314                         for ($i = $nqrg; !$cand && $i <= $nqrg+$search; $i += 1) {
315                                 $new = "$call|$i";
316                                 $cand = $spots->{$new}, last if exists $spots->{$new};
317                         }
318                         if ($cand) {
319                                 my $diff = $i - $nqrg;
320                                 dbg(qq{RBN: QRG Diff using $new (+$diff) for $sp for qrg $qrg}) if (isdbg('rbnqrg') || isdbg('rbn'));
321                                 $sp = $new;
322                         }
323                 }
324                 unless ($cand) {
325                         my ($i, $new);
326                         for ($i = $nqrg; !$cand && $i >= $nqrg-$search; $i -= 1) {
327                                 $new = "$call|$i";
328                                 $cand = $spots->{$new}, last if exists $spots->{$new};
329                         }
330                         if ($cand) {
331                                 my $diff = $nqrg - $i;
332                                 dbg(qq{RBN: QRG Diff using $new (-$diff) for $sp for qrg $qrg}) if (isdbg('rbnqrg') || isdbg('rbn'));
333                                 $sp = $new;
334                         }
335                 }
336                 
337                 # if we have one and there is only one slot and that slot's time isn't expired for respot then return
338                 my $respot = 0;
339                 if ($cand && ref $cand) {
340                         if (@$cand <= CData) {
341                                 unless ($self->{minspottime} > 0 && $now - $cand->[CTime] >= $self->{minspottime}) {
342                                         dbg("RBN: key: '$sp' call: $call qrg: $qrg DUPE \@ ". atime(int $cand->[CTime])) if isdbg('rbn');
343                                         return;
344                                 }
345                                 
346                                 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $cand->[CTime])) if isdbg('rbn');
347                                 $cand->[CTime] = $now;
348                                 ++$respot;
349                         }
350
351                         # otherwise we have a spot being built up at the moment
352                 } elsif ($cand) {
353                         dbg("RBN: key '$sp' = '$cand' not ref");
354                         return;
355                 }
356
357                 # here we either have an existing spot record buildup on the go, or we need to create the first one
358                 unless ($cand) {
359                         $spots->{$sp} = $cand = [$now, 0];
360                         dbg("RBN: key: '$sp' call: $call qrg: $qrg NEW" . ($respot ? ' RESPOT' : '')) if isdbg('rbn');
361                 }
362
363                 # add me to the display queue unless we are waiting for initial in rush to finish
364                 return unless $noinrush || $self->{inrushpreventor} < $main::systime;
365
366                 # build up a new record and store it in the buildup
367                 # deal with the unix time
368                 my ($hh,$mm) = $t =~ /(\d\d)(\d\d)Z$/;
369                 my $utz = $hh*3600 + $mm*60 + $main::systime_daystart; # possible issue with late spot from previous day
370                 $utz -= 86400 if $utz > $now+3600;                                         # too far ahead, drag it back one day
371
372                 # create record and add into the buildup
373                 my $r = [$origin, nearest(.1, $qrg), $call, $mode, $s, $t, $utz, $respot, $u];
374                 my @s =  Spot::prepare($r->[RQrg], $r->[RCall], $r->[RUtz], '', $r->[ROrigin]);
375                 if ($s[5] == 666) {
376                         dbg("RBN: ERROR invalid prefix/callsign $call from $origin-# on $qrg, dumped");
377                         return;
378                 }
379                 
380                 if ($self->{inrbnfilter}) {
381                         my ($want, undef) = $self->{inrbnfilter}->it($s);
382                         return unless $want;    
383                 }
384                 $r->[RSpotData] = \@s;
385
386                 ++$self->{queue}->{$sp};# unless @$cand>= CData; # queue the KEY (not the record)
387
388                 dbg("RBN: key: '$sp' ADD RECORD call: $call qrg: $qrg origin: $origin") if isdbg('rbn');
389
390                 push @$cand, $r;
391
392         } else {
393                 dbg "RBN:DATA,$line" if isdbg('rbn');
394         }
395 }
396
397 # we should get the spot record minus the time, so just an array of record (arrays)
398 sub send_dx_spot
399 {
400         my $self = shift;
401         my $quality = shift;
402         my $cand = shift;
403
404         ++$self->{norbn};
405         ++$self->{norbn10};
406         ++$self->{norbnhour};
407         
408         # $r = [$origin, $qrg, $call, $mode, $s, $utz, $respot];
409
410         my $mode = $cand->[CData]->[RMode]; # as all the modes will be the same;
411         
412         my @dxchan = DXChannel::get_all();
413
414         foreach my $dxchan (@dxchan) {
415                 next unless $dxchan->is_user;
416                 my $user = $dxchan->{user};
417                 next unless $user &&  $user->wantrbn;
418
419                 # does this user want this sort of spot at all?
420                 my $want = 0;
421                 ++$want if $user->wantbeacon && $mode =~ /^BCN|DXF/;
422                 ++$want if $user->wantcw && $mode =~ /^CW/;
423                 ++$want if $user->wantrtty && $mode =~ /^RTT/;
424                 ++$want if $user->wantpsk && $mode =~ /^PSK|FSK|MSK/;
425                 ++$want if $user->wantft && $mode =~ /^FT/;
426
427                 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",
428                                         $user->wantrbn,
429                                         $user->wantft,
430                                         $user->wantbeacon,
431                                         $user->wantcw,
432                                         $user->wantpsk,
433                                         $user->wantrtty,
434                                    )) if isdbg('rbnll');
435
436                 # send one spot to one user out of the ones that we have
437                 $self->dx_spot($dxchan, $quality, $cand) if $want;
438         }
439 }
440
441 sub dx_spot
442 {
443         my $self = shift;
444         my $dxchan = shift;
445         my $quality = shift;
446         my $cand = shift;
447         my $call = $dxchan->{call};
448         my $strength = 100;             # because it could if we talk about FTx
449         my $saver;
450         my %zone;
451         my $respot;
452         my $qra;
453
454         ++$self->{nousers}->{$call};
455         ++$self->{nousers10}->{$call};
456         ++$self->{nousershour}->{$call};
457
458         my $filtered;
459         my $rf = $dxchan->{rbnfilter} || $dxchan->{spotsfilter};
460         my $comment;
461         
462         foreach my $r (@$cand) {
463                 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
464                 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
465                 next unless $r && ref $r;
466
467                 $qra = $r->[RQra] if !$qra && $r->[RQra] && is_qra($r->[RQra]);
468
469                 $comment = sprintf "%-3s %2ddB $quality", $r->[RMode], $r->[RStrength];
470                 my $s = $r->[RSpotData];                # the prepared spot
471                 $s->[SComment] = $comment;              # apply new generated comment
472                 
473                 ++$zone{$s->[SZone]};           # save the spotter's zone
474  
475                 # save the lowest strength one
476                 if ($r->[RStrength] < $strength) {
477                         $strength = $r->[RStrength];
478                         $saver = $s;
479                         dbg("RBN: STRENGTH spot: $s->[SCall] qrg: $s->[SQrg] origin: $s->[SOrigin] dB: $r->[RStrength] < $strength") if isdbg 'rbnll';
480                 }
481
482                 if ($rf) {
483                         my ($want, undef) = $rf->it($s);
484                         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';
485                         next unless $want;
486                         $filtered = $s;
487 #                       last;
488                 }
489         }
490
491         if ($rf) {
492                 $saver = $filtered;             # if nothing passed the filter's lips then $saver == $filtered == undef !
493         }
494         
495         if ($saver) {
496                 my $buf;
497                 # create a zone list of spotters
498                 delete $zone{$saver->[SZone]};  # remove this spotter's zone (leaving all the other zones)
499                 my $z = join ',', sort {$a <=> $b} keys %zone;
500
501                 # alter spot data accordingly
502                 $saver->[SComment] .= " Z:$z" if $z;
503                 
504                 dbg("RBN: SENDING to $call spot: $saver->[SCall] qrg: $saver->[SQrg] origin: $saver->[SOrigin] $saver->[SComment]") if isdbg 'rbnll';
505                 if ($dxchan->{ve7cc}) {
506                         my $call = $saver->[SOrigin];
507                         $saver->[SOrigin] .= '-#';
508                         $buf = VE7CC::dx_spot($dxchan, @$saver);
509                         $saver->[SOrigin] = $call;
510                 } else {
511                         my $call = $saver->[SOrigin];
512                         $saver->[SOrigin] = substr($call, 0, 6);
513                         $saver->[SOrigin] .= '-#';
514                         $buf = $dxchan->format_dx_spot(@$saver);
515                         $saver->[SOrigin] = $call;
516                 }
517 #               $buf =~ s/^DX/RB/;
518                 $dxchan->local_send('N', $buf);
519
520                 ++$self->{nospot};
521                 ++$self->{nospot10};
522                 ++$self->{nospothour};
523                 
524                 if ($qra) {
525                         my $user = DXUser::get_current($saver->[SCall]) || DXUser->new($saver->[SCall]);
526                         unless ($user->qra && is_qra($user->qra)) {
527                                 $user->qra($qra);
528                                 dbg("RBN: update qra on $saver->[SCall] to $qra");
529                                 $user->put;
530                         }
531                 }
532         }
533 }
534
535 # per second
536 sub process
537 {
538         foreach my $dxchan (DXChannel::get_all()) {
539                 next unless $dxchan->is_rbn;
540
541                 # At this point we run the queue to see if anything can be sent onwards to the punter
542                 my $now = $main::systime;
543                 my $ta = [gettimeofday];
544                 my $items = 0;
545                 
546                 # now run the waiting queue which just contains KEYS ($call|$qrg)
547                 foreach my $sp (keys %{$dxchan->{queue}}) {
548                         my $cand = $spots->{$sp};
549                         ++$items;
550                         unless ($cand && $cand->[CTime]) {
551                                 dbg "RBN Cand $sp " . ($cand ? 'def' : 'undef') . " [CTime] " . ($cand->[CTime] ? 'def' : 'undef') . " dwell $dwelltime";
552                                 next;
553                         } 
554                         if ($now >= $cand->[CTime] + $dwelltime ) {
555                                 # we have a candidate, create qualitee value(s);
556                                 unless (@$cand > CData) {
557                                         dbg "RBN: QUEUE key '$sp' MISSING RECORDS, IGNORED" . dd($cand) if isdbg 'rbnqueue';
558                                         next;
559                                 }
560                                 dbg "RBN: QUEUE PROCESSING key: '$sp' $now >= $cand->[CTime]" if isdbg 'rbnqueue'; 
561                                 my $quality = @$cand - CData;
562                                 my $spotters = $quality;
563
564                                 # dump it and remove it from the queue if it is of unadequate quality
565                                 if ($quality < $minqual) {
566                                         if (isdbg('rbnskim')) {
567                                                 my $r = $cand->[CData];
568                                                 if ($r) {
569                                                         my $s = "RBN: SPOT IGNORED(Q:$quality < Q:$minqual) key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] route: $dxchan->{call}";
570                                                         dbg($s);
571                                                 }
572                                         }
573                                         delete $spots->{$sp}; # don't remember it either - this means that a spot HAS to come in with sufficient spotters to be processed.
574                                         delete $dxchan->{queue}->{$sp};
575                                         next;
576                                 }
577
578                                 $quality = 9 if $quality > 9;
579                                 $cand->[CQual] = $quality if $quality > $cand->[CQual];
580
581                                 my $r;
582                                 my %qrg;
583                                 my $skimmer;
584                                 my $sk;
585                                 my $band;
586                                 my %seen;
587                                 foreach $r (@$cand) {
588                                         next unless ref $r;
589                                         if (exists $seen{$r->[ROrigin]}) {
590                                                 undef $r;
591                                                 next;
592                                         }
593                                         $seen{$r->[ROrigin]} = 1;
594                                         $band ||= int $r->[RQrg] / 1000;
595                                         $sk = "SKIM|$r->[ROrigin]|$band";
596                                         $skimmer = $spots->{$sk};
597                                         unless ($skimmer) {
598                                                 $skimmer = $spots->{$sk} = [0+0, 0+0, 0+0, $now, []]; # this stupid incantation is to make sure than there are no JSON nulls!
599                                                 dbg("RBN:SKIM new slot $sk " . $json->encode($skimmer)) if isdbg('rbnskim');
600                                         }
601                                         $qrg{$r->[RQrg]} += ($skimmer->[DScore] || 1);
602                                 }
603                                 
604                                 # determine the most likely qrg and then set it
605                                 my @deviant;
606                                 my $c = 0;
607                                 my $mv = 0;
608                                 my $qrg;
609                                 while (my ($k, $votes) = each %qrg) {
610                                         $qrg = $k, $mv = $votes if $votes >= $mv;
611                                         ++$c;
612                                 }
613                                 # spit out the deviants
614                                 foreach $r (@$cand) {
615                                         next unless $r && ref $r;
616                                         my $diff = $c > 1 ? nearest(.1, $r->[RQrg] - $qrg) : 0;
617                                         $sk = "SKIM|$r->[ROrigin]|$band";
618                                         $skimmer = $spots->{$sk};
619                                         $skimmer->[DBad] ||= 0+0; # stop JSON nulls?
620                                         $skimmer->[DEviants] ||= []; # ditto
621                                         if ($diff) {
622                                                 ++$skimmer->[DBad] if $skimmer->[DBad] < $maxdeviants;
623                                                 --$skimmer->[DGood] if $skimmer->[DGood] > 0;
624                                                 push @deviant, sprintf("$r->[ROrigin]:%+.1f", $diff);
625                                                 push @{$skimmer->[DEviants]}, $diff;
626                                                 shift @{$skimmer->[DEviants]} while @{$skimmer->[DEviants]} > $maxdeviants;
627                                         } else {
628                                                 ++$skimmer->[DGood] if $skimmer->[DGood] < $maxdeviants;
629                                                 --$skimmer->[DBad] if $skimmer->[DBad] > 0;
630                                                 shift @{$skimmer->[DEviants]};
631                                         }
632                                         $skimmer->[DScore] = $skimmer->[DGood] - $skimmer->[DBad];
633                                         $skimmer->[DScore] ||= 0.2; # minimun score
634                                         dbg("RBN:SKIM key $sp slot $sk $r->[RQrg] - $qrg = $diff " . $json->encode($skimmer)) if isdbg('rbnskim'); 
635                                         $skimmer->[DLastin] = $now;
636                                         $r->[RSpotData]->[SQrg] = $qrg if $qrg && $c > 1; # set all the QRGs to the agreed value
637                                 }
638
639                                 $qrg = (sprintf "%.1f",  $qrg)+0;
640                                 $r = $cand->[CData];
641                                 $r->[RQrg] = $qrg;
642                                 my $squality = "Q:$cand->[CQual]";
643                                 $squality .= '*' if $c > 1; 
644                                 $squality .= '+' if $r->[Respot];
645
646                                 if (isdbg('progress')) {
647                                         my $s = "RBN: SPOT key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] $squality route: $dxchan->{call}";
648                                         my $td = @deviant;
649                                         $s .= " QRGScore $mv Deviants ($td/$spotters): ";
650                                         $s .= join(', ', sort @deviant) if $td;
651                                         dbg($s);
652                                 }
653
654                                 # finally send it out to any waiting public
655                                 send_dx_spot($dxchan, $squality, $cand);
656                                 
657                                 # clear out the data and make this now just "spotted", but no further action required until respot time
658                                 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
659
660                                 delete $spots->{$sp};
661                                 delete $dxchan->{queue}->{$sp};
662
663                                 # calculate new sp (which will be 70% likely the same as the old one)
664                                 # we do this to cope with the fact that the first spotter may well be "wrongly calibrated" giving a qrg that disagrees with the majority.
665                                 # and we want to store the key that corresponds to majority opinion. 
666                                 my $nqrg = nearest(1, $qrg * 10);  # normalised to nearest Khz
667                                 my $nsp = "$r->[RCall]|$nqrg";
668                                 if ($sp ne $nsp) {
669                                         dbg("RBN:SKIM CHANGE KEY sp '$sp' -> '$nsp' for storage") if isdbg('rbnskim');
670                                         $spots->{$nsp} = [$now, $cand->[CQual]];
671                                 }
672                         }
673                         else {
674                                 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $cand->[CTime] + $dwelltime - $now) if isdbg 'rbnqueue'; 
675                         }
676                 }
677                 if (isdbg('rbntimer')) {
678                         my $diff = _diffus($ta);
679                         dbg "RBN: TIMER process queue for call: $dxchan->{call} $items spots $diff uS";
680                 }
681         }
682 }
683
684 sub per_minute
685 {
686         foreach my $dxchan (DXChannel::get_all()) {
687                 next unless $dxchan->is_rbn;
688                 dbg "RBN:STATS minute $dxchan->{call} raw: $dxchan->{noraw} retrieved spots: $dxchan->{norbn} delivered: $dxchan->{nospot} after filtering to users: " . scalar keys %{$dxchan->{nousers}} if isdbg('rbnstats');
689                 if ($dxchan->{noraw} == 0 && $dxchan->{lasttime} > 60) {
690                         LogDbg('RBN', "RBN: no input from $dxchan->{call}, disconnecting");
691                         $dxchan->disconnect;
692                 }
693                 $dxchan->{noraw} = $dxchan->{norbn} = $dxchan->{nospot} = 0; $dxchan->{nousers} = {};
694                 $runtime{$dxchan->{call}} += 60;
695         }
696
697         # save the spot cache
698         write_cache() unless $main::systime + $startup_delay < $main::systime;;
699 }
700
701 sub per_10_minute
702 {
703         my $count = 0;
704         my $removed = 0;
705         while (my ($k,$cand) = each %{$spots}) {
706                 next if $k eq 'VERSION';
707                 next if $k =~ /^O\|/;
708                 next if $k =~ /^SKIM\|/;
709                 
710                 if ($main::systime - $cand->[CTime] > $minspottime*2) {
711                         delete $spots->{$k};
712                         ++$removed;
713                 }
714                 else {
715                         ++$count;
716                 }
717         }
718         dbg "RBN:STATS spot cache remain: $count removed: $removed"; # if isdbg('rbn');
719         foreach my $dxchan (DXChannel::get_all()) {
720                 next unless $dxchan->is_rbn;
721                 my $nq = keys %{$dxchan->{queue}};
722                 my $pc = $dxchan->{noraw10} ? sprintf("%.1f%%",$dxchan->{norbn10}*100/$dxchan->{noraw10}) : '0.0%';
723                 dbg "RBN:STATS 10-minute $dxchan->{call} queue: $nq raw: $dxchan->{noraw10} retrieved spots: $dxchan->{norbn10} ($pc) delivered: $dxchan->{nospot10} after filtering to  users: " . scalar keys %{$dxchan->{nousers10}};
724                 $dxchan->{noraw10} = $dxchan->{norbn10} = $dxchan->{nospot10} = 0; $dxchan->{nousers10} = {};
725         }
726 }
727
728 sub per_hour
729 {
730         foreach my $dxchan (DXChannel::get_all()) {
731                 next unless $dxchan->is_rbn;
732                 my $nq = keys %{$dxchan->{queue}};
733                 my $pc = $dxchan->{norawhour} ? sprintf("%.1f%%",$dxchan->{norbnhour}*100/$dxchan->{norawhour}) : '0.0%';
734                 dbg "RBN:STATS hour $dxchan->{call} queue: $nq raw: $dxchan->{norawhour} retrieved spots: $dxchan->{norbnhour} ($pc) delivered: $dxchan->{nospothour} after filtering to users: " . scalar keys %{$dxchan->{nousershour}};
735                 $dxchan->{norawhour} = $dxchan->{norbnhour} = $dxchan->{nospothour} = 0; $dxchan->{nousershour} = {};
736         }
737 }
738
739 sub finish
740 {
741         write_cache();
742 }
743
744 sub write_cache
745 {
746         my $ta = [ gettimeofday ];
747         $json->indent(1);
748         my $s = eval {$json->encode($spots)};
749         if ($s) {
750                 my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
751                 $fh->print($s);
752                 $fh->close;
753         } else {
754                 dbg("RBN:Write_cache error '$@'");
755         }
756         $json->indent(0);
757         my $diff = _diffms($ta);
758         dbg("RBN:WRITE_CACHE time to write: $diff mS");
759 }
760
761 sub check_cache
762 {
763         if (-e $cachefn) {
764                 my $mt = (stat($cachefn))[9];
765                 my $t = $main::systime - $mt || 1;
766                 my $p = difft($mt, 2);
767                 if ($t < $cache_valid) {
768                         dbg("RBN:check_cache '$cachefn' spot cache exists, created $p ago and not too old");
769                         my $fh = IO::File->new($cachefn);
770                         my $s;
771                         if ($fh) {
772                                 local $/ = undef;
773                                 $s = <$fh>;
774                                 dbg("RBN:check_cache cache read size " . length $s);
775                                 $fh->close;
776                         } else {
777                                 dbg("RBN:check_cache file read error $!");
778                                 return undef;
779                         }
780                         if ($s) {
781                                 eval {$spots = $json->decode($s)};
782                                 if ($spots && ref $spots) {     
783                                         if (exists $spots->{VERSION} && $spots->{VERSION} == $DATA_VERSION) {
784                                                 # now clean out anything that is current
785                                                 while (my ($k, $cand) = each %$spots) {
786                                                         next if $k eq 'VERSION';
787                                                         next if $k =~ /^O\|/;
788                                                         next if $k =~ /^SKIM\|/;
789                                                         if (@$cand > CData) {
790                                                                 $spots->{$k} = [$cand->[CTime], $cand->[CQual]];
791                                                         }
792                                                 }
793                                                 dbg("RBN:check_cache spot cache restored");
794                                                 return 1;
795                                         } 
796                                 }
797                                 dbg("RBN::checkcache error decoding $@");
798                         }
799                 } else {
800                         my $d = difft($main::systime-$cache_valid);
801                         dbg("RBN::checkcache '$cachefn' created $p ago is too old (> $d), ignored");
802                 }
803         } else {
804                 dbg("RBN:check_cache '$cachefn' spot cache not present");
805         }
806         
807         return undef;
808 }
809
810 1;