added mqtt publishing
[vaillant-thermostat] / serial.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use Device::SerialPort;
5 use Data::Dump qw(dump);
6 use Time::HiRes qw(time);
7
8 my $read_len = 255;
9
10 my $path = shift @ARGV || '/dev/serial/by-path/platform-20980000.usb-usb-0:1.3.1:1.0-port0';
11
12 $|=1;
13
14 my $s = new Device::SerialPort( $path ) || die $!;
15 $s->baudrate(2400);
16 $s->databits(8); # 7
17 $s->parity('none');
18 $s->stopbits(1);
19 $s->handshake('none');
20 $s->read_char_time(2);
21 $s->read_const_time(3);
22
23 #$s->write('o');
24
25 my $t = time();
26
27 my $sym;
28
29 sub _mqtt_pub {
30         my ( $t, $m ) = @_;
31         my $cmd = "mosquitto_pub -h rpi2 -t 'stat/rpi/$t' -m '$m'";
32         #warn "# _mqtt_pub [$t] = [$m]\n";
33         warn "## $cmd";
34         system $cmd;
35 }
36
37 while (1) {
38         my ($len, $string) = $s->read($read_len);
39         my $ts = time();
40
41         if ( $len > 0 ) {
42                 my $hex = unpack('H*',$string);
43                 $hex =~ s/(..)/$1 /g;
44 =for later
45                 my $ascii;
46                 foreach ( split(/ /, $hex) ) {
47                         if ( ! exists $sym->{$_} ) {
48                                 $chr++;
49                         $ascii 
50 =cut
51
52                 my $temp = `curl localhost:3000/temp.txt`;
53                 $temp =~ s/\s+/ /gs;
54
55                 #printf "%s %2d  %s\n", time(), $len, $hex;
56                 printf "%8.4f %6.2f %2d  %s | %s\n", $ts, $ts - $t, $len, $hex, $temp;
57                 $t = time();
58
59                 if ( $hex =~ m/^.+aa fc 39 aa (.+)/ ) {
60                         my @l = split(/\s+/,$1);
61                         my @d = (
62                                 hex( $l[0] . $l[1] ),
63                                 hex( $l[3] . $l[4] ),
64                                 hex( $l[6] ),
65                                 hex( $l[12] ),
66                                 hex( $l[14] ), # * 300,
67                                 hex( $l[15] ), # * 400,
68                                 hex( $l[18] ),
69                         );
70
71                         _mqtt_pub "stat/boiler/" . chr(ord('a') + $_) => $d[$_] foreach 0 .. $#d;
72                 }
73
74         }
75 }
76
77 $s->close;