smart_brain/base.py

47 lines
1.7 KiB
Python
Raw Normal View History

2023-01-20 08:03:06 +01:00
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)
2023-01-20 08:03:06 +01:00
self['__type__'] = self.__class__.__name__
#
self.__callback_list__ = []
self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
def add_callback(self, key, data, callback, on_change_only=False):
2023-01-20 08:03:06 +01:00
"""
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=[]):
2023-01-20 08:03:06 +01:00
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])
2023-01-20 08:03:06 +01:00
class mqtt_base(common_base):
def __init__(self, mqtt_client, topic, default_values=None):
super().__init__(default_values)
2023-01-20 08:03:06 +01:00
#
self.mqtt_client = mqtt_client
self.topic = topic
for entry in self.topic.split('/'):
self.logger = self.logger.getChild(entry)