MQTT is a publish and subscribe protocol with no direct connection between clients.
However many applications require a client to client type connection. Examples are:
- Sensor or device control
This can be achieved in all versions of MQTT but it has been made easier in MQTTv5 with the introduction of request response in the publish payload.
In this tutorial we look at achieving the same in MQTTv3.1.1.
If you look at the simple diagram below which show a typical communication between MQTT clients.
Because there is no direct connection between client A and client B when any of the clients receives data it doesn’t know who sent it.
There are however several ways of overcoming this the main ones are:
- Include the client name in the payload data
- Use a topic that identifies the sending client
The most common implementation is using topic names.A typical design uses a topic structure of:
for two two clients called a and b.
Client A publishes to topic client_b using the topic topic_base/client_b/client_a.
Client B subscribes to topic_base/# and must extract the sender client topic and the destination topic from the received messages. It only replies to messages sent to itself.
Client B publishes to topic client_a using the topic topic_base/client_a/client_b.
Client A subscribes to topic_base/# subscribes to topic_base/# and must extract the sender client topic and the destination topic from the received messages. It only replies to messages sent to itself.
Example Python Scripts
You can download example scripts for client A and Client B. When you run them you should see messages on Client A from Client B and vice versa.
Although the scripts use Python the technique is applicable to all client types.
- Receiving Messages with the Paho MQTT Python Client
- Checking Active MQTT Client Connections
- How to Send and Receive JSON Data Over MQTT with Python
- How to Send a File Using MQTT and Python
- How to Encrypt MQTT Payloads with Python – Example Code