Skip to content
Boris Lovosevic edited this page May 10, 2018 · 6 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).

Note:
When using secure connection (mbedTLS) more memory is required.
If not using psRAM, you may need to lower the MicroPython heap.
You may try to set → Component config → mbedTLS → TLS maximum message content length to a lower value than default 16 kB, for example to 4 kB. The TLS may fail if the server side does not support TLS Maximum Fragment Length Negotiation Extension.



Create mqtt instance object:

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

Creates the mqtt object and starts the mqtt client task.

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
ws:// non secure mqtt connection over Websocket
wss:// secure (SSL) mqtt connection over Websocket

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: "mpy_mqtt_client"
cleansession bool, if True, do not use mqtt persistent session feature, default: False
keepalive int, Keep Alive interval in seconds, default: 120
lwt_topic string, LWT topic, default: None; max 32 characters
lwt_msg string, LWT message, default 'offline'; max 128 characters
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
cert Certificate file name
connected_cb callback function executed when mqtt is connected to the server; arguments: mqtt_name
disconnected_cb callback function executed when mqtt is disconnected to the server; arguments: mqtt_name
subscribed_cb callback function executed on succesful topic subscription; arguments: (mqtt_name, topic)
unsubscribed_cb callback function executed when the topic is unsubscribed; arguments: (mqtt_name, topic)
published_cb callback function executed when the topic is published; arguments: (mqtt_name, publish_result)
data_cb callback function executed when new subscribed topic data arrives; arguments: (mqtt_name, topic_data_length, topic_data)

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


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.

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 subscribed, False if not.

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

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.

Returns True if successfully subscribed, False if not.

mqtt.stop()

Stop the mqtt client task. Used resources are freed.

mqtt.start()

Start the stopped mqtt client task.

mqtt.free()

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


Example

def conncb(task):
    print("[{}] Connected".format(task))

def disconncb(task):
    print("[{}] Disconnected".format(task))

def subscb(task):
    print("[{}] Subscribed".format(task))

def pubcb(pub):
    print("[{}] Published: {}".format(pub[0], pub[1]))

def datacb(msg):
    print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])

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

# secure connection requires more memory and may not work
# mqtts = network.mqtt("eclipse", "mqtts://iot.eclipse.org", cleansession=True, data_cb=datacb)

# mqtt over Websocket can also be used
# mqttws = network.mqtt("eclipse", "ws://iot.eclipse.org:80", cleansession=True, data_cb=datacb)
# mqttwss = network.mqtt("eclipse", "wss://iot.eclipse.org:80", cleansession=True, data_cb=datacb)

# Start the mqtt
mqtt.start()

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

mqtt.subscribe('test')
mqtt.publish('test', 'Hi from Micropython')

'''

Example connecting to ThingSpeak

import network

def datacb(msg):
    print("[{}] Data arrived from topic: {}, Message:\n".format(msg[0], msg[1]), msg[2])

thing = network.mqtt("thingspeak", "mqtt://mqtt.thingspeak.com", user="anyName", password="ThingSpeakMQTTid", cleansession=True, data_cb=datacb)
# or secure connection
#thing = network.mqtt("thingspeak", "mqtts://mqtt.thingspeak.com", user="anyName", password="ThingSpeakMQTTid", cleansession=True, data_cb=datacb)

thingspeakChannelId = "123456"                           # enter Thingspeak Channel ID
thingspeakChannelWriteApiKey = "ThingspeakWriteAPIKey"   # EDIT - enter Thingspeak Write API Key
thingspeakFieldNo = 1
thingSpeakChanelFormat = "json"

pubchan = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteApiKey)
pubfield =  "channels/{:s}/publish/fields/field{}/{:s}".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)
subchan = "channels/{:s}/subscribe/{:s}/{:s}".format(thingspeakChannelId, thingSpeakChanelFormat, thingspeakChannelWriteApiKey)
subfield = "channels/{:s}/subscribe/fields/field{}/{:s}".format(thingspeakChannelId, thingspeakFieldNo, thingspeakChannelWriteApiKey)

thing.start()
tmo = 0
while thing.status()[0] != 2:
    utime.sleep_ms(100)
    tmo += 1
    if tmo > 80:
        print("Not connected")
        break

# subscribe to channel
thing.subscribe(subchan)

# subscribe to field
thing.subscribe(subfield)

# publish to channel
# Payload can include any of those fields separated b< ';':
# "field1=value;field2=value;...;field8=value;latitude=value;longitude=value;elevation=value;status=value"
thing.publish(pubchan, "field1=25.2;status=On line")

# Publish to field
thing.publish(pubfield, "24.5")