Esempio n. 1
0
class MyLogger:
    def __init__(self, mqtt=False, mqtt_conf="/conf/mqtt_conf.txt"):
        self.mqtt = mqtt

        if mqtt:
            config_loader = ConfigurationLoader(mqtt_conf)
            broker = config_loader.load_configuration(
                'mqtt_broker')['mqtt_broker']
            self.publisher = MQTTClient('logger', broker)
            self.publisher.DEBUG = True
            self.publisher.MSG_QUEUE_MAX = 0

        self.rtc = RTC()
        self.colors = {
            "DEBUG": "\033[0m",
            "RESET": "\033[0m",
            "WARNING": "\033[35m",
            "ERROR": "\033[33m",
            "CRITICAL": "\033[31m",
            "INFO": "\033[32m"
        }

    def log(self, level, caller, *message):
        timestamp_tuple = self.rtc.datetime()
        timestamp = "{}/{}/{} {}:{}:{}".format(
            timestamp_tuple[2], timestamp_tuple[1], timestamp_tuple[0],
            timestamp_tuple[4], timestamp_tuple[5], timestamp_tuple[6])
        if message:
            log = "{} [{}]: [{}] {}".format(timestamp, level, caller,
                                            message[0])
        else:
            message = caller
            log = "{} [{}]: {}".format(timestamp, level, message)

        try:
            sys.stdout.write(self.colors[level])
            print(log)
            sys.stdout.write(self.colors["RESET"])
            if level != 'DEBUG' and level != 'INFO' and self.mqtt:
                self._send_over_mqtt("log" + level, log)
        except:
            print(log)

    def _send_over_mqtt(self, topic, log):
        try:
            self.publisher.ping()
            self.publisher.publish(topic, log, qos=1)
        except:
            try:
                self.publisher.connect()
                self.publisher.publish(topic, log, qos=1)
            except:
                None
Esempio n. 2
0
class Updater:
    def __init__(self, config_file):
        self.config_loader = ConfigurationLoader(config_file)
        configs = self.config_loader.load_configuration(
            'check_delay', 'broker', 'topic', 'mqtt_id',
            'installed_version_file', 'mqtt_logger_conf')
        self.check_delay = int(configs['check_delay'])
        self.logger = MyLogger(True, configs['mqtt_logger_conf'])
        self.mqtt_client = MQTTClient(configs['mqtt_id'], configs['broker'])
        self.mqtt_client.DEBUG = True
        self.mqtt_client.set_callback(self.read_update)
        self.mqtt_topic = configs['topic']

    def read_update(self, topic, msg, retained, duplicate):
        print(json.loads(msg))
        self.reset_retained()

    def reset_retained(self):
        try:
            self.mqtt_client.publish(self.mqtt_topic, '', retain=True)
        except:
            None

    def fetch_update(self):
        mqtt_client = self.mqtt_client
        if not self._connected_to_mqtt():
            self.logger.log('WARNING', 'Updater', 'Reconnecting to the broker')
            try:
                mqtt_client.connect()
                self.mqtt_client.subscribe(self.mqtt_topic)
                self.logger.log('DEBUG', 'Updater',
                                'Reconnected to the broker')
            except:
                self.logger.log('ERROR', 'Updater',
                                'Broker reconnection error!')

        try:
            mqtt_client.check_msg()
        except:
            None

    def _connected_to_mqtt(self):
        try:
            self.mqtt_client.ping()
            return True
        except:
            return False
class SwitchReader:
    def __init__(self, config_file='/config/switch.txt'):
        config_loader = ConfigurationLoader(config_file)
        configs = config_loader.load_configuration('mqtt_broker', 'mqtt_topic',
                                                   'mqtt_id', 'switch_pin',
                                                   'switch_update_period')
        self.config_file = config_file
        self.switch_update_period = int(configs['switch_update_period'])
        self.mqtt_client = MQTTClient(configs['mqtt_id'],
                                      configs['mqtt_broker'])
        self.mqtt_client.DEBUG = True
        self.mqtt_topic = configs['mqtt_topic']
        self.switch_pin_num = int(configs['switch_pin'])
        self.switch_pin = Pin(self.switch_pin_num, Pin.IN)
        self.id = configs['mqtt_id']
        self.mqtt_broker = configs['mqtt_broker']
        self.logger = MyLogger(False)
        self.logger.log('DEBUG', self.id,
                        'Connecting to {}...'.format(self.mqtt_broker))
        try:
            self.mqtt_client.connect()
            self.logger.log('INFO', self.id,
                            'Reconnected to {}'.format(self.mqtt_broker))
        except:
            self.logger.log(
                'ERROR', self.id,
                'Connection failure to {}'.format(self.mqtt_broker))
        self.last_switch_position = self.switch_pin.value()
        self.mqtt_messages_sent = 0
        self.debounce_time = 0.5
        self.timer = None
        self.init_timer()

    def init_timer(self):
        self.deinit_timer()
        self.timer = Timer(-1)
        self.timer.init(period=self.switch_update_period,
                        mode=Timer.ONE_SHOT,
                        callback=lambda t: self.loop())

    def loop(self):
        self.read_switch()
        self.init_timer()

    def deinit_timer(self):
        if isinstance(self.timer, Timer):
            self.timer.deinit()
        self.timer = None

    def read_switch(self):
        switch_position = self.switch_pin.value()
        if switch_position != self.last_switch_position:
            self.last_switch_position = switch_position
            self.notify_hub()
            self.deinit_timer()
            sleep(self.debounce_time)

    def notify_hub(self):
        if not self._connected_to_broker():
            try:
                self.mqtt_client.connect()
                self.logger.log('INFO', self.id,
                                'Reconnected to {}'.format(self.mqtt_broker))
            except:
                self.logger.log(
                    'ERROR', self.id,
                    'Connection failure to {}'.format(self.mqtt_broker))

        try:
            '''
			if self.mqtt_messages_sent > 3:
				self.reset_mqtt_connection()
			'''
            self.mqtt_client.publish(topic=self.mqtt_topic,
                                     msg='pressed',
                                     qos=1)
            self.logger.log('INFO', self.id, 'hub successfully notified')
            self.mqtt_messages_sent += 1
            self.reset_mqtt_connection()
        except Exception as e:
            self.logger.log('ERROR', self.id,
                            "Can't notify the hub; {}".format(e))

    def reset_mqtt_connection(self):
        self.mqtt_client.disconnect()
        sleep(0.1)
        self.mqtt_client.connect()
        self.mqtt_messages_sent = 0

    def _connected_to_broker(self):
        try:
            self.mqtt_client.ping()
            return True
        except:
            return False

    def edit_configuration(self, key, value):
        try:
            with open(self.config_file, 'rb') as file:
                configs = json.load(file)
        except Exception as e:
            self.logger.log('ERROR', self.__class__.__name__,
                            "Can't open configuration file; {}".format(e))
            return False

        configs[key] = value

        try:
            with open(self.config_file, 'wb') as file:
                json.dump(configs, file)
        except Exception as e:
            self.logger.log('ERROR', self.__class__.__name__,
                            "Can't save configuration; {}".format(e))
            return False

        return True