Smarthome Functionen
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import logging
  2. try:
  3. from config import APP_NAME as ROOT_LOGGER_NAME
  4. except ImportError:
  5. ROOT_LOGGER_NAME = 'root'
  6. class common_base(dict):
  7. DEFAULT_VALUES = {}
  8. def __init__(self):
  9. super().__init__(self.DEFAULT_VALUES)
  10. self['__type__'] = self.__class__.__name__
  11. #
  12. self.__callback_list__ = []
  13. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  14. def add_callback(self, key, data, callback, on_change_only=True):
  15. """
  16. key: key or None for all keys
  17. data: data or None for all data
  18. """
  19. cb_tup = (key, data, callback, on_change_only)
  20. if cb_tup not in self.__callback_list__:
  21. self.__callback_list__.append(cb_tup)
  22. def set(self, key, data):
  23. value_changed = self[key] != data
  24. self[key] = data
  25. for cb_key, cb_data, callback, on_change_only in self.__callback_list__:
  26. if cb_key is None or key == cb_key: # key fits to callback definition
  27. if cb_data is None or cb_data == self[key]: # data fits to callback definition
  28. if value_changed or not on_change_only: # change status fits to callback definition
  29. callback(self, key, self[key])
  30. class mqtt_base(common_base):
  31. def __init__(self, mqtt_client, topic):
  32. super().__init__()
  33. #
  34. self.mqtt_client = mqtt_client
  35. self.topic = topic
  36. for entry in self.topic.split('/'):
  37. self.logger = self.logger.getChild(entry)