Browse Source

Deny callbacks while connecting

master
Dirk Alders 2 years ago
parent
commit
3d9fc164b4
1 changed files with 7 additions and 0 deletions
  1. 7
    0
      __init__.py

+ 7
- 0
__init__.py View File

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

Loading…
Cancel
Save