IoT Bytes

Bits and Bytes of IoT

Paho MQTT with Python

Pradeep Singh | 29th March 2016
paho_logo

Prerequisites:

Computer with Python 2.7 and working internet connection.

Client Installation:

Install Paho MQTT Client on your machine using pip command –

pip install paho-mqtt

Once the client is installed you write the code for Publisher and Subscriber using Python. Here in this example I am going to use Python 2.7 –

MQTT Subscribe:

Following code will subscribe our client to”helloTopic” (GitHub Link for Code File) –

# Import package
import paho.mqtt.client as mqtt

# Define Variables
MQTT_HOST = "iot.eclipse.org"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "helloTopic"
MQTT_MSG = "hello MQTT"

# Define on connect event function
# We shall subscribe to our Topic in this function
def on_connect(mosq, obj, rc):
 mqttc.subscribe(MQTT_TOPIC, 0)

# Define on_message event function. 
# This function will be invoked every time,
# a new message arrives for the subscribed topic 
def on_message(mosq, obj, msg):
 print "Topic: " + str(msg.topic)
 print "QoS: " + str(msg.qos)
 print "Payload: " + str(msg.payload)

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed to Topic: " + 
 MQTT_MSG + " with QoS: " + str(granted_qos))

# Initiate MQTT Client
mqttc = mqtt.Client()

# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

# Continue monitoring the incoming messages for subscribed topic
mqttc.loop_forever()

MQTT Publish:

Following code will register with MQTT Server and Publish Message to “helloTopic” (GitHub Link for Code File)-

# Import package
import paho.mqtt.client as mqtt

# Define Variables
MQTT_HOST = "iot.eclipse.org"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "helloTopic"
MQTT_MSG = "hello MQTT"

# Define on_publish event function
def on_publish(client, userdata, mid):
 print "Message Published..."

# Initiate MQTT Client
mqttc = mqtt.Client()

# Register publish callback function
mqttc.on_publish = on_publish

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL) 

# Publish message to MQTT Broker 
mqttc.publish(MQTT_TOPIC,MQTT_MSG)

# Disconnect from MQTT_Broker
mqttc.disconnect()

Result:

Execute the Subscriber followed by Publisher code in two different terminals. After successful execution you should be able to see “hello MQTT” message in the terminal where you ran Subscriber code.

Subscribed to Topic: hello MQTT with QoS: (0,)
Topic: helloTopic
QoS: 0
Payload: hello MQTT

8 thoughts on “Paho MQTT with Python

  1. Hi,

    I would like to use your two scripts on my computer, I have downloaded wireshark for windows (I use windows), I have already pycharm for python with correct version 2.7. It miss the library paho.mqtt.client, I can see above that you give a command to get it, but it doesn’t work on my side, is it a command for windows or other environment ? thanks for your support

    Liked by 1 person

  2. Hi,
    Is there someone to explain why all callbacks functions seem never called in this test code on Linux Ubuntu. The publish topics work well.

    Thanks

    import paho.mqtt.client as mqtt
    import time

    def on_connect(client, userdata, flags, rc):
    print (“Connected result code : ” + str(rc))

    def on_message(client,userdata,msg):
    print(msg.topic + ‘:’ + msg.payload)

    def on_subscribe(client,userdata,mid,granted_qos):
    print(“Subscribe”)

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_subscribe = on_subscribe

    client.connect(‘broker.hivemq.com’,1883,60)
    client.subscribe((‘/wipy63/temp’,1),(‘/wipy63/data’, 1))
    while 1:
    client.publish(‘/pc/patrice/init’, b’1234lm’, 0)
    client.loop
    # print (“boucle”)
    time.sleep(1)

    Like

    1. Hi,

      I don’t think your issue is related to Ubuntu. Why are you using “client.loop” inside “while” loop? As per my understanding, you should use it before “while” loop. In my script, I used “loop_forever()” after subscribing to a Topic.

      I see that you are trying to subscribe to “/wipy63/temp” and “/wipy63/data” and publishing to “/pc/patrice/init”. Are you publishing something to the topics you are subscribed to from any other publisher?

      If I were you, I would try to break Publisher and Subscriber modules into two different scripts to make troubleshooting easier.

      You may use following scripts to rule out any Linux or Broker related issue.

      Subscriber –
      https://github.com/pradeesi/Paho-MQTT-with-Python/blob/master/mqtt_subscribe.py

      Publisher –
      https://github.com/pradeesi/Paho-MQTT-with-Python/blob/master/mqtt_publish.py

      Like

      1. Thanks for your reply, I have found a basic syntax error in my callbacks code, but don’t display by my editor.
        the bad code :
        def on_connect(client, userdata, flags, rc):
        print (“Connected result code : ” + str(rc))

        def on_message(client,userdata,msg):
        print(msg.topic + ‘:’ + msg.payload)

        The good one :

        def on_connect(client, userdata, flags, rc):
        print (“Connected result code : ” , str(rc))

        def on_message(client,userdata,mes):
        print(mes.topic,’:’,mes.payload)

        Thanks Pradeep Singh

        Like

  3. The subscribe code didn’t really work for me, it threw a ‘4 arguments’ error. Can be fixed bij adding the ‘self’ method to connect like this:
    def on_connect(self, mosq, obj, rc):
    self.subscribe(MQTT_Topic, 0)

    Like

Leave a comment