import config import json import lirc import mqtt import report import socket import time logger = report.default_logging_config() class remote_control(mqtt.mqtt_client): def __init__(self): self.__lirc_client__ = None self.__lirc_init__() # self.__start_data__ = None # mqtt.mqtt_client.__init__(self, config.APP_NAME, config.MQTT_SERVER, 1883, config.MQTT_USER, config.MQTT_PASS) # for remote in config.SUPPORTED_REMOTES: for command in config.SUPPORTED_REMOTES[remote]: topic = config.MQTT_TOPIC + "/" + remote + "/" + command self.add_callback(topic, self.mqtt_to_lirc) def __lirc_init__(self): if self.__lirc_client__ is not None: logger.info("Closing crashed lirc client instance") self.__lirc_client__.close() logger.info("Initiating lirc connection") self.__lirc_client__ = lirc.Client() def mqtt_to_lirc(self, client, userdata, message): try: payload = json.loads(message.payload) except json.decoder.JSONDecodeError: payload = None # remote = message.topic.split("/")[-2] command = message.topic.split("/")[-1] # if payload is None: if self.__start_data__ is not None: self.__send_stop__(*self.__start_data__) self.__start_data__ = None self.__send_once__(remote, command) elif payload is True: if self.__start_data__ is not None: self.__send_stop__(*self.__start_data__) self.__start_data__ = None self.__start_data__ = remote, command self.__send_start__(remote, command) elif payload is False: if self.__start_data__ is None: self.__send_stop__(remote, command) else: self.__send_stop__(*self.__start_data__) self.__start_data__ = None def __send_once__(self, remote, command): try: self.__lirc_client__.send_once(remote, command) except (TimeoutError, socket.timeout) as e: self.__lirc_timeout_error__() else: logger.info("Sending once: %s to %s.", command, remote) def __send_start__(self, remote, command): try: self.__lirc_client__.send_start(remote, command) except (TimeoutError, socket.timeout) as e: self.__lirc_timeout_error__() else: logger.info("Sending start: %s to %s.", command, remote) def __send_stop__(self, remote, command): try: self.__lirc_client__.send_stop(remote, command) except (TimeoutError, socket.timeout) as e: self.__lirc_timeout_error__() else: logger.info("Sending stop: %s to %s.", command, remote) def __lirc_timeout_error__(self): logger.error("Timeout-Error while sending IR-Command.") self.__lirc_init__() if __name__ == '__main__': rc = remote_control() # while (True): time.sleep(30)