main
John Lauer Require a qualified case-temperature bound in firmware and control panel 6d89978
"""Bounded serial transport for the proposed adom.load/1 firmware protocol.

No automatic reconnect or replay of an arm/current request. This is a host
implementation, not evidence that a physical MCU implements the protocol.
"""
import json
import math
import secrets


class LinkError(RuntimeError):
    pass


class SerialLoad:
    def __init__(self, stream, serial):
        self.stream, self.serial = stream, serial
        self.seq = 0
        self.boot = None
        self.owner = secrets.token_hex(12)

    def request(self, cmd, **fields):
        if self.seq >= 0xFFFFFFFF:
            raise LinkError("Sequence exhausted; a fresh device boot is required")
        self.seq += 1
        packet = dict(id=self.seq, cmd=cmd, **fields)
        if self.boot is not None:
            packet.update(boot=self.boot, owner=self.owner)
        wire = json.dumps(packet, separators=(",", ":"), allow_nan=False).encode() + b"\n"
        if len(wire) > 256:
            raise LinkError("Request exceeds firmware frame limit")
        try:
            if self.stream.write(wire) != len(wire):
                raise LinkError("Incomplete serial write; command outcome unknown")
            raw = self.stream.read_until(b"\n", 2049)
            if not raw.endswith(b"\n") or len(raw) > 2048:
                raise LinkError("Missing or oversized reply; command outcome unknown")
            def reject_constant(value):
                raise ValueError("Non-finite reply: " + value)
            result = json.loads(raw, parse_constant=reject_constant)
            if not isinstance(result, dict) or type(result.get("id")) is not int or result["id"] != self.seq:
                raise LinkError("Reply sequence mismatch; command outcome unknown")
            if result.get("ok") is not True:
                raise LinkError(str(result.get("error", "Device rejected command")))
            if self.boot is not None and result.get("boot") != self.boot:
                raise LinkError("Device reset; explicit reconnect required")
            return result
        except (OSError, ValueError, TypeError) as exc:
            raise LinkError(str(exc)) from exc

    def connect(self):
        d = self.request("identify")
        if d.get("protocol") != "adom.load/1" or d.get("serial") != self.serial:
            raise LinkError("Wrong instrument identity or unsupported protocol")
        if not isinstance(d.get("boot"), str) or not 8 <= len(d["boot"]) <= 32:
            raise LinkError("Missing boot identity")
        floor = d.get("last_sequence")
        if type(floor) is not int or not 0 <= floor <= 0xFFFFFFFF - 4:
            raise LinkError("Missing or exhausted device sequence floor")
        self.seq = max(self.seq, floor)
        self.boot = d["boot"]
        self.request("claim")
        self.request("off")
        state = self.status()
        if state["enabled"] or state["dac_code"] != 0:
            raise LinkError("Startup OFF was not confirmed")
        return state

    def status(self):
        d = self.request("status")
        for key in ("sensors_valid", "assembly_qualified"):
            if type(d.get(key)) is not bool:
                raise LinkError("Missing instrument qualification: " + key)
        for key in ("volts", "amps", "case_c"):
            if key not in d:
                raise LinkError("Missing telemetry: " + key)
            value = d[key]
            if value is None and not d["sensors_valid"]:
                continue
            if type(value) not in (float, int) or not math.isfinite(value):
                raise LinkError("Invalid telemetry: " + key)
        # Older firmware remains monitorable while OFF, but lacks temperature qualification.
        d.setdefault("temperature_qualified", False)
        d.setdefault("case_margin_c", None)
        d.setdefault("case_upper_c", None)
        if type(d["temperature_qualified"]) is not bool:
            raise LinkError("Invalid temperature qualification")
        margin, upper = d["case_margin_c"], d["case_upper_c"]
        if margin is not None and (type(margin) not in (float, int) or not math.isfinite(margin) or margin <= 0):
            raise LinkError("Invalid case-temperature allowance")
        if d["temperature_qualified"] and margin is None:
            raise LinkError("Missing qualified case-temperature allowance")
        if d["temperature_qualified"] and d["sensors_valid"]:
            if type(upper) not in (float, int) or not math.isfinite(upper) or abs(upper - (d["case_c"] + margin)) > 0.0001:
                raise LinkError("Invalid case-temperature upper bound")
        elif upper is not None:
            raise LinkError("Unqualified temperature bound must be unknown")
        for key in ("requested_a", "applied_a", "power_limit_w", "sample_age_ms"):
            value = d.get(key)
            if type(value) not in (float, int) or not math.isfinite(value):
                raise LinkError("Invalid telemetry: " + key)
        if type(d.get("rpm_valid")) is not bool:
            raise LinkError("Missing fan feedback validity")
        if d["rpm_valid"]:
            if type(d.get("rpm")) not in (int, float) or not math.isfinite(d["rpm"]) or not 0 <= d["rpm"] <= 10000:
                raise LinkError("Invalid fan RPM")
        elif d.get("rpm") is not None:
            raise LinkError("Unqualified fan feedback must use null RPM")
        if d.get("state") not in ("OFF", "ARMED", "RUNNING", "FAULT") or type(d.get("enabled")) is not bool:
            raise LinkError("Invalid device state")
        if type(d.get("dac_code")) is not int or not 0 <= d["dac_code"] <= 4095:
            raise LinkError("Invalid DAC telemetry")
        if type(d["sample_age_ms"]) is not int or not 0 <= d["sample_age_ms"] <= 0xFFFFFFFF:
            raise LinkError("Invalid device sample age")
        if d["sensors_valid"] and d["sample_age_ms"] > 50:
            raise LinkError("Device sensor sample is stale")
        if not d["sensors_valid"] or not d["assembly_qualified"] or not d["temperature_qualified"]:
            if d["state"] not in ("OFF", "FAULT") or d["enabled"] or d["dac_code"] != 0 or d["applied_a"] != 0:
                raise LinkError("Unqualified instrument must confirm output OFF")
        if upper is not None and upper >= 55 and (d["state"] in ("ARMED", "RUNNING") or d["enabled"]):
            raise LinkError("Active load exceeds case-temperature upper bound")
        if not 0 < d["power_limit_w"] <= 5:
            raise LinkError("This bring-up adapter requires a device ceiling of at most 5 W")
        return d

    def close(self):
        self.stream.close()