aboutsummaryrefslogtreecommitdiffstats
path: root/scd4x
diff options
context:
space:
mode:
Diffstat (limited to 'scd4x')
-rwxr-xr-xscd4x88
1 files changed, 37 insertions, 51 deletions
diff --git a/scd4x b/scd4x
index aae5919..e0a496f 100755
--- a/scd4x
+++ b/scd4x
@@ -1,51 +1,37 @@
-#!/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;
-}
+#!/usr/bin/python3
+import sys
+import json
+
+import paho.mqtt.client as mqtt
+
+def main():
+ if len(sys.argv) < 3:
+ print(len(sys.argv))
+ print(f'usage: {sys.argv[0]} json-file mqtt-host')
+ return 1
+
+ filename = sys.argv[1]
+ mqtthost = sys.argv[2]
+
+ client = mqtt.Client()
+ client.connect(mqtthost, 1883)
+
+ pvalues = {}
+ while True:
+ with open(filename, 'r', encoding = 'utf-8') as f:
+ values = json.loads(f.read())
+
+ for key in ('co2', 'temperature', 'humidity'):
+ curr = values.get(key)
+ prev = pvalues.get(key)
+ if prev and prev == curr:
+ continue
+
+ topic = f'sensors/{key}/scd4x/{values.get("serial")}'
+ #print(f'{topic} = {curr}')
+ client.publish(topic, curr)
+
+ pvalues = values
+
+if __name__ == '__main__':
+ sys.exit(main())