# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """1-minute aggregates. Gauges (a level: power, temperature): time-weighted mean, min, max and the last value. A sample mean would overweight bursts of fast updates, so each value counts for as long as it held. A gauge's last value carries into the next window, so a steady sensor that reports rarely still has a mean. Counters (a growing total: energy): the delta over the window. A total that goes down is a meter reset or replacement: the new reading counts from zero instead of a negative delta. Unavailable: seconds of the window without a valid value are reported, so the platform can tell "0 W" from "unknown". """ from dataclasses import dataclass, field @dataclass class _Gauge: value: float | None = None # the value holding since `since` since: float = 0.0 area: float = 0.0 # value x seconds within the window valid_s: float = 0.0 lo: float | None = None hi: float | None = None n: int = 0 def _hold(self, until: float): if self.value is not None and until > self.since: self.area += self.value * (until - self.since) self.valid_s += until - self.since self.since = until @dataclass class _Counter: last: float | None = None delta: float = 0.0 resets: int = 0 n: int = 0 @dataclass class Aggregator: interval: int = 60 start: float = 0.0 gauges: dict = field(default_factory=dict) counters: dict = field(default_factory=dict) def begin(self, ts: float): self.start = ts - ts % self.interval def sample(self, asset: str, kind: str, value: float | None, ts: float): """value None = unavailable / unknown / not a number.""" if kind == "counter": c = self.counters.setdefault(asset, _Counter()) if value is None: return if c.last is not None: if value >= c.last: c.delta += value - c.last else: c.delta += value c.resets += 1 c.last, c.n = value, c.n + 1 return g = self.gauges.setdefault(asset, _Gauge(since=self.start)) g._hold(max(ts, self.start)) g.value = value if value is not None: g.lo = value if g.lo is None else min(g.lo, value) g.hi = value if g.hi is None else max(g.hi, value) g.n += 1 def flush(self, end: float) -> list[dict]: """Records for [start, end); the next window starts at end.""" span = end - self.start out = [] for asset, g in sorted(self.gauges.items()): g._hold(end) rec = {"asset": asset, "kind": "gauge", "n": g.n, "unavailable_s": round(span - g.valid_s, 3)} if g.valid_s > 0: rec.update(mean=g.area / g.valid_s, min=g.lo if g.lo is not None else g.value, max=g.hi if g.hi is not None else g.value, last=g.value) out.append(rec) # carry the holding value; min/max start from it self.gauges[asset] = _Gauge(value=g.value, since=end, lo=g.value, hi=g.value) for asset, c in sorted(self.counters.items()): out.append({"asset": asset, "kind": "counter", "delta": c.delta, "last": c.last, "resets": c.resets, "n": c.n}) self.counters[asset] = _Counter(last=c.last) self.start = end return out