小程序
传感搜
传感圈

The Basics of the MQTT Protocol

2023-06-11 08:07:27
关注

Illustration: © IoT For All

We will discuss the basics and how to get started with the MQTT protocol, with code examples. Beginners of the IoT and MQTT can utilize this information to understand MQTT-related concepts and quickly start developing MQTT services and applications.

MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe-based messaging protocol designed for resource-constrained devices and low-bandwidth, high-latency, or unreliable networks. It is widely used in Internet of Things (IoT) applications, providing efficient communication between sensors, actuators, and other devices.

“MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe based messaging protocol designed for resource-constrained devices and low-bandwidth, high-latency, or unreliable networks.”

Why Is MQTT the Best Protocol for IoT?

MQTT has emerged as one of the best IoT protocols due to its unique features and capabilities tailored to the specific needs of IoT systems. Some of the key reasons include:

  • Lightweight: IoT devices are often constrained in terms of processing power, memory, and energy consumption. MQTT’s minimal overhead and small packet size make it ideal for these devices, as it consumes fewer resources, enabling efficient communication even with limited capabilities.

  • Reliable: IoT networks can experience high latency or unstable connections. MQTT’s support for different QoS levels, session awareness, and persistent connections ensures reliable message delivery even in challenging conditions, making it well-suited for IoT applications.

  • Secure communications: Security is crucial in IoT networks as they often transmit sensitive data. MQTT supports Transport Layer Security (TLS) and Secure Sockets Layer (SSL) encryption, ensuring data confidentiality during transmission. Additionally, it provides authentication and authorization mechanisms through username/password credentials or client certificates, safeguarding access to the network and its resources.

  • Bi-directionality: MQTT’s publish-subscribe model allows for seamless bi-directional communication between devices. Clients can both publish messages to topics and subscribe to receive messages on specific topics, enabling effective data exchange in diverse IoT ecosystems without direct coupling between devices. This model also simplifies the integration of new devices, ensuring easy scalability.

  • Continuous, stateful sessions: MQTT allows clients to maintain stateful sessions with the broker, enabling the system to remember subscriptions and undelivered messages even after disconnection. Clients can also specify a keep-alive interval during connection, which prompts the broker to periodically check the connection status. If the connection is lost, the broker stores undelivered messages (depending on the QoS level) and attempts to deliver them when the client reconnects. This feature ensures reliable communication and reduces the risk of data loss due to intermittent connectivity.

  • Large-scale IoT device support: IoT systems often involve a large number of devices, requiring a protocol that can handle massive-scale deployments. MQTT’s lightweight nature, low bandwidth consumption, and efficient use of resources make it well-suited for large-scale IoT applications. The publish-subscribe pattern allows MQTT to scale effectively, as it decouples sender and receiver, reducing network traffic and resource usage. Furthermore, the protocol’s support for different QoS levels allows customization of message delivery based on the application’s requirements, ensuring optimal performance in various scenarios.

  • Language support: IoT systems often include devices and applications developed using various programming languages. MQTT’s broad language support enables easy integration with multiple platforms and technologies, fostering seamless communication and interoperability in diverse IoT ecosystems.

How Does MQTT Work?

To understand how MQTT works, you need to first master the basics for each concept: MQTT Client, MQTT Broker, Publish-Subscribe mode, Topic, and QoS:

MQTT Client

Any application or device running the MQTT client library is an MQTT client. For example, an instant messaging app that uses MQTT is a client, various sensors that use MQTT to report data are a client, and various MQTT testing tools are also a client.

MQTT Broker

The MQTT Broker handles client connection, disconnection, subscription, and unsubscription requests, and routing messages. A powerful MQTT broker can support massive connections and million-level message throughput, helping IoT service providers focus on business and quickly create a reliable MQTT application.

Publish–subscribe Pattern

The publish-subscribe pattern differs from the client-server pattern in that it separates the client that sends messages (publisher) from the client that receives messages (subscriber). Publishers and subscribers do not need to establish a direct connection, and the MQTT Broker is responsible for routing and distributing all messages.

The following diagram shows the MQTT publish/subscribe process. The temperature sensor connects to the MQTT server as a client and publishes temperature data to a topic (e.g., Temperature), and the server receives the message and forwards it to the client subscribed to the Temperature topic.

EMQ Technologies Inc.

Topic

The MQTT protocol routes messages based on topic. The topic distinguishes the hierarchy by slash /, which is similar to URL paths, for example:

chat/room/1

sensor/10/temperature

sensor/+/temperature

MQTT topic supports the following wildcards: + and #.

  • +: indicates a single level of wildcards, such as a/+ matching a/x or a/y.
  • #: indicates multiple levels of wildcards, such as a/# matching a/xa/b/c/d.

For more details on MQTT topics, please check the blog Understanding MQTT Topics & Wildcards by Case.

Quality of Service (QoS)

MQTT provides three kinds of Quality of Service and guarantees messaging reliability in different network environments.

  1. QoS 0: The message is delivered at most once. If the client is not available currently, it will lose this message.
  2. QoS 1: The message is delivered at least once.
  3. QoS 2: The message is delivered only once.

The MQTT Workflow

Now that we understand the basics of MQTT, let’s see how the general workflow works:

  1. Clients initiate a connection to the broker using TCP/IP, with optional TLS/SSL encryption for secure communication. Clients provide authentication credentials and specify a clean or persistent session.

  2. Clients either publish messages to specific topics or subscribe to topics to receive messages. Publishing clients send messages to the broker while subscribing clients express interest in receiving messages on particular topics.

  3. The broker receives published messages and forwards them to all clients subscribed to the relevant topics. It ensures reliable message delivery according to the specified Quality of Service (QoS) level and manages message storage for disconnected clients based on the session type.

Tweet

Share

Share

Email

  • Connectivity
  • IoT Platforms
  • Network and Protocols

  • Connectivity
  • IoT Platforms
  • Network and Protocols

