Files
serversdownandClaude Opus 5.5 4117b056aa scratch: ring-path poller for the Runs A/B bench test
Asks the bench SFM for a Micromate's status on a fixed interval (Run B) or
once (Run A), with run_state=true, and logs each answer with its time as JSON
lines: HTTP status, seconds, the raw 0x49 code, and the detail of any refusal
(503 call-home-in-progress / could-not-connect).  Read-only on the unit;
refuses :8200.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 13:17:43 -04:00

91 lines
3.9 KiB
Python

"""Ring-path bench test, Runs A/B: ask SFM for a Micromate's status on a fixed
interval and log every answer with its time. Read-only on the unit.
python scratch/ring_path_poller.py --sfm http://127.0.0.1:8299 \
--serial UM20147 --host <modem ip> --tcp-port 9034 --interval 10 \
--log <run dir>/poller.jsonl
Run A: --count 1 (one call-up; SFM then holds the line until its 5-minute idle
hang-up or a RADIO RING). Run B: the default, every --interval seconds until
Ctrl-C. Each poll asks for the raw SUB 0x49 code (run_state=true), so a
call-home in progress shows as its own code rather than as "not monitoring".
What the log is for (spec, "Open questions this design leaves for the bench"):
a 503 "call home in progress" is SFM seeing the ring and hanging up; a 503/504
on connect while THOR's watchdog holds the line is contention; THOR's own ACH
log says when the call reached THOR.
"""
from __future__ import annotations
import argparse
import datetime
import json
import time
import urllib.error
import urllib.parse
import urllib.request
def poll_once(sfm: str, serial: str, host: str, tcp_port: int, timeout: float) -> dict:
q = urllib.parse.urlencode({"serial": serial, "host": host, "tcp_port": tcp_port, "run_state": "true"})
t0 = time.monotonic()
started = datetime.datetime.now().isoformat(timespec="milliseconds")
try:
with urllib.request.urlopen(f"{sfm}/device/monitor/status?{q}", timeout=timeout) as r:
code, body = r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
code = e.code
try:
body = json.loads(e.read() or b"{}")
except ValueError:
body = {}
except (urllib.error.URLError, TimeoutError, OSError) as e:
code, body = None, {"error": f"{type(e).__name__}: {e}"}
secs = round(time.monotonic() - t0, 2)
d = body.get("detail") if isinstance(body, dict) else None
rs = d.get("run_state") if isinstance(d, dict) else None # an error's detail is a string
return {"at": started, "secs": secs, "http": code,
"monitoring": body.get("monitoring") if isinstance(body, dict) else None,
"run_state": rs, "device_time": body.get("device_time") if isinstance(body, dict) else None,
"detail": None if code == 200 else (body.get("detail") or body.get("error"))}
def line(rec: dict) -> str:
rs = rec["run_state"]
state = f"0x{rs['code']:02X} {rs['name']}" if rs else "-"
tail = f" {rec['detail']}" if rec["detail"] else ""
return f"{rec['at']} http={rec['http']} {rec['secs']:>6} s 0x49={state} monitoring={rec['monitoring']}{tail}"
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--sfm", default="http://127.0.0.1:8299")
ap.add_argument("--serial", required=True)
ap.add_argument("--host", required=True)
ap.add_argument("--tcp-port", type=int, default=9034)
ap.add_argument("--interval", type=float, default=10.0, help="seconds between polls (start to start)")
ap.add_argument("--count", type=int, default=0, help="stop after N polls (0 = until Ctrl-C)")
ap.add_argument("--timeout", type=float, default=180.0)
ap.add_argument("--log", required=True, help="JSON lines, appended")
a = ap.parse_args()
if a.sfm.rstrip("/").endswith(":8200"):
raise SystemExit("refusing :8200 -- use the bench SFM")
n = 0
with open(a.log, "a") as f:
while True:
t0 = time.monotonic()
rec = poll_once(a.sfm.rstrip("/"), a.serial, a.host, a.tcp_port, a.timeout)
f.write(json.dumps(rec) + "\n"); f.flush()
print(line(rec), flush=True)
n += 1
if a.count and n >= a.count:
return
time.sleep(max(0.0, a.interval - (time.monotonic() - t0)))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass