This commit is contained in:
Matthew Slowe 2021-01-23 17:27:16 +00:00
commit 84d352ad4d
2 changed files with 69 additions and 0 deletions

3
Dockerfile Normal file
View File

@ -0,0 +1,3 @@
FROM perl-mqtt
COPY update-berths.pl /
ENTRYPOINT "/update-berths.pl"

66
update-berths.pl Executable file
View File

@ -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();