remove only device info
[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 $delay = $ENV{DELAY} || 1;
12
13 my $hostname = `hostname -s`;
14 chomp($hostname);
15
16 while(1) {
17
18         my $t = Time::HiRes::time;
19         my $t_influx = int( $t * 1_000_000_000 );
20
21         my $iio = `iio_info`;
22
23         my $device;
24         my $name;
25
26         my $influx = '';
27
28         foreach ( split(/\n/, $iio) ) {
29                 if ( m/iio:device\d+:\s+(\S+)/ ) {
30                         $device = $1;
31
32                         if ( $influx =~ m/,$/ ) {
33                                 $influx =~ s/,$/ $t_influx\n/;
34                         } elsif ( $influx =~ m/ $/ ) { # only device
35                                 $influx =~ s/\S+\s$//;
36                         }
37                         $influx .= "iio,dc=trnjanska,host=$hostname,device=$device ";
38
39                 } elsif ( m/(\S+):\s+\(input\)/ ) {
40                         $name = $1;
41                 } elsif ( m/attr\s+0:\s+input\svalue: (\d+[\.\d]+)/ ) {
42                         my $val = $1;
43                         if ( $val !~ m/\d+\.\d+/ ) {
44                                 $val = $val / 1000;
45                         }
46                         my $topic = "iio/$hostname/$device/$name";
47                         #print "$topic $val\n";
48                         system "mosquitto_pub -h rpi2 -t $topic -m $val";
49
50                         $influx .= "$name=$val,";
51                 } else {
52                         #warn "# $_\n";
53                 }
54         }
55
56         $influx =~ s/,$/ $t_influx/;
57         system "curl --silent -XPOST '$influx_url' --data-binary '$influx'";
58         warn "$influx\n";
59
60         sleep Time::HiRes::time + $delay - $t;
61 }