简体   繁体   中英

How to temporary disconnect from MQTT topics

I implemented connection to broker like:
app.py

import paho.mqtt.client as mqtt
client = mqtt.Client(client_id='my_client', clean_session=False)
my_client = MyClient(client)
try:
    my_client.start()
    while True:
        try:
            client.loop()
        except Exception as e:
            my_client.start()
except Exception as e:
    client.loop_stop()
    exit(1)

MyClient.py

class MyClient:
    def __init__(self, mqtt=None):
         self.mqtt = mqtt

    def start(self):
        self.mqtt.subscribe('some/topic')

I have part of code where I want to pause topics listening:

self.mqtt.unsubscribe('some/topic')

And later I want to subscribe back to it I want to call start() again like: self.start()

But it never subscribe again. Any idea why?

Calling start() after the exception is thrown won't work as the client is most likely not connected at that point.

You should move your subscriptions to the on_connect callback then it will always re-subscribe after the client has (re)connected

As for your original question, probably better to just set a boolean flag and use it to gate processing the message rather than unsubscribing/subscribing when you want to ignore messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM