Introduction to MQTT
Before you learn how to build a MQTT network, it will help to understand some of the jargon that's used and how each piece fits together to create your network.
- Broker - The broker is the server that distributes the information to the interested clients connected to the server.
- Client - The device that connects to broker to send or receive information.
- Topic - The name that the message is about. Clients publish, subscribe, or do both to a topic.
- Publish - Clients that send information to the broker to distribute to interested clients based on the topic name.
- Subscribe - Clients tell the broker which topic(s) they're interested in. When a client subscribes to a topic, any message published to the broker is distributed to the subscribers of that topic. Clients can also unsubscribe to stop receiving messages from the broker about that topic.
- QoS - Quality of Service. Each connection can specify a quality of service to the broker with an integer value ranging from 0-2. The QoS does not affect the handling of the TCP data transmissions, only between the MQTT clients. Note: In the examples later on, we'll only be using QoS 0.
- 0 specifies at most once, or once and only once without requiring an acknowledgment of delivery. This is often refered to as fire and forget.
- 1 specifies at least once. The message is sent multiple times until an acknowledgment is received, known otherwise as acknowledged delivery.
- 2 specifies exactly once. The sender and receiver clients use a two level handshake to ensure only one copy of the message is received, known as assured delivery.
How MQTT Works
As mentioned in the introduction, MQTT is a publish/subcribe messaging protocol. Clients will connect to the network, which can subscribe or publish to a topic. When a client publishes to a topic, the data is sent to the broker, which then is distributed to all the clients that are subscribed to that topic.
Topics are arranged in a directory-like structure. A topic might be "LivingRoom", or "LivingRoom/Light" if you have multiple clients within that parent topic. The subscriber client will listen for incoming messages from the subscribed topic and react to what was published to that topic, such as "on" or "off". Clients can subscribe to one topic and publish to another as well. If the client subscribes to "LivingRoom/Light", it might also want to publish to another topic like "LivingRoom/Light/State" so that other clients can monitor the state of that light.
Now that we understand the theory of how MQTT works, lets build a quick and easy example with a Raspberry Pi and ESP32 Thing boards to see it working in action. We'll start by setting up the broker and running a quick test to make sure it's working correctly.