Python and MQTT

I got python to subscribe to an MQTT broker from a CentOS 6 box.

First off you need to install the mqtt libraries for python.  In this example we use the paho-mqtt libraries.

You don’t use YUM, you use easy_install.  Here is the command

easy_install paho-mqtt

After that you can connect via python whether this is a script or in the interpreter

Here is the script scrubbed of usernames and passwords

import paho.mqtt.client as mqtt

def on_connect(mqttc, userdata, rc):
   print('connected...rc=' + str(rc))
   mqttc.subscribe(topic='home/message', qos=0)

def on_disconnect(mqttc, userdata, rc):
   print('disconnected...rc=' + str(rc))

def on_message(mqttc, userdata, msg):
   print('message received...')
   print('topic: ' + msg.topic + ', qos: ' + 
   str(msg.qos) + ', message: ' + str(msg.payload))

def on_subscribe(mqttc, userdata, mid, granted_qos):
   print('subscribed (qos=' + str(granted_qos) + ')')

def on_unsubscribe(mqttc, userdata, mid, granted_qos):
   print('unsubscribed (qos=' + str(granted_qos) + ')')

mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_message = on_message
mqttc.on_subscribe = on_subscribe
mqttc.on_unsubscribe = on_unsubscribe
mqttc.username_pw_set('usernamehere', 'passwordhere')
mqttc.connect(host='mqttbroker.example.local', port=1883)
mqttc.loop_forever()

This was pretty easy for subscribing.

Here is the code that matters, just need to inject what the script will do.

def on_message(mqttc, userdata, msg):
   print('message received...')
   print('topic: ' + msg.topic + ', qos: ' + 
   str(msg.qos) + ', message: ' + str(msg.payload))

Was pretty easy to get this subscribe working, not sure how the publish will work.

This entry was posted in Technical, Training. Bookmark the permalink.

One Response to Python and MQTT

  1. Jim Van Avery says:

    Larry,
    Looks like you are working OT on this project.
    Your postings are way over my head, however I really like the results, “IT WORKS”
    Hope to see you at next meet up, will be much clearer when described/demonstrated.
    Jim

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.