blob: aae591954bea13dbda2cee95a5f48a844e61cc34 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#!/usr/bin/perl
use warnings;
use strict;
use English;
use POSIX;
use JSON;
use Net::MQTT::Simple;
my $file = shift;
my $host = shift;
my $json = JSON->new->allow_nonref;
my $mqtt;
my $values;
my $pvalues;
my $serial;
sub read_json_file {
my $filename = shift;
my $content;
open FILE, '<', $filename or die "read $filename: $!";
{ local $/; undef $/; $content = <FILE> }
close FILE;
return $json->decode($content);
}
if (defined($host)) {
$mqtt = Net::MQTT::Simple->new($host) or die "mqtt init (server $host)"
}
for (;;) {
$values = read_json_file($file);
$serial = $values->{'serial'};
for my $key ('co2', 'temperature', 'humidity') {
next if defined($pvalues->{$key}) and $pvalues->{$key} eq $values->{$key};
my $topic = "sensors/" . $key . "/scd4x/" . $serial;
if (defined($mqtt)) {
$mqtt->retain( $topic => $values->{$key} );
} else {
my $ts = POSIX::ctime(time());
chomp($ts);
printf("[%s] %-40s: %s\n",
$ts, $topic, $values->{$key});
}
}
$pvalues = $values;
sleep 60;
}
|