commit 84d352ad4d08f34a30053f24be4196c77535b907 Author: Matthew Slowe Date: Sat Jan 23 17:27:16 2021 +0000 starting diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a2d44dc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,3 @@ +FROM perl-mqtt +COPY update-berths.pl / +ENTRYPOINT "/update-berths.pl" \ No newline at end of file diff --git a/update-berths.pl b/update-berths.pl new file mode 100755 index 0000000..931aec2 --- /dev/null +++ b/update-berths.pl @@ -0,0 +1,66 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +use Net::MQTT::Simple; +use JSON; +use Data::Dumper; + +sub assert($;$) { + my ($required, $message) = @_; + unless ($required) { + my $msg = "Assertion failed"; + $msg .= " ($message)" if $message; + die $msg; + } +} + +sub _debug($) { + my $msg = shift; + return unless $ENV{DEBUG}; + printf("%s [%s] %s\n", time, "DEBUG", $msg); +} + +sub _error($) { + my $msg = shift; + printf("%s [%s] %s\n", time, "ERROR", $msg); +} + +sub handle($$) { + my ($topic, $json) = @_; + my $data; + + eval { + $data = from_json($json) + }; + + if ($data) { + _debug( Dumper($data) ); + } else { + _error("Got invalid JSON data from $topic: $json"); + } +} + +### Check required environement variables are present +foreach ( + qw( + MQTT_SERVER + MQTT_MONITOR + ) +) { + assert($ENV{$_}, "`$_' not available"); +} + +## Connect to MQTT +_debug("Connecting to mqtt://$ENV{MQTT_SERVER}/$ENV{MQTT_MONITOR}"); +my $mqtt = Net::MQTT::Simple->new($ENV{MQTT_SERVER}) or die "Failed to connect to mqtt://$ENV{MQTT_SERVER}"; + +$mqtt->subscribe( + "$ENV{MQTT_MONITOR}" => sub { + my ($topic, $message) = @_; + handle($topic, $message); + }, +); + +$mqtt->run(); \ No newline at end of file