fix: address PR review — flash state race, error paths, test robustness, nits

- server.py: claim the flash (state=bootloader) before spawning the task so
  the concurrent-request guard is effective immediately; guard the bundled
  image existence in the flash endpoint; single device.info() call per
  endpoint; 400 for refused flashes (409 stays for already-running);
  remove stale nvcurve-wireview-fw-*.bin temp files at startup
- wireview_firmware.py: drain stderr in its own reader thread (a full pipe
  buffer would have hung the flash until timeout); chunked stdout reads
  instead of per-character read(2); BuildStruct field checks in dataclass
  order
- wireview.py: document the intentional 0xF1 overlap between CMD_BOOTLOADER
  and SCREEN_RESUME_UPDATES (different command namespaces)
- tests: check() now fails loudly under pytest (optional import, standalone
  runs unaffected); explicit reader-thread sync in test_enter_bootloader;
  less brittle flash-progress assertion; self-documenting checksum
  corruption in test_hex_parser
- frontend: refreshFirmware in useCallback + effect deps; NaN% guard on
  flash.progress; explicit clear/keep masks in handleClear; WS firmware
  message reuses WireViewFlashProgress via Pick
- docs: clarify that the dfu-util :leave modifier is what makes the device
  exit the bootloader and reboot; document the 400 vs 409 API contract;
  README now mentions per-pin readings, pin-imbalance gauge and fault
  clearing
