Skip to content
Boris Lovosevic edited this page Jul 29, 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.



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
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: 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
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
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)
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.

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. Free all used resources.

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")
Clone this wiki locally