Free MQTT broker with python documentation

Shelwyn Corte
2 min readJun 2, 2022

--

Why MQTT?

MQTT is the most used protocol for IoT to exchange data between devices over the internet. The protocol follows a set of rules on how devices can publish and subscribe to data. Both the publisher and the subscriber communicate using topics which are handled by the MQTT broker.

The broker will filter all messages which are published to a topic and will distribute them to the subscribers who have subscribed to the topic.

We will use the HiveMQ broker for our below example to see how MQTT works (https://www.hivemq.com/public-mqtt-broker/).

Server: broker.hivemq.com
Port: 1883

Code [python]

Code to publish to a topic [publisher.py]

import paho.mqtt.client as paho
import random
import time

broker = "broker.hivemq.com"
port = 1883

def on_publish(client, userdata, result):
print("Publisher: Data published.")

client = paho.Client()
client.on_publish = on_publish
client.connect(broker, port)

for x in range(100):
d = random.randint(1, 500)
message = str(d)
ret = client.publish("<your_topic_here>", message) #Update your topic here
print(message)
time.sleep(5)

Code to subscribe to a topic [subscriber.py]

import paho.mqtt.client as mqtt

broker ="broker.hivemq.com"
port = 1883
timelive = 60

def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("<your_topic_here>") #Update your topic here

def on_message(client, userdata, msg):
print(msg.payload.decode())

client = mqtt.Client()
client.connect(broker, port, timelive)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

--

--

Shelwyn Corte
Shelwyn Corte

Written by Shelwyn Corte

Automation Engineer | https://shelwyn.in/ | Currently in Bengaluru

No responses yet