Python - MQTT Basic Configuration

December 19, 2018

Using MQTT in python is simple, you can use a library from pypi.org called paho-mqtt please visit this link for more information https://pypi.org/project/paho-mqtt/

The library can be installed by using this command below
pip install paho-mqtt

once the library successfully installed, you can start the coding by follow this steps below:

  • Create a new project folder
  • Open the visual studio code or any code editor and open the project folder
  • Create a python script called app.py
  • Copy and paste this script below
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.
    client.subscribe("/sensor") # topic you want to subscribe

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload)) # displaying the data on console

client = mqtt.Client()
client.username_pw_set("/train:trainsensor", password="12345") #vhost username & password
client.on_connect = on_connect
client.on_message = on_message

client.connect("192.168.1.7", 1883, 60) # your mqtt host and port

# 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.
client.loop_forever()


  • Run the script by using command: python app.py
  • Testing using MQTT-Box

REMEMBER

make sure that you edit this and pointing to your MQTT host
client.username_pw_set("/train:trainsensor", password="12345")
client.connect("192.168.1.7", 1883, 60)

No comments:

Powered by Blogger.