MQTT Communication

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol based on the publish-subscribe pattern. It features small code footprint and low bandwidth consumption, making it ideal for communication between IoT nodes.

MQTT Basic Concepts

MQTT communication consists of three roles:

  • Broker: A server responsible for receiving and forwarding messages

  • Publisher: A client that sends messages

  • Subscriber: A client that receives messages

The publisher sends messages to a specified topic, and the broker forwards the messages to all clients subscribed to that topic. mPython IoT can act as either a publisher to report data or a subscriber to receive control commands.

Connecting to the Broker

mPython IoT uses the umqtt.simple library to implement MQTT client functionality. First connect to Wi-Fi, then instantiate MQTTClient and connect to the broker:

from umqtt.simple import MQTTClient
import network
import time

# Connect to Wi-Fi
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('your_ssid', 'your_password')
while not sta.isconnected():
    time.sleep(0.5)

# MQTT configuration
SERVER = "broker.example.com"      # Broker address
PORT = 1883                        # Port number, typically 1883
CLIENT_ID = "mpython_iot_001"      # Unique client ID
TOPIC = "iot/mpython/data"         # Topic

# Instantiate and connect
client = MQTTClient(CLIENT_ID, SERVER, PORT)
client.connect()
print("Connected to MQTT server: %s" % SERVER)

Publishing Messages

Use the publish() method to send messages to a specified topic:

client.publish(TOPIC, "hello mpython iot")
print("Message published")

Note

In publish(topic, msg), topic is the topic to publish to and msg is the message content for that topic. Both should be byte type; MicroPython will automatically encode strings.

Subscribing to Topics

Before subscribing to a topic, set the callback function for received messages via set_callback():

def sub_cb(topic, msg):
    print("Received topic: %s, message: %s" % (topic.decode(), msg.decode()))

client.set_callback(sub_cb)         # Set callback function
client.subscribe(TOPIC)             # Subscribe to topic
print("Subscribed to topic: %s" % TOPIC)

while True:
    client.wait_msg()               # Loop waiting for and receiving messages

Complete Example

The following is a complete MQTT communication example with exception handling and periodic keepalive:

from umqtt.simple import MQTTClient
import network
import time

SERVER = "broker.example.com"
PORT = 1883
CLIENT_ID = "mpython_iot_001"
TOPIC = "iot/mpython/data"

def connect_wifi():
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    sta.connect('your_ssid', 'your_password')
    while not sta.isconnected():
        time.sleep(0.5)

def sub_cb(topic, msg):
    print((topic, msg))

connect_wifi()

try:
    client = MQTTClient(CLIENT_ID, SERVER, PORT, keepalive=30)
    client.connect()
    client.set_callback(sub_cb)
    client.subscribe(TOPIC)
    print("Connected to %s" % SERVER)

    count = 0
    while True:
        client.publish(TOPIC, "count: %d" % count)   # Publish count
        count += 1
        client.check_msg()                            # Non-blocking message check
        time.sleep(2)
except Exception as e:
    print("Exception occurred: ", e)
finally:
    client.disconnect()                               # Disconnect
    print("MQTT disconnected")

Hint

  • wait_msg() blocks while waiting for messages, suitable for programs that only need to respond to MQTT messages.

  • check_msg() is a non-blocking check, suitable for programs that also need to perform other tasks.

  • Setting the keepalive parameter maintains the connection and prevents the server from disconnecting due to prolonged inactivity.