Learn Python MQTT for industrial automation using paho-mqtt. Publish process data as JSON, subscribe to IIoT topics, use QoS and connect plant data to brokers safely.
Architecture: Python MQTT for IIoT
Python MQTT for IIoT
Plant Data
PLC/SQL/process values
Temp_Act = 850.2Python
Build payload
dict → JSONMQTT Client
paho-mqtt
Client()Broker
Route messages by topic
factory/sqf02/processSubscriber
Dashboard / historian / app
subscribe(...)Monitor
Log delivery/reconnect
on_connect / logging1. Install paho-mqtt
python -m pip install paho-mqtt2. Create a JSON payload
import json
from datetime import datetime payload = { "DT": datetime.now().isoformat(timespec="seconds"), "SQF_No": 2, "Temp_Act": 850.2, "Fan_Status": True,
}
message = json.dumps(payload)
print(message)3. Publish a message
import paho.mqtt.client as mqtt client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect("mqtt.example.local", 1883, 60)
client.publish("factory/sqf02/process", message, qos=1)
client.disconnect()4. Subscribe to a topic
def on_message(client, userdata, msg): print(msg.topic, msg.payload.decode("utf-8")) client.on_message = on_message
client.subscribe("factory/sqf02/#", qos=1)5. QoS comparison
| QoS | Meaning | Typical use |
|---|---|---|
| 0 | At most once | Fast non-critical telemetry |
| 1 | At least once | Common industrial telemetry when duplicates can be handled |
| 2 | Exactly once protocol flow | Use only when required because it adds overhead |
6. Industrial MQTT checks
- Use TLS/authentication when required
- Design stable topic names
- Timestamp payloads
- Handle reconnects and duplicate QoS 1 messages
- Do not expose control topics without authorization and validation
Frequently Asked Questions
What is MQTT used for in industrial automation?
MQTT is a lightweight publish/subscribe protocol commonly used to move telemetry between edge devices, brokers, applications and cloud/IIoT platforms.
Why serialize data as JSON?
JSON provides readable structured key/value data that many MQTT consumers can parse easily.
Which QoS should I use?
Choose based on delivery requirements and system design; QoS 1 is common for telemetry where duplicates can be handled.
