send iio sensors to mqtt
[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 $hostname = `hostname -s`;
10 chomp($hostname);
11
12 while(1) {
13
14         my $t = Time::HiRes::time;
15
16         my $iio = `iio_info`;
17
18         my $device;
19         my $name;
20
21         foreach ( split(/\n/, $iio) ) {
22                 if ( m/iio:device\d+:\s+(\S+)/ ) {
23                         $device = $1;
24                 } elsif ( m/(\S+):\s+\(input\)/ ) {
25                         $name = $1;
26                 } elsif ( m/attr\s+0:\s+input\svalue: (\d+[\.\d]+)/ ) {
27                         my $val = $1;
28                         if ( $val !~ m/\d+\.\d+/ ) {
29                                 $val = $val / 1000;
30                         }
31                         my $topic = "iio/$hostname/$device/$name";
32                         #print "$topic $val\n";
33                         system "mosquitto_pub -h rpi2 -t $topic -m $val";
34                 } else {
35                         #warn "# $_\n";
36                 }
37         }
38
39         sleep Time::HiRes::time + 1 - $t;
40 }