umqtt.default

umqtt.default rewrites the subscribe() method and supports ca file.

Micropython Example:

 1# SPDX-FileCopyrightText: 2024 M5Stack Technology CO LTD
 2#
 3# SPDX-License-Identifier: MIT
 4
 5import os, sys, io
 6import M5
 7from M5 import *
 8from umqtt import *
 9
10
11label0 = None
12mqtt_client = None
13
14
15def mqtt_testtopic_event(data):
16    global label0, mqtt_client
17    label0.setText(str(data[1]))
18
19
20def setup():
21    global label0, mqtt_client
22
23    M5.begin()
24    Widgets.fillScreen(0x222222)
25    label0 = Widgets.Label("Text", 25, 20, 1.0, 0xFFFFFF, 0x222222, Widgets.FONTS.DejaVu18)
26
27    mqtt_client = MQTTClient(
28        "umqtt-client",
29        "emqxsl.cn",
30        port=8883,
31        user="test",
32        password="test",
33        keepalive=60,
34        ssl=True,
35        ssl_params={"server_hostname": "emqxsl.cn"},
36    )
37    mqtt_client.connect(clean_session=True)
38    mqtt_client.subscribe("testtopic", mqtt_testtopic_event, qos=0)
39
40
41def loop():
42    global label0, mqtt_client
43    M5.update()
44    mqtt_client.check_msg()
45
46
47if __name__ == "__main__":
48    try:
49        setup()
50        while True:
51            loop()
52    except (Exception, KeyboardInterrupt) as e:
53        try:
54            from utility import print_error_msg
55
56            print_error_msg(e)
57        except ImportError:
58            print("please update to latest firmware")

UIFLOW2 Example:

example.png

mqtts_cores3_example.m5f2

Constructors

class umqtt.MQTTClient(client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}) None

Create an MQTTClient object.

Parameters:
  • client_id (str) – the unique client id string used when connecting to the broker.

  • server (str) – the hostname or IP address of the remote broker.

  • port (int) – the network port of the server host to connect to.

  • user (str or None) – a username for broker authentication.

  • password (str or None) – a password for broker authentication.

  • keepalive (int) – maximum period in seconds allowed between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker.

  • ssl (bool) – Whether to use ssl.

  • ssl_params (dict) – Some parameters required to initiate an ssl connection.

Returns:

MQTTClient object

Return type:

MQTTClient

UIFLOW2:

init.png

init_ssl.png

Methods

MQTTClient.connect(clean_session=True) bool

Connect to a server. Returns True if this connection uses persisten session stored on a server (this will be always False if clean_session=True argument is used (default)).

UIFLOW2:

connect.png

MQTTClient.disconnect() None

Disconnect from a server, release resources.

UIFLOW2:

disconnect.png

MQTTClient.reconnect() None

Disconnect from a server, release resources.

UIFLOW2:

reconnect.png

MQTTClient.ping() None

Ping server (response is processed automatically by wait_msg()).

UIFLOW2:

None

MQTTClient.publish(topic, msg, retain=False, qos=0) None

Publish a message.

Parameters:
  • topic (str or bytes or bytearray) – the topic that the message should be published on.

  • msg (str or bytes or bytearray) – the message to send as a will.

  • retain (bool) – if set to True, the will message will be set as the “last will”/retained message for the topic.

  • qos (int) – the quality of service level to use

UIFLOW2:

publish.png

MQTTClient.subscribe(topic, handler, qos=0) None

Subscribe to a topic.

Parameters:
  • topic (str or bytes or bytearray) – a string specifying the subscription topic to subscribe to.

  • handler (function) – called when a message has been received on a topic that the client subscribes to and the message does match an existing topic filter callback.

  • qos (int) – the desired quality of service level for the subscription. Defaults to 0.

UIFLOW2:

subscribe.png

An handler showing a message has been received:

def on_sub_cb(data):
    print("topic:", data[0])
    print("msg:", data[1])

On uiflow2, you can get the topic and message of the current handler through get_topic.png and get_msg.png.

MQTTClient.set_last_will(topic, msg, retain=False, qos=0) None

Important

Should be called before connect().

Set MQTT “last will” message.

Parameters:
  • topic (str or bytes or bytearray) – the topic that the will message should be published on.

  • msg (str or bytes or bytearray) – the message to send as a will. If not given, or set to None a zero length message will be used as the will.

  • retain (bool) – if set to True, the will message will be set as the “last will”/retained message for the topic.

  • qos (int) – the quality of service level to use for the will.

UIFLOW2:

subscribe.png

MQTTClient.wait_msg() None

Important

wait_msg() and check_msg() are “main loop iteration” methods, blocking and non-blocking version. They should be called periodically in a loop, wait_msg() if you don’t have any other foreground tasks to perform (i.e. your app just reacts to subscribed MQTT messages), check_msg() if you process other foreground tasks too.

Note that you don’t need to call wait_msg() / check_msg() if you only publish messages, never subscribe to them.

Wait for a server message.

UIFLOW2:

None

MQTTClient.check_msg(attempts=2) None

Check if there’s pending message from server. If yes, process the same way as wait_msg(), if not, return immediately.

UIFLOW2:

wait_msg.png