support requence, cleanup protocol parsing
[zc] / unpack.pl
index 00f840f..1e04e2d 100755 (executable)
--- a/unpack.pl
+++ b/unpack.pl
@@ -75,6 +75,7 @@ sub modbus_crc16 {
 my $protocol;
 while(<DATA>) {
        chomp;
+       next if m{^\s*$}; # skip empty lines
        my @a = split(/\s*\t\s*/, $_,7);
        my $id = hex( $a[0] );
        my $pack_fmt = $a[2]; $pack_fmt =~ s/\s+.*$//;
@@ -91,16 +92,24 @@ while(<DATA>) {
 
 warn "## protocol = ",dump( $protocol ) if $debug;
 
+my $pkg_nr = 0;
 
 sub protocol_decode {
-       my ( $up_down, $raw ) = @_;
+       my ( $up_down, $hex ) = @_;
 
-warn "up/down: $up_down raw = ",dump($raw);
+warn "up/down: $up_down hex = ",dump($hex);
 
-my $bin = join('', map { chr(hex($_)) } split(/\s+/,$raw));
+my $bin = join('', map { chr(hex($_)) } split(/\s+/,$hex));
 
 warn "bin = ", dump($bin);
 
+if ( $debug ) {
+       open(my $dump, '>', "/dev/shm/zc.$pkg_nr.$up_down");
+       print $dump $bin;
+       close($dump);
+       $pkg_nr++;
+}
+
 my $cksum = substr($bin, -2, 2);
 
 if ( my $crc = modbus_crc16( substr($bin,0,-2) ) ) {
@@ -144,13 +153,21 @@ while ( $data ) {
        warn "XXX data = $hex\n";
 
        my $data_id = unpack( 'C', substr($data,0,1) );
-       my $data_id_desc = $protocol->{$data_id}->{description} || die "can't find description for data_id $data_id";
+       my $data_id_desc = $protocol->{$data_id}->{description};
+       if ( ! $data_id_desc ) {
+                       warn "ERROR: no description for data_id $data_id SKIPPING!";
+               $data = substr($data,1);
+               next;
+       }
        my $pack_fmt = $protocol->{$data_id}->{pack_fmt} || die "can't find pack_fmt for data_id $data_id";
 
        my $data_range;
 
        if ( $data_id == 0x00 ) {
-               warn "FIXME seq number?";
+               # sequence number
+
+               $data_range = substr($data,2,4);
+               $data = substr($data,6);
 
        } elsif ( $up_down eq 'down' && $function_code == 0x03 ) {
                # type A
@@ -227,6 +244,12 @@ while(<>) {
 
 }
 
+if ( $raw ) {
+       $raw =~ s{^\s+}{}; # strip leading spaces
+       print "## $timestamp $sensor $imei $up_down $raw\n";
+       protocol_decode( $up_down, $raw );
+}
+
 print "stat = ",dump($stat), "\n";
 
 # 6. Protocol Format