【问题标题】:Interrupt paho mqtt client to reload subscriptions中断 paho mqtt 客户端以重新加载订阅
【发布时间】:2017-10-17 13:14:55
【问题描述】:

我有一个基于配置文件订阅主题的 mqtt 客户端应用程序。比如:

def connectMQTT():
    global Connection
    Connection = Client()
    Connection.on_message = handleQuery
    for clientid in clientids.allIDs(): # clientids.allIDs() reads files to get this
        topic = '{}/{}/Q/+'.format(Basename, clientid)
        print('subscription:', topic)
        Connection.subscribe(topic)

我一直在使用它进行简单的调用,例如:

def main():
    connectMQTT()
    Connection.loop_forever()

loop_forever 将永远阻塞。但我想注意clientids.allIDs() 读取的信息何时过期,我应该重新连接强制它重新订阅。

我可以使用pyinotify 检测文件中的更改:

def filesChanged():
    # NOT SURE WHAT TO DO HERE

def watchForChanges():
    watchManager = pyinotify.WatchManager()
    notifier = pyinotify.ThreadedNotifier(watchManager, FileEventHandler(eventCallback))
    notifier.start()
    watchManager.add_watch('/etc/my/config/dir', pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE)

基本上,我需要 loop_forever(或其他一些 paho mqtt 机制)运行,直到某些信号来自 pyinotify 机器。不过,我不确定如何将这两者焊接在一起。在伪代码中,我想要类似的东西

def main():
    signal = setup_directory_change_signal()
    while True:
        connectMQTT()
        Connection.loop(until=signal)
        Connection.disconnect()

我不确定如何实现。

【问题讨论】:

  • 您查看过文档中的其他 loop 函数吗?
  • 是的,我正在使用loop_start()loop_stop() 并正在尝试使用非线程通知程序。不过还没有运气。
  • 也不需要断开连接,只需保留订阅的主题列表,然后与新列表进行比较,取消订阅旧的不需要并订阅新的

标签: python-3.x mqtt paho pyinotify


【解决方案1】:

我终于找到了以下似乎可行的解决方案。虽然我试图在另一个线程中运行通知程序并在主线程中运行 mqtt 循环,但技巧似乎是反转该设置:

def restartMQTT():
    if Connection:
        Connection.loop_stop()
    connectMQTT()
    Connection.loop_start()

class FileEventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, fileEvent):
        restartMQTT()

    def process_IN_DELETE(self, fileEvent):
        restartMQTT()


def main():
    restartMQTT()
    watchManager = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(watchManager, FileEventHandler())
    watchManager.add_watch('/etc/my/config_directory', pyinotify.IN_CREATE | pyinotify.IN_DELETE)
    notifier.loop()

connectMQTTConnection 全局中存储新连接和配置的 MQTT 客户端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多