5 use Data::Dump qw(dump);
6 my $debug = $ENV{DEBUG} || 0;
10 use Device::SerialPort qw(:STAT);
12 my $port = Device::SerialPort->new('/dev/ttyUSB0');
13 die "can't open serial port" unless $port;
14 $port->baudrate(9600);
16 $port->parity('none');
18 $port->handshake('none');
20 $port->read_char_time(500);
21 $port->read_const_time(1000);
25 return $port->read( $len );
30 return $port->write( $bytes );
35 # TODO: implement remote serial port
36 # remserial -x 2 -p 23000 -s "9600 raw" /dev/ttyUSB0
40 my $sock = IO::Socket::INET->new(
41 PeerAddr => '192.168.1.148',
49 $sock->read( $buffer, $len );
50 warn "## read $len ",as_hex($buffer) if $debug;
56 return $sock->print( $bytes );
62 foreach my $str ( @_ ) {
63 my $hex = uc unpack( 'H*', $str );
64 $hex =~ s/(..)/$1 /g if length( $str ) > 2;
68 return join(' | ', @out);
73 $bytes .= pack('C', hex('0x' . $_)) foreach split(/\s+/,join(' ',@_));
80 for my $i ( 0 .. length($data) - 2 ) {
82 $crc = ( $crc << 1 ) ^ 25;
87 my $byte = ord(substr($data,$i,1));
89 # warn "## ", as_hex(chr($byte)), " crc = ", $crc, " ", as_hex(chr($crc));
91 # ignore checksum errors for FF, we will calulate them!
92 if ( chr($crc) ne substr($data,-1,1) && substr($data,-1,1) ne "\xFF" ) {
93 warn "CRC error for ",as_hex($data), " calulated ", as_hex(chr($crc));
96 return substr($data,0,-1) . chr($crc);
100 my ($bytes,$desc) = @_;
103 warn ">> ",as_hex( $bytes );
105 write_serial( $bytes );
107 my $data = read_serial(1);
108 warn "<< len: ",ord($data) if $debug;
110 goto retry if ord($data) == 0;
112 $data .= read_serial(ord($data) - 1);
114 warn "<< ",as_hex($data);
117 while ( $o < length($data) - 2 ) {
118 my $n = unpack('n', substr($data,$o,2));
119 $n = -( 0xffff - $n ) if $n & 0x8000;
120 warn "## $o = ",$n, "\t",$n / 16,"\n";
124 while ( $o < length($data) - 1 ) {
125 my $n = unpack('c', substr($data,$o,1));
126 warn "## $o = ", $n, "\n";
134 my ($hex,$desc) = @_;
135 v_bytes( hex2bytes( $hex ), $desc );
139 v '07 02 00 00 00 04 C4', "hardware version";
141 v '07 0A 00 00 00 04 44', 'software version';
143 v '07 00 01 00 06 0E EA', 'temperatures';
145 v '07 00 00 00 26 0A A6', 'last errros';
148 #v '07 00 00 00 26 00 AC', 'last errros (with invalid length)';
150 foreach my $reg ( @ARGV ) {
151 warn "# send user $reg\n";
153 crc( hex2bytes( "07 00 00 00 $reg 01 FF" ) )