Bench: plugmeter reads the N100's metered plug (tinytuya + Home Assistant from the catalog)
gates / gates (push) Successful in 6m43s
gates / gates (push) Successful in 6m43s
scripts/bench/plugmeter.py prints watts/mA/V/kWh as CSV from the Tuya plug on the LAN (default) or from Home Assistant on demo-hp's guest. 10-minute side by side and a 3-minute control in documentation/audits/plugmeter-2026-10-13/: Home Assistant alone did not move for 3 minutes, so the LAN reader is the measurement source. No key, device id or token in the repo; secrets scan 0 hits with a positive control.
This commit is contained in:
@@ -1,3 +1,14 @@
|
||||
## 2026-10-13 (evening) — plugmeter: the N100's power plug, read from DooPlex
|
||||
|
||||
- New `scripts/bench/plugmeter.py` + `scripts/bench/README.md`: reads the Tuya meter plug the N100 runs on and prints
|
||||
CSV (`utc_time, watts, milliamps, volts, kwh_total`) every `--interval` s (default 2); `--duration`, `--once`.
|
||||
`--source tuya` (default) talks to the plug on the LAN (tinytuya 1.20.0, protocol 3.4) and forces a re-measure on
|
||||
each read; `--source ha` reads Home Assistant on demo-hp's guest. Keys and the token stay in DooPlex
|
||||
`~/.config/felhom-bench/` (700/600), never in a repo. A failed read logs to stderr and the run goes on.
|
||||
- Measured (`documentation/audits/plugmeter-2026-10-13/`): 10 min side by side, both mean ~8.4 W, median 7.2 W.
|
||||
Home Assistant alone did not change for 3 minutes — the plug reports to the cloud only when the local reader asks.
|
||||
Recommended source: tuya.
|
||||
- `documentation/operations/nodes.md`: the N100 is on a metered plug; Home Assistant on demo-hp stays installed.
|
||||
## 2026-10-13 (night) — estimator v3.1 tests
|
||||
|
||||
- `test_build_sizing_web.py` (12 tests): the bar is never below the smallest named box, its parts still sum to it
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# scripts/bench — bench tools that run on DooPlex
|
||||
|
||||
## plugmeter.py — the N100's power meter
|
||||
|
||||
The N100 demo box (`demo-felhom`) is on a Tuya Wi-Fi plug with a power meter. `plugmeter.py` reads it and
|
||||
prints CSV (`utc_time, watts, milliamps, volts, kwh_total`) every `--interval` seconds (default 2).
|
||||
|
||||
```
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --once # one reading
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --duration 600 > a.csv # 10 minutes
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --source ha --once # through Home Assistant
|
||||
```
|
||||
|
||||
- **`--source tuya` (default) — use this for measurements.** It talks to the plug on the home LAN and
|
||||
makes it re-measure on every read; a new value every 2 s. Each value is the plug's previous measurement
|
||||
(it answers a refresh with what it holds), so a row lags by about one interval. About one read in four takes
|
||||
up to 8 s instead of 2 s; the row is late, not lost.
|
||||
- **`--source ha` — the backup.** Home Assistant on demo-hp's guest (`https://ha.enkisfelhom.hu`, installed
|
||||
from the Felhom catalog) reads the plug through Tuya's cloud. **On its own it did not change for 3 minutes**
|
||||
(2026-10-13); it moves only when something makes the plug report — the tuya reader does. It keeps history and graphs. Its `felhom-bench` user is local-access-only, so the tool connects
|
||||
to the guest's LAN address and still checks the certificate by name.
|
||||
|
||||
Setup (done 2026-10-13, `documentation/audits/plugmeter-2026-10-13/`): a user venv
|
||||
(`python3 -m venv ~/.venvs/plugmeter && ~/.venvs/plugmeter/bin/pip install tinytuya`), and the files under
|
||||
`~/.config/felhom-bench/` (700; every file 600): `plug.json` (device id, local key, address, data points),
|
||||
`ha.json`, `ha.token`, and the tinytuya wizard's output. **None of them ever goes into a repo.**
|
||||
|
||||
`kwh_total` is the plug's `add_ele` counter — energy since the plug last reported to the cloud, not a
|
||||
lifetime total. Use watts × time for energy.
|
||||
|
||||
When the plug moves address or is paired again: re-run the tinytuya wizard in `~/.config/felhom-bench/`
|
||||
(credentials `TUYA_ID`, `TUYA_SECRET`, `TUYA_DEVICE_ID` from `~/.config/credentials`, region `eu`) and
|
||||
update `plug.json`. Its output prints the key — send it to a file, never to a terminal or a log.
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""plugmeter.py — read the N100 bench's metered Wi-Fi plug and print CSV.
|
||||
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --once
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --duration 600 > run.csv
|
||||
~/.venvs/plugmeter/bin/python scripts/bench/plugmeter.py --source ha --once
|
||||
|
||||
CSV columns: utc_time, watts, milliamps, volts, kwh_total.
|
||||
|
||||
Sources:
|
||||
tuya (default) the plug directly on the LAN (tinytuya, protocol 3.4). Reads
|
||||
~/.config/felhom-bench/plug.json: id, key, ip, version, dps.
|
||||
ha Home Assistant on demo-hp's guest (Tuya cloud integration). Reads
|
||||
~/.config/felhom-bench/ha.json (url, connect_ip, entities) and
|
||||
~/.config/felhom-bench/ha.token (a non-admin long-lived token).
|
||||
connect_ip sends the request to the guest on the LAN while TLS still
|
||||
checks the certificate of the url's host name: the felhom-bench user is
|
||||
"local access only", so the public (Cloudflare) path is refused.
|
||||
|
||||
Data points (read from the device 2026-10-13, documentation/audits/plugmeter-2026-10-13/):
|
||||
19 cur_power W x10, 18 cur_current mA, 20 cur_voltage V x10, 17 add_ele kWh x1000.
|
||||
kwh_total is the plug's add_ele counter: energy since the plug last reported to the Tuya
|
||||
cloud, NOT a lifetime total. It can drop back to 0. Use watts x time for energy.
|
||||
|
||||
A failed read logs one line to stderr and the loop continues. The key and the token are
|
||||
never printed. Secrets live only in ~/.config/felhom-bench/ (700/600), never in a repo.
|
||||
"""
|
||||
import argparse, datetime, http.client, json, os, socket, ssl, sys, time
|
||||
|
||||
CONF = os.path.expanduser('~/.config/felhom-bench')
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(f'{now()} plugmeter: {msg}', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')[:-4] + 'Z'
|
||||
|
||||
|
||||
class TuyaSource:
|
||||
def __init__(self):
|
||||
import tinytuya
|
||||
c = json.load(open(os.path.join(CONF, 'plug.json')))
|
||||
self.dps = c['dps']
|
||||
self.dev = tinytuya.OutletDevice(c['id'], c['ip'], c['key'], version=float(c['version']))
|
||||
self.dev.set_socketTimeout(5)
|
||||
self.dev.set_socketRetryLimit(1)
|
||||
# updatedps asks the plug to re-measure; without it status() repeats a cached reading.
|
||||
self.refresh = [int(self.dps[k][0]) for k in ('milliamps', 'watts', 'volts')]
|
||||
# The plug answers a refresh with the reading it already holds; the new one arrives later. So the
|
||||
# first read of a run can be minutes old (measured 2026-10-13: 18.7 W first, 6.8 W two seconds
|
||||
# later). Ask once now, so the first printed row is already fresh.
|
||||
self.dev.updatedps(self.refresh)
|
||||
time.sleep(1)
|
||||
|
||||
def read(self):
|
||||
self.dev.updatedps(self.refresh)
|
||||
s = self.dev.status()
|
||||
if not isinstance(s, dict) or 'dps' not in s:
|
||||
# tinytuya returns an error dict, not an exception; it never holds the key.
|
||||
raise RuntimeError(f"tuya error {s.get('Err') if isinstance(s, dict) else ''} {s.get('Error') if isinstance(s, dict) else s}")
|
||||
d = s['dps']
|
||||
|
||||
def val(name):
|
||||
dp, div = self.dps[name]
|
||||
return d[dp] / div if dp in d else None
|
||||
return val('watts'), val('milliamps'), val('volts'), val('kwh_added')
|
||||
|
||||
|
||||
class HASource:
|
||||
def __init__(self):
|
||||
c = json.load(open(os.path.join(CONF, 'ha.json')))
|
||||
self.host = c['url'].split('://', 1)[1].rstrip('/')
|
||||
self.ip = c.get('connect_ip') or self.host
|
||||
self.entities = c['entities'] # {"watts": "sensor.…", "milliamps": …, "volts": …, "kwh_total": …}
|
||||
self.token = open(os.path.join(CONF, 'ha.token')).read().strip()
|
||||
self.ctx = ssl.create_default_context()
|
||||
|
||||
def state(self, entity):
|
||||
sock = socket.create_connection((self.ip, 443), timeout=5)
|
||||
conn = http.client.HTTPSConnection(self.host, timeout=5, context=self.ctx)
|
||||
conn.sock = self.ctx.wrap_socket(sock, server_hostname=self.host) # SNI + cert check on the name
|
||||
try:
|
||||
conn.request('GET', f'/api/states/{entity}', headers={'Authorization': 'Bearer ' + self.token})
|
||||
r = conn.getresponse()
|
||||
body = r.read()
|
||||
if r.status != 200:
|
||||
raise RuntimeError(f'HA {entity}: HTTP {r.status}')
|
||||
return json.loads(body)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def read(self):
|
||||
out = []
|
||||
for name in ('watts', 'milliamps', 'volts', 'kwh_total'):
|
||||
ent = self.entities.get(name)
|
||||
if not ent:
|
||||
out.append(None)
|
||||
continue
|
||||
st = self.state(ent)
|
||||
try:
|
||||
v = float(st['state'])
|
||||
except (TypeError, ValueError):
|
||||
v = None
|
||||
if v is not None and name == 'milliamps' and st.get('attributes', {}).get('unit_of_measurement') == 'A':
|
||||
v *= 1000
|
||||
out.append(v)
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def fmt(v):
|
||||
return '' if v is None else f'{v:g}'
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
|
||||
ap.add_argument('--source', choices=('tuya', 'ha'), default='tuya')
|
||||
ap.add_argument('--interval', type=float, default=2.0, help='seconds between reads (default 2)')
|
||||
ap.add_argument('--duration', type=float, default=0, help='seconds to run; 0 = until stopped')
|
||||
ap.add_argument('--once', action='store_true', help='one read, then exit (rc 1 if it failed)')
|
||||
a = ap.parse_args()
|
||||
|
||||
src = TuyaSource() if a.source == 'tuya' else HASource()
|
||||
print('utc_time,watts,milliamps,volts,kwh_total', flush=True)
|
||||
start = time.monotonic()
|
||||
fails = 0
|
||||
while True:
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
w, ma, v, kwh = src.read()
|
||||
print(f'{now()},{fmt(w)},{fmt(ma)},{fmt(v)},{fmt(kwh)}', flush=True)
|
||||
except Exception as e: # one bad read must not end a measurement run
|
||||
fails += 1
|
||||
log(f'read failed ({type(e).__name__}: {e})')
|
||||
if a.once:
|
||||
return 1
|
||||
if a.once:
|
||||
return 0
|
||||
if a.duration and time.monotonic() - start >= a.duration:
|
||||
log(f'done, {fails} failed reads')
|
||||
return 0
|
||||
time.sleep(max(0.0, a.interval - (time.monotonic() - t0)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
sys.exit(main())
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(0)
|
||||
Reference in New Issue
Block a user