Skip to content
Boris Lovosevic edited this page Jul 31, 2019 · 5 revisions

network Module

Class mqtt

MQTT stands for MQ Telemetry Transport. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks. The design principles are to minimise network bandwidth and device resource requirements whilst also attempting to ensure reliability and some degree of assurance of delivery. These principles also turn out to make the protocol ideal of the emerging “machine-to-machine” (M2M) or “Internet of Things” world of connected devices, and for mobile applications where bandwidth and battery power are at a premium.

mqtt runs in separate thread (FreeRTOS task).

Standard mqtt (TCP, port 1883), Secured mqtt (TCP over SSL/TLS, port 8883), mqtt over WebSockets and secured mqtt over WebSockets are all supported.

Can be used with WiFi or GSM interface.
Secured mqtt is supported only with WiFi interface



Create mqtt instance object:

mqtt = network.mqtt(name, server [optional_arguments])

Creates the mqtt object.

mqtt service (mqtt client FreeRTOS task) will not be started after creating the mqtt instance.
It must be started using mqtt.start() method,

Only the two first arguments are mandatory:

Argument Function
name string, mqtt identifier, used to identify the mqtt client object, for example in collback functions
server string, mqtt server (broker) ip address or domain name prefixed with mqtt protocol identifier
mqtt:// non secure mqtt connection
mqtts:// secure (SSL) mqtt connection (WiFi only)
ws:// non secure mqtt connection over Websocket
wss:// secure (SSL) mqtt connection over Websocket (WiFi only)

Other arguments are optional, if entered they must be entered as kw arguments (arg=value):

