Easy Code Share > Python > MQTT Python Client Example to a Free MQTT Server

MQTT Python Client Example to a Free MQTT Server


We provide a MQTT client example using Python, and furthermore, reveal for you extra information about a free MQTT broker server. You don’t have to build a MQTT broker for testing programs, the free broker can help your study.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 4 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare Python environment for Windows by clicking Python Downloads, or search a Python setup pack for Linux.
  • The pack of Windows version also contains pip install for you to obtain more Python libraries in the future.
 DOWNLOAD SOURCE

 

SECTION 1
MQTT Python Client Library

Most IoT (Internet of Things) systems use MQTT protocol, which works for lightweight data. Eclipse Paho Python library to build MQTT client is introduced here.

 

How MQTT Works

MQTT can exchange lightweight IoT messages efficiently. Our previous post has described MQTT roles and its mechanism. Based on Topic, the roles publisher and subscriber, send and receive data through a middle-ware software called MQTT brokers.

 

Install MQTT Python Client Library

For Python client examples to run, issuing command line pip install can complete the installation.

c:\>pip install paho-mqtt

You can find documents about MQTT client library for Python here.

 

SECTION 2
MQTT Broker Host for Free

You can test programs on a free MQTT broker host, or even always run on it if required traffic is not heavy.

 

Mosquitto Test Server

Eclipse Mosquitto™ – An open source MQTT broker is a free MQTT broker for developers to use. The public address is test.mosquitto.org, and the public port is 1883 for unencrypted MQTT.

Mosquitto Test Broker 1883 Port

 

Is Mosquitto Test Server Popular?

If you are wondering its client popularity, install mosquitto client on Windows to check how many messages are passing through at any moment.

c:\>mosquitto_sub -h test.mosquitto.org -t "#" -v

After installation, issue the command to subscribe all topics on this server. It will be surprising.

 

SECTION 3
Python Clients Examples

This example uses Eclipse Paho MQTT library. Let’s explain codes according to MQTT concepts, and show you how to make a test using command lines.

 

Subscriber

To create a MQTT client using Python, you should include paho.mqtt.client at the first beginning. Then new a instant, assign callback functions, and connect to Mosquitto test server with a client id sub-client-id. If connected, on_connect() callback function subscribe the Topic and starts to listen all messages around the topic of world.

sub.py
import util
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
    print("on_connect: " + mqtt.connack_string(rc))
    client.subscribe(util.topic_name, 2)
client = mqtt.Client("sub-client-id")
client.on_connect = on_connect
client.on_message = util.on_message
client.on_subscribe = util.on_subscribe
client.on_disconnect = util.on_disconnect
client.connect(util.mqtt_host["hostname"], util.mqtt_host["port"], 60)
client.loop_forever()

The common utility file util.py for both subscriber and publisher includes configuration and callback functions.

util.py
mqtt_host = dict({ "hostname": "test.mosquitto.org", "port": 1883 })
topic_name = "world"
def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection: {}".format(rc) )
def on_message(client, userdata, msg):
    print("onMessageArrived: " + msg.topic + " " + str(msg.payload))
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed: mid=" + str(mid) + " QoS=" + str(granted_qos))
def on_publish(client, userdata, mid):
    print("Published: mid=" + str(mid) )

 

Publisher

Similarly, publishers include paho.mqtt.client, but connect to Mosquitto test server with another client id pub-client-id. If connected, callback function send messages periodically to MQTT broker with the same topic world.

pub.py
import util
import paho.mqtt.client as mqtt
import time
mqtt_connected = False
def on_connect(client, userdata, flags, rc):
    global mqtt_connected
    print("on_connect: " + mqtt.connack_string(rc))
    mqtt_connected = True
client = mqtt.Client("pub-client-id")
client.on_connect = on_connect
client.on_message = util.on_message
client.on_publish = util.on_publish
client.on_disconnect = util.on_disconnect
client.connect(util.mqtt_host["hostname"], util.mqtt_host["port"], 60)
client.loop_start()
def loopX() :
    global mqtt_connected
    while 1:
        if mqtt_connected :
            client.publish(util.topic_name, "Hello from a publish call")
            time.sleep(3)
loopX()

 

MQTT Testing

Due to Python, the best testing environment is in command lines. Open a Windows Box to execute subscriber role. If connected, try to subscribe to the MQTT broker, and listen messages.

c:\>python sub.py
on_connect: Connection Accepted.
Subscribed: mid=1 QoS=(2,)
onMessageArrived: world b'Hello from a publish call'
onMessageArrived: world b'Hello from a publish call'
onMessageArrived: world b'Hello from a publish call'
onMessageArrived: world b'Hello from a publish call'
onMessageArrived: world b'Hello from a publish call'

Open another Windows Box to perform publish role. If connected, send a message per 3 seconds, and meanwhile, the subscriber role receives messages around a specific Topic.

c:\>python pub.py
on_connect: Connection Accepted.
Published: mid=1
Published: mid=2
Published: mid=3
Published: mid=4
Published: mid=5

 

FINAL
Conclusion

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

Leave a Comment