5 use Data::Dump qw(dump);
6 use Device::SerialPort qw(:STAT);
8 my $debug = $ENV{DEBUG} || 0;
10 my $port = Device::SerialPort->new('/dev/ttyUSB0');
11 die "can't open serial port" unless $port;
12 $port->baudrate(9600);
14 $port->parity('none');
16 $port->handshake('none');
18 $port->read_char_time(500);
19 $port->read_const_time(1000);
23 return $port->read( $len );
28 return $port->write( $bytes );
31 # TODO: implement remote serial port
32 # remserial -x 2 -p 23000 -s "9600 raw" /dev/ttyUSB0
36 foreach my $str ( @_ ) {
37 my $hex = uc unpack( 'H*', $str );
38 $hex =~ s/(..)/$1 /g if length( $str ) > 2;
42 return join(' | ', @out);
47 $bytes .= pack('C', hex('0x' . $_)) foreach split(/\s+/,join(' ',@_));
54 for my $i ( 0 .. length($data) - 2 ) {
56 $crc = ( $crc << 1 ) ^ 25;
61 my $byte = ord(substr($data,$i,1));
63 # warn "## ", as_hex(chr($byte)), " crc = ", $crc, " ", as_hex(chr($crc));
65 # ignore checksum errors for FF, we will calulate them!
66 if ( chr($crc) ne substr($data,-1,1) && substr($data,-1,1) ne "\xFF" ) {
67 warn "CRC error for ",as_hex($data), " calulated ", as_hex(chr($crc));
70 return substr($data,0,-1) . chr($crc);
74 my ($bytes,$desc) = @_;
77 warn ">> ",as_hex( $bytes );
79 write_serial( $bytes );
81 my $data = read_serial(1);
82 warn "<< len: ",ord($data) if $debug;
84 goto retry if ord($data) == 0;
86 $data .= read_serial(ord($data) - 1);
88 warn "<< ",as_hex($data);
91 while ( $o < length($data) - 2 ) {
92 my $n = unpack('n', substr($data,$o,2));
93 $n = -( 0xffff - $n ) if $n & 0x8000;
94 warn "## $o = ",$n, "\t",$n / 16,"\n";
98 while ( $o < length($data) - 1 ) {
99 my $n = unpack('c', substr($data,$o,1));
100 warn "## $o = ", $n, "\n";
108 my ($hex,$desc) = @_;
109 v_bytes( hex2bytes( $hex ), $desc );
113 v '07 02 00 00 00 04 C4', "hardware version";
115 v '07 0A 00 00 00 04 44', 'software version';
117 v '07 00 01 00 06 0E EA', 'temperatures';
119 v '07 00 00 00 26 0A A6', 'last errros';
122 #v '07 00 00 00 26 00 AC', 'last errros (with invalid length)';
124 foreach my $reg ( @ARGV ) {
125 warn "# send user $reg\n";
127 crc( hex2bytes( "07 00 00 00 $reg 01 FF" ) )