From 5974ec1c8b0a82344e5172a85c4113f456cd9111 Mon Sep 17 00:00:00 2001 From: Dirk Alders Date: Wed, 28 Sep 2022 18:21:09 +0200 Subject: [PATCH] Enable / disable implemented --- example_config/config.py | 2 ++ exec_command.py | 29 ++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/example_config/config.py b/example_config/config.py index a55c92c..1ddcf16 100644 --- a/example_config/config.py +++ b/example_config/config.py @@ -9,6 +9,8 @@ MQTT_USER = "user" MQTT_PASS = "pass" MQTT_SERVER = "host" +ENABLED_TOPIC = 'topic' + EXEC_LIST = { 'topic_1': { 'key': 'key', # Give a key or None to compare plain DATA diff --git a/exec_command.py b/exec_command.py index 7b73f6a..f9f0128 100644 --- a/exec_command.py +++ b/exec_command.py @@ -24,12 +24,24 @@ bell_log.addHandler(my_handler) class exec_command(mqtt.mqtt_client): def __init__(self): - self.__block_execution__ = False + self.__enabled__ = True mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS) + self.add_callback(config.ENABLED_TOPIC + '/set', self.set_enabled) for topic in config.EXEC_LIST: self.add_callback(topic, self.mqtt_rx) # Start a pseudo process self.process = subprocess.Popen(["sleep", "0"]) + self.publish_states() + + def set_enabled(self, client, userdata, message): + try: + payload = json.loads(message.payload) + except: + logger.exception("Error decoding json mqtt message") + else: + if self.__enabled__ != payload: + self.__enabled__ = payload + self.publish_states() def exec_command(self, cmd, message): self.process = subprocess.Popen(cmd.split(" ")) @@ -56,10 +68,16 @@ class exec_command(mqtt.mqtt_client): except AttributeError: logger.exception("payload seems to be no dictionary") if data is None or payload == data: - if self.process.poll() is None: - self.process.kill() - logger.debug("Starting execution in background...") - self.exec_command(config.EXEC_LIST[message.topic]['command'], message) + if self.__enabled__: + if self.process.poll() is None: + self.process.kill() + logger.debug("Starting execution in background...") + self.exec_command(config.EXEC_LIST[message.topic]['command'], message) + else: + logger.info("Execution is disabled") + + def publish_states(self): + self.send(config.ENABLED_TOPIC, json.dumps(self.__enabled__)) if __name__ == '__main__': @@ -69,6 +87,7 @@ if __name__ == '__main__': # while True: time.sleep(30) + ec.publish_states() try: ec.join() finally: