« script/perl-WebService-Whistle-Pet-Tracker-API-device.pl
↑ Summary
script/perl-WebService-Whistle-Pet-Tracker-API-pets.pl »
| 1 | #!/usr/local/bin/perl | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use File::Basename qw{basename}; | ||
| 5 | use Getopt::Std qw{getopts}; | ||
| 6 | use Tie::IxHash qw{}; | ||
| 7 | use JSON::XS qw{encode_json}; | ||
| 8 | use Time::HiRes qw{}; | ||
| 9 | use WebService::Whistle::Pet::Tracker::API qw{}; | ||
| 10 | require Net::MQTT::Simple; #skip import | ||
| 11 | |||
| 12 | my $basename = basename($0); | ||
| 13 | my $syntax = "$basename -h MQTT_HOST -e WHISTLE_EMAIL -p WHISTLE_PASSWORD #or from environment\n"; | ||
| 14 | my $opt = {}; | ||
| 15 | |||
| 16 | getopts('e:p:h:', $opt); | ||
| 17 | |||
| 18 | my $host = $opt->{'h'} || $ENV{'MQTT_HOST'} || 'mqtt'; | ||
| 19 | my $email = $opt->{'e'} || $ENV{'WHISTLE_EMAIL'} or die($syntax); | ||
| 20 | my $password = $opt->{'p'} || $ENV{'WHISTLE_PASSWORD'} or die($syntax); | ||
| 21 | |||
| 22 | my $timer = Time::HiRes::time; | ||
| 23 | my $mqtt = Net::MQTT::Simple->new($host); | ||
| 24 | { | ||
| 25 | #Net::MQTT::Simple warns on connection error but we want die | ||
| 26 | local $0 = 'MQTT'; | ||
| 27 | local $SIG{'__WARN__'} = sub {my $error = shift; die "Error: $error"}; | ||
| 28 | $mqtt->_connect; | ||
| 29 | } | ||
| 30 | |||
| 31 | my $ws = WebService::Whistle::Pet::Tracker::API->new(email=>$email, password=>$password); | ||
| 32 | my $url = $WebService::Whistle::Pet::Tracker::API::API_URL; | ||
| 33 | my $pets = $ws->pets; | ||
| 34 | my $count = 0; | ||
| 35 | |||
| 36 | foreach my $pet (@$pets) { | ||
| 37 | my $topic = "stat/whistle-pet-tracker/pet/". $pet->{'id'}; | ||
| 38 | |||
| 39 | tie my %location, 'Tie::IxHash', ( | ||
| 40 | lat => $pet->{'last_location'}->{'latitude'}, | ||
| 41 | lon => $pet->{'last_location'}->{'longitude'}, | ||
| 42 | t => $pet->{'last_location'}->{'timestamp'}, | ||
| 43 | ); | ||
| 44 | |||
| 45 | $count++ if $mqtt->publish("$topic/name" => $pet->{'name'} ); | ||
| 46 | $count++ if $mqtt->publish("$topic/last_location" => encode_json(\%location) ); | ||
| 47 | $count++ if $mqtt->publish("$topic/device/battery_level" => $pet->{'device'}->{'battery_level'} ); | ||
| 48 | $count++ if $mqtt->publish("$topic/device/battery_status" => $pet->{'device'}->{'battery_status'} ); | ||
| 49 | } | ||
| 50 | |||
| 51 | $mqtt->tick(0.1); | ||
| 52 | $mqtt->disconnect; | ||
| 53 | |||
| 54 | $timer = Time::HiRes::time - $timer; | ||
| 55 | printf "Finished: Whistle: %s, MQTT: %s, Messages: %s, Time: %0.1f ms\n", $url, $host, $count, $timer * 1000; | ||
| 56 | |||
| 57 | __END__ |