Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

python - Paho mqtt on internet disconnect not running callback

I have this mqtt class

class MQTT():
    def __init__(self):
        # Observer.__init__(self) # DON'T FORGET THIS

        self.mqttClient = paho.Client(client_id=constants.MQTT_CLIENT_ID)
        self.mqttClient.username_pw_set(username=constants.MQTT_BROKER_USERNAME, password=constants.MQTT_BROKER_PASSWORD)

        # assign mqtt event callbacks
        self.mqttClient.on_message = self.on_message
        self.mqttClient.on_connect = self.on_connect
        self.mqttClient.on_disconnect = self.on_disconnect
        self.mqttClient.on_socket_close = self.on_disconnect
        self.mqttClient.on_log = self.on_log

   def on_disconnect(self,client, userdata, rc):
        log("MQTT DISCONNECT:",client, userdata, rc)

and then

mqtt = MQTT()

If i run my code it work perfectly but then i have to run some functions when internet connection is lost. So for that i am using on_disconnect and after running code if turn of network nothing happen. I want some call back to run on Internet connection lost. Do we have any ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

on_disconnect is the right callback for this - the question is when it gets called?

If the network connection is lost your client will only notice it at its next attempt of transmission. So if the client is not about to publish something (or acknowledge a subscription which was received just before the connection dropped) the next transmission will be the PINGREQ

By default keepalive is set to 60 - that means your client will send a PINGREQ every 60 seconds if no other control package was sent within this time interval.

So the on_disconnect callback will be called, it just does not happen as fast as you expected. Try a lower keepalive to improve on this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...