Nowadays IoT is a buzzword. It is about making various consumer electronic devices smarter by connecting them to the Internet and to cloud services. MQTT is a one of the popular messaging protocols for use on top of the TCP/IP protocol. It is convenient for real time communication between embedded devices. MQTT was invented in 1999 and initially it was used internally only by IBM. In 2010 version 3.1 was released royalty free.
MQTT implements the publish-subscribe messaging pattern using a broker. All clients connect to the broker and subscribe to different topics. Each client is capable of publishing messages. The broker is responsible for delivering messages to subscribed clients.
The work flow of a MQTT client is first to establish a connection with MQTT broker and after that to subscribe to a topic. At this point the client will receive messages from the broker depending on their topics. Furthermore, the client is capable of publishing messages at any time.
Each MQTT message contains a topic which is used by the broker to forward it to the interested clients. Typically, the message also has a payload. It is up to the developers to define the most appropriate format of the payload. It could be a binary data, plain text, JSON, XML or something else. There are a couple of other attributes of a MQTT message. Quality of Service (QoS) defines how hard the broker will try to deliver the message to the interested clients. There are three levels which guarantee how the message is delivered:
0 - At most once
1 - At least once
2 - Exactly once
The retain flag instructs the broker whether to save the last known good value. If this attribute is set to 1, the broker will deliver the last retained message to all new clients immediately after they subscribe to the topic.
The MQTT topic is UTF-8 string with one or more levels. The separator symbol between levels is a slash. The MQTT broker uses the topic to filter and deliver messages to each connected client depending on its subscriptions. Clients can use wild cards while subscribing to a topic. Plus is used for a single level wildcard. Hash is a multi level wildcard that covers all levels and can be situated only at the end of a topic.
The Last Will and Testament (LWT) is an MQTT feature to notify other clients about an ungracefully disconnected client. Upon connecting to the broker each client can specify MQTT message which will be its last will. The broker will store the message until it detects that the client has disconnected ungracefully. Last will is an important MQTT feature for Internet of Things because it allows you to detect if a device has disappeared due to force majeure circumstances.
MQTT supports transport layer security (TLS/SSL) and authentication with username and password. Authorization policies can be implemented using access control lists.