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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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, default_values=None):
  9. super().__init__(default_values or self.DEFAULT_VALUES)
  10. #
  11. self.__callback_list__ = []
  12. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild("devices")
  13. def add_callback(self, key, data, callback, on_change_only=False):
  14. """
  15. key: key or None for all keys
  16. data: data or None for all data
  17. """
  18. cb_tup = (key, data, callback, on_change_only)
  19. if cb_tup not in self.__callback_list__:
  20. self.__callback_list__.append(cb_tup)
  21. def set(self, key, data, block_callback=[]):
  22. if key in self.keys():
  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. if not callback in block_callback: # block given callbacks
  30. callback(self, key, self[key])
  31. else:
  32. self.logger.warning("Unexpected key %s", key)
  33. class mqtt_base(common_base):
  34. def __init__(self, mqtt_client, topic, default_values=None):
  35. super().__init__(default_values)
  36. #
  37. self.mqtt_client = mqtt_client
  38. self.topic = topic
  39. for entry in self.topic.split('/'):
  40. self.logger = self.logger.getChild(entry)