46 rader
1.5 KiB
Python
46 rader
1.5 KiB
Python
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):
|
|
super().__init__(self.DEFAULT_VALUES)
|
|
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=True):
|
|
"""
|
|
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):
|
|
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
|
|
callback(self, key, self[key])
|
|
|
|
|
|
class mqtt_base(common_base):
|
|
def __init__(self, mqtt_client, topic):
|
|
super().__init__()
|
|
#
|
|
self.mqtt_client = mqtt_client
|
|
self.topic = topic
|
|
for entry in self.topic.split('/'):
|
|
self.logger = self.logger.getChild(entry)
|