In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services

In previous articles, such as the “Aizhi Wish Tree from 0 to Perfection Series” and the communication methods between Raspberry Pi and EdgerOS, we often mentioned a “lightweight” communication protocol, which is MQTT. This article will guide everyone to understand the general content of MQTT and the MQTT module of JSRE.1Introduction to MQTT01Advantages of MQTTMQTT (Message Queuing Telemetry Transport) is a “lightweight” communication protocol based on the Publish/Subscribe model, built on top of the TCP/IP protocol, and was released by IBM in 1999.The traditional TCP-based MQTT can be quite heavy for small memory sensors or IoT devices, hence there is MQTT-SN (Sensor Networks) based on UDP, which is currently widely used in the sensor field. Additionally, there is MQTT over WebSocket.The greatest advantage of MQTT is that it can provide real-time and reliable messaging services for connecting remote devices with minimal code and limited bandwidth. As a low-overhead, low-bandwidth instant messaging protocol, it has a wide range of applications in IoT, small devices, and mobile applications.The main features of the MQTT protocol include: lightweight and efficient, reliable message delivery, bidirectional communication, support for unreliable networks, security enablement, and scalability to millions of devices. In the Aizhi ecosystem, we can use Spirit 1 to communicate with various smart devices to create a personalized smart home, or communicate with sensors and production equipment to build smart parks for industrial production.02MQTT FrameworkThe MQTT network architecture consists of a message server (Broker), subscribers (Subscriber), and publishers (Publisher). Both subscribers and publishers are MQTT clients, and publishers can also subscribe to the messages they send.In our previous articles in the “Aizhi Wish Tree from 0 to Perfection” series, Spirit 1 serves as the message server, where we publish wish information through the EdgerOS APP, and finally subscribe to the wish information via Raspberry Pi to control the LED display and light strips.

In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services

MQTT Communication Model

03MQTT Topics

Publishers send messages on a specific topic to the server, and then the server forwards all messages under that topic to the subscribers. Due to the large scale of communication messages in MQTT, topics are divided into different levels using the / separator, allowing clients to send and receive the messages they want. The basic structure of a topic is as follows:

EdgerOSEdgerOS/MQTTEdgerOS/MQTT/APIEdgerOS/MQTT/ApplyEdgerOS/SDDC/Apply


Subscribing to EdgerOS will only receive messages from the EdgerOS topic, while subscribing to EdgerOS/SDDC will only receive messages from the EdgerOS/SDDC topic. Topics can also include two wildcards, + and #, where + represents the current level and # represents the current level and its sub-levels. For example, subscribing to EdgerOS/+ can receive EdgerOS/MQTT and EdgerOS/SDDC. Subscribing to EdgerOS/# can receive messages like EdgerOS/SDDC, EdgerOS/MQTT/API, etc.

In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services

04Message QoS

QoS indicates the service level of the message, and MQTT specifies three levels of message service:

  • QoS 0: The message is delivered at most once; if the receiver is unavailable, the message will be lost.
  • QoS 1: The message is delivered at least once.
  • QoS 2: The message is delivered exactly once.

