12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import logging
-
- try:
- from config import APP_NAME as ROOT_LOGGER_NAME
- except ImportError:
- ROOT_LOGGER_NAME = 'root'
-
-
- class common_base(dict):
- DEFAULT_VALUES = {}
-
- def __init__(self, default_values=None):
- super().__init__(default_values or self.DEFAULT_VALUES)
- self['__type__'] = self.__class__.__name__
- #
- self.__callback_list__ = []
- self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild("devices")
-
- def add_callback(self, key, data, callback, on_change_only=False):
- """
- key: key or None for all keys
- data: data or None for all data
- """
- cb_tup = (key, data, callback, on_change_only)
- if cb_tup not in self.__callback_list__:
- self.__callback_list__.append(cb_tup)
-
- def set(self, key, data, block_callback=[]):
- if key in self.keys():
- value_changed = self[key] != data
- self[key] = data
- for cb_key, cb_data, callback, on_change_only in self.__callback_list__:
- if cb_key is None or key == cb_key: # key fits to callback definition
- if cb_data is None or cb_data == self[key]: # data fits to callback definition
- if value_changed or not on_change_only: # change status fits to callback definition
- if not callback in block_callback: # block given callbacks
- callback(self, key, self[key])
- else:
- self.logger.warning("Unexpected key %s", key)
-
-
- class mqtt_base(common_base):
- def __init__(self, mqtt_client, topic, default_values=None):
- super().__init__(default_values)
- #
- self.mqtt_client = mqtt_client
- self.topic = topic
- for entry in self.topic.split('/'):
- self.logger = self.logger.getChild(entry)
|