added --max-time to curl so we fail quickly without network
[air-quality] / zph02.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 # sudo apt install libdevice-serialport-perl libdata-dump-perl
5 use Device::SerialPort;
6 use Time::HiRes;
7 use Data::Dump qw(dump);
8
9 my $port = shift @ARGV || '/dev/serial/by-path/platform-3f980000.usb-usb-0:1.5:1.0';
10 my $influx_url = shift @ARGV || 'http://10.13.37.92:8086/write?consistency=any&db=rot13';
11
12 my $s = new Device::SerialPort( $port ) || die $!;
13 $s->baudrate(9600);
14 $s->databits(8);
15 $s->parity('none');
16 $s->stopbits(1);
17 $s->handshake('none');
18 $s->read_char_time(5);
19 $s->read_const_time(10);
20
21
22 while (1) {
23
24         alarm 3;
25         # Usb serial which I'm using is buggy and blocks from time to time.
26         # This will ensure that we have passed here every 3 seconds
27         # or we will be killed and systemd will restart us
28
29         my ($len, $string) = $s->read(9);
30         my $t = int( Time::HiRes::time() * 1_000_000_000 );
31         die $! if ! defined($len);
32         if ( $len > 0 ) {
33                 my @v = unpack('C*', $string);
34                 #warn "# $len ",dump($string), dump( @v ), $/;
35
36                 my $sum = 0;
37                 # -2 is specified in datasheet, next byte is 0 so it's same as -1
38                 foreach my $i ( 0 .. $#v - 2 ) {
39                         $sum += $v[$i];
40                         $sum = $sum & 0xff;
41                 }
42                 $sum = ~$sum & 0xff;
43
44                 my $checksum = $v[8];
45                 my $pcnt = $v[3] + ( $v[4] / 100 );
46                 if ( $v[0] == 0xff && $sum == $checksum ) {
47                         my $influx = "zph02,dc=trnjanska pm25_pcnt=$pcnt $t";
48                         print "$influx\n";
49                         system "curl --max-time 2 --silent -XPOST '$influx_url' --data-binary '$influx'";
50                         system "mosquitto_pub -h rpi2 -t 'air/zph02/pm25' -m $pcnt";
51                 }
52         }
53
54 };
55
56
57 $s->close;