From 2e86bcfc7a5a21389f4f67ae77923ba1474a75ba Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Thu, 26 Nov 2026 11:36:01 +0100 Subject: [PATCH] Bench: power_ab.py measures through a solar controller's INA226 (--ina), without USB Co-Authored-By: Claude Opus 5.5 --- tools/README.md | 2 +- tools/power_ab.py | 106 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/tools/README.md b/tools/README.md index c9a28aaf..54929ef8 100644 --- a/tools/README.md +++ b/tools/README.md @@ -73,7 +73,7 @@ How it works: [docs/ota.md](../docs/ota.md). | `mesh_sniffer.py` | passive sniffer: every frame the radio hears, decoded on the host | | `preset_trace.py` | TRACE along a fixed path on a chosen radio preset | | `fw_room_smoke.py` | smoke test of a firmware room server over the air | -| `power_ab.py` | A/B current measurement with a UC96 meter (alternating cells) | +| `power_ab.py` | A/B current measurement with a UC96 meter (alternating cells); `--ina ` uses a solar controller's live INA226 instead, without USB, and saves the raw samples | | `companion_backup.py` | back up a companion (contacts, channels, settings) before flashing, diff and restore after | | `gen_node_id.py` | a node identity whose path hash collides with no known repeater | diff --git a/tools/power_ab.py b/tools/power_ab.py index d2228522..17b9a17f 100755 --- a/tools/power_ab.py +++ b/tools/power_ab.py @@ -36,6 +36,7 @@ polluted cell looks like a real regression. import argparse import glob import json +import random import re import sys import time @@ -98,6 +99,73 @@ def cbprom_sample(url, meter, device): out.get("cb_meter_last_seen_timestamp_seconds", 0.0)) +_ina = {"t": None, "i": None, "mah": 0.0} + + +def ina_sample(url): + """Live INA226 on a Chytra Budka, read from its own /sensors page. + + No counter here: the box reports instantaneous current (0.25 mA steps on its + 10 mOhm shunt), so this integrates it (trapezoid) into a synthetic mAh + counter and the rest of the tool fits it like the meter's staircase. Not via + cbprom: its `cb_solar_*` series lags the live page by minutes (25. 11. 2026 + it held 3.26 V while /sensors read 4.98 V). The shunt offset (~0.3 mA) is in + every cell alike, so it cancels in an A/B delta but not in the absolute mA. + The box serves a self-signed cert on the LAN, hence no verification. + """ + import ssl + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + # The box now and then serves the page without the INA rows (a bus read + # that lost the race, 25. 11. 2026 on the first minute of a run): retry + # those like a network error. Only a page that never shows them is fatal. + v = i = None + for _ in range(10): + try: + with urllib.request.urlopen(url, timeout=10, context=ctx) as r: + body = r.read().decode() + v = re.search(r"solar_v\s*=\s*([-\d.]+)", body) + i = re.search(r"solar_i\s*=\s*([-\d.]+)", body) + if v and i: + break + except OSError: + pass + time.sleep(1) + if not (v and i): + # An overnight run makes ~20 000 requests; one dead stretch of the box + # must not throw the whole cell away. Before the first reading there is + # nothing to hold, so that is still fatal; later, skip the gap: the next + # good sample integrates across it, and the raw series shows the hole. + if _ina["t"] is None: + raise SystemExit(f"{url} neukazuje solar_v/solar_i -- INA226 nepritomen?") + _ina["gaps"] = _ina.get("gaps", 0) + 1 + return _ina["mah"], _ina.get("v", 0.0), _ina["i"], _ina["t"] + now, amps = time.time(), float(i.group(1)) + if _ina["t"] is not None: + _ina["mah"] += (amps + _ina["i"]) / 2 * 1000.0 * (now - _ina["t"]) / 3600.0 + _ina["t"], _ina["i"], _ina["v"] = now, amps, float(v.group(1)) + # Raw (epoch, mA) for the run's JSON: the fit over an integral hides a bimodal + # cell (11.5 <-> 14 mA flips) and cannot be lined up against other logs. + _ina.setdefault("raw", []).append((round(now, 2), round(amps * 1000.0, 3))) + return _ina["mah"], _ina["v"], amps, now + + +def ina_stats(): + """Mean/SD of the raw INA samples of the cell, plus the series itself. + + Mean of samples is the honest estimator here: the fit's standard error over + an integrated series is autocorrelated nonsense (it reads +-0.00).""" + raw = _ina.get("raw") or [] + if not raw: + return {} + ma = [x[1] for x in raw] + mean = sum(ma) / len(ma) + sd = (sum((x - mean) ** 2 for x in ma) / max(1, len(ma) - 1)) ** 0.5 + return {"ina_mean_ma": round(mean, 3), "ina_sd_ma": round(sd, 3), "ina_n": len(ma), + "ina_gaps": _ina.get("gaps", 0), "ina_raw": raw} + + def meter_sample(url, meter=None, device=None): """One reading of the exporter: (capacity_mAh, volts, amps, unix_ts).""" if device: @@ -299,6 +367,9 @@ def main(): ap.add_argument("--url", default=None, help=f"exporter (vychozi {EXPORTER}, s --budka {CBPROM})") ap.add_argument("--budka", metavar="DEVICE", help="merak cte Chytra Budka: id (napr. fbfe18), seznam id pres carku, nebo any = nejcerstvejsi ramec z kterekoli; data z cbprom, vyzaduje --meter") + ap.add_argument("--ina", metavar="URL", + help="misto meraku zivy INA226 Chytre Budky, napr. https://budka.local/sensors " + "(proud se integruje, vzorkuj --poll 2)") ap.add_argument("--json", help="ulozit vysledek jako JSON") args = ap.parse_args() @@ -309,8 +380,19 @@ def main(): if args.url is None: args.url = CBPROM if args.budka else EXPORTER - # +-1 counter step over the window; through a budka the step is 10 mWh ~ 2 mAh - err_ma = (2.0 if args.budka else 1.0) * 60.0 / args.minutes + def sample_ina(): + return ina_sample(args.ina) + + def sample_meter(): + return meter_sample(args.url, args.meter, args.budka) + + sample = sample_ina if args.ina else sample_meter + if args.ina: + # no counter to quantise: one 0.25 mA LSB is the floor (offset cancels in A/B) + err_ma = 0.25 + else: + # +-1 counter step over the window; through a budka the step is 10 mWh ~ 2 mAh + err_ma = (2.0 if args.budka else 1.0) * 60.0 / args.minutes print(f"okno {args.minutes:g} min => kvantizace merice je +-{err_ma:.2f} mA na bunku") if err_ma > 1.5: print(" POZOR: to je vic, nez kolik ceka vetsina uspor. Delsi --minutes, nebo " @@ -369,7 +451,9 @@ def main(): "state": state, "tx_air_delta": None, "rx_air_delta": None, "samples": 0, "invalid": "neaplikovano"}) continue - cap0, v0, _, _ = meter_sample(args.url, args.meter, args.budka) + _ina["raw"] = [] + _ina["gaps"] = 0 + cap0, v0, _, _ = sample() t0 = time.time() print(f" start: cap={cap0:.0f} mAh, U={v0:.2f} V, stav={state}") @@ -380,8 +464,11 @@ def main(): # exactly how a good run got killed two minutes before it finished. next_beat = t0 + 60 while time.time() < deadline: - time.sleep(min(args.poll, max(0.0, deadline - time.time()))) - cap, v1, i1, _ = meter_sample(args.url, args.meter, args.budka) + # INA samples are snapshots: jitter the period so they cannot lock + # onto a periodic load (BLE advertising, rxps cycle) and alias. + period = args.poll * random.uniform(0.5, 1.5) if args.ina else args.poll + time.sleep(min(period, max(0.0, deadline - time.time()))) + cap, v1, i1, _ = sample() now = time.time() series.append((now - t0, cap)) if now >= next_beat: @@ -390,7 +477,7 @@ def main(): print(f" ... {el:.0f}/{args.minutes:g} min, +{cap-cap0:.0f} mAh, " f"zatim {(cap-cap0)/((now-t0)/3600.0):.1f} mA", flush=True) - cap1, v1, i1, _ = meter_sample(args.url, args.meter, args.budka) + cap1, v1, i1, _ = sample() series.append((time.time() - t0, cap1)) dt_h = (time.time() - t0) / 3600.0 tx1, rx1 = con.air() if con else (None, None) @@ -417,6 +504,10 @@ def main(): print(f" ==> endpoint {avg:.2f} +-{err_ma:.2f} mA | fit {fit_ma:.2f} " f"+-{se_ma:.2f} mA (rezidua {resid:.2f} mAh) @ {v1:.2f} V " f"(instant {i1*1000:.0f} mA, 10mA krok)") + st = ina_stats() if args.ina else {} + if st: + print(f" ==> INA prumer vzorku {st['ina_mean_ma']:.2f} mA, SD {st['ina_sd_ma']:.2f}, " + f"n={st['ina_n']}, mezer {st['ina_gaps']}") if abs(fit_ma - avg) > err_ma: print(" POZOR: estimatory se rozchazi vic nez chyba -- bunka nebyla " "stacionarni, zopakuj ji") @@ -430,7 +521,8 @@ def main(): "resid_mah": resid, "se_ma": se_ma, "delta_mah": dcap, "minutes": dt_h * 60, "err_ma": err_ma, "volts": v1, "state": state, "tx_air_delta": d_tx, "rx_air_delta": d_rx, - "samples": len(series)}) + "samples": len(series), "t0": t0, "t1": time.time(), + **ina_stats()}) finally: if con: con.close()