You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.2 KiB

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Net::MQTT::Simple;
use Zabbix::Sender;
use Getopt::Std;
use YAML;
my $opts = {};
my ($cfg, $mqtt, $zbx);
sub usage {
print "Usage: $0 -c <config> [-h] [-v]\n";
exit (shift // 0);
}
sub msg_handler {
my ($topic, $message) = @_;
if (my $map = $cfg->{topics}->{$topic}) {
$zbx->hostname($map->{host});
my $res = $zbx->send($map->{item}, $message);
unless ($res and $res->{response} eq 'success') {
printf "can't send data to zabbix server: %s", $res->{message} || 'unknown error';
}
} else {
print "ignore message [$topic] $message\n";
}
return;
}
getopts('c:hv', $opts)
or usage(1);
if ($opts->{h}) {
usage(0);
}
unless ($opts->{c} and -f $opts->{c}) {
usage(1);
}
$cfg = YAML::LoadFile($opts->{c}) or do {
print "can't load config\n";
usage(1);
};
$zbx = Zabbix::Sender->new(server => $cfg->{zabbix}->{server});
$ENV{MQTT_SIMPLE_ALLOW_INSECURE_LOGIN} = 1;
$mqtt = Net::MQTT::Simple->new($cfg->{mqtt}->{server});
$mqtt->login($cfg->{mqtt}->{username}, $cfg->{mqtt}->{password});
foreach my $t (keys %{ $cfg->{topics} }) {
$mqtt->subscribe($t => \&msg_handler);
}
while (1) {
$mqtt->tick(15);
}
exit 0;