Example: send messages (publish) with MQTT
A basic Python example of a node publishing (sending) a message is:
mqttc = mqtt.Client("digitest") # Create instance of client with client ID “digitest”
mqttc.connect("m2m.eclipse.org", 1883) # Connect to (broker, port, keepalive-time)
mqttc.loop_start() # Start networking daemon
mqttc.publish("digitest/test1", "Hello, World!") # Publish message to “digitest /test1” topic
mqttc.loop_stop() # Kill networking daemon
Note You can easily copy and paste code from the online version of this guide. Use caution with the PDF version, as it may not maintain essential indentations.
This example imports the MQTT library, allowing you to use the MQTT protocol via APIs in the library, such as the connect(), subscribe(), and publish() methods.
The second line creates an instance of the client, named mqttc. The client ID is the argument you passed in: digitest (this is optional).
In line 3, the client connects to a public broker, in this case m2m.eclipse.org, on port 1883 (the default MQTT port, or 8883 for MQTT over TLS). There are many publicly available brokers available, you can find a list of them here: https://github.com/mqtt/mqtt.github.io/wiki/brokers.
Line 4 starts the networking daemon with client.loop_start() to handle the background network/data tasks.
Finally, the client publishes its message Hello, World! to the broker under the topic digitest/backlog/test1. Any nodes (devices, phones, computers, even microcontrollers) subscribed to that same topic on the same broker receive the message.
Once no more messages need to be published, the last line stops the network daemon with client.loop_stop().