Smarthome Functionen
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

base.py 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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(__name__)
  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. 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. class mqtt_base(common_base):
  32. def __init__(self, mqtt_client, topic, default_values=None):
  33. super().__init__(default_values)
  34. #
  35. self.mqtt_client = mqtt_client
  36. self.topic = topic
  37. for entry in self.topic.split('/'):
  38. self.logger = self.logger.getChild(entry)