summaryrefslogtreecommitdiff
path: root/tools/beacon/decode.pl
blob: 28bf82bbe0290cb266c2e49348a3e9c0969e94b9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/perl -w

use strict;
use MIME::Base32 qw( RFC ); 

my @beacons;
if(!$ARGV[0] || $ARGV[0] eq "-") {
  @beacons = <STDIN>;
} else {
  open(my $fh, "<", $ARGV[0]) or die "Unable to open file " . $ARGV[0];
  @beacons = <$fh>;  
  close($fh)
}

foreach(@beacons) { 
  my $beacon = $_;
  $beacon =~ s/\s*$//g; 
  $beacon =~ s/^\s*//g; 

  if($beacon =~ /([^ ]+) ([A-Z2-7]{3}) ([A-Z2-7])/) {
    my $preamble = $1;
    my $cnt = $2;
    my $checksum = $3;

    my $cntval = unpack("n", MIME::Base32::decode($cnt . "=")) >> 1;
    my $csval_recv = unpack("C", MIME::Base32::decode($checksum . "=")) >> 3;

    my $csval_calc = ord('N') - ord(' ');
    my @values = unpack("C*", $preamble);
    @values = (@values, unpack("C*", $cnt));
    foreach(@values) { $csval_calc ^= $_ - ord(' '); }
    $csval_calc = ($csval_calc & 0x1F) ^ (($csval_calc & 0x20) >> 5);
   
    print $beacon . " ->  cnt: " . $cntval;
    if($csval_calc != $csval_recv) {
      print "  checksom wrong! (" . sprintf("%02X", $csval_recv) . " vs. " . sprintf("%02X", $csval_calc) . ")\n";
    } else {
      print "  checksom ok! (" . sprintf("%02X", $csval_recv) . ")\n";
    }


  } else {
    print $beacon . " -> Beacon format error!\n";
  }


}