Explain the working of MQTT
Answer:-
- MQTT (Message Queue Telemetry Transport) is a lightweight publish-subscribe messaging protocol designed for constrained devices and networks.
- It is efficient, payload-agnostic, and reliable even over high-latency or low-bandwidth networks.
- Operates on the client-server model, where the server is referred to as the broker, and clients act as publishers or subscribers.
Working of MQTT
Illustration (Figure)
- Devices like refrigerators, thermometers, or lights act as publishers/subscribers.
- Topics (e.g., “Appliances,” “Lights”) allow communication through the broker, ensuring decoupled and streamlined messaging.
Operational Principles
- Hierarchical Topics:
- MQTT uses a hierarchy of topics to organize messages.
- Publishers send messages tagged with specific topics, and subscribers retrieve messages for topics of interest.
- Broker’s Role:
- The broker manages communication by receiving messages from publishers and forwarding them to subscribers of the same topic.
- If no subscriber exists for a topic, the broker discards the message unless specified otherwise by the publisher.
- Last Will and Testament:
- Publishers can configure a default message (Last Will and Testament) to be delivered by the broker if the publisher disconnects unexpectedly.
- Communication:
- MQTT operates over TCP for reliable data transfer.
- Messages consist of a control message and a data message.
- Message Types:
MQTT supports 14 message types for various operations:- CONNECT/CONNACK: Connection initiation and acknowledgment between publisher/subscriber and broker.
- PUBLISH/PUBACK: Message publishing and acknowledgment between publisher and broker or broker and subscriber.
- PUBREC/PUBREL/PUBCOMP: Assured delivery components ensuring the successful reception, release, and completion of the publish operation.
- SUBSCRIBE/SUBACK: Topic subscription request and acknowledgment from subscriber to broker.
- UNSUBSCRIBE/UNSUBACK: Request to unsubscribe from a topic and acknowledgment of the unsubscription.
- PINGREQ/PINGRESP: Keep-alive request and response messages to maintain an active connection.
- DISCONNECT: Message signaling the disconnection of publisher/subscriber from the broker.
MQTT Message Delivery QoS
- At most once:
- Best-effort delivery.
- No guarantees; messages may be lost or duplicated.
- At least once:
- Guarantees delivery but may lead to message duplication.
- Exactly once:
- Ensures message delivery without duplication.
Advantages
- Lightweight, making it ideal for IoT devices.
- Minimizes network traffic with a small fixed header (2 bytes).
- Efficient message delivery tailored for constrained environments.