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
class WifiManager: def __init__(self, config_file, networks_file): self.config_loader = ConfigurationLoader(config_file) self.wlan = network.WLAN(network.STA_IF) self.wlan.active(False) sleep(0.5) self.wlan.active(True) sleep(0.5) self.wlan.disconnect() configs = self.config_loader.load_configuration( 'check_delay', 'mqtt_conf_file') self.check_delay = int(configs['check_delay']) mqtt_conf_file = configs['mqtt_conf_file'] self.logger = MyLogger(mqtt=True, mqtt_conf=mqtt_conf_file) self.networks_file = networks_file def scan(self): try: with open(self.networks_file, 'rb') as file: saved_networks = json.load(file) networks_ssids = list(saved_networks.keys()) except Exception: try: self.logger.log('ERROR', 'WifiManager', 'Error loading networks file.') except OSError: None raise OSError("Error loading networks file.") try: scan_results = [str(result[0]) for result in self.wlan.scan()] except OSError: self.logger.log("ERROR", "WifiManager", "No networks!") scan_results = list() available_networks = [ network for network in scan_results and networks_ssids ] try: self.logger.log( 'INFO', 'WifiManager', 'Available networks: {}'.format(available_networks)) except OSError: None return available_networks, saved_networks def connect(self, available_networks, networks): for network_ssid in available_networks: self.logger.log("DEBUG", 'WifiManager', 'Trying connection to {}'.format(network_ssid)) self.wlan.connect(network_ssid, networks[network_ssid]) while self.wlan.status() is network.STAT_CONNECTING: sleep(0.250) if self.wlan.status() == network.STAT_GOT_IP: return network_ssid return None def check_connection(self): if not self.wlan.status() is network.STAT_GOT_IP: available_networks, saved_networks = self.scan() ssid = self.connect(available_networks, saved_networks) try: if ssid: self.logger.log( 'INFO', 'WifiManager', 'Connected to: {}; IP:{}'.format( ssid, self.wlan.ifconfig()[0])) else: self.logger.log('ERROR', 'WifiManager', 'Not connected') except OSError as oe: print(str(oe))