Smarthome Functionen
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

base.py 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. self['__type__'] = self.__class__.__name__
  11. #
  12. self.__callback_list__ = []
  13. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild("devices")
  14. def add_callback(self, key, data, callback, on_change_only=False):
  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, block_callback=[]):
  23. if key in self.keys():
  24. value_changed = self[key] != data
  25. self[key] = data
  26. for cb_key, cb_data, callback, on_change_only in self.__callback_list__:
  27. if cb_key is None or key == cb_key: # key fits to callback definition
  28. if cb_data is None or cb_data == self[key]: # data fits to callback definition
  29. if value_changed or not on_change_only: # change status fits to callback definition
  30. if not callback in block_callback: # block given callbacks
  31. callback(self, key, self[key])
  32. else:
  33. self.logger.warning("Unexpected key %s", key)
  34. class mqtt_base(common_base):
  35. def __init__(self, mqtt_client, topic, default_values=None):
  36. super().__init__(default_values)
  37. #
  38. self.mqtt_client = mqtt_client
  39. self.topic = topic
  40. for entry in self.topic.split('/'):
  41. self.logger = self.logger.getChild(entry)