Files
jens a1864a5257 log: route task/component status output through logging, not print()
AttributeChange (the common base of every ATask and component ABC) now
sets self.log = logging.getLogger(type(self).__name__), so components
no longer need to hand-type their own name into each message. Wired
logging.basicConfig() in server/brewpi.py with a bare "%(name)s:
%(message)s" formatter - Tee (see prior commit) still supplies the
"<date>T<time>:" prefix, so lines read "<date>T<time>:<component>:
<message>" without double-stamping, and third-party loggers
(websockets, asyncio) now get the same formatting for free.

Converted the print() call sites that were standing in for this in
tasks/ and components/ (leaving __main__ demo blocks and explicit
debug-dump helpers alone).
2026-07-10 22:00:04 +02:00

80 lines
1.8 KiB
Python

import logging
class Value:
def __init__(self, initial=None):
self.value = initial
self.has_changed = True
def set(self, value):
self.has_changed = self.value != value
self.value = value
def is_changed(self):
return self.has_changed
def get(self):
self.has_changed = False
return self.value
class ChangedFloat(object):
def __init__(self, on_changed, prec=2, initial=None):
self.on_changed = on_changed
self.prec = prec
self.value = initial
def set(self, value):
has_changed = True
value_rounded = round(value, self.prec)
if self.value is not None:
has_changed = self.value != value_rounded
self.value = value_rounded
if has_changed:
self.on_changed(value_rounded)
class ChangedInteger(object):
def __init__(self, on_changed, initial=None):
self.on_changed = on_changed
self.value = initial
def set(self, value):
value = round(value)
has_changed = True
if self.value is not None:
has_changed = self.value != value
self.value = value
if has_changed:
self.on_changed(value)
class AttributeChange(object):
def __init__(self):
self.callbacks = {}
# Common ancestor of every task (tasks/task.py's ATask) and component
# (Connectable/APid/APlant/ATemperatureSensor) - giving it a logger
# here makes self.log available everywhere via one change, named
# after the concrete subclass so log lines self-identify their
# component without each call site typing it out.
self.log = logging.getLogger(type(self).__name__)
def set_on_changed(self, key, on_changed):
if key not in self.callbacks:
self.callbacks[key] = [on_changed]
else:
self.callbacks[key].append(on_changed)
def __setattr__(self, key, value):
try:
old = super().__getattribute__(key)
except:
pass
super().__setattr__(key, value)
if key in self.callbacks:
for cb in self.callbacks[key]:
cb(value)