Skip to content

Instantly share code, notes, and snippets.

@EatMoreCode
Created August 28, 2015 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EatMoreCode/bdc895b845b1fb647c6d to your computer and use it in GitHub Desktop.
Save EatMoreCode/bdc895b845b1fb647c6d to your computer and use it in GitHub Desktop.
WebApp consuming MQTT messages and providing data via HTTP
#!/usr/bin/env perl
# ./mojo_and_mqtt.pl daemon
use Mojolicious::Lite;
use EV;
use AnyEvent;
use AnyEvent::MQTT;
my $mqtt = AnyEvent::MQTT->new;
my $mq_stats = {};
# subscribe to the mosquitto metadata and update a hash when we receive messages
my $cv = $mqtt->subscribe(topic => '$SYS/#',
callback => sub {
my ($topic, $message) = @_;
$mq_stats->{$topic} = $message;
});
my $qos = $cv->recv; # subscribed, negotiated QoS == $qos
get '/' => sub {
my $c = shift;
my $out = join ("\n", map { sprintf("%-20s => %-s", $_, $mq_stats->{$_}) } sort keys %$mq_stats);
$c->render(text => $out);
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment