Selaa lähdekoodia

Deny callbacks while connecting

master
Dirk Alders 2 vuotta sitten
vanhempi
commit
3d9fc164b4
1 muutettua tiedostoa jossa 7 lisäystä ja 0 poistoa
  1. 7
    0
      __init__.py

+ 7
- 0
__init__.py Näytä tiedosto

@@ -30,6 +30,7 @@ __DEPENDENCIES__ = []
30 30
 import logging
31 31
 import paho.mqtt.client as paho
32 32
 import socket
33
+import time
33 34
 
34 35
 try:
35 36
     from config import APP_NAME as ROOT_LOGGER_NAME
@@ -40,6 +41,7 @@ logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
40 41
 
41 42
 class mqtt_client(object):
42 43
     def __init__(self, name, host, port=1883, username=None, password=None):
44
+        self.__block_add_callbacks__ = False
43 45
         logger.info("Initiating mqtt client instance")
44 46
         self.__callbacks__ = {}
45 47
         self.__client__ = paho.Client(name)                                     # create client object
@@ -56,6 +58,9 @@ class mqtt_client(object):
56 58
         self.__client__.loop_start()                                            # start the loop
57 59
 
58 60
     def add_callback(self, topic, callback):
61
+        while self.__block_add_callbacks__:
62
+            time.sleep(.1)
63
+        logger.debug("Adding callback for topic %s", topic)
59 64
         self.__callbacks__[topic] = callback
60 65
         self.__client__.subscribe(topic)
61 66
 
@@ -65,9 +70,11 @@ class mqtt_client(object):
65 70
     def __on_connect__(self, client, userdata, flags, rc):
66 71
         logger.debug("Connect with rc=%d", rc)
67 72
         if rc == 0:
73
+            self.__block_add_callbacks__ = True
68 74
             logger.debug("Registering topics...")
69 75
             for topic in self.__callbacks__:
70 76
                 self.__client__.subscribe(topic)
77
+            self.__block_add_callbacks__ = False
71 78
  
72 79
     def __on_disconnect__(self, client, flags, rc):
73 80
         logger.warning("Disconnect with rc=%d", rc)

Loading…
Peruuta
Tallenna