40815400627b94709c4894f2cce456128d198dc8
[air-quality] / iio2mqtt.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 use Time::HiRes;
6
7 # sudo apt install libiio-utils mosquitto-clients
8
9 my $influx_url = shift @ARGV || 'http://10.13.37.92:8086/write?consistency=any&db=rot13';
10
11 my $hostname = `hostname -s`;
12 chomp($hostname);
13
14 while(1) {
15
16         my $t = Time::HiRes::time;
17         my $t_influx = int( $t * 1_000_000_000 );
18
19         my $iio = `iio_info`;
20
21         my $device;
22         my $name;
23
24         foreach ( split(/\n/, $iio) ) {
25                 if ( m/iio:device\d+:\s+(\S+)/ ) {
26                         $device = $1;
27                 } elsif ( m/(\S+):\s+\(input\)/ ) {
28                         $name = $1;
29                 } elsif ( m/attr\s+0:\s+input\svalue: (\d+[\.\d]+)/ ) {
30                         my $val = $1;
31                         if ( $val !~ m/\d+\.\d+/ ) {
32                                 $val = $val / 1000;
33                         }
34                         my $topic = "iio/$hostname/$device/$name";
35                         #print "$topic $val\n";
36                         system "mosquitto_pub -h rpi2 -t $topic -m $val";
37
38                         my $influx = "iio,dc=trnjanska,host=$hostname,device=$device $name=$val $t_influx";
39                         system "curl --silent -XPOST '$influx_url' --data-binary '$influx'";
40                 } else {
41                         #warn "# $_\n";
42                 }
43         }
44
45         sleep Time::HiRes::time + 1 - $t;
46 }