added crc implementation
authorDobrica Pavlinusic <dpavlin@rot13.org>
Fri, 12 Dec 2014 13:13:21 +0000 (14:13 +0100)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Fri, 12 Dec 2014 13:13:24 +0000 (14:13 +0100)
based on code from
http://www.ab-log.ru/smart-house/heating-automation/gaz_meter

dialog.pl

index ee20fd1..7daf81c 100755 (executable)
--- a/dialog.pl
+++ b/dialog.pl
@@ -32,12 +32,32 @@ sub hex2bytes {
        return $bytes;
 }
 
+sub crc {
+       my $data = shift;
+       my $crc = 0;
+       for my $i ( 0 .. length($data) - 2 ) {
+               if ( $crc & 0x80 ) {
+                       $crc = ( $crc << 1 ) ^ 25;
+               } else {
+                       $crc = $crc << 1;
+               }
+               $crc = $crc & 0xff;
+               my $byte = ord(substr($data,$i,1));
+               $crc = $crc ^ $byte;
+#              warn "## ", as_hex(chr($byte)), " crc = ", $crc, " ", as_hex(chr($crc));
+       }
+       if ( chr($crc) ne substr($data,-1,1) ) {
+               warn "CRC error for ",as_hex($data), " calulated ", as_hex(chr($crc));
+       }
+}
+
 sub v {
        my ($hex,$desc) = @_;
        my $bytes = hex2bytes( $hex );
        warn "# $desc\n";
 retry:
        warn ">> ",as_hex( $bytes );
+       crc( $bytes );
        $port->write( $bytes );
 
        my $data = $port->read(1);
@@ -46,6 +66,7 @@ retry:
        goto retry if ord($data) == 0;
 
        $data .= $port->read(ord($data) - 1);
+       crc($data);
        warn "<< ",as_hex($data);
 
 }