AcademyEngineer

Networking with MQTT: Make Your Devices Talk

Run a Mosquitto broker on your Pi and send messages between sensors, robots and dashboards.

LevelEngineer
Time30 min
Est. costFree
Steps5

MQTT is the language of IoT. Devices 'publish' messages to topics like garden/soil, and anything 'subscribed' to that topic receives them instantly. Home Assistant, Node-RED and ESPHome all speak it.

Video tutorial

Video by HiveMQ, embedded from YouTube. The written steps below are our own and match the parts list.

Mission steps

  1. Install the broker

    Install Mosquitto and its command-line clients on the Pi.

  2. Subscribe in one window

    Open an SSH session and subscribe to a test topic.

  3. Publish in another

    Open a second session and publish a message. It appears instantly in the first window.

  4. Secure it for your network

    Mosquitto 2 only accepts local connections by default. To accept other devices, add a listener and a password file — never expose it to the internet without TLS.

  5. Publish from Python

    Use the paho-mqtt library to send sensor readings from any script.

Code

sudo apt install -y mosquitto mosquitto-clients
# window 1
mosquitto_sub -h localhost -t lab/test
# window 2
mosquitto_pub -h localhost -t lab/test -m "hello from the pi"
# pip install paho-mqtt (inside your venv)
import paho.mqtt.publish as publish
publish.single("lab/temperature", "24.5", hostname="localhost")

Tip: test every script on the bench before installing it in a moving machine.

Questions

MQTT vs HTTP?

MQTT keeps a light, always-open connection that is perfect for tiny devices and live updates. HTTP is better for web pages and occasional requests.