Here I have discussed how to subscribe to/publish a message via MQTT using a code (the code being written in python language). We would be working with the mosquitto broker. The installation, setup and testing of the mosquitto in debian have been stated in my previous blog Mosquitto in Debian
To achieve the above mentioned goal, testing of Paho Python Client has been briefly described.
The Paho project consists of a number of clients and utilities for working with MQTT. The Paho Python Client provides a client class and some helper functions to make publishing messages to an MQTT server very straightforward.
The Python client can be downloaded and installed from the repository using the following commands-
git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git
sudo python setup.py install
Now, in the containing folder, create a file and copy-paste the python code given below which will help subscribe to a certain topic , for e.g., in this case it is “hello/world” –
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(“localhost”, 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
Compiling this code, starts the client and the following output is obtained –
Connected with result code 0
Open another terminal and create a file containing the following code –
mqttc = mosquitto.Mosquitto("python_pub")
mqttc.will_set("/event/dropped", "Sorry, I seem to have died.")
mqttc.connect("127.0.0.1", 1883, 60, True)
mqttc.publish("hello/world", "Hello, World!:this works now!!:D")
Each time this piece of code is compiled, something of this sort is displayed in the previous terminal (i.e., from where we started the client) –
hello/world Hello, World!:this works now!!:D
This means that the message ” hello/world Hello, World!:this works now!!:D ” is pushed to all the clients that subscribed to the topic “hello/world”.