Python MQTT on_subscribes 触发额外时间

问题描述 投票:0回答:1

我正在使用loop_start和循环。我在 on_connection 回调中订阅了 1 个主题。但是,on_subscribe 回调会被触发 2 次。然后第二个来了,下一个loop()出错了

loop: bad char in struct format

这是代码的主要部分,减去回调(只是打印语句。

    self.client.connect(self.broker, self.port, 60)
    self.client.loop_start()

    self.client.on_connect = self.onConnect
    self.client.on_publish = self.onPublish
    self.client.on_subscribe = self.on_subscribe

 
  def run(self):
    while not self.client.is_connected():
      time.sleep(1)

    self.running = True
    while(self.running):
      row = self.db.getMessage()
      if(row != None):
        message = row[2]
        topic = 'data'
        timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime())
        try:
          ret = self.client.publish(topic, message, 0)
          pass
        except Exception as ex:
          print(str(ex))
      try:
        self.client.loop(0.1)
      except Exception as ex:
        print('loop:', str(ex))

关于如何防止订阅回调以及更重要的是结构格式错误中的坏字符有什么建议吗?

python mqtt mosquitto
1个回答
0
投票

根据文档“不要混合不同的循环函数”。

您正在调用

self.client.loop_start()
,它“在后台运行一个线程来自动调用loop()”;然后,您可以在代码的循环中调用
self.client.loop(0.1)
。这将导致不可预测的结果(
loop
未设计为同时运行多次,因此不采用同步)。

正如文档所说“不再建议单独使用loop()”,我建议将

self.client.loop(0.1)
替换为
time.sleep()
或等效项。

© www.soinside.com 2019 - 2024. All rights reserved.