In this article, we will develop a PHP client for subscribing and publishing messages for MQTT communication using Mosquitto-PHP library available here.
1. Installing pecl
$sudo apt-get install php-pear
2. Install PHP developer packages
$sudo apt-get install php5-dev
3. Install Mosquitto-PHP library
sudo pecl install Mosquitto-alpha
4. Add extension=mosquitto.so
under Dynamic Extensions
of the file /etc/php5/cli/php.ini
5. Creating an MQTT subscriber ( sub.php
) using Mosquitto-PHP library
<?php $client = new Mosquitto\Client(); $client->onConnect('connect'); $client->onDisconnect('disconnect'); $client->onSubscribe('subscribe'); $client->onMessage('message'); $client->connect("localhost", 1883, 60); $client->subscribe('/#', 1); while (true) { $client->loop(); sleep(2); } $client->disconnect(); unset($client); function connect($r) { echo "I got code {$r}\n"; } function subscribe() { echo "Subscribed to a topic\n"; } function message($message) { printf("\nGot a message on topic %s with payload:%s", $message->topic, $message->payload); } function disconnect() { echo "Disconnected cleanly\n"; }
6. Run the subscriber using php command line tool
$php sub.php
On executing the above command, we will get an output as shown below :
I got code 0
Subscribed to a topic
7. Test the MQTT subscriber using mosquitto_pub
command line tool
$mosquitto_pub -h localhost -t "/mqtt" -m "HelloWorld"
On executing the above command, we will get an output as shown below :
Got a message on topic /mqtt with payload:HelloWorld
8. Creating an MQTT publisher ( pub.php ) using Mosquitto-PHP library
<?php $client = new Mosquitto\Client(); $client->onConnect('connect'); $client->onDisconnect('disconnect'); $client->onPublish('publish'); $client->connect("localhost", 1883, 5); while (true) { try{ $client->loop(); $mid = $client->publish('/mqtt', "Hello from PHP"); $client->loop(); }catch(Mosquitto\Exception $e){ return; } sleep(2); } $client->disconnect(); unset($client); function connect($r) { echo "I got code {$r}\n"; } function publish() { global $client; echo "Mesage published\n"; $client->disconnect(); } function disconnect() { echo "Disconnected cleanly\n"; }
9. Run the publisher using php command line tool
$php pub.php
On executing the above command, we will get a message as shown below :
I got code 0
Mesage published
Disconnected cleanly
Also, we can see the published message as shown below at the terminal where the subscriber ( sub.php
) is running :
I got code 0
Subscribed to a topicGot a message on topic /mqtt with payload:Hello from PHP
Comments on this post