kuhinja battery change
[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.2:1.0-port0';
11
12 $|=1;
13
14 connect_again:
15
16 my $s = new Device::SerialPort( $path ) || die $!;
17 $s->baudrate(2400);
18 $s->databits(8); # 7
19 $s->parity('none');
20 $s->stopbits(1);
21 $s->handshake('none');
22 $s->read_char_time(2);
23 $s->read_const_time(3);
24
25 #$s->write('o');
26
27 my $t = time();
28
29 my $sym;
30
31 sub _mqtt_pub {
32         my ( $t, $m ) = @_;
33         my $cmd = "mosquitto_pub -h rpi2 -t '$t' -m '$m'";
34         #warn "# _mqtt_pub [$t] = [$m]\n";
35         #warn "## $cmd";
36         system $cmd;
37 }
38
39 while (1) {
40         my ($len, $string) = $s->read($read_len);
41         goto connect_again if ! defined $len;
42         my $ts = time();
43
44         if ( $len > 0 ) {
45                 my $hex = unpack('H*',$string);
46                 $hex =~ s/(..)/$1 /g;
47
48                 my $temp = `curl --silent localhost:3000/temp.txt`;
49                 $temp =~ s/\s+/ /gs;
50                 $temp =~ s/^\s+//;
51
52                 #printf "%s %2d  %s\n", time(), $len, $hex;
53                 printf "%8.4f %6.2f %2d  %s | %s\n", $ts, $ts - $t, $len, $hex, $temp;
54                 $t = time();
55
56                 if ( $hex =~ m/^.+aa fc 39 aa (.+)/ ) {
57                         my @l = split(/\s+/,$1);
58                         my @d = (
59                                 hex( $l[0] . $l[1] ),
60                                 hex( $l[3] . $l[4] ),
61                                 hex( $l[6] ),
62                                 hex( $l[12] ),
63                                 hex( $l[14] ), # * 300,
64                                 hex( $l[15] ), # * 400,
65                                 hex( $l[18] ),
66                         );
67
68                         _mqtt_pub "stat/boiler/" . chr(ord('a') + $_) => $d[$_] foreach 0 .. $#d;
69                 }
70
71                 my @v = split(/\s+/, $temp, 4);
72                 my @n = qw( DS18B20/temperature DHT22/temperature DHT22/humidity DHT22/errors );
73                    @n = qw( DS18B20/temperature DHT22/temperature DHT22/humidity DHT22/errors ) if $#v == 1; # no DS18B20
74                 foreach (@v) {
75                         _mqtt_pub "stat/boiler/" . shift(@n) => $_;
76                 }
77
78         }
79 }
80
81 $s->close;