| 1 | #!/usr/local/bin/perl | ||
| 2 | # | ||
| 3 | # publish.pl | ||
| 4 | # | ||
| 5 | |||
| 6 | use WebSphere::MQTT::Client; | ||
| 7 | #use WebSphere::MQTT::Persist::File; | ||
| 8 | use Data::Dumper; | ||
| 9 | use strict; | ||
| 10 | |||
| 11 | sub getline($;$); | ||
| 12 | |||
| 13 | # | ||
| 14 | my $mqtt = new WebSphere::MQTT::Client( | ||
| 15 | Hostname => 'smartlab.combe.chem.soton.ac.uk', | ||
| 16 | Port => 1883, | ||
| 17 | Debug => 1, | ||
| 18 | #Clientid => 'MyFixedClientId', | ||
| 19 | #Clean_start = 0, | ||
| 20 | #Persist => WebSphere::MQTT::Persist::File->new('/tmp/wmqtt'), | ||
| 21 | #Async => 1, | ||
| 22 | ); | ||
| 23 | |||
| 24 | my $qos = 0; # 1 | ||
| 25 | |||
| 26 | # Connect to Broker | ||
| 27 | my $res = $mqtt->connect(); | ||
| 28 | die "Failed to connect: $res\n" if ($res); | ||
| 29 | |||
| 30 | print Dumper( $mqtt ); | ||
| 31 | |||
| 32 | while (1) { | ||
| 33 | my $data = getline($mqtt, "Enter data:\n"); | ||
| 34 | last unless $data; | ||
| 35 | my $topic = getline($mqtt, "Enter topic:\n"); | ||
| 36 | last unless $topic; | ||
| 37 | my $res = $mqtt->publish($data, $topic, $qos); | ||
| 38 | print "Failed to publish: $res\n" if ($res); | ||
| 39 | } | ||
| 40 | |||
| 41 | print "status=".$mqtt->status()."\n"; | ||
| 42 | |||
| 43 | # Clean up | ||
| 44 | $mqtt->terminate(); | ||
| 45 | |||
| 46 | print Dumper( $mqtt ); | ||
| 47 | |||
| 48 | exit 0; | ||
| 49 | |||
| 50 | # Note: we must call the API periodically (and not block on read), otherwise | ||
| 51 | # the connection will time out | ||
| 52 | |||
| 53 | sub getline($;$) { | ||
| 54 | my $mqtt = shift; | ||
| 55 | my $prompt = shift; | ||
| 56 | |||
| 57 | while(1) { | ||
| 58 | $mqtt->status(); | ||
| 59 | print $prompt if defined $prompt; | ||
| 60 | my $rin = ''; | ||
| 61 | vec($rin,fileno(STDIN),1) = 1; | ||
| 62 | my $timeout = 5; | ||
| 63 | my ($nfound,$timeleft) = select($rin, undef, undef, $timeout); | ||
| 64 | last if $nfound > 0; | ||
| 65 | } | ||
| 66 | $res = <>; | ||
| 67 | chomp($res); | ||
| 68 | return $res; | ||
| 69 | } |