First, install an MQTT broker of your choice. My choice is Eclipse Mosquitto. On Fedora, you install that package like so …
# dnf install mosquitto
Then, to communicate with that broker from Python programs, you install a Python client implementation of your choice. My choice is the Paho implementation, which is installed like so …
$ pip install paho-mqtt
This is Fedorish, your mileage might vary:
# systemctl start mosquitto.service # netstat -antp|grep mosquitto tcp 0 0 0.0.0.0:1883 0.0.0.0:* LISTEN 53767/mosquitto tcp6 0 0 :::1883 :::* LISTEN 53767/mosquitto
Ah, runs on port 1883.
See if it works. In one terminal, subscribe to a random topic. (Topic are created as soon as they are mentioned.)
$ mosquitto_sub --host localhost --port 1883 --topic /random/topic ...sit and wait for message...
In another terminal, publish a message,
$ mosquitto_pub --host localhost --port 1883 --topic /random/topic --message blah
You should see “blah” as the output of
mosquitto_sub in the other
This is the easiest, so lets start with that.
#!/usr/bin/env python from paho.mqtt import client c = client.Client() c.connect('localhost', 1883) c.publish('/random/topic', 'blech')
Run it, and in the terminal running
mosquitto_sub you’ll see
A little more complicated - we have to
run an event loop: we want to see more than one message coming in
register a callback function that is called by MQTT to notify us about an incoming message
#!/usr/bin/env python from paho.mqtt import client def message_received(client, userdata, message): print(message.payload) c = client.Client() c.connect('localhost', 1883) c.on_message = message_received c.subscribe('/random/topic') c.loop_forever()
Run it, possibly side by side with
mosquitto_sub. Publish a
message, using either the
publish.py program above, or
$ ./subscribe.py b'blech'
b in the output: what comes in is not a string. MQTT’s
transport is encoding-free; what is sent is completely up to the
You should probably read up on