参考译文
MQTT 协议基础
图示:© IoT For All --> 我们将讨论MQTT协议的基本内容和如何开始使用MQTT协议,并提供代码示例。物联网(IoT)和MQTT的初学者可以利用这些信息来理解MQTT相关概念,并快速开始开发MQTT服务和应用。MQTT(Message Queuing Telemetry Transport)是一种轻量级的、基于发布-订阅的消息协议,设计用于资源受限的设备和低带宽、高延迟或不可靠的网络。它在物联网(IoT)应用中被广泛使用,为传感器、执行器和其他设备提供高效的通信。“MQTT(Message Queuing Telemetry Transport)是一种轻量级的、基于发布-订阅的消息协议,设计用于资源受限的设备和低带宽、高延迟或不可靠的网络。” 为什么MQTT是物联网的最佳协议?MQTT之所以成为最佳的物联网协议之一,是因为它具有独特功能和能力,能够满足物联网系统特定的需求。一些主要原因包括:轻量级:物联网设备通常在处理能力、内存和能源消耗方面受限。MQTT的最小开销和小数据包大小使其非常适合这些设备,因为它消耗的资源更少,即使在能力有限的情况下也能实现高效通信。可靠:物联网网络可能会遇到高延迟或不稳定的连接。MQTT对不同服务质量(QoS)等级的支持、会话感知和持久连接,确保了即使在恶劣条件下也能实现可靠的消息传递,这使得MQTT非常适合物联网应用。安全通信:在物联网网络中,安全性至关重要,因为这些网络经常传输敏感数据。MQTT支持传输层安全(TLS)和安全套接字层(SSL)加密,确保传输过程中的数据保密性。此外,它还通过用户名/密码凭证或客户端证书提供身份验证和授权机制,确保对网络和资源的访问得到保障。双向通信:MQTT的发布-订阅模式允许设备之间进行无缝双向通信。客户端既可以发布消息到主题,也可以订阅以接收特定主题的消息,使得在各种物联网生态系统中能够有效交换数据,而无需设备之间直接耦合。这种模式还简化了新设备的集成,确保了轻松的可扩展性。持续的状态会话:MQTT允许客户端与代理保持状态会话,使系统即使在断开连接后也能记住订阅和未交付的消息。客户端还可以在连接时指定一个保持活动的时间间隔,该时间间隔会促使代理定期检查连接状态。如果连接丢失,代理会存储未发送的消息(具体取决于QoS等级),并在客户端重新连接时尝试发送这些消息。这一功能确保了通信的可靠性,并减少了因间歇性连接而造成的数据丢失风险。大规模物联网设备支持:物联网系统通常涉及大量设备,因此需要一种能够处理大规模部署的协议。MQTT的轻量级特性、低带宽消耗和高效的资源利用,使其非常适合大规模物联网应用。发布-订阅模式使得MQTT能够有效扩展,因为它解耦了发送方和接收方,减少了网络流量和资源使用。此外,该协议对不同QoS等级的支持允许根据应用程序的需求定制消息传递,确保在各种场景下的最佳性能。语言支持:物联网系统通常包括使用各种编程语言开发的设备和应用。MQTT广泛的语言支持使其能够轻松集成到多个平台和技术中,促进各种物联网生态系统中无缝的通信和互操作性。MQTT是如何工作的?要了解MQTT是如何工作的,您需要首先掌握每个概念的基本知识:MQTT客户端、MQTT代理、发布-订阅模式、主题和QoS:MQTT客户端:任何运行MQTT客户端库的应用程序或设备都是MQTT客户端。例如,使用MQTT的即时通讯应用是一个客户端,各种使用MQTT报告数据的传感器也是一个客户端,各种MQTT测试工具也是客户端。MQTT代理:MQTT代理处理客户端的连接、断开连接、订阅和退订请求,并路由消息。一个强大的MQTT代理可以支持大量的连接和百万级的消息吞吐量,帮助物联网服务提供商专注于业务,并快速创建可靠的MQTT应用。发布-订阅模式:发布-订阅模式不同于客户端-服务器模式,因为它将发送消息的客户端(发布者)与接收消息的客户端(订阅者)分离开来。发布者和订阅者不需要建立直接连接,MQTT代理负责路由和分发所有消息。下图显示了MQTT的发布/订阅过程。温度传感器作为客户端连接到MQTT服务器,并将温度数据发布到一个主题(例如,Temperature),服务器接收消息并将其转发给订阅Temperature主题的客户端。EMQ Technologies Inc.主题:MQTT协议根据主题路由消息。主题通过斜线/区分层次,这类似于URL路径,例如:chat/room/1 sensor/10/temperature sensor/+/temperature MQTT主题支持以下通配符:+和#。+:表示单级通配符,例如a/+匹配a/x或a/y。#:表示多级通配符,例如a/#匹配a/x,a/b/c/d。更多关于MQTT主题的信息,请查阅博客《理解MQTT主题与通配符的实例》。服务质量(QoS):MQTT提供三种不同的服务质量等级,并在不同的网络环境中保证消息传递的可靠性。QoS 0:消息最多传递一次。如果当前客户端不可用,则会丢失消息。QoS 1:消息至少传递一次。QoS 2:消息仅传递一次。MQTT的工作流程:既然我们已经了解了MQTT的基本知识,现在来看看典型的工作流程是怎样的:客户端使用TCP/IP与代理建立连接,可以选择使用TLS/SSL加密以实现安全通信。客户端提供身份验证凭据,并指定一个干净会话或持久会话。客户端可以选择向特定主题发布消息或订阅主题以接收消息。发布消息的客户端将消息发送到代理,而订阅消息的客户端则表示对特定主题的消息感兴趣。代理接收已发布的消息,并将其转发给所有订阅了相关主题的客户端。它确保根据指定的服务质量(QoS)等级实现可靠的消息传递,并根据会话类型管理已断开连接客户端的消息存储。连接性 物联网平台 网络与协议 --> 连接性 物联网平台 网络与协议
您觉得本篇内容如何
评分

评论

您需要登录才可以回复|注册

提交评论

广告
提取码
复制提取码
点击跳转至百度网盘