diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 10014db..b5099ca 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -196,6 +196,17 @@ export const api = { ), /** WireView Pro II */ + /** + * Clear fault status and/or latched fault log. + * keepStatus/keepLog are 16-bit masks of bits to RETAIN; all other bits + * are cleared (0x0000 clears all, 0xFFFF keeps all). + */ + wireviewClearFault: (keepStatus: number, keepLog: number) => + post<{ ok: boolean }>("/wireview/clear-fault", { + keep_status: keepStatus, + keep_log: keepLog, + }), + /** * Firmware check: device firmware vs. the bundled image (verdict, * dfu-util availability, flash state). diff --git a/frontend/src/components/WireView/WireViewPanel.tsx b/frontend/src/components/WireView/WireViewPanel.tsx index 4cd471f..9b169c6 100644 --- a/frontend/src/components/WireView/WireViewPanel.tsx +++ b/frontend/src/components/WireView/WireViewPanel.tsx @@ -51,9 +51,13 @@ function pluck(history: WireViewSample[], key: keyof WireViewSample): number[] { function FaultBadge({ label, mask, + onClear, + clearing, }: { label: string; mask: number; + onClear?: () => void; + clearing?: boolean; }) { const faults = decodeFaults(mask); return ( @@ -68,13 +72,25 @@ function FaultBadge({ {label} - 0 ? "text-red-400" : "text-zinc-600" - }`} - > - 0x{mask.toString(16).toUpperCase().padStart(4, "0")} - +
+ {mask !== 0 && onClear && ( + + )} + 0 ? "text-red-400" : "text-zinc-600" + }`} + > + 0x{mask.toString(16).toUpperCase().padStart(4, "0")} + +
{faults.length > 0 ? (
@@ -174,6 +190,7 @@ function InfoItem({ } export function WireViewPanel({ info, sample, history, flash }: Props) { + const [clearing, setClearing] = useState<"status" | "log" | null>(null); const [firmware, setFirmware] = useState(null); const [firmwareError, setFirmwareError] = useState(null); const [confirming, setConfirming] = useState( @@ -232,6 +249,26 @@ export function WireViewPanel({ info, sample, history, flash }: Props) { } } + async function handleClear(which: "status" | "log") { + setClearing(which); + try { + // Keep-mask semantics: 0x0000 clears, 0xFFFF keeps. + await api.wireviewClearFault( + which === "status" ? 0x0000 : 0xffff, + which === "log" ? 0x0000 : 0xffff, + ); + toast.success( + which === "status" ? "Fault status cleared" : "Fault log cleared", + ); + } catch (err) { + toast.error( + err instanceof Error ? err.message : "Failed to clear fault", + ); + } finally { + setClearing(null); + } + } + if (!sample) { return (
@@ -370,10 +407,14 @@ export function WireViewPanel({ info, sample, history, flash }: Props) { handleClear("status")} + clearing={clearing === "status"} /> handleClear("log")} + clearing={clearing === "log"} />
diff --git a/nvcurve/server.py b/nvcurve/server.py index 3fa61f0..e05d53e 100644 --- a/nvcurve/server.py +++ b/nvcurve/server.py @@ -842,6 +842,14 @@ class ConfigUpdateRequest(BaseModel): gpu_index: int = 0 +class WireViewClearFaultRequest(BaseModel): + """16-bit masks of the fault bits to RETAIN; every other bit is cleared + (0x0000 clears all, 0xFFFF keeps all).""" + + keep_status: int + keep_log: int + + class FanCurvePoint(BaseModel): temp_c: int fan_pct: int @@ -1878,6 +1886,46 @@ async def api_wireview(): } +@app.post("/api/wireview/clear-fault", tags=["WireView"], responses=R_AUTH) +async def api_wireview_clear_fault(req: WireViewClearFaultRequest): + """Clear the WireView fault status and/or the latched fault log. + + keep_status/keep_log are 16-bit masks of the bits to retain; all other + bits are cleared. Serial transport only — in hwmon mode the wireviewd + daemon owns the port and the masks are read-only from here. + """ + if not (0 <= req.keep_status <= 0xFFFF and 0 <= req.keep_log <= 0xFFFF): + raise HTTPException( + status_code=422, + detail="keep_status/keep_log must be 16-bit masks (0x0000-0xFFFF)", + ) + wv = _state["wireview"] + device = wv["device"] + if device is None: + raise HTTPException(status_code=503, detail="No WireView connected") + if device.transport != "serial": + raise HTTPException( + status_code=501, + detail=( + "Fault clearing requires the serial transport " + "(wireviewd owns the port in hwmon mode)" + ), + ) + if not await _run(device.clear_faults, req.keep_status, req.keep_log): + raise HTTPException( + status_code=502, detail="Failed to send clear command to device" + ) + # Re-read immediately so clients see the cleared masks without waiting + # for the next poll tick. + sample = await _run(device.read_sample) + if wv["device"] is device and sample is not None: + wv["last_sample"] = sample + await _broadcast( + wv["clients"], {"type": "sample", "info": wv["info"], "sample": sample} + ) + return {"ok": True} + + # ── WireView Pro II firmware (check + DFU flash) ───────────────────────────── diff --git a/nvcurve/wireview.py b/nvcurve/wireview.py index 044b99f..b8071da 100644 --- a/nvcurve/wireview.py +++ b/nvcurve/wireview.py @@ -18,6 +18,7 @@ Protocol notes (matches the firmware's DEVICE_STR_LEN=32 layout): import logging import os import struct +import threading import time from typing import Any @@ -58,6 +59,7 @@ CMD_READ_VENDOR_DATA = 0x01 CMD_READ_UID = 0x02 CMD_READ_SENSOR_VALUES = 0x04 CMD_READ_CONFIG = 0x05 +CMD_CLEAR_FAULTS = 0x0E CMD_SCREEN_CHANGE = 0x0C CMD_READ_BUILD_INFO = 0x0D # Top-level command (not a screen subcommand): restarts the device into its @@ -294,6 +296,11 @@ class WireViewSerialDevice: self._uid = "" self._build = "" self._config_version = -1 + # Serializes all port access: the poller, the clear-fault endpoint and + # the watchdog all open the port from thread-pool threads, and a second + # opener mid-transaction desyncs the stream (the device interleaves its + # welcome handshake into the other side's frame). + self._lock = threading.RLock() # ── Identity ── @@ -424,6 +431,21 @@ class WireViewSerialDevice: return None return parse_sensor_struct(buf) + def clear_faults(self, keep_status: int, keep_log: int) -> bool: + """Clear fault status and/or the latched fault log. + + keep_status/keep_log are 16-bit masks of the bits to RETAIN; every + other bit is cleared (0x0000 clears all, 0xFFFF keeps all). The + device answers no reply, so success means the command was written + to the port. + """ + if not self._connected: + return False + cmd = struct.pack( + " bool: """Restart the device into the STM32 DFU bootloader (0483:df11). @@ -461,6 +483,10 @@ class WireViewSerialDevice: def _read_welcome(self) -> str | None: """Assert RTS and read the NUL-terminated welcome string the device answers with. Null when nothing (or no terminator) arrives in time.""" + with self._lock: + return self._read_welcome_unlocked() + + def _read_welcome_unlocked(self) -> str | None: ser = self._open_port() if ser is None: return None @@ -498,6 +524,10 @@ class WireViewSerialDevice: """Open the port, send cmd, read exactly response_size bytes (one second budget), close the port. None when the port is unavailable or the reply is incomplete.""" + with self._lock: + return self._transaction_unlocked(cmd, response_size) + + def _transaction_unlocked(self, cmd: bytes, response_size: int) -> bytes | None: ser = self._open_port() if ser is None: return None @@ -596,6 +626,11 @@ class WireViewHwmonDevice: def close(self) -> None: self._connected = False + def clear_faults(self, keep_status: int, keep_log: int) -> bool: + """Not supported: the wireviewd daemon owns the serial port in hwmon + mode, so the fault masks cannot be cleared from here.""" + return False + def enter_bootloader(self) -> bool: """Not supported: the wireviewd daemon owns the serial port in hwmon mode, and nvcurve does not speak the daemon protocol.""" diff --git a/tests/test_wireview.py b/tests/test_wireview.py index 28b2591..05be0b5 100644 --- a/tests/test_wireview.py +++ b/tests/test_wireview.py @@ -297,6 +297,10 @@ def test_hwmon_device(): dev = wv.WireViewHwmonDevice(p) check("hwmon connect", dev.connect()) check("hwmon node exists", dev.node_exists()) + check( + "hwmon clear unsupported", + dev.clear_faults(0x0000, 0x0000) is False, + ) s = dev.read_sample() check("hwmon sample", s is not None) if s: @@ -456,6 +460,100 @@ def test_serial_device_protocol(): t.join(timeout=2) +def test_serial_clear_faults(): + """CMD_CLEAR_FAULTS sends 0x0E + two little-endian uint16 keep masks + (0x0000 clears, 0xFFFF keeps), matching the protocol table: + clear fault and log -> 0x0E 00 00 00 00 + clear fault only, keep log -> 0x0E 00 00 FF FF + clear log only, keep fault -> 0x0E FF FF 00 00 + """ + import pty + import queue + import threading + + master, slave = pty.openpty() + slave_path = os.ttyname(slave) + received: queue.Queue = queue.Queue() + + def run(): + while True: + try: + cmd = os.read(master, 1) + except OSError: + return + if not cmd: + return + if cmd[0] == wv.CMD_CLEAR_FAULTS: + rest = b"" + while len(rest) < 4: + try: + chunk = os.read(master, 4 - len(rest)) + except OSError: + return + if not chunk: + return + rest += chunk + received.put(cmd + rest) + continue + resp = { + wv.CMD_READ_VENDOR_DATA: bytes([0xEF, 0x05, 1]), + wv.CMD_READ_CONFIG: bytes([0, 0, 1, 0]), + wv.CMD_READ_UID: bytes(12), + wv.CMD_READ_BUILD_INFO: _build_info_struct( + "WireView Pro II", "test" + ), + }.get(cmd[0]) + if resp: + try: + os.write(master, resp) + except OSError: + return + + t = threading.Thread(target=run, daemon=True) + t.start() + try: + dev = wv.WireViewSerialDevice(slave_path) + check("clear: connect", dev.connect()) + + cases = [ + ("clear fault and log", 0x0000, 0x0000, bytes([0x0E, 0, 0, 0, 0])), + ( + "clear fault only, keep log", + 0x0000, + 0xFFFF, + bytes([0x0E, 0, 0, 0xFF, 0xFF]), + ), + ( + "clear log only, keep fault", + 0xFFFF, + 0x0000, + bytes([0x0E, 0xFF, 0xFF, 0, 0]), + ), + ] + for name, keep_status, keep_log, expected in cases: + check(f"clear: {name} sent", dev.clear_faults(keep_status, keep_log)) + try: + got = received.get(timeout=2) + except queue.Empty: + check(f"clear: {name} bytes", False) + continue + check(f"clear: {name} bytes", got == expected) + + # Out-of-range masks are clamped to 16 bits, not sent verbatim. + check("clear: out-of-range sent", dev.clear_faults(0x1FFFF, 0x1FFFF)) + try: + got = received.get(timeout=2) + check("clear: out-of-range clamped", got == bytes([0x0E, 0xFF, 0xFF, 0xFF, 0xFF])) + except queue.Empty: + check("clear: out-of-range clamped", False) + + dev.close() + check("clear: rejected when disconnected", not dev.clear_faults(0, 0)) + finally: + os.close(master) + t.join(timeout=2) + + def test_serial_device_rejected_product(): """An unsupported product id is rejected and memoized via .rejected.""" responses = {wv.CMD_READ_VENDOR_DATA: bytes([0xEF, 0x07, 1])} @@ -530,6 +628,7 @@ def main() -> int: test_hwmon_device() test_hwmon_legacy_attrs() test_serial_device_protocol() + test_serial_clear_faults() test_serial_device_rejected_product() test_serial_device_no_response() test_serial_transport_missing_pyserial()