QoS 0 is a “fire and forget” message sending mode: the sender (which can be either the Publisher or the Broker) sends a message and does not care whether it has been received by the other party, nor does it set any retransmission mechanism.QoS 1 includes a simple retransmission mechanism; the sender sends a message and waits for the receiver’s ACK. If the ACK is not received, the message is resent. This mode ensures that the message is delivered at least once but does not guarantee that the message is not duplicated.QoS 2 is the highest level of MQTT QoS service, designed with retransmission and duplicate message detection mechanisms, requiring two communications to complete:<span>PUBLISH <-> PUBREC, PUBREL <-> PUBCOMP</span>, ensuring that the message reaches the other party and is strictly delivered only once.In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services2JSRE’s MQTT ModuleWe can use this module to create an MQTT client, using TCP and TLS as secure connection methods to interact with the Spirit 1 MQTT server or other IoT cloud services. MQTT does not restrict the types of topics and message content transmitted, but for compatibility reasons, JSRE recommends using JSON data format for publishing and subscribing.01APImqtt.open(saddr[, tlsOpt[, timeout])Creates an MQTT client and connects to the specified MQTT server using synchronous mode.saddr: Server socket address.tlsOpt: TLS secure connection options. Default is undefined, indicating a TCP connection.timeout: The waiting time for synchronous connection, in milliseconds. Default: undefined, indicating the default connection timeout settings.

const serAddr = socket.sockaddr('192.168.128.1', 1883)const client = mqtt.open(serAddr, undefined, 5000)if (!client) {  console.log('Cannot connect to broker.')}

mqtt.mode()

Gets the current MQTT working mode of the process, which can be one of the following three modes:off: MQTT is not enabled.listener: MQTT is in listener mode and cannot publish topic messages.publisher: MQTT can subscribe and publish messages.

client.close()

Closes the connection to the MQTT server.

client.connect(clientOpt[, callback])

Connects to the MQTT server using specified parameters.clientOpt: MQTT connection parameters.callback: Callback function after connection, with the client parameter being the MQTT client object.MQTT connection parameters are as follows:client: Client ID recognizable by the server.user: Username for the server.passwd: Password for the server.keepalive: Keep-alive time in seconds. If no data is sent within the given time, the server will disconnect from the client.will: If this flag is set to true, the message and topic QoS must be specified between 0 and 2.qos: If will is set to true, the message will be sent with the specified QoS value.message: Only processed when will is set to true, sends this message when the connection is interrupted.topic: Only processed when will is set to true, the topic of the message.

/* MQTT Client Options */const options = { client: 'Spirit', user: 'admin', passwd: 'password', will: false, topic: '', message: '', keepalive: 60, qos: 0 }client.connect(options, (client) =&gt; {  console.log('MQTT Connected!')  // do something})

client.isConnected()

Gets the current connection status of the client, true means connected, false means not connected.

client.isQueued()

Gets whether the send queue contains messages that have not been confirmed by the server.

client.publish(topic, message[, options[, callback]])

Publishes a message using the specified parameters.topic: Message topic.message: Content of the message.options: Default qos is 0, retain is false.callback: Callback function during publishing, with the parameter being error; if error is true, the publishing failed.qos: Default is 0.retain: If true, the server will retain the message so that later subscribers with retain set to true can receive it.

client.publish('topic1', 'message1')client.publish('topic2', 'message2', { qos: 1 })client.publish('topic3', 'message3', { qos: 1 }, (error) =&gt; {  if (error) {    console.log('Publish error:', error)  }})

client.subscribe(topic[, options[, callback]])

Subscribes to messages using the specified parameters.topic: Subscription message topic.options: Subscription options, default qos is 0, retain is false.callback: Callback function during subscription, with the parameter being error; if error is true, the subscription failed.qos: Default is 0.retain: If true, the subscriber will receive previously retained messages from the server after connecting.

client.subscribe('topic1', { qos: 1 })

client.unsubscribe(topic[, callback])

Unsubscribes from messages.topic: Topic to unsubscribe from.callback: Callback function for unsubscribing, with the parameter being error; if error is true, the unsubscription failed.

client.unsubscribe('topic1', (error) =&gt; {  if (error) {    console.log('Unsubscribe error:', error)  }})

02EventsUnder certain circumstances, the following events will be triggered through the client’s event emitter:

connect

This event is triggered when the client establishes a connection with the server.

disconnect

This event is triggered when the network link is disconnected.

close

This event is triggered when the server and client disconnect normally.

error

If an error occurs and the callback function is not called, an event containing the error information will be emitted. If this event is not listened to, it will throw an exception.

message

This event is triggered when the client receives a message from the server.At this point, we have roughly covered the protocol specifications of MQTT and the application of the MQTT-related modules in JSRE. For a more specific and in-depth study of MQTT, please refer to the articles in the “Aizhi Wish Tree from 0 to Perfection Series” and the communication methods between Raspberry Pi and EdgerOS for further thought and practice.

In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging ServicesAizhi Exclusive BenefitsIn-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services

Free Red Packet Cover for the Year of the Tiger!

Wishing you a different kind of luck in the Year of the Tiger!

Click the image below to claim it for free

Limited quantity, first come first served

Previous Recommendations

How to Use MQTT and CoAP Protocols to Enable Data Interaction Between Raspberry Pi and EdgerOS, Understand in One Article!

Solving the “Chip Shortage” Problem: Edge Computing Operating Systems Provide Infrastructure for the Digital Economy

From NPM to EPM, Aizhi Provides Maximum Compatibility

In-Depth Analysis of MQTT: Providing Real-Time and Reliable Messaging Services

Leave a Comment