【问题标题】:How do I change the qos level and message retain?如何更改 qos 级别和消息保留?
【发布时间】:2019-12-09 19:46:15
【问题描述】:

您好,我有一些在 python 中用于 mqtt 发布/订阅的代码。我想更改 qos 值和消息保留,但我不知道如何更改,因为目前 qos 值始终只打印 0,我想将消息保留标志更改为 true 或 false 而不是 0。感谢所有帮助.

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

谢谢

【问题讨论】:

    标签: python-3.x mqtt paho


    【解决方案1】:

    来自 Paho Python docs

    PUBLISH()

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

    这会导致将消息发送到代理,然后从 订阅匹配主题的任何客户端的代理。它需要 以下论点:

    • topic应该发布消息的主题
    • payload 要发送的实际消息。如果没有给出,或者设置为 None,将使用零长度消息。传递一个 int 或 float 将导致 在被转换为表示该数字的字符串的有效负载中。 如果您希望发送真正的 int/float,请使用 struct.pack() 创建 您需要的有效负载
    • qos 使用的服务质量等级
    • retain 如果设置为 True,则该消息将被设置为该主题的“最后一个已知良好”/保留消息。

    要将 QOS 设置为 2 并将保留标志设置为 true,请将发布行更改为以下内容:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2021-12-27
      • 2016-02-20
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多