Installation

To make use of MQTT in Python, we need to install a library to communicate with the server. A populat choice is Paho from Eclipse.

As usual we can use pip to install it

!!pip3 install paho-mqtt 
['Requirement already satisfied: paho-mqtt in /home/luis/.local/lib/python3.8/site-packages (1.5.1)']

Publish a message

import paho.mqtt.client as mqtt

help(mqtt.Client.publish)
Help on function publish in module paho.mqtt.client:

publish(self, topic, payload=None, qos=0, retain=False, properties=None)
    Publish a message on a topic.
    
    This causes a message to be sent to the broker and subsequently from
    the broker to any clients subscribing to matching topics.
    
    topic: The topic that the message should be published on.
    payload: The actual message to send. If not given, or set to None a
    zero length message will be used. Passing an int or float will result
    in the payload being converted to a string representing that number. If
    you wish to send a true int/float, use struct.pack() to create the
    payload you require.
    qos: The quality of service level to use.
    retain: If set to true, the message will be set as the "last known
    good"/retained message for the topic.
    properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included.
    Use the Properties class.
    
    Returns a MQTTMessageInfo class, which can be used to determine whether
    the message has been delivered (using info.is_published()) or to block
    waiting for the message to be delivered (info.wait_for_publish()). The
    message ID and return code of the publish() call can be found at
    info.mid and info.rc.
    
    For backwards compatibility, the MQTTMessageInfo class is iterable so
    the old construct of (rc, mid) = client.publish(...) is still valid.
    
    rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the
    client is not currently connected.  mid is the message ID for the
    publish request. The mid value can be used to track the publish request
    by checking against the mid argument in the on_publish() callback if it
    is defined.
    
    A ValueError will be raised if topic is None, has zero length or is
    invalid (contains a wildcard), except if the MQTT version used is v5.0.  
    For v5.0, a zero length topic can be used when a Topic Alias has been set.
    
    A ValueError will be raised if qos is not one of 0, 1 or 2, or if
    the length of the payload is greater than 268435455 bytes.

client = mqtt.Client()

client.connect("localhost", 1883, 60)

client.publish('example/path', 'Hello world!', retain=True)
<paho.mqtt.client.MQTTMessageInfo at 0x7fa8440554f0>

Retrieve message

client2 = mqtt.Client()

client2.connect("localhost", 1883, 60)

def on_message(client, userdata, msg, properties=None):
    print(msg.topic+" "+str(msg.payload))

client2.on_message = on_message

client2.subscribe('example/path')

client2.loop_start()
example/path b'Hello world!'

If everything went well, we should see Hello world as output.

This is a very simple example, and Paho provides support for reconnecting and more callbacks functions, while here we only saw on_message