Argument Function
user string, user name if requred by mqtt server
default: ""
password string, user password if requred by mqtt server
default: ""
port int, server's mqtt port
default: 1883 (mqtt://), 8883 (mqtts://), 80 (ws://), 433 (wss://)
autoreconnect bool, if True, reconnect to server if disconnected for some reason
default: False
clientid string, mqtt client id, it is recomended to enter some unique ID
default: random id in form of 'mpy_mqtt_id_xxxxxxxx', where 'xxxxxxxx' is 8-digit random number
cleansession bool, if True, do not use mqtt persistent session feature
default: False
If cleansession is True, after mqtt.stop() mqtt.start() cannot be used. mqtt instance must be freed and new one created
keepalive int, Keep Alive interval in seconds
default: 120
lwt_topic string, LWT topic; max 32 characters
default: None
lwt_msg string, LWT message; max 128 characters
default: 'offline'
only valid if lwt_topic is set
lwt_retain bool, LWT retain flag
default 0
only valid if lwt_topic is set
lwt_qos int, LWT QoS level
default 0
only valid if lwt_topic is set
connected_cb callback function executed when mqtt is connected to the server
argument: (mqtt_obj, mqtt_name)
disconnected_cb callback function executed when mqtt is disconnected to the server
argument: (mqtt_obj, mqtt_name)
subscribed_cb callback function executed on succesful topic subscription
argument: (mqtt_obj, mqtt_name, topic)
unsubscribed_cb callback function executed when the topic is unsubscribed
argument: (mqtt_obj, mqtt_name, topic)
published_cb callback function executed when the topic is published
argument: (mqtt_obj, mqtt_name, topic, publish_type)
data_cb callback function executed when new subscribed topic data arrives
argument: (mqtt_obj, mqtt_name, topic_name, topic_data)
client_key string, client Certicate
cert Name of the file containg the mqtt server Certificate

Methods


mqtt.config([optional_arguments])

Reconfigure the mqtt client object.
All arguments are optional, if entered they must be entered as kw arguments (arg=value).
See the optional arguments table above.
Arguments other than callbacks can only be set if mqtt is not connected.

mqtt.status()

Returns the status of mqtt client task.

The status is returned as tuple: (num_stat, description).
Possible values are:
(0, "Unknown") not yet initialized, service not started
(1, "Initialized") service started, not connected
(2, "Connected") connected to mqtt server
(3, "Wait timeout") timeout waiting for connection

Note: Before issuing any other mqtt command it is recommended to check the mqtt status.

mqtt.subscribe(topic [,qos])

Subscribe to the topic, wait max 2 seconds.
Argument topic is string, the topic name.
Optional argument qos sets the subscribe QoS level. Default is 0.

Returns True if successfully subscribed, False if not.

mqtt.unsubscribe(topic)

Unsubscribe from the topic, wait max 2 seconds.
Argument topic is string, the topic name.

Returns True if successfully unsubscribed, False if not.

mqtt.publish(topic, msg [,qos [, retain]])

Publish message to the topic.
Argument topic is string, the topic name; msg is string, the topic message.
Optional argument qos sets the publish QoS level. Default is 0.
Optional argument retain sets the publish retain flag, Default is 0.

Returns True if successfully subscribed, False if not.

mqtt.stop()

Stop the mqtt client task. Free all used resources.

mqtt.start()

Start the stopped mqtt client task.
Only persistent sessions (cleansession = False) can be started after mqtt.stop()

mqtt.free()

Stop the mqtt client task. Free resources and destroy the mqtt object

mqtt.debug(True|False)

Enable or disable printing mqtt log messages.
The desired log level must also be set with machine.loglevel().


Example

import network, machine

#machine.loglevel(machine.LOG_DEBUG)

def conncb(res):
    print("mqtt '{}': Connected".format(res[1]))

def disconncb(res):
    print("mqtt '{}': Disconnected".format(res[1]))

def subscb(res):
    print("mqtt '{}': Subscribed to topic '{}'".format(res[1], res[2]))

def unsubscb(res):
    print("mqtt '{}': Un-subscribed from topic '{}'".format(res[1], res[2]))

def pubcb(res):
    print("mqtt '{}': Published to topic {}, type {}".format(res[1], res[2], res[3]))

def datacb(res):
    print("mqtt '{}': Data arrived from topic: {}, Message:\n".format(res[1], res[2]), res[3])


mqtt = network.mqtt("loboris", "mqtt://loboris.eu", user="wifimcu", password="wifimculobo")
#mqtt = network.mqtt("loboris", "mqtt://loboris.eu", user="wifimcu", password="wifimculobo", cleansession=True)
# Set callbacks
mqtt.config(connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, unsubscribed_cb=unsubscb, published_cb=pubcb, data_cb=datacb)

#mqtt.debug(True)

# secure connection
# mqtts = network.mqtt("eclipse", "mqtts//iot.eclipse.org", cleansession=True, connected_cb=conncb, disconnected_cb=disconncb, subscribed_cb=subscb, published_cb=pubcb, data_cb=datacb)
# wsmqtt = network.mqtt("eclipse", "ws://iot.eclipse.org:80/ws", cleansession=True, data_cb=datacb)

# Wait until status is: (2, 'Connected')

Test:

>>> mqtt.start()
>>> mqtt 'loboris': Connected

>>> mqtt.subscribe('test')
True
>>> mqtt 'loboris': Subscribed to topic 'test'

>>> mqtt.publish('test', 'Hi from Micropython')
True
>>> mqtt 'loboris': Data arrived from topic: test, Message:
 Hi from Micropython

>>> mqtt.unsubscribe('test')
True
>>> mqtt 'loboris': Un-subscribed from topic 'test'

>>> mqtt.publish('test', 'Another message from Micropython', qos=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument num/types mismatch
>>> mqtt.publish('test', 'Another message from Micropython', 1, 1)
True
>>> mqtt 'loboris': Published to topic test, type 4

>>> mqtt.subscribe('test')
True
>>> mqtt 'loboris': Subscribed to topic 'test'
mqtt 'loboris': Data arrived from topic: test, Message:
 Another message from Micropython

>>>