| 1 | #!/usr/local/bin/perl | ||
| 2 | # | ||
| 3 | # subscribe.pl | ||
| 4 | # | ||
| 5 | # Subscribe to a MQTT topic | ||
| 6 | # and display message to STDOUT | ||
| 7 | # | ||
| 8 | |||
| 9 | use WebSphere::MQTT::Client; | ||
| 10 | use Data::Dumper; | ||
| 11 | use strict; | ||
| 12 | |||
| 13 | |||
| 14 | # | ||
| 15 | my $mqtt = new WebSphere::MQTT::Client( | ||
| 16 | Hostname => 'smartlab.combe.chem.soton.ac.uk', | ||
| 17 | Port => 1883, | ||
| 18 | Debug => 1, | ||
| 19 | ); | ||
| 20 | |||
| 21 | |||
| 22 | # Connect to Broker | ||
| 23 | my $res = $mqtt->connect(); | ||
| 24 | die "Failed to connect: $res\n" if ($res); | ||
| 25 | |||
| 26 | print Dumper( $mqtt ); | ||
| 27 | |||
| 28 | |||
| 29 | sleep 1; | ||
| 30 | print "status=".$mqtt->status()."\n"; | ||
| 31 | sleep 1; | ||
| 32 | print "status=".$mqtt->status()."\n"; | ||
| 33 | |||
| 34 | # Subscribe to topic | ||
| 35 | my $res = $mqtt->subscribe( '#' ); | ||
| 36 | print "Subscribe result=$res\n"; | ||
| 37 | |||
| 38 | |||
| 39 | sleep 2; | ||
| 40 | print "status=".$mqtt->status()."\n"; | ||
| 41 | sleep 2; | ||
| 42 | |||
| 43 | |||
| 44 | # Get Messages | ||
| 45 | while( 1 ) { | ||
| 46 | |||
| 47 | my @res = $mqtt->receivePub(); | ||
| 48 | #errors can be caught by eval { } | ||
| 49 | |||
| 50 | print Dumper(@res); | ||
| 51 | } | ||
| 52 | |||
| 53 | |||
| 54 | |||
| 55 | # Unsubscribe from topic | ||
| 56 | my $res = $mqtt->unsubscribe( '#' ); | ||
| 57 | print "Unubscribe result=$res\n"; | ||
| 58 | |||
| 59 | |||
| 60 | sleep 2; | ||
| 61 | |||
| 62 | print "status=".$mqtt->status()."\n"; | ||
| 63 | |||
| 64 | # Clean up | ||
| 65 | $mqtt->terminate(); | ||
| 66 | |||
| 67 | print Dumper( $mqtt ); | ||
| 68 |