"""Chart view-models. Python works out the geometry (percent positions, nice axis ticks); the templates draw plain HTML/SVG, so there is no JS chart library to load and the charts stay crisp at phone width.""" import math from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta from .models import DeviceReport from .services.catalog import battery_percent from .services.stats import DayStats from .timeutil import Formatter, local_today, unix @dataclass class Column: label: str value: float height: float # % of plot height tip: str show_value: bool display: str partial: bool = False # today: the day isn't over yet @dataclass class Tick: label: str pct: float @dataclass class ColumnChart: key: str title: str cat: str columns: list[Column] ticks: list[Tick] summary: str def nice_ticks(vmax: float, *, integer: bool, target: int = 3) -> list[float]: vmax = vmax if vmax > 0 else 1 raw = vmax / target mag = 10 ** math.floor(math.log10(raw)) steps = (1, 2, 5, 10) if integer else (1, 2, 2.5, 5, 10) step = next(m * mag for m in steps if m * mag >= raw) if integer: step = max(1, round(step)) top = step * math.ceil(vmax / step) return [i * step for i in range(int(round(top / step)) + 1)] def column_chart( key: str, title: str, cat: str, days: list[DayStats], get: Callable[[DayStats], float], fmt: Callable[[float], str], f: Formatter, *, integer: bool = True, summary: str = "", ) -> ColumnChart: values = [get(d) for d in days] ticks = nice_ticks(max(values, default=0), integer=integer) top = ticks[-1] # Label the newest day and the highest one; the axis and tooltips carry the rest. peak = max(range(len(values)), key=lambda i: values[i], default=-1) today = local_today(f.tz) cols = [] for i, (d, v) in enumerate(zip(days, values)): partial = d.day == today cols.append( Column( label=f.day_short(d.day), value=v, height=v / top * 100 if top else 0, tip=f"{f.day(d.day)}{' so far' if partial else ''} · {fmt(v)}", show_value=(i == len(days) - 1 or i == peak) and v > 0, display=fmt(v), partial=partial, ) ) return ColumnChart( key=key, title=title, cat=cat, columns=cols, ticks=[Tick(f"{t:g}", t / top * 100) for t in ticks], summary=summary, ) @dataclass class LinePoint: x: float # 0..1000 (viewBox units) y: float # 0..300 t: int tip: str @dataclass class LineChart: path: str area: str points: list[LinePoint] yticks: list[Tick] xticks: list[Tick] empty: bool BATTERY_MIN_MV, BATTERY_MAX_MV = 3300, 4300 VB_W, VB_H = 1000, 300 def battery_chart(reports: list[DeviceReport], f: Formatter, start: datetime, end: datetime) -> LineChart: pts = [r for r in reports if r.battery_mv] span = (end - start).total_seconds() or 1 def y_of(mv: float) -> float: mv = min(max(mv, BATTERY_MIN_MV), BATTERY_MAX_MV) return VB_H - (mv - BATTERY_MIN_MV) / (BATTERY_MAX_MV - BATTERY_MIN_MV) * VB_H points = [] for r in pts: x = (r.received_at - start).total_seconds() / span * VB_W pct = battery_percent(r.battery_mv) charging = " · charging" if r.charging else "" points.append( LinePoint( x=round(x, 1), y=round(y_of(r.battery_mv), 1), t=unix(r.received_at), tip=f"{r.battery_mv / 1000:.2f} V · {pct}%{charging}|{f.when(r.received_at)}", ) ) path = " ".join(f"{'M' if i == 0 else 'L'}{p.x},{p.y}" for i, p in enumerate(points)) area = f"{path} L{points[-1].x},{VB_H} L{points[0].x},{VB_H} Z" if points else "" yticks = [ Tick(f"{mv / 1000:.1f} V", (mv - BATTERY_MIN_MV) / (BATTERY_MAX_MV - BATTERY_MIN_MV) * 100) for mv in (3400, 3600, 3800, 4000, 4200) ] days = max(1, round(span / 86400)) step = max(1, days // 5) xticks = [] for i in range(0, days + 1, step): t = start + timedelta(days=i) if t <= end: xticks.append(Tick(f.day_short(f.local(t).date()), (t - start).total_seconds() / span * 100)) return LineChart(path=path, area=area, points=points, yticks=yticks, xticks=xticks, empty=not points)