simply the RBN skimmer scoring system
[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 $dbgrbn = isdbg('rbn');
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 $dbgrbn;
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') || $dbgrbn);
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') || $dbgrbn);
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 $dbgrbn;
343                                         return;
344                                 }
345                                 
346                                 dbg("RBN: key: '$sp' RESPOTTING call: $call qrg: $qrg last seen \@ ". atime(int $cand->[CTime])) if $dbgrbn;
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 $dbgrbn;
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 $dbgrbn;
389
390                 push @$cand, $r;
391
392         } else {
393                 dbg "RBN:DATA,$line" if $dbgrbn;
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 $seeme = $dxchan->user->rbnseeme();
449         my $strength = 100;             # because it could if we talk about FTx
450         my $saver;
451         my %zone;
452         my $respot;
453         my $qra;
454
455         ++$self->{nousers}->{$call};
456         ++$self->{nousers10}->{$call};
457         ++$self->{nousershour}->{$call};
458
459         my $filtered;
460         my $rf = $dxchan->{rbnfilter} || $dxchan->{spotsfilter};
461         my $comment;
462         
463         foreach my $r (@$cand) {
464                 # $r = [$origin, $qrg, $call, $mode, $s, $t, $utz, $respot, $qra];
465                 # Spot::prepare($qrg, $call, $utz, $comment, $origin);
466                 next unless $r && ref $r;
467
468                 $qra = $r->[RQra] if !$qra && $r->[RQra] && is_qra($r->[RQra]);
469
470                 $comment = sprintf "%-3s %2ddB $quality", $r->[RMode], $r->[RStrength];
471                 my $s = $r->[RSpotData];                # the prepared spot
472                 $s->[SComment] = $comment;              # apply new generated comment
473
474                 ++$zone{$s->[SZone]};           # save the spotter's zone
475
476                 # if the 'see me' flag is set, then show all the spots without further adornment (see set/rbnseeme for more info)
477                 if ($seeme) {
478                         send_final($dxchan, $s);
479                         next;
480                 }
481
482                 # save the lowest strength one
483                 if ($r->[RStrength] < $strength) {
484                         $strength = $r->[RStrength];
485                         $saver = $s;
486                         dbg("RBN: STRENGTH spot: $s->[SCall] qrg: $s->[SQrg] origin: $s->[SOrigin] dB: $r->[RStrength] < $strength") if isdbg 'rbnll';
487                 }
488
489                 if ($rf) {
490                         my ($want, undef) = $rf->it($s);
491                         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';
492                         next unless $want;
493                         $filtered = $s;
494                 }
495         }
496
497         if ($rf) {
498                 $saver = $filtered;             # if nothing passed the filter's lips then $saver == $filtered == undef !
499         }
500         
501         if ($saver) {
502                 my $buf;
503                 # create a zone list of spotters
504                 delete $zone{$saver->[SZone]};  # remove this spotter's zone (leaving all the other zones)
505                 my $z = join ',', sort {$a <=> $b} keys %zone;
506
507                 # alter spot data accordingly
508                 $saver->[SComment] .= " Z:$z" if $z;
509                 
510                 send_final($dxchan, $saver);
511                 
512                 ++$self->{nospot};
513                 ++$self->{nospot10};
514                 ++$self->{nospothour};
515                 
516                 if ($qra) {
517                         my $user = DXUser::get_current($saver->[SCall]) || DXUser->new($saver->[SCall]);
518                         unless ($user->qra && is_qra($user->qra)) {
519                                 $user->qra($qra);
520                                 dbg("RBN: update qra on $saver->[SCall] to $qra");
521                                 $user->put;
522                         }
523                 }
524         }
525 }
526
527 sub send_final
528 {
529         my $dxchan = shift;
530         my $saver = shift;
531         my $call = $dxchan->{call};
532         my $buf;
533         
534         dbg("RBN: SENDING to $call spot: $saver->[SCall] qrg: $saver->[SQrg] origin: $saver->[SOrigin] $saver->[SComment]") if isdbg 'rbnll';
535         if ($dxchan->{ve7cc}) {
536                 my $call = $saver->[SOrigin];
537                 $saver->[SOrigin] .= '-#';
538                 $buf = VE7CC::dx_spot($dxchan, @$saver);
539                 $saver->[SOrigin] = $call;
540         } else {
541                 my $call = $saver->[SOrigin];
542                 $saver->[SOrigin] = substr($call, 0, 6);
543                 $saver->[SOrigin] .= '-#';
544                 $buf = $dxchan->format_dx_spot(@$saver);
545                 $saver->[SOrigin] = $call;
546         }
547         $dxchan->local_send('N', $buf);
548 }
549
550 # per second
551 sub process
552 {
553         my $rbnskim = isdbg('rbnskim');
554         
555         foreach my $dxchan (DXChannel::get_all()) {
556                 next unless $dxchan->is_rbn;
557
558                 # At this point we run the queue to see if anything can be sent onwards to the punter
559                 my $now = $main::systime;
560                 my $ta = [gettimeofday];
561                 my $items = 0;
562                 
563                 # now run the waiting queue which just contains KEYS ($call|$qrg)
564                 foreach my $sp (keys %{$dxchan->{queue}}) {
565                         my $cand = $spots->{$sp};
566                         ++$items;
567                         unless ($cand && $cand->[CTime]) {
568                                 dbg "RBN Cand $sp " . ($cand ? 'def' : 'undef') . " [CTime] " . ($cand->[CTime] ? 'def' : 'undef') . " dwell $dwelltime";
569                                 next;
570                         } 
571                         if ($now >= $cand->[CTime] + $dwelltime ) {
572                                 # we have a candidate, create qualitee value(s);
573                                 unless (@$cand > CData) {
574                                         dbg "RBN: QUEUE key '$sp' MISSING RECORDS, IGNORED" . dd($cand) if isdbg 'rbnqueue';
575                                         next;
576                                 }
577                                 dbg "RBN: QUEUE PROCESSING key: '$sp' $now >= $cand->[CTime]" if isdbg 'rbnqueue'; 
578                                 my $quality = @$cand - CData;
579                                 my $spotters = $quality;
580
581                                 # dump it and remove it from the queue if it is of unadequate quality
582                                 if ($quality < $minqual) {
583                                         if ($rbnskim) {
584                                                 my $r = $cand->[CData];
585                                                 if ($r) {
586                                                         my $s = "RBN:SKIM Ignored (Q:$quality < Q:$minqual) key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] route: $dxchan->{call}";
587                                                         dbg($s);
588                                                 }
589                                         }
590                                         delete $spots->{$sp}; # don't remember it either - this means that a spot HAS to come in with sufficient spotters to be processed.
591                                         delete $dxchan->{queue}->{$sp};
592                                         next;
593                                 }
594
595                                 $quality = 9 if $quality > 9;
596                                 $cand->[CQual] = $quality if $quality > $cand->[CQual];
597
598                                 my $r;
599
600                                 # this scores each candidate according to its skimmer's QRG score (i.e. how often it agrees with its peers)
601                                 # what happens is hash of all QRGs in candidates are incremented by that skimmer's reputation for "accuracy"
602                                 # or, more exactly, past agreement with the consensus. This score can be from -5 -> +5. 
603                                 my %qrg = ();
604                                 my $skimmer;
605                                 my $sk;
606                                 my $band;
607                                 my %seen = ();
608                                 foreach $r (@$cand) {
609                                         next unless ref $r;
610                                         if (exists $seen{$r->[ROrigin]}) {
611                                                 undef $r;
612                                                 next;
613                                         }
614                                         $seen{$r->[ROrigin]} = 1;
615                                         $band ||= int $r->[RQrg] / 1000;
616                                         $sk = "SKIM|$r->[ROrigin]|$band"; # thus only once per set of candidates
617                                         $skimmer = $spots->{$sk};
618                                         unless ($skimmer) {
619                                                 $skimmer = $spots->{$sk} = [1, 0, 0, $now, []]; # this first time, this new skimmer gets the benefit of the doubt on frequency.
620                                                 dbg("RBN:SKIM new slot $sk " . $json->encode($skimmer)) if $rbnskim;
621                                         }
622                                         $qrg{$r->[RQrg]} += ($skimmer->[DScore] || 1);
623                                 }
624                                 
625                                 # determine the most likely qrg and then set it - NOTE (-)ve votes, generated by the skimmer scoring system above, are ignored
626                                 my @deviant;
627                                 my $c = 0;
628                                 my $mv = 0;
629                                 my $qrg = 0;
630                                 while (my ($k, $votes) = each %qrg) {
631                                         if ($votes >= $mv) {
632                                                 $qrg = $k;
633                                                 $mv = $votes;
634                                         }
635                                         ++$c;
636                                 }
637
638                                 # Ignore possible spots with 0 QRG score - as determined by the skimmer scoring system above -  as they are likely to be wrong 
639                                 unless ($qrg > 0) {
640                                         if ($rbnskim) {
641                                                 my $keys;
642                                                 while (my ($k, $v) = (each %qrg)) {
643                                                         $keys .= "$k=>$v, ";
644                                                 }
645                                                 $keys =~ /,\s*$/;
646                                                 my $i = 0;
647                                                 foreach $r (@$cand) {
648                                                         next unless $r && ref $r;
649                                                         dbg "RBN:SKIM cand $i QRG likely wrong from '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] (qrgs: $keys c: $c) route: $dxchan->{call}, ignored";
650                                                         ++$i;
651                                                 }
652                                         }
653                                         delete $spots->{$sp}; # get rid
654                                         delete $dxchan->{queue}->{$sp};
655                                         next;
656                                 }
657
658                                 # detemine and spit out the deviants. Then adjust the scores according to whether it is a deviant or good
659                                 # NOTE: deviant nodes can become good (or less bad), and good nodes bad (or less good) on each spot that
660                                 # they generate. This is based solely on each skimmer's agreement (or not) with the "consensus" score generated
661                                 # above ($qrg). The resultant score + good + bad is stored per band and will be used the next time a spot
662                                 # appears on this band from each skimmer.
663                                 foreach $r (@$cand) {
664                                         next unless $r && ref $r;
665                                         my $diff = $c > 1 ? nearest(.1, $r->[RQrg] - $qrg) : 0;
666                                         $sk = "SKIM|$r->[ROrigin]|$band";
667                                         $skimmer = $spots->{$sk};
668                                         if ($diff) {
669                                                 ++$skimmer->[DBad] if $skimmer->[DBad] < $maxdeviants;
670                                                 --$skimmer->[DGood] if $skimmer->[DGood] > 0;
671                                                 push @deviant, sprintf("$r->[ROrigin]:%+.1f", $diff);
672                                                 push @{$skimmer->[DEviants]}, $diff;
673                                                 shift @{$skimmer->[DEviants]} while @{$skimmer->[DEviants]} > $maxdeviants;
674                                         } else {
675                                                 ++$skimmer->[DGood] if $skimmer->[DGood] < $maxdeviants;
676                                                 --$skimmer->[DBad] if $skimmer->[DBad] > 0;
677                                                 shift @{$skimmer->[DEviants]};
678                                         }
679                                         $skimmer->[DScore] = $skimmer->[DGood] - $skimmer->[DBad];
680                                         my $lastin = difft($skimmer->[DLastin], $now, 2);
681                                         my $difflist = join(', ', @{$skimmer->[DEviants]});
682                                         $difflist = " ($difflist)" if $difflist;
683                                         dbg("RBN:SKIM key $sp slot $sk $r->[RQrg] - $qrg = $diff Skimmer score: $skimmer->[DGood] - $skimmer->[DBad] = $skimmer->[DScore] lastseen:$lastin ago$difflist") if $rbnskim; 
684                                         $skimmer->[DLastin] = $now;
685                                         $r->[RSpotData]->[SQrg] = $qrg if $qrg && $c > 1; # set all the QRGs to the agreed value
686                                 }
687
688                                 $qrg = (sprintf "%.1f",  $qrg)+0;
689                                 $r = $cand->[CData];
690                                 $r->[RQrg] = $qrg;
691                                 my $squality = "Q:$cand->[CQual]";
692                                 $squality .= '*' if $c > 1; 
693                                 $squality .= '+' if $r->[Respot];
694
695                                 if (isdbg('progress')) {
696                                         my $s = "RBN: SPOT key: '$sp' = $r->[RCall] on $r->[RQrg] by $r->[ROrigin] \@ $r->[RTime] $squality route: $dxchan->{call}";
697                                         my $td = @deviant;
698                                         $s .= " QRGScore $mv Deviants ($td/$spotters): ";
699                                         $s .= join(', ', sort @deviant) if $td;
700                                         dbg($s);
701                                 }
702
703                                 # finally send it out to any waiting public
704                                 send_dx_spot($dxchan, $squality, $cand);
705                                 
706                                 # clear out the data and make this now just "spotted", but no further action required until respot time
707                                 dbg "RBN: QUEUE key '$sp' cleared" if isdbg 'rbn';
708
709                                 delete $spots->{$sp};
710                                 delete $dxchan->{queue}->{$sp};
711
712                                 # calculate new sp (which will be 70% likely the same as the old one)
713                                 # 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.
714                                 # and we want to store the key that corresponds to majority opinion. 
715                                 my $nqrg = nearest(1, $qrg * 10);  # normalised to nearest Khz
716                                 my $nsp = "$r->[RCall]|$nqrg";
717                                 if ($sp ne $nsp) {
718                                         dbg("RBN:SKIM CHANGE KEY sp '$sp' -> '$nsp' for storage") if $rbnskim;
719                                         $spots->{$nsp} = [$now, $cand->[CQual]];
720                                 }
721                         }
722                         else {
723                                 dbg sprintf("RBN: QUEUE key: '$sp' SEND time not yet reached %.1f secs left", $cand->[CTime] + $dwelltime - $now) if isdbg 'rbnqueue'; 
724                         }
725                 }
726                 if (isdbg('rbntimer')) {
727                         my $diff = _diffus($ta);
728                         dbg "RBN: TIMER process queue for call: $dxchan->{call} $items spots $diff uS";
729                 }
730         }
731 }
732
733 sub per_minute
734 {
735         foreach my $dxchan (DXChannel::get_all()) {
736                 next unless $dxchan->is_rbn;
737                 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');
738                 if ($dxchan->{noraw} == 0 && $dxchan->{lasttime} > 60) {
739                         LogDbg('RBN', "RBN: no input from $dxchan->{call}, disconnecting");
740                         $dxchan->disconnect;
741                 }
742                 $dxchan->{noraw} = $dxchan->{norbn} = $dxchan->{nospot} = 0; $dxchan->{nousers} = {};
743                 $runtime{$dxchan->{call}} += 60;
744         }
745
746         # save the spot cache
747         write_cache() unless $main::systime + $startup_delay < $main::systime;;
748 }
749
750 sub per_10_minute
751 {
752         my $count = 0;
753         my $removed = 0;
754         while (my ($k,$cand) = each %{$spots}) {
755                 next if $k eq 'VERSION';
756                 next if $k =~ /^O\|/;
757                 next if $k =~ /^SKIM\|/;
758                 
759                 if ($main::systime - $cand->[CTime] > $minspottime*2) {
760                         delete $spots->{$k};
761                         ++$removed;
762                 }
763                 else {
764                         ++$count;
765                 }
766         }
767         dbg "RBN:STATS spot cache remain: $count removed: $removed"; # if isdbg('rbn');
768         foreach my $dxchan (DXChannel::get_all()) {
769                 next unless $dxchan->is_rbn;
770                 my $nq = keys %{$dxchan->{queue}};
771                 my $pc = $dxchan->{noraw10} ? sprintf("%.1f%%",$dxchan->{norbn10}*100/$dxchan->{noraw10}) : '0.0%';
772                 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}};
773                 $dxchan->{noraw10} = $dxchan->{norbn10} = $dxchan->{nospot10} = 0; $dxchan->{nousers10} = {};
774         }
775 }
776
777 sub per_hour
778 {
779         foreach my $dxchan (DXChannel::get_all()) {
780                 next unless $dxchan->is_rbn;
781                 my $nq = keys %{$dxchan->{queue}};
782                 my $pc = $dxchan->{norawhour} ? sprintf("%.1f%%",$dxchan->{norbnhour}*100/$dxchan->{norawhour}) : '0.0%';
783                 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}};
784                 $dxchan->{norawhour} = $dxchan->{norbnhour} = $dxchan->{nospothour} = 0; $dxchan->{nousershour} = {};
785         }
786 }
787
788 sub finish
789 {
790         write_cache();
791 }
792
793 sub write_cache
794 {
795         my $ta = [ gettimeofday ];
796         $json->indent(1) if isdbg 'rbncache';
797         my $s = eval {$json->encode($spots)};
798         if ($s) {
799                 my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
800                 $fh->print($s);
801                 $fh->close;
802         } else {
803                 dbg("RBN:Write_cache error '$@'");
804         }
805         $json->indent(0);
806         my $diff = _diffms($ta);
807         dbg("RBN:WRITE_CACHE time to write: $diff mS");
808 }
809
810 sub check_cache
811 {
812         if (-e $cachefn) {
813                 my $mt = (stat($cachefn))[9];
814                 my $t = $main::systime - $mt || 1;
815                 my $p = difft($mt, 2);
816                 if ($t < $cache_valid) {
817                         dbg("RBN:check_cache '$cachefn' spot cache exists, created $p ago and not too old");
818                         my $fh = IO::File->new($cachefn);
819                         my $s;
820                         if ($fh) {
821                                 local $/ = undef;
822                                 $s = <$fh>;
823                                 dbg("RBN:check_cache cache read size " . length $s);
824                                 $fh->close;
825                         } else {
826                                 dbg("RBN:check_cache file read error $!");
827                                 return undef;
828                         }
829                         if ($s) {
830                                 eval {$spots = $json->decode($s)};
831                                 if ($spots && ref $spots) {     
832                                         if (exists $spots->{VERSION} && $spots->{VERSION} == $DATA_VERSION) {
833                                                 # now clean out anything that has spot build ups in progress
834                                                 while (my ($k, $cand) = each %$spots) {
835                                                         next if $k eq 'VERSION';
836                                                         next if $k =~ /^O\|/;
837                                                         next if $k =~ /^SKIM\|/;
838                                                         if (@$cand > CData) {
839                                                                 $spots->{$k} = [$cand->[CTime], $cand->[CQual]];
840                                                         }
841                                                 }
842                                                 dbg("RBN:check_cache spot cache restored");
843                                                 return 1;
844                                         } 
845                                 }
846                                 dbg("RBN::checkcache error decoding $@");
847                         }
848                 } else {
849                         my $d = difft($main::systime-$cache_valid);
850                         dbg("RBN::checkcache '$cachefn' created $p ago is too old (> $d), ignored");
851                 }
852         } else {
853                 dbg("RBN:check_cache '$cachefn' spot cache not present");
854         }
855         
856         return undef;
857 }
858
859 1;