Publish Message to MQTT Broker using Python

paho-mqtt library

  1. Install paho-mqtt library from the command line:
pip install paho-mqtt
  1. Publish message to MQTT broker:
import paho.mqtt.client as paho

MQTT_HOST = '192.168.0.174'
MQTT_PORT = 1883
MQTT_CLIENT_ID = 'Python-MQTT-client'
MQTT_USER = 'YOUR MQTT USER'
MQTT_PASSWORD = 'YOUR MQTT USER PASSWORD'
TOPIC = 'python/test'

client = paho.Client(MQTT_CLIENT_ID)

client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
client.connect(MQTT_HOST, MQTT_PORT)

data = 'Hello'
client.publish(TOPIC, data)

Leave a Comment

Cancel reply

Your email address will not be published.