Просмотр исходного кода

Exception handling for MQTT

master
Dirk Alders 2 лет назад
Родитель
Сommit
5425af984b
1 измененных файлов: 13 добавлений и 7 удалений
  1. 13
    7
      powerplug.py

+ 13
- 7
powerplug.py Просмотреть файл

@@ -77,7 +77,10 @@ class sispmctl(object):
77 77
     def send_state(self, output):
78 78
         topic = config.MQTT_TOPIC + "/status/" + str(output)
79 79
         logger.info("Sending Powerplug status information of plug %s to mqtt %s = %s", str(output), topic, str(self.__state__[output - 1]))
80
-        self.__mqtt_client__.publish(topic, "true" if self.__state__[output - 1] else "false")
80
+        try:
81
+            self.__mqtt_client__.publish(topic, "true" if self.__state__[output - 1] else "false")
82
+        except (socket.timeout, OSError) as e:
83
+            logger.warning("Erro while sending state information information")
81 84
 
82 85
 
83 86
 class mqtt_powerplug(object):
@@ -98,12 +101,15 @@ class mqtt_powerplug(object):
98 101
         self.__client__ = mqtt.Client("mqtt_powerplug")                         # create client object
99 102
         self.__client__.on_message = self.__receive__                           # attach function to callback
100 103
         self.__client__.username_pw_set(config.MQTT_USER, config.MQTT_PASS)     # login with credentials
101
-        self.__client__.connect(config.MQTT_SERVER, 1883)                       # establish connection
102
-        self.__client__.loop_start()                                            # start the loop
103
-        self.__topics__ = []
104
-        for subtopic in self.SUBTOPICS:
105
-            self.__topics__.append(config.MQTT_TOPIC + "/" + subtopic)
106
-            self.__client__.subscribe(self.__topics__[-1])                      # subscibe a topic
104
+        try:
105
+            self.__client__.connect(config.MQTT_SERVER, 1883)                       # establish connection
106
+            self.__client__.loop_start()                                            # start the loop
107
+            self.__topics__ = []
108
+            for subtopic in self.SUBTOPICS:
109
+                self.__topics__.append(config.MQTT_TOPIC + "/" + subtopic)
110
+                self.__client__.subscribe(self.__topics__[-1])                      # subscibe a topic
111
+        except (socket.timeout, OSError) as e:
112
+            logger.warning("Erro while setting up mqtt instance and listener")
107 113
         self.__sc__ = sispmctl(self.__client__)
108 114
 
109 115
     def __receive__(self, client, userdata, message):

Загрузка…
Отмена
Сохранить