MQTT ===== MQTT (Message Queue Telemetry Transport) is a telemetry transport protocol that provides a subscribe/publish mode. It is more simple, lightweight, and easy to use, targeting constrained environments (low bandwidth, high network latency, unstable network communication). It can be simply summarized as built for the Internet of Things. MQTT is a "lightweight" publish-subscribe based messaging protocol used on top of the TCP/IP protocol. It is suitable for connections at remote locations that require a "small code footprint" or where network bandwidth is limited. It is a protocol that can achieve one-to-many communication (which people call publish or subscribe type). It consists of 3 functions: the broker, the publisher, and the subscriber. .. figure:: /_static/products/ledong-v2/_static/image/tutorials/IoT/mqtt.png :align: center :width: 600 broker, publisher, subscriber The broker acts as the server that forwards MQTT communication. In contrast, the publisher and subscriber act as clients. The publisher is the client responsible for sending messages, while the subscriber is the client responsible for receiving messages. All messages exchanged by MQTT carry a "topic" address, and each client treats this "topic" as the destination address and performs the operation of transmitting messages to it. To use a vivid analogy, the broker is the mailbox that receives mail. .. figure:: /_static/products/ledong-v2/_static/image/tutorials/IoT/iot_publish.png :align: center :width: 600 MQTT communication mechanism The broker waits for each client to connect to it. The subscriber connects to the broker and tells the broker the name of the topic it wants to subscribe to. This is called subscribing. Then the publisher connects to the broker and sends messages with the topic as the destination address. This is publishing. Once the publisher publishes a topic, the broker delivers the message to the subscribers who have subscribed to that topic. As shown in the figure above, if a subscriber subscribes to topic A, the broker will deliver the message to the subscriber only when the publisher publishes topic A. The subscriber and the broker are always in a connected state, while the publisher only needs to establish a connection when publishing. However, when publishing several times in a short period, it needs to maintain the connection. Because the broker plays the role of forwarding messages, there is no need for the clients to know each other's network destination addresses such as IP addresses. Also, because multiple clients can subscribe to the same topic, the publisher and subscribers have a one-to-many relationship. In the communication between a device and a server, the device is equivalent to the publisher, and the server is equivalent to the subscriber. .. figure:: /_static/products/ledong-v2/_static/image/tutorials/IoT/IoT_subscribe.png :align: center :width: 600 MQTT topic examples Topics use a hierarchical structure. Symbols such as "#" and "+" can specify multiple topics. As shown in the figure above, /Sensor/temperature/# uses the "#" symbol, which specifies all topics that start with /Sensor/temperature/. In addition, /Sensor/+/room1 uses the "+" symbol, which specifies all topics that start with /Sensor/ and end with /room1. *The MQTT principle is reprinted from [Illustrated Internet of Things / written by NTT DATA Group of Japan; translated by Ding Ling. --Beijing: Posts & Telecom Press, 2017.4]* IoT Platform Introduction ------------------------- The publish-subscribe messaging pattern requires a message broker server. The broker server is responsible for distributing messages to interested clients according to the message topic. .. Hint:: Currently, there are a variety of MQTT IoT platforms on the Internet. You can choose the mqtt IoT platform that suits you according to your own requirements. I recommend the following good IoT platforms. * OneNet China Mobile IoT Platform: https://open.iot.10086.cn/ - Advantages: Supports multiple communication protocols, such as MQTT, HTTP, etc.; editable application functions, can create page UI for data display and switch controls. - Disadvantages: The platform operation is relatively complex and slightly different from the official MQTT, which is harder for beginners to understand. * DFRobot Easy IoT Platform: http://iot.dfrobot.com.cn/ - Advantages: Simple operation, suitable for beginners to learn. - Disadvantages: Cannot customize topic; lacks application-side UI editing, unable to present data. * Adafruit IO Platform: https://io.adafruit.com/ - Advantages: Simple operation, suitable for MQTT teaching; rich dashboard editing functions, can present data well; supports IFTTT, can associate with many Internet services, with diverse ways to play. - Disadvantages: Overseas servers, unstable connection, often unable to connect. In addition to the above, you can also build your own mqtt server. Connecting to the MQTT Broker Server ------------------------------------ The following uses Easy IoT to explain how to use mqtt to subscribe to topics and publish messages. First, import the required modules:: from umqtt.simple import MQTTClient # Import the umqtt.simple module for simple mqtt client functionality from mpython import * # Import the mpython module The mPython Board first connects to the Internet:: mywifi=wifi() # Instantiate the wifi class mywifi.connectWiFi("ssid","password") # wifi connection, ssid is the username, password is the password Instantiate MQTTClient:: SERVER = "182.254.130.180" # MQTT server address of Easy IoT username='yourIotUserName' # Your Iot_id on Easy IoT password='yourIotPassword' # Your Iot_pwd on Easy IoT CLIENT_ID = "yourClientID" # Your Client ID on Easy IoT c = MQTTClient(CLIENT_ID, SERVER,1883,username,password) # MQTTClient class instance c.connect() # mqtt connection MQTTClient(client_id, server, port=0, user=None, password=None, keepalive=0). The ``client_id`` parameter is the unique id of the mqtt client; the ``server`` parameter is the IP address of the mqtt broker server; the ``port`` parameter is the port number for accessing the mqtt server, usually 1883, and the port may be different for different platforms; the ``user`` parameter is the username used to obtain mqtt authentication; the ``password`` parameter is the password for obtaining mqtt authentication; the ``keepalive`` parameter is the connection keep-alive time. When there are no subscribe or publish packets within the keepalive interval, the connection will be automatically disconnected. .. image:: /_static/products/ledong-v2/_static/image/tutorials/mqtt_1.png :scale: 60% Publishing Messages ------------------- Publish the device topic on Easy IoT:: c.publish("Bkgk2zXb4",'hello') .. Note:: ``publish(topic, msg)``. The ``topic`` parameter is the published topic. On the Easy IoT management interface, devices are distinguished by topic and cannot be modified, which needs to be noted; the ``msg`` parameter is the message of this topic; After publishing, you can query the message just published in the "View Details" of the device in the Easy IoT workspace, as follows: .. image:: /_static/products/ledong-v2/_static/image/tutorials/mqtt_2.png .. image:: /_static/products/ledong-v2/_static/image/tutorials/mqtt_3.png Subscribing to Topics --------------------- Set to print output after receiving a message:: def sub_cb(topic, msg): print((topic, msg)) c.set_callback(sub_cb) Before subscribing to a topic, you need to set the callback function ``set_callback(sub_cb)`` first. ``sub_cb`` is the function that handles the received message and must contain two parameters. Subscribe to a topic. The ``topic`` parameter is the topic to subscribe to:: c.subscribe(topic) Finally, use ``wait_msg()`` to wait for incoming messages:: while True: c.wait_msg() Remote Light Switch ^^^^^^^^^^^^^^^^^^^ The following example uses the mqtt topic subscription function to make a remote control light switch:: from umqtt.simple import MQTTClient from mpython import * from machine import Timer SERVER = "182.254.130.180" # MQTT server address of Easy IoT username='yourIotUserName' # Your Iot_id on Easy IoT password='yourIotPassword' # Your Iot_pwd on Easy IoT CLIENT_ID = "yourClientID" # Your Client ID on Easy IoT TOPIC='yourTopic' # Your device topic on Easy IoT mywifi=wifi() # Instantiate the wifi class mywifi.connectWiFi("ssid","password") # wifi connection, ssid is the username, password is the password try: def sub_cb(topic, msg): # Callback function when a subscribed message is received print((topic, msg)) # Print the received topic message if topic == TOPIC.encode(): # If the topic is our device's topic, since it is received as a byte type, TOPIC needs to be converted to a byte type here. if msg == b"on": # If the message is "on", turn on the light rgb.fill((0,20,0)) rgb.write() elif msg == b"off": # If the message is "off", turn off the light rgb.fill((0,0,0)) rgb.write() c = MQTTClient(CLIENT_ID, SERVER,1883,username,password,keepalive=30) # MQTTClient class instance, and set the connection keep-alive interval to 30 seconds c.connect() # mqtt connection c.set_callback(sub_cb) # Set the callback function c.subscribe(TOPIC) # Subscribe to the topic print("Connected to %s" % SERVER) tim1 = Timer(1) # Create timer 1 tim1.init(period=20000, mode=Timer.PERIODIC,callback=lambda n:c.ping()) # Send Ping at 20-second intervals to keep the connection while True: c.wait_msg() # Loop waiting for messages finally: c.disconnect() # Disconnect the mqtt connection on exception Then click to enter the "Send Message" of the device in the Easy IoT workspace to send the topic message, as follows: .. image:: /_static/products/ledong-v2/_static/image/tutorials/mqtt_4.png .. image:: /_static/products/ledong-v2/_static/image/tutorials/mqtt_5.gif :scale: 50%