Search code examples
python-3.xmqttpaho

How do I change the qos level and message retain?


Hi I have some code for mqtt publish/subscribe in python. I want to change the qos value and message retain but I don't know how to because at the moment the qos value always only prints 0 and I want to change the message retain flag to either true or false and not 0. All help appreciated.

import paho.mqtt.client as mqtt
import time
class laser(mqtt.Client):
    def on_connect(self, mqttc, obj, flags, rc):
        print("rc: "+str(rc))
        print("Subscribing to topic","microscope/light_sheet_microscope/laser")
        mqttc.subscribe("microscope/light_sheet_microscope/laser")

    def on_message(self, mqttc, userdata, message):
        print("message received " ,str(message.payload.decode("utf-8")))
        print("message topic=",message.topic)
        print("message qos=",message.qos)
        print("message retain flag=",message.retain)

    def on_publish(self, mqttc, obj, mid):
        print("mid: "+str(mid))

    def on_subscribe(self, mqttc, obj, mid, granted_qos):
        print("Subscribed: "+str(mid)+" "+str(granted_qos))

    def on_log(self, mqttc, userdata, level, buf):
        print("log: ",buf)

    def run(self):
        self.connect("broker.hivemq.com", 1883, 60)

print("creating new instance")
client = laser("Laser")
client.run()

client.loop_start() #start the loop
time.sleep(2)
print("Publishing message to topic","microscope/light_sheet_microscope/laser")
client.publish("microscope/light_sheet_microscope/laser","Hello World Im a laser!")
time.sleep(2) # wait
client.loop_stop() #stop the loop

Thanks


Solution

  • From the Paho Python docs

    PUBLISH()

    publish(topic, payload=None, qos=0, retain=False)

    This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics. It takes the following arguments:

    • 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.

    To set QOS to 2 and the retained flag to true change the publish line to the following:

    client.publish("microscope/light_sheet_microscope/laser","Hello World Im a laser!",2,True)