This commit is contained in:
ARIA committed 2026-10-05 20:40:05 +02:00
1 parent dbb6856a6d
commit 6e87dcf862
8 files changed
+104 -48

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ NVCurve brings MSI Afterburner-style per-point voltage-frequency curve control t
> **Blackwell GPU memory** — This is a specialized fork with extended memory offset support (up to +3000 MHz) for Blackwell GPUs (RTX 50-series). \
> **Fan Controls** — There is an additional "Fans" tab to setup a customized fan curve, controlling all fans or individual fans. \
> **Dashboard** — The default tab is an Dashboard with additional information (PCIe link speed, VBIOS information, Max Core Clock, Throttle Reason and much much more.) \
> **WireView Pro II** — Native monitoring of the Thermal Grizzly WireView Pro II 12VHPWR connector: a dedicated tab shows live temperature, power and current readings — no external exporter or kernel module required. It also raises a big warning in the app header (visible on all tabs) when the current between two power pins diverges by more than 2 A — the signature of a bad pin contact (faulty cable/adapter) that can overheat and melt the connector. The tab includes a firmware check/update: it compares the device firmware against the bundled image and can flash it over USB DFU (requires `dfu-util`). The host needs a one-time setup (udev rule + port access, see [WireView Pro II Setup](docs/WireView.md)); after that the device is auto-detected over USB and the tab only appears while it is connected. \
> **WireView Pro II** — Native monitoring of the Thermal Grizzly WireView Pro II 12VHPWR connector: a dedicated tab shows live temperature, power and current readings — including per-pin values, the pin-imbalance spread, and the (clearable) device fault status — no external exporter or kernel module required. It also raises a big warning in the app header (visible on all tabs) when the current between two power pins diverges by more than 2 A — the signature of a bad pin contact (faulty cable/adapter) that can overheat and melt the connector. The tab includes a firmware check/update: it compares the device firmware against the bundled image and can flash it over USB DFU (requires `dfu-util`). The host needs a one-time setup (udev rule + port access, see [WireView Pro II Setup](docs/WireView.md)); after that the device is auto-detected over USB and the tab only appears while it is connected. \
> **Authentication** — For production deployment, I added authentication with bcrypt hashing to allow only one or multiple people to have access. \
> Installing the pre-built PyPI package will NOT include these features. You must build from source.
+2 -2
View File
@@ -90,7 +90,7 @@ Flashing requires:
- the `dfu-util` package (`sudo apt install dfu-util` / `sudo dnf install dfu-util` / …) — the card shows a warning when it is missing;
- the udev rule above, which already covers the DFU bootloader (`0483:df11`).
The flash procedure: NVCurve sends the bootloader command over the serial port, the device reboots into its STM32 DFU bootloader (`0483:df11`), the bundled Intel-HEX image is flattened to a raw binary (gaps padded with `0xFF`) and downloaded with `dfu-util -d 0483:df11 -a 0 -s 0x08000000:leave -D <image>`. The device reboots on its own and the watchdog reconnects it; the card then re-checks and shows the new firmware. Progress is streamed live over the WebSocket.
The flash procedure: NVCurve sends the bootloader command over the serial port, the device reboots into its STM32 DFU bootloader (`0483:df11`), the bundled Intel-HEX image is flattened to a raw binary (gaps padded with `0xFF`) and downloaded with `dfu-util -d 0483:df11 -a 0 -s 0x08000000:leave -D <image>`. The `:leave` modifier tells the device to exit the bootloader after the download, so it reboots into the new firmware on its own and the watchdog reconnects it; the card then re-checks and shows the new firmware. Progress is streamed live over the WebSocket.
> [!WARNING]
> Flashing restarts the device into its bootloader and rewrites its flash. A power loss or unplug mid-flash can leave the device unbootable until it is reflashed manually. This is unofficial software, not affiliated with Thermal Grizzly — flash at your own risk.
@@ -98,7 +98,7 @@ The flash procedure: NVCurve sends the bootloader command over the serial port,
API:
- `GET /api/wireview/firmware` — device vs. bundled firmware, the verdict (`newer` | `same` | `unknown` | `downgrade` | `product_mismatch` | `too_old_for_noctua`), `dfu-util` availability, and the flash state;
- `POST /api/wireview/firmware/flash` — `{"override": false}`; `override=true` is required for a downgrade or identical build. Returns `409` when the flash is refused or already running.
- `POST /api/wireview/firmware/flash` — `{"override": false}`; `override=true` is required for a downgrade or identical build. Returns `400` when the flash is refused (product mismatch, Noctua floor, downgrade/same without `override=true`) and `409` when a flash is already running.
## Pin current imbalance warning
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { api } from "../../api/client.js";
import { ConfirmDialog } from "../common/ConfirmDialog.js";
@@ -203,7 +203,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
flash.state === "waiting" ||
flash.state === "flashing";
async function refreshFirmware() {
const refreshFirmware = useCallback(async () => {
try {
setFirmware(await api.wireviewFirmware());
setFirmwareError(null);
@@ -212,7 +212,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
err instanceof Error ? err.message : "Failed to load firmware state",
);
}
}
}, []);
const hasSample = sample !== null;
// Fetch the firmware check when a device appears (the panel early-returns
@@ -222,7 +222,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
// body (rule false-positive on async fetch).
// eslint-disable-next-line react-hooks/set-state-in-effect
if (hasSample) refreshFirmware();
}, [hasSample]);
}, [hasSample, refreshFirmware]);
// After a flash the device reboots and re-enumerates; re-check once it is
// back so the verdict reflects the new firmware.
@@ -232,7 +232,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
refreshFirmware();
}, 3000);
return () => clearTimeout(t);
}, [flash.state]);
}, [flash.state, refreshFirmware]);
async function startFlash(override: boolean) {
setConfirming(null);
@@ -253,10 +253,10 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
setClearing(which);
try {
// Keep-mask semantics: 0x0000 clears, 0xFFFF keeps.
await api.wireviewClearFault(
which === "status" ? 0x0000 : 0xffff,
which === "log" ? 0x0000 : 0xffff,
);
const clear = 0x0000, keep = 0xffff;
const statusMask = which === "status" ? clear : keep;
const logMask = which === "status" ? keep : clear;
await api.wireviewClearFault(statusMask, logMask);
toast.success(
which === "status" ? "Fault status cleared" : "Fault log cleared",
);
@@ -508,7 +508,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
<div className="flex items-center justify-between text-xs text-zinc-400">
<span>{flash.status || "Starting…"}</span>
<span className="font-mono">
{Math.round(flash.progress * 100)}%
{Math.round((flash.progress ?? 0) * 100)}%
</span>
</div>
<div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden">
+4 -6
View File
@@ -249,9 +249,7 @@ export interface WireViewFirmwareState {
export type WireViewWsMessage =
| { type: "unavailable" }
| { type: "sample"; info: WireViewInfo; sample: WireViewSample }
| {
type: "firmware";
state: WireViewFlashProgress["state"];
progress: number;
status: string;
};
// Flat payload: the flash progress fields are re-declared (not nested) to
// match the WS message shape; keep in sync with WireViewFlashProgress.
| ({ type: "firmware" } &
Pick<WireViewFlashProgress, "state" | "progress" | "status">);
+30 -17
View File
@@ -25,8 +25,7 @@ from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from . import __version__
from . import auth
from . import __version__, auth
from .config import Config, default_config, tls_enabled
from .hal.dashboard import get_dashboard_info
from .hal.fans import (
@@ -540,6 +539,11 @@ async def lifespan(app: FastAPI):
# ── WireView Pro II detection ─────────────────────────────────────────────
# Independent of GPU discovery: the tab appears whenever the connector
# monitor is attached, and the watchdog handles hot-plug afterwards.
# Remove stale firmware temp files left behind if a previous run was
# killed (SIGKILL) between writing and unlinking them.
for stale in Path(tempfile.gettempdir()).glob("nvcurve-wireview-fw-*.bin"):
with suppress(OSError):
stale.unlink()
try:
await _wireview_connect()
except Exception as exc:
@@ -1929,10 +1933,9 @@ async def api_wireview_clear_fault(req: WireViewClearFaultRequest):
# ── WireView Pro II firmware (check + DFU flash) ─────────────────────────────
def _wireview_device_firmware(device) -> tuple[int | None, str | None]:
"""(version, build string) of the connected device, version None when
def _device_firmware_version(info: dict) -> tuple[int | None, str | None]:
"""(version, build string) from a device info dict, version None when
unparsable."""
info = device.info()
try:
version = int(info["firmware_version"])
except (TypeError, ValueError):
@@ -2021,8 +2024,10 @@ async def api_wireview_firmware():
device_version: int | None = None
device_build: str | None = None
device_info = None
if device is not None:
device_version, device_build = await _run(_wireview_device_firmware, device)
device_info = await _run(device.info)
device_version, device_build = _device_firmware_version(device_info)
# Re-read the bundled image: it may have been swapped on disk.
image = None
@@ -2035,13 +2040,12 @@ async def api_wireview_firmware():
image_error = str(exc)
verdict = None
if image is not None and device is not None:
info = device.info()
if image is not None and device_info is not None:
verdict = await _run(
evaluate,
image,
info["vendor_id"],
info["product_id"],
device_info["vendor_id"],
device_info["product_id"],
device_version,
parse_build_timestamp(device_build),
)
@@ -2101,16 +2105,22 @@ async def api_wireview_firmware_flash(req: WireViewFirmwareFlashRequest):
detail="dfu-util not found. Install the 'dfu-util' package and try again.",
)
image_path = bundled_firmware_path()
if not image_path.is_file():
raise HTTPException(
status_code=500,
detail="The bundled firmware image is missing from the installation.",
)
try:
image = await _run(read_firmware_info, bundled_firmware_path())
image = await _run(read_firmware_info, image_path)
except FirmwareImageError as exc:
raise HTTPException(
status_code=500,
detail=f"Could not parse the bundled firmware image: {exc}",
) from exc
info = device.info()
device_version, device_build = await _run(_wireview_device_firmware, device)
info = await _run(device.info)
device_version, device_build = _device_firmware_version(info)
verdict = await _run(
evaluate,
image,
@@ -2121,12 +2131,12 @@ async def api_wireview_firmware_flash(req: WireViewFirmwareFlashRequest):
)
if verdict == VERDICT_PRODUCT_MISMATCH:
raise HTTPException(
status_code=409,
status_code=400,
detail="The bundled firmware does not match this device. Nothing was flashed.",
)
if verdict == VERDICT_TOO_OLD_FOR_NOCTUA:
raise HTTPException(
status_code=409,
status_code=400,
detail=(
"The bundled firmware predates Noctua Edition support and cannot be "
"flashed to this device. Nothing was flashed."
@@ -2134,14 +2144,17 @@ async def api_wireview_firmware_flash(req: WireViewFirmwareFlashRequest):
)
if verdict in (VERDICT_DOWNGRADE, VERDICT_SAME) and not req.override:
raise HTTPException(
status_code=409,
status_code=400,
detail=(
"The bundled firmware is not newer than the device firmware. "
"Retry with override=true to flash anyway."
),
)
fw.update(state="idle", progress=0.0, status="Starting…")
# Claim the flash before spawning the task: the task only starts when
# this coroutine yields, so a concurrent request must see a non-idle
# state here for the guard above to be effective.
fw.update(state="bootloader", progress=0.0, status="Starting…")
wv["flash_task"] = asyncio.create_task(_wireview_firmware_flash())
return {"ok": True}
+3
View File
@@ -66,6 +66,9 @@ CMD_READ_BUILD_INFO = 0x0D
# STM32 DFU bootloader (USB 0483:df11) for firmware flashing.
CMD_BOOTLOADER = 0xF1
# Screen subcommand value; intentionally overlaps CMD_BOOTLOADER (0xF1) —
# it is only ever sent as a subcommand after CMD_SCREEN_CHANGE, never as a
# top-level command, so the two namespaces cannot collide.
SCREEN_RESUME_UPDATES = 0xF1
# ── Wire layout ───────────────────────────────────────────────────────────────
+25 -8
View File
@@ -147,13 +147,13 @@ def read_firmware_info(hex_path: str | Path) -> FirmwareImageInfo:
if not mem:
raise FirmwareImageError("HEX file does not contain data records.")
build_struct = min(mem) + BUILD_STRUCT_OFFSET
if build_struct + VERSION_OFFSET_IN_BUILD_STRUCT not in mem:
raise FirmwareImageError("BuildStruct firmware version byte not found.")
if (
build_struct + VENDOR_ID_OFFSET_IN_BUILD_STRUCT not in mem
or build_struct + PRODUCT_ID_OFFSET_IN_BUILD_STRUCT not in mem
):
raise FirmwareImageError("BuildStruct vendor/product id not found.")
if build_struct + VERSION_OFFSET_IN_BUILD_STRUCT not in mem:
raise FirmwareImageError("BuildStruct firmware version byte not found.")
build_string: str | None = None
build_info_base = build_struct + BUILD_INFO_OFFSET_IN_BUILD_STRUCT
@@ -390,16 +390,20 @@ class DfuUtilFlasher:
raise FirmwareFlashError(f"Could not run dfu-util: {exc}") from exc
stdout_parts: list[str] = []
stderr_parts: list[str] = []
def _read_stdout() -> None:
# dfu-util redraws its progress bar with '\r', so read
# char-by-char and surface the latest percentage as it arrives.
# dfu-util redraws its progress bar with '\r', so track the
# current line and surface its latest percentage as it arrives.
# Read in chunks (one read(2) per 256 chars instead of per
# character) while keeping the per-character line tracking.
line: list[str] = []
while True:
ch = proc.stdout.read(1) # type: ignore[union-attr]
if ch == "":
chunk = proc.stdout.read(256) # type: ignore[union-attr]
if chunk == "":
break
stdout_parts.append(ch)
stdout_parts.append(chunk)
for ch in chunk:
if ch in "\r\n":
m = _PROGRESS_RE.search("".join(line))
if m and progress_cb is not None:
@@ -408,18 +412,31 @@ class DfuUtilFlasher:
else:
line.append(ch)
def _read_stderr() -> None:
# Drain stderr concurrently: a full pipe buffer would block
# dfu-util and hang the flash until the timeout fires.
while True:
chunk = proc.stderr.read(4096) # type: ignore[union-attr]
if chunk == "":
break
stderr_parts.append(chunk)
reader = threading.Thread(target=_read_stdout, daemon=True)
stderr_reader = threading.Thread(target=_read_stderr, daemon=True)
reader.start()
stderr_reader.start()
try:
proc.wait(timeout=timeout_s)
except subprocess.TimeoutExpired:
proc.kill()
reader.join(timeout=5)
stderr_reader.join(timeout=5)
raise FirmwareFlashError(
f"dfu-util did not finish within {timeout_s:.0f}s."
) from None
reader.join(timeout=5)
stderr = proc.stderr.read() if proc.stderr else ""
stderr_reader.join(timeout=5)
stderr = "".join(stderr_parts)
stdout = "".join(stdout_parts)
downloaded = "File downloaded successfully" in (stdout + stderr)
+29 -4
View File
@@ -21,6 +21,11 @@ from unittest import mock
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
try:
import pytest # type: ignore[import-unresolved] # optional: not installed for standalone runs
except ImportError: # standalone run without pytest installed
pytest = None
from nvcurve import wireview as wv # noqa: E402
from nvcurve import wireview_firmware as wf # noqa: E402
@@ -36,6 +41,10 @@ def check(name: str, cond: bool) -> None:
else:
FAIL += 1
print(f" FAIL {name}")
# Fail loudly under pytest (standalone runs rely on the FAIL count
# and main()'s exit code).
if pytest is not None:
pytest.fail(name)
def _hex_line(addr: int, data: bytes, record_type: int = 0) -> str:
@@ -128,8 +137,10 @@ def test_hex_parser():
check("hex segment address", mem2 == {0x100: 0x42})
# A bad checksum must be rejected — a corrupt image must never flash.
# Corrupt the record by forcing its checksum byte to 0x00.
bad = _hex_line(0x0000, bytes([0x00, 0x60]))
bad = bad[:-2] + ("00" if bad[-2:] != "00" else "01")
assert bad[-2:] != "00" # the correct checksum of this line is non-zero
bad = bad[:-2] + "00"
path3 = _write_hex(tmp, [bad])
try:
wf._parse_hex_to_memory_map(path3)
@@ -281,8 +292,10 @@ class _FakeStderr:
def __init__(self, text: str):
self._text = text
def read(self) -> str:
return self._text
def read(self, n: int | None = None) -> str:
# The flasher drains stderr in a read() loop until EOF.
out, self._text = self._text, ""
return out
class _FakeProc:
@@ -341,7 +354,12 @@ def test_dfu_flash():
wf.DfuUtilFlasher.flash(bin_path, 0x08000000,
progress_cb=progress.append)
check("flash no error", True)
check("flash progress", progress == [0.0, 0.25, 0.5, 1.0])
check(
"flash progress",
len(progress) >= 2
and progress[-1] == 1.0
and all(a <= b for a, b in zip(progress, progress[1:], strict=False)),
)
args = popen.call_args.args[0]
check("flash args",
args == ["dfu-util", "-d 0483:df11", "-a", "0",
@@ -410,8 +428,12 @@ def test_enter_bootloader():
master, slave = pty.openpty()
slave_path = os.ttyname(slave)
received: queue.Queue = queue.Queue()
reader_started = threading.Event()
def run():
# Signal that the reader is alive and about to enter its read loop,
# so the test can wait for it before the first command is written.
reader_started.set()
while True:
try:
cmd = os.read(master, 1)
@@ -439,6 +461,9 @@ def test_enter_bootloader():
t = threading.Thread(target=run, daemon=True)
t.start()
try:
# Wait until the reader thread is actually reading, so the first
# command from the device cannot be missed.
check("boot: reader ready", reader_started.wait(timeout=5))
dev = wv.WireViewSerialDevice(slave_path)
check("boot: connect", dev.connect())
check("boot: enter", dev.enter_bootloader())