diff options
Diffstat (limited to 'scd4x.pl')
-rwxr-xr-x | scd4x.pl | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/scd4x.pl b/scd4x.pl new file mode 100755 index 0000000..aae5919 --- /dev/null +++ b/scd4x.pl @@ -0,0 +1,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; +} |