Merge pull request 'feat: wireview firmware check + DFU flash, fault clearing, pin-imbalance gauge' (#19) from feat/wireview-firmware-flash-faults into main

Reviewed-on: #19
This commit was merged in pull request #19.
This commit is contained in:
Pakobbix committed 2026-10-05 18:40:35 +00:00
commit 84eb8bc44d
14 files changed
+10014 -22

No files matched your search

+1
View File
@@ -26,6 +26,7 @@ test: ## Run the test suite
$(UV) run python tests/test_security.py
$(UV) run python tests/test_rm_power.py
$(UV) run python tests/test_wireview.py
$(UV) run python tests/test_wireview_firmware.py
$(UV) run python tests/test_processes.py
clean: ## Remove build artifacts
+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 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.
+26
View File
@@ -74,6 +74,32 @@ ls -l /dev/wireview-pro2 # -> /dev/ttyACM0
With the device plugged in, start (or restart) the NVCurve server. The **WireView** tab appears in the web UI and `GET /api/wireview` returns the device info and live samples. The tab disappears when the device is unplugged and reappears on re-plug — no restart needed.
## Firmware check and update
The WireView tab has a **Firmware** card that compares the device's firmware (version + build date, read from the device) against the image bundled with NVCurve (`nvcurve/firmware/TG-WV-PRO2-FW.hex`, v05, build `20260902_0741`) and can flash it over USB DFU.
Comparison rules (same as the official client and wireview-linux):
- the image must match the device's product — the Noctua Edition (product `06`) runs the Pro II (`05`) firmware, so a Pro II image is accepted for it;
- an image without a build date of 2026-09-02 or later is refused for a Noctua Edition (that build added Noctua support);
- version first, then build date: a **downgrade** or an **identical** build is refused unless you explicitly confirm it ("Flash anyway"); a newer image offers a normal "Update firmware" button.
Flashing requires:
- the **serial transport** (in hwmon mode the `wireviewd` daemon owns the port, so the card shows a hint instead of a button);
- 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 `: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.
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 `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
The 12 VHPWR connector is the most fragile part of a PC's power delivery: if one power pin has a bad contact (worn cable, faulty adapter, loose plug), the remaining pins are forced to carry the missing current. Under heavy load this can overheat and melt the connector — in rare cases even start a fire.
+1
View File
@@ -332,6 +332,7 @@ function MainApp({
info={wireview.info}
sample={wireview.sample}
history={wireview.history}
flash={wireview.flash}
/>
) : (
<div className="flex gap-4 items-start w-full">
+26
View File
@@ -9,6 +9,7 @@ import type {
FanPoint,
DashboardInfo,
ProcessListResponse,
WireViewFirmwareState,
} from "../types.js";
export class ApiError extends Error {
@@ -193,4 +194,29 @@ export const api = {
"/report-bug",
{ title, body },
),
/** 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).
*/
wireviewFirmware: () => get<WireViewFirmwareState>("/wireview/firmware"),
/**
* Flash the bundled firmware over USB DFU. override=true is required when
* the bundled firmware is not newer than the device firmware.
*/
wireviewFlashFirmware: (override: boolean) =>
post<{ ok: boolean }>("/wireview/firmware/flash", { override }),
};
@@ -1,11 +1,27 @@
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { api } from "../../api/client.js";
import { ConfirmDialog } from "../common/ConfirmDialog.js";
import { GaugeCard } from "../Monitor/GaugeCard.js";
import { fmt } from "../../utils/units.js";
import type { WireViewInfo, WireViewSample } from "../../types.js";
import type {
WireViewFlashProgress,
WireViewFirmwareState,
WireViewInfo,
WireViewSample,
} from "../../types.js";
interface Props {
info: WireViewInfo | null;
sample: WireViewSample | null;
history: WireViewSample[];
flash: WireViewFlashProgress;
}
// "v05 (TG-WV-PRO2-FW_20260902_0741)" — version padded like the official app.
function formatFw(version: number | null, build: string | null): string {
const v = version !== null ? `v${String(version).padStart(2, "0")}` : "?";
return build ? `${v} (${build})` : v;
}
// Per-pin current rating of the 12 VHPWR connector (A). The bar's
@@ -35,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 (
@@ -52,13 +72,25 @@ function FaultBadge({
<span className="text-xs text-zinc-500 uppercase tracking-wider">
{label}
</span>
<span
className={`text-xs font-mono ${
faults.length > 0 ? "text-red-400" : "text-zinc-600"
}`}
>
0x{mask.toString(16).toUpperCase().padStart(4, "0")}
</span>
<div className="flex items-center gap-2">
{mask !== 0 && onClear && (
<button
onClick={onClear}
disabled={clearing}
className="px-2 py-0.5 rounded text-[11px] font-medium bg-red-500/20 border border-red-500/50 text-red-200 hover:bg-red-500/30 disabled:opacity-50 disabled:cursor-not-allowed"
title={`Clear ${label.toLowerCase()}`}
>
{clearing ? "Clearing…" : "Clear"}
</button>
)}
<span
className={`text-xs font-mono ${
faults.length > 0 ? "text-red-400" : "text-zinc-600"
}`}
>
0x{mask.toString(16).toUpperCase().padStart(4, "0")}
</span>
</div>
</div>
{faults.length > 0 ? (
<div className="flex flex-wrap gap-1">
@@ -157,7 +189,86 @@ function InfoItem({
);
}
export function WireViewPanel({ info, sample, history }: Props) {
export function WireViewPanel({ info, sample, history, flash }: Props) {
const [clearing, setClearing] = useState<"status" | "log" | null>(null);
const [firmware, setFirmware] = useState<WireViewFirmwareState | null>(null);
const [firmwareError, setFirmwareError] = useState<string | null>(null);
const [confirming, setConfirming] = useState<null | "update" | "override">(
null,
);
const [starting, setStarting] = useState(false);
const flashActive =
flash.state === "bootloader" ||
flash.state === "waiting" ||
flash.state === "flashing";
const refreshFirmware = useCallback(async () => {
try {
setFirmware(await api.wireviewFirmware());
setFirmwareError(null);
} catch (err) {
setFirmwareError(
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
// without a sample, so no reset is needed when the device goes away).
useEffect(() => {
// setState calls happen after the await, not synchronously in the effect
// body (rule false-positive on async fetch).
// eslint-disable-next-line react-hooks/set-state-in-effect
if (hasSample) refreshFirmware();
}, [hasSample, refreshFirmware]);
// After a flash the device reboots and re-enumerates; re-check once it is
// back so the verdict reflects the new firmware.
useEffect(() => {
if (flash.state !== "done" && flash.state !== "failed") return;
const t = setTimeout(() => {
refreshFirmware();
}, 3000);
return () => clearTimeout(t);
}, [flash.state, refreshFirmware]);
async function startFlash(override: boolean) {
setConfirming(null);
setStarting(true);
try {
await api.wireviewFlashFirmware(override);
toast.success("Firmware update started");
} catch (err) {
toast.error(
err instanceof Error ? err.message : "Failed to start firmware update",
);
} finally {
setStarting(false);
}
}
async function handleClear(which: "status" | "log") {
setClearing(which);
try {
// Keep-mask semantics: 0x0000 clears, 0xFFFF keeps.
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",
);
} catch (err) {
toast.error(
err instanceof Error ? err.message : "Failed to clear fault",
);
} finally {
setClearing(null);
}
}
if (!sample) {
return (
<div className="bg-zinc-900 rounded-lg p-10 text-center text-zinc-500 flex flex-col items-center gap-2">
@@ -226,11 +337,11 @@ export function WireViewPanel({ info, sample, history }: Props) {
max={13}
/>
<GaugeCard
label="Fan Duty"
value={fmt.pct(sample.fan_duty_pct)}
history={pluck(history, "fan_duty_pct")}
color="#fb923c"
max={100}
label="Pin Imbalance"
value={`${sample.pin_imbalance_a.toFixed(2)} A`}
history={pluck(history, "pin_imbalance_a")}
color="#fbbf24"
max={4}
/>
</div>
</div>
@@ -258,7 +369,7 @@ export function WireViewPanel({ info, sample, history }: Props) {
<div className="text-xs text-zinc-500 uppercase tracking-wider font-semibold pb-3 border-b border-zinc-800">
Temperatures
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-3">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3 mt-3">
<GaugeCard
label="Temp In"
value={fmt.celsius(sample.temp_in_c, 1)}
@@ -287,14 +398,31 @@ export function WireViewPanel({ info, sample, history }: Props) {
color="#a78bfa"
max={90}
/>
<GaugeCard
label="Fan Duty"
value={fmt.pct(sample.fan_duty_pct)}
history={pluck(history, "fan_duty_pct")}
color="#fb923c"
max={100}
/>
</div>
</div>
{/* ── Faults + device info ───────────────────────────────────── */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex flex-col gap-3">
<FaultBadge label="Fault Status" mask={sample.fault_status} />
<FaultBadge label="Fault Log (latched)" mask={sample.fault_log} />
<FaultBadge
label="Fault Status"
mask={sample.fault_status}
onClear={() => handleClear("status")}
clearing={clearing === "status"}
/>
<FaultBadge
label="Fault Log (latched)"
mask={sample.fault_log}
onClear={() => handleClear("log")}
clearing={clearing === "log"}
/>
</div>
<div className="bg-zinc-900 rounded-lg p-4">
<div className="text-xs text-zinc-500 uppercase tracking-wider font-semibold pb-3 border-b border-zinc-800">
@@ -310,6 +438,141 @@ export function WireViewPanel({ info, sample, history }: Props) {
</div>
</div>
</div>
{/* ── Firmware ─────────────────────────────────────────── */}
<div className="bg-zinc-900 rounded-lg p-4 border border-zinc-800">
<div className="text-xs text-zinc-500 uppercase tracking-wider font-semibold pb-3 border-b border-zinc-800">
Firmware
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 mt-3">
<div className="flex flex-col gap-0.5 min-w-0">
<span className="text-xs text-zinc-500">Device</span>
<span className="text-sm font-mono text-zinc-200 truncate">
{firmware?.device.connected
? formatFw(firmware.device.version, firmware.device.build)
: "not connected"}
</span>
</div>
<div className="flex flex-col gap-0.5 min-w-0">
<span className="text-xs text-zinc-500">Bundled image</span>
<span className="text-sm font-mono text-zinc-200 truncate">
{firmware?.image.available
? formatFw(firmware.image.version, firmware.image.build)
: firmware?.image.error ?? "missing"}
</span>
</div>
</div>
{firmwareError && (
<div className="mt-3 text-xs text-red-400">{firmwareError}</div>
)}
{firmware && (
<div className="mt-3 flex flex-col gap-2">
{(() => {
const v = firmware.verdict;
const text =
v === "newer"
? { cls: "text-emerald-400", msg: "Newer firmware available." }
: v === "same"
? { cls: "text-zinc-400", msg: "Device already runs this firmware build." }
: v === "unknown"
? { cls: "text-zinc-400", msg: "Firmware comparison unknown (no build date)." }
: v === "downgrade"
? { cls: "text-amber-400", msg: "Bundled firmware is older than the device firmware." }
: v === "product_mismatch"
? { cls: "text-red-400", msg: "The bundled firmware does not match this device." }
: v === "too_old_for_noctua"
? { cls: "text-red-400", msg: "The bundled firmware predates Noctua Edition support." }
: { cls: "text-zinc-500", msg: "" };
return text.msg ? (
<div className={`text-sm font-medium ${text.cls}`}>{text.msg}</div>
) : null;
})()}
{firmware.device.connected &&
firmware.device.transport !== "serial" && (
<div className="text-xs text-zinc-500">
Flashing requires the serial transport (wireviewd owns the
port in hwmon mode).
</div>
)}
{firmware.dfu_util === null && (
<div className="text-xs text-amber-400">
dfu-util not installed — install the "dfu-util" package to
enable flashing.
</div>
)}
{flashActive || starting ? (
<div className="flex flex-col gap-1.5">
<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 ?? 0) * 100)}%
</span>
</div>
<div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden">
<div
className="h-full rounded-full bg-violet-500 transition-all duration-300"
style={{ width: `${flash.progress * 100}%` }}
/>
</div>
</div>
) : (
firmware.device.connected &&
firmware.device.transport === "serial" &&
firmware.image.available &&
firmware.dfu_util !== null &&
firmware.verdict !== "product_mismatch" &&
firmware.verdict !== "too_old_for_noctua" && (
<button
onClick={() =>
setConfirming(
firmware.verdict === "same" ||
firmware.verdict === "downgrade"
? "override"
: "update",
)
}
className={`self-start px-3 py-1.5 rounded text-xs font-semibold transition-colors ${
firmware.verdict === "same" ||
firmware.verdict === "downgrade"
? "bg-amber-600 hover:bg-amber-500 text-white"
: "bg-emerald-600 hover:bg-emerald-500 text-white"
}`}
>
{firmware.verdict === "same" ||
firmware.verdict === "downgrade"
? "Flash anyway"
: "Update firmware"}
</button>
)
)}
</div>
)}
</div>
{/* Confirm dialogs */}
{confirming !== null && firmware && (
<ConfirmDialog
message={
confirming === "override"
? firmware.verdict === "downgrade"
? "The bundled firmware is older than the device firmware. Flash it anyway?"
: "The device already runs this firmware build. Flash it again?"
: `Flash firmware ${formatFw(firmware.image.version, firmware.image.build)} to ${info?.device_name ?? "WireView Pro II"}?`
}
detail={`The device runs ${
firmware.device.connected
? formatFw(firmware.device.version, firmware.device.build)
: "an unknown firmware version"
}.\n\nThe device restarts into its bootloader and is flashed over USB DFU. Do not unplug it until the update finishes.\n\nThis is unofficial software, not affiliated with Thermal Grizzly — flashing is at your own risk.`}
confirmLabel={confirming === "override" ? "Flash anyway" : "Flash"}
isDestructive={confirming === "override"}
onConfirm={() => startFlash(confirming === "override")}
onCancel={() => setConfirming(null)}
/>
)}
</div>
);
}
+11 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { createWsConnection } from "../api/websocket.js";
import type {
WireViewFlashProgress,
WireViewInfo,
WireViewSample,
WireViewWsMessage,
@@ -8,11 +9,14 @@ import type {
const MAX_HISTORY = 120; // ~2 min at 1 s polling
const IDLE_FLASH: WireViewFlashProgress = { state: "idle", progress: 0, status: "" };
export function useWireview() {
const [available, setAvailable] = useState(false);
const [info, setInfo] = useState<WireViewInfo | null>(null);
const [sample, setSample] = useState<WireViewSample | null>(null);
const [history, setHistory] = useState<WireViewSample[]>([]);
const [flash, setFlash] = useState<WireViewFlashProgress>(IDLE_FLASH);
const wsRef = useRef<ReturnType<typeof createWsConnection> | null>(null);
useEffect(() => {
@@ -24,6 +28,12 @@ export function useWireview() {
setInfo(msg.info);
setSample(msg.sample);
setHistory((h) => [...h.slice(-(MAX_HISTORY - 1)), msg.sample]);
} else if (msg.type === "firmware") {
setFlash({
state: msg.state,
progress: msg.progress,
status: msg.status,
});
} else {
setAvailable(false);
setInfo(null);
@@ -36,5 +46,5 @@ export function useWireview() {
return () => wsRef.current?.close();
}, []);
return { available, info, sample, history };
return { available, info, sample, history, flash };
}
+40 -1
View File
@@ -211,6 +211,45 @@ export interface WireViewState {
sample: WireViewSample | null;
}
// ── WireView Pro II firmware (check + DFU flash) ──
export type WireViewFirmwareVerdict =
| "newer"
| "same"
| "unknown"
| "downgrade"
| "product_mismatch"
| "too_old_for_noctua";
export interface WireViewFlashProgress {
state: "idle" | "bootloader" | "waiting" | "flashing" | "done" | "failed";
progress: number;
status: string;
}
export interface WireViewFirmwareState {
device: {
connected: boolean;
transport: "serial" | "hwmon" | null;
version: number | null;
build: string | null;
};
image: {
available: boolean;
error: string | null;
version: number | null;
build: string | null;
};
verdict: WireViewFirmwareVerdict | null;
/** dfu-util version string, null when the binary is missing */
dfu_util: string | null;
flash: WireViewFlashProgress;
}
export type WireViewWsMessage =
| { type: "unavailable" }
| { type: "sample"; info: WireViewInfo; sample: WireViewSample };
| { type: "sample"; info: WireViewInfo; sample: WireViewSample }
// 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">);
File diff suppressed because it is too large. Load diff
+306 -2
View File
@@ -11,7 +11,9 @@ import logging
import os
import signal
import socket
import tempfile
import time
import uuid
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from typing import Any, Protocol
@@ -23,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 (
@@ -80,6 +81,19 @@ from .profiles.native import (
)
from .safety import check_negative_freq_warnings, validate_write
from .wireview import create_device, find_wireview_ports
from .wireview_firmware import (
VERDICT_DOWNGRADE,
VERDICT_PRODUCT_MISMATCH,
VERDICT_SAME,
VERDICT_TOO_OLD_FOR_NOCTUA,
DfuUtilFlasher,
FirmwareImageError,
bundled_firmware_path,
evaluate,
parse_build_timestamp,
read_firmware_image,
read_firmware_info,
)
log = logging.getLogger("nvcurve.server")
@@ -118,6 +132,12 @@ _state: dict[str, Any] = {
"connected": False, # last read succeeded
"failures": 0, # consecutive failed reads
"rejected_ports": set(), # ports reporting an unsupported product
"firmware": { # flash state (idle|bootloader|waiting|flashing|done|failed)
"state": "idle",
"progress": 0.0,
"status": "",
},
"flash_task": None, # running flash task, if any
},
}
@@ -519,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:
@@ -821,6 +846,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
@@ -1857,6 +1890,275 @@ 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) ─────────────────────────────
def _device_firmware_version(info: dict) -> tuple[int | None, str | None]:
"""(version, build string) from a device info dict, version None when
unparsable."""
try:
version = int(info["firmware_version"])
except (TypeError, ValueError):
version = None
return version, info["build"] or None
async def _wireview_firmware_flash() -> None:
"""Background task: enter bootloader → wait for the DFU device → flash.
State transitions are kept in _state["wireview"]["firmware"] and
broadcast to /ws/wireview clients. The device drops off while the flash
runs; the watchdog reconnects it once it reboots back into normal mode.
"""
wv = _state["wireview"]
fw = wv["firmware"]
device = wv["device"]
loop = asyncio.get_running_loop()
bin_path = Path(tempfile.gettempdir()) / f"nvcurve-wireview-fw-{uuid.uuid4().hex}.bin"
def announce(state: str, status: str, progress: float | None = None) -> None:
"""Update the flash state and push it to WS clients. Safe to call
from the flasher's reader thread (the broadcast is scheduled onto
the event loop)."""
if progress is not None:
fw["progress"] = progress
fw["state"] = state
fw["status"] = status
with suppress(RuntimeError): # event loop closed (server shutting down)
asyncio.run_coroutine_threadsafe(
_broadcast(
wv["clients"],
{
"type": "firmware",
"state": state,
"progress": fw["progress"],
"status": status,
},
),
loop,
)
try:
# Re-read the bundled image: it may have been swapped on disk since
# the gate, so the flash is gated on exactly the bytes it writes.
image_path = bundled_firmware_path()
base_address, image = await _run(read_firmware_image, image_path)
bin_path.write_bytes(image)
announce("bootloader", "Restarting device into DFU bootloader…")
if not await _run(device.enter_bootloader):
announce("failed", "Could not restart the device into its bootloader.")
return
announce("waiting", "Waiting for the DFU bootloader (0483:df11) to appear…")
if not await _run(DfuUtilFlasher.wait_for_dfu_device, 20.0):
announce(
"failed",
"The DFU bootloader did not appear. Check that the udev rule for "
"0483:df11 is installed, then power-cycle the device and try again.",
)
return
announce("flashing", "Flashing firmware…")
await _run(DfuUtilFlasher.flash, bin_path, base_address, announce)
announce("done", "Firmware update complete. The device is restarting.", 1.0)
except Exception as exc:
log.warning("WireView firmware flash failed: %s", exc)
announce("failed", f"Firmware update failed: {exc}")
finally:
with suppress(OSError):
bin_path.unlink()
wv["flash_task"] = None
@app.get("/api/wireview/firmware", tags=["WireView"], responses=R_AUTH)
async def api_wireview_firmware():
"""Firmware check: device firmware vs. the bundled image.
verdict: newer | same | unknown | downgrade | product_mismatch |
too_old_for_noctua — None when the device or the bundled image is
unknown. flash: the state of a running/last firmware flash.
"""
wv = _state["wireview"]
device = wv["device"]
device_version: int | None = None
device_build: str | None = None
device_info = None
if device is not None:
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
image_error = None
image_path = bundled_firmware_path()
if image_path.is_file():
try:
image = await _run(read_firmware_info, image_path)
except FirmwareImageError as exc:
image_error = str(exc)
verdict = None
if image is not None and device_info is not None:
verdict = await _run(
evaluate,
image,
device_info["vendor_id"],
device_info["product_id"],
device_version,
parse_build_timestamp(device_build),
)
return {
"device": {
"connected": device is not None,
"transport": device.transport if device is not None else None,
"version": device_version,
"build": device_build,
},
"image": {
"available": image is not None,
"error": image_error,
"version": image.version if image is not None else None,
"build": image.build_string if image is not None else None,
},
"verdict": verdict,
"dfu_util": await _run(DfuUtilFlasher.dfu_util_version),
"flash": wv["firmware"],
}
class WireViewFirmwareFlashRequest(BaseModel):
override: bool = False # flash anyway when the verdict is downgrade/same
@app.post("/api/wireview/firmware/flash", tags=["WireView"], responses=R_AUTH)
async def api_wireview_firmware_flash(req: WireViewFirmwareFlashRequest):
"""Flash the bundled firmware over USB DFU.
Gates (same rules as wireview-linux): the device must be connected over
the serial transport (wireviewd owns the port in hwmon mode), the
bundled image must parse and match the device product, and dfu-util must
be installed. A downgrade or identical build requires override=true.
"""
wv = _state["wireview"]
fw = wv["firmware"]
if fw["state"] not in ("idle", "done", "failed"):
raise HTTPException(
status_code=409, detail="A firmware flash is already running"
)
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=(
"Firmware flashing requires the serial transport "
"(wireviewd owns the port in hwmon mode)"
),
)
if await _run(DfuUtilFlasher.dfu_util_version) is None:
raise HTTPException(
status_code=501,
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, image_path)
except FirmwareImageError as exc:
raise HTTPException(
status_code=500,
detail=f"Could not parse the bundled firmware image: {exc}",
) from exc
info = await _run(device.info)
device_version, device_build = _device_firmware_version(info)
verdict = await _run(
evaluate,
image,
info["vendor_id"],
info["product_id"],
device_version,
parse_build_timestamp(device_build),
)
if verdict == VERDICT_PRODUCT_MISMATCH:
raise HTTPException(
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=400,
detail=(
"The bundled firmware predates Noctua Edition support and cannot be "
"flashed to this device. Nothing was flashed."
),
)
if verdict in (VERDICT_DOWNGRADE, VERDICT_SAME) and not req.override:
raise HTTPException(
status_code=400,
detail=(
"The bundled firmware is not newer than the device firmware. "
"Retry with override=true to flash anyway."
),
)
# 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}
# ── Write endpoints ────────────────────────────────────────────────────────────
@@ -2438,6 +2740,8 @@ async def ws_wireview(ws: WebSocket):
Messages:
{"type": "unavailable"} — no device connected
{"type": "sample", "info": {...}, "sample": {...}} — new reading
{"type": "firmware", "state", "progress", "status"} — firmware flash
progress (state: idle|bootloader|waiting|flashing|done|failed)
"""
if not _ws_authenticated(ws):
await ws.close(code=1008)
+65
View File
@@ -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,9 +59,16 @@ 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
# 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 ───────────────────────────────────────────────────────────────
@@ -291,6 +299,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 ──
@@ -319,6 +332,8 @@ class WireViewSerialDevice:
self._product_id, "WireView Pro II"
),
"hw_rev": f"{self._vendor_id:02X}{self._product_id:02X}",
"vendor_id": self._vendor_id,
"product_id": self._product_id,
"firmware_version": self._firmware_version,
"uid": self._uid,
"build": self._build,
@@ -419,6 +434,36 @@ 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(
"<BHH", CMD_CLEAR_FAULTS, keep_status & 0xFFFF, keep_log & 0xFFFF
)
return self._transaction(cmd, 0) is not None
def enter_bootloader(self) -> bool:
"""Restart the device into the STM32 DFU bootloader (0483:df11).
The device stops answering on the serial port and re-enumerates as a
DFU device, so nothing further can be sent over the port. The caller
is responsible for the rest of the flash procedure (see
wireview_firmware.DfuUtilFlasher) and for the reconnect that the
watchdog performs once the device reboots back into normal mode.
"""
if not self._connected:
return False
ok = self._transaction(bytes([CMD_BOOTLOADER]), 0) is not None
self.close()
return ok
# ── Transport ──
def _open_port(self):
@@ -441,6 +486,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
@@ -478,6 +527,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
@@ -544,6 +597,8 @@ class WireViewHwmonDevice:
return {
"device_name": "WireView Pro II",
"hw_rev": "",
"vendor_id": 0,
"product_id": 0,
"firmware_version": "",
"uid": "",
"build": "",
@@ -574,6 +629,16 @@ 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."""
return False
def read_sample(self) -> dict | None:
if not self._connected:
return None
+452
View File
@@ -0,0 +1,452 @@
"""Firmware check and DFU flashing for the Thermal Grizzly WireView Pro II.
Ported from the wireview-linux project (WireView2/Services/FirmwareHexInfo.cs
and DfuUtilFlasher.cs), which follows the same DFU procedure as the official
Windows client:
1. The device is restarted into its STM32 DFU bootloader over the serial
port (top-level command 0xF1). It re-enumerates as USB device 0483:df11.
2. The bundled Intel-HEX image is flattened to a raw binary (gaps padded
with 0xFF, the erased-flash value) and downloaded with
``dfu-util -d 0483:df11 -a 0 -s 0x<base>:leave -D <bin>``.
The firmware's BuildStruct sits at a fixed offset from the image's lowest
address: vendor id at +192, product id at +193, version byte at +194, a
32-byte NUL-terminated ASCII build string at +227 (192+35). Comparisons
match the upstream Windows client so verdicts agree across ports.
Flashing is at your own risk: a power loss or unplug mid-flash can leave the
device unbootable until it is reflashed manually.
"""
from __future__ import annotations
import logging
import re
import subprocess
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date, datetime
from pathlib import Path
log = logging.getLogger("nvcurve.wireview_firmware")
# ── Bundled image ─────────────────────────────────────────────────────────────
FIRMWARE_FILENAME = "TG-WV-PRO2-FW.hex"
def bundled_firmware_path() -> Path:
"""Path of the firmware image shipped with nvcurve."""
return Path(__file__).resolve().parent / "firmware" / FIRMWARE_FILENAME
# ── Intel-HEX parsing ─────────────────────────────────────────────────────────
BUILD_STRUCT_OFFSET = 192
VENDOR_ID_OFFSET_IN_BUILD_STRUCT = 0
PRODUCT_ID_OFFSET_IN_BUILD_STRUCT = 1
VERSION_OFFSET_IN_BUILD_STRUCT = 2
BUILD_INFO_OFFSET_IN_BUILD_STRUCT = 35
BUILD_INFO_LENGTH = 32
MAX_IMAGE_SIZE = 4 * 1024 * 1024 # sanity cap, as in wireview-linux
class FirmwareImageError(ValueError):
"""The firmware image is missing, malformed, or implausible."""
def _parse_hex_to_memory_map(hex_path: str | Path) -> dict[int, int]:
"""Parse an Intel-HEX file into {absolute_address: byte}.
Supports data records (0x00), EOF (0x01), extended segment address
(0x02) and extended linear address (0x04). Record checksums are
verified; a corrupt file must never be flashed.
"""
mem: dict[int, int] = {}
upper_linear = 0
upper_segment = 0
have_linear = False
try:
path = Path(hex_path)
if not path.is_file():
raise FirmwareImageError(f"Firmware image not found: {hex_path}")
f = path.open(encoding="ascii", errors="replace")
except OSError as exc:
raise FirmwareImageError(f"Cannot read firmware image {hex_path}: {exc}") from exc
with f:
for raw in f:
line = raw.strip()
if len(line) < 11 or not line.startswith(":"):
continue
# Checksum: low byte of the sum of all bytes in the record (the
# count/address/type fields plus data) must be 0.
try:
record_bytes = bytes.fromhex(line[1:])
except ValueError as exc:
raise FirmwareImageError(f"Malformed HEX record: {line!r}") from exc
if sum(record_bytes) & 0xFF != 0:
raise FirmwareImageError(f"Bad checksum in HEX record: {line!r}")
count = record_bytes[0]
addr = int.from_bytes(record_bytes[1:3], "big")
record_type = record_bytes[3]
if record_type == 0: # data
base = (upper_linear << 16) if have_linear else upper_segment
for i in range(count):
mem[base + addr + i] = record_bytes[4 + i]
elif record_type == 1: # EOF
break
elif record_type == 2: # extended segment address
upper_segment = int.from_bytes(record_bytes[4:6], "big") << 4
have_linear = False
elif record_type == 4: # extended linear address
upper_linear = int.from_bytes(record_bytes[4:6], "big")
have_linear = True
return mem
@dataclass(frozen=True)
class FirmwareImageInfo:
"""Identity of a firmware image: the BuildStruct's vendor/product id,
version and build string (e.g. "TG-WV-PRO2-FW_20260902_0741")."""
vendor_id: int
product_id: int
version: int
build_string: str | None
@property
def build_time(self) -> datetime | None:
"""The build string's yyyyMMdd_HHmm timestamp, None when absent."""
return parse_build_timestamp(self.build_string)
def parse_build_timestamp(build_string: str | None) -> datetime | None:
"""Parse the build timestamp out of a build string such as
"TG-WV-PRO2-FW_20260902_0741" (upstream's TryParseBuildTimestamp)."""
if not build_string:
return None
m = re.search(r"_(\d{8})_(\d{4})(?!\d)", build_string)
if not m:
return None
try:
return datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M")
except ValueError:
return None
def read_firmware_info(hex_path: str | Path) -> FirmwareImageInfo:
"""Read the firmware identity out of a bundled Intel-HEX image."""
mem = _parse_hex_to_memory_map(hex_path)
if not mem:
raise FirmwareImageError("HEX file does not contain data records.")
build_struct = min(mem) + BUILD_STRUCT_OFFSET
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
text = bytearray()
complete = True
for i in range(BUILD_INFO_LENGTH):
if build_info_base + i not in mem:
complete = False
break
text.append(mem[build_info_base + i])
if complete:
nul = text.find(0)
build_string = (
bytes(text[: nul if nul >= 0 else BUILD_INFO_LENGTH])
.decode("ascii", errors="replace")
.strip()
)
return FirmwareImageInfo(
mem[build_struct + VENDOR_ID_OFFSET_IN_BUILD_STRUCT],
mem[build_struct + PRODUCT_ID_OFFSET_IN_BUILD_STRUCT],
mem[build_struct + VERSION_OFFSET_IN_BUILD_STRUCT],
build_string,
)
def read_firmware_image(hex_path: str | Path) -> tuple[int, bytes]:
"""Convert an Intel-HEX image to a flat binary suitable for dfu-util,
padding gaps with 0xFF (erased-flash value). Returns (base_address, image)."""
mem = _parse_hex_to_memory_map(hex_path)
if not mem:
raise FirmwareImageError("HEX file does not contain data records.")
min_addr, max_addr = min(mem), max(mem)
size = max_addr - min_addr + 1
if size > MAX_IMAGE_SIZE:
raise FirmwareImageError(f"Firmware image is implausibly large ({size} bytes).")
buf = bytearray(b"\xFF" * size)
for addr, value in mem.items():
buf[addr - min_addr] = value
return min_addr, bytes(buf)
# ── Compatibility verdicts ────────────────────────────────────────────────────
# Same rules as wireview-linux's FirmwareCompatibility (upstream 1.0.8's
# FirmwareProductIdAliases / CompareBundledFirmwareToDevice, plus the Noctua
# Edition floor).
VENDOR_ID_THERMAL_GRIZZLY = 0xEF
PRODUCT_ID_PRO2 = 0x05
PRODUCT_ID_PRO2_NOCTUA = 0x06
#: Device (vendor, product) served by another product's image: the Noctua
#: Edition runs the Pro II firmware.
PRODUCT_ALIASES = {(VENDOR_ID_THERMAL_GRIZZLY, PRODUCT_ID_PRO2_NOCTUA): PRODUCT_ID_PRO2}
#: First firmware build with Noctua Edition support
#: (TG-WV-PRO2-FW_20260902_0741). An older image never goes onto product 6.
NOCTUA_MINIMUM_BUILD_DATE = date(2026, 9, 2)
# Verdicts, in gate order: product (with the alias), then the Noctua date
# floor, then version and build date. product_mismatch and too_old_for_noctua
# refuse the flash outright; downgrade and same need an explicit override;
# unknown (equal version, a build date missing) goes ahead like upstream.
VERDICT_NEWER = "newer"
VERDICT_SAME = "same"
VERDICT_UNKNOWN = "unknown"
VERDICT_DOWNGRADE = "downgrade"
VERDICT_PRODUCT_MISMATCH = "product_mismatch"
VERDICT_TOO_OLD_FOR_NOCTUA = "too_old_for_noctua"
def firmware_product_id(vendor_id: int, product_id: int) -> int:
"""The product id whose firmware serves this device (alias applied)."""
return PRODUCT_ALIASES.get((vendor_id, product_id), product_id)
def product_matches(
image: FirmwareImageInfo, device_vendor_id: int, device_product_id: int
) -> bool:
"""Same vendor, and the image's product is the device's (aliased) one."""
return (
device_vendor_id != 0
and image.vendor_id == device_vendor_id
and image.product_id == firmware_product_id(device_vendor_id, device_product_id)
)
def compare(
image: FirmwareImageInfo,
device_version: int | None,
device_build_time: datetime | None,
) -> int | None:
"""Version first, then build timestamp. Positive when the image is newer,
negative when older, None when either side is unknown."""
if device_version is None:
return None
by_version = (image.version > device_version) - (image.version < device_version)
if by_version != 0:
return by_version
image_time = image.build_time
if image_time is None or device_build_time is None:
return None
return (image_time > device_build_time) - (image_time < device_build_time)
def is_below_noctua_floor(
image: FirmwareImageInfo, device_vendor_id: int, device_product_id: int
) -> bool:
"""True when the image predates Noctua Edition support and the device is
one. An image without a parsable build date counts as too old."""
if (device_vendor_id, device_product_id) != (
VENDOR_ID_THERMAL_GRIZZLY,
PRODUCT_ID_PRO2_NOCTUA,
):
return False
t = image.build_time
return t is None or t.date() < NOCTUA_MINIMUM_BUILD_DATE
def evaluate(
image: FirmwareImageInfo,
device_vendor_id: int,
device_product_id: int,
device_version: int | None,
device_build_time: datetime | None,
) -> str:
"""Whether a firmware image may go onto a device, as a verdict string."""
if not product_matches(image, device_vendor_id, device_product_id):
return VERDICT_PRODUCT_MISMATCH
if is_below_noctua_floor(image, device_vendor_id, device_product_id):
return VERDICT_TOO_OLD_FOR_NOCTUA
cmp = compare(image, device_version, device_build_time)
if cmp is None:
return VERDICT_UNKNOWN
if cmp < 0:
return VERDICT_DOWNGRADE
if cmp > 0:
return VERDICT_NEWER
return VERDICT_SAME
# ── DFU flashing via dfu-util ─────────────────────────────────────────────────
DFU_VID = "0483"
DFU_PID = "df11"
DFU_DEVICE_TAG = f"[{DFU_VID}:{DFU_PID}]"
#: dfu-util redraws its progress bar with '\r' — the latest percentage in the
#: current line.
_PROGRESS_RE = re.compile(r"(\d{1,3})\s*%")
#: dfu-util exits 74 ("EX_IOERR") on some versions when the device detaches
#: right after ":leave" even though the download finished.
_DFU_UTIL_IOERR = 74
class FirmwareFlashError(RuntimeError):
"""The DFU flash failed; the message carries dfu-util's output."""
class DfuUtilFlasher:
"""Flashes firmware to the WireView Pro II's STM32 DFU bootloader
(0483:df11) by driving the system dfu-util binary. Requires the dfu-util
package and the udev rule for unprivileged USB access."""
@staticmethod
def dfu_util_version() -> str | None:
"""The dfu-util version string (first output line), or None if the
binary is missing or broken."""
try:
proc = subprocess.run(
["dfu-util", "--version"],
capture_output=True,
text=True,
timeout=5,
)
except (OSError, subprocess.TimeoutExpired):
return None
if proc.returncode != 0:
return None
out = proc.stdout.strip()
first = out.splitlines()[0].strip() if out else ""
return first or None
@staticmethod
def wait_for_dfu_device(timeout_s: float = 20.0) -> bool:
"""Poll ``dfu-util -l`` until the bootloader shows up (the device
re-enumerates a moment after the bootloader command). False on timeout."""
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
try:
proc = subprocess.run(
["dfu-util", "-l"],
capture_output=True,
text=True,
timeout=5,
)
if proc.returncode == 0 and DFU_DEVICE_TAG in proc.stdout.lower():
return True
except (OSError, subprocess.TimeoutExpired):
# dfu-util hiccup; keep polling until the deadline.
pass
time.sleep(0.5)
return False
@staticmethod
def flash(
bin_path: str | Path,
base_address: int,
progress_cb: Callable[[float], None] | None = None,
timeout_s: float = 300.0,
) -> None:
"""Download a flat firmware image to internal flash and reboot the
device (DfuSe ":leave"). progress_cb receives 0..1, parsed from
dfu-util's output. Raises FirmwareFlashError with dfu-util's output on
failure."""
args = [
"dfu-util",
f"-d {DFU_VID}:{DFU_PID}",
"-a",
"0",
f"-s 0x{base_address:08X}:leave",
"-D",
str(bin_path),
]
try:
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
except OSError as exc:
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 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:
chunk = proc.stdout.read(256) # type: ignore[union-attr]
if chunk == "":
break
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:
progress_cb(min(100, max(0, int(m.group(1)))) / 100.0)
line = []
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_reader.join(timeout=5)
stderr = "".join(stderr_parts)
stdout = "".join(stdout_parts)
downloaded = "File downloaded successfully" in (stdout + stderr)
if proc.returncode != 0 and not downloaded:
detail = (stderr or stdout).strip()
if len(detail) > 600:
detail = "…" + detail[-600:]
raise FirmwareFlashError(f"dfu-util failed (exit {proc.returncode}).\n{detail}")
if proc.returncode == _DFU_UTIL_IOERR:
log.warning(
"dfu-util exited %d after the device detached (treated as success)",
_DFU_UTIL_IOERR,
)
+99
View File
@@ -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()
+507
View File
@@ -0,0 +1,507 @@
"""Tests for the WireView Pro II firmware check + DFU flasher
(nvcurve/wireview_firmware.py).
Standalone (no pytest required):
python tests/test_wireview_firmware.py
Also works under pytest. Covers the Intel-HEX parser (including checksum
verification), the BuildStruct identity extraction, the compatibility
verdicts (product alias, Noctua floor, version/build comparison), the
bundled image, the dfu-util flasher (mocked subprocess), and the
bootloader command on the serial device.
"""
import os
import subprocess
import sys
import tempfile
from datetime import datetime
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
PASS = 0
FAIL = 0
def check(name: str, cond: bool) -> None:
global PASS, FAIL
if cond:
PASS += 1
print(f" PASS {name}")
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:
"""One Intel-HEX line (count, address, type, data) with a correct
checksum (the count byte is part of the sum)."""
payload = bytes([len(data)]) + addr.to_bytes(2, "big") + bytes([record_type]) + data
checksum = (-sum(payload)) & 0xFF
return ":" + (payload + bytes([checksum])).hex().upper()
def _write_hex(tmp: str, lines: list[str]) -> str:
path = os.path.join(tmp, "fw.hex")
with open(path, "w") as f:
f.write("\n".join(lines) + "\n")
return path
def _build_struct_lines(vendor=0xEF, product=0x05, version=0x05,
build="TG-WV-PRO2-FW_20260902_0741") -> list[str]:
"""HEX lines placing a BuildStruct at image offset 192 (base 0). The
leading byte at offset 0 anchors min(address) so the BuildStruct lands
exactly 192 bytes above the image base."""
lines = [_hex_line(0x0000, bytes([0x00]), record_type=4)] # linear addr 0
lines.append(_hex_line(0x0000, bytes([0x00])))
lines.append(_hex_line(wf.BUILD_STRUCT_OFFSET,
bytes([vendor, product, version])))
build_bytes = build.encode().ljust(wf.BUILD_INFO_LENGTH, b"\x00")
lines.append(
_hex_line(wf.BUILD_STRUCT_OFFSET + wf.BUILD_INFO_OFFSET_IN_BUILD_STRUCT,
build_bytes)
)
lines.append(":00000001FF") # EOF
return lines
# ── Build timestamp ───────────────────────────────────────────────────────────
def test_parse_build_timestamp():
t = wf.parse_build_timestamp("TG-WV-PRO2-FW_20260902_0741")
check("timestamp parsed", t == datetime(2026, 9, 2, 7, 41))
check("timestamp None input", wf.parse_build_timestamp(None) is None)
check("timestamp empty input", wf.parse_build_timestamp("") is None)
check("timestamp no match", wf.parse_build_timestamp("TG-WV-PRO2-FW") is None)
check(
"timestamp trailing digit rejected",
wf.parse_build_timestamp("TG-WV-PRO2-FW_20260902_07411") is None,
)
check(
"timestamp invalid date",
wf.parse_build_timestamp("TG-WV-PRO2-FW_20261399_0741") is None,
)
# ── Intel-HEX parser ──────────────────────────────────────────────────────────
def test_hex_parser():
with tempfile.TemporaryDirectory() as tmp:
# Linear base 0x08000000, two data records with a gap, then EOF.
path = _write_hex(
tmp,
[
_hex_line(0x0000, bytes([0x08, 0x00]), record_type=4),
_hex_line(0x0000, bytes([0x00, 0x60])),
_hex_line(0x0005, bytes([0xAA])),
":00000001FF",
],
)
mem = wf._parse_hex_to_memory_map(path)
check(
"hex memory map",
mem == {0x08000000: 0x00, 0x08000001: 0x60, 0x08000005: 0xAA},
)
base, image = wf.read_firmware_image(path)
check("hex base address", base == 0x08000000)
check("hex image size", len(image) == 6)
check("hex gap padded 0xFF", image == bytes([0x00, 0x60, 0xFF, 0xFF, 0xFF, 0xAA]))
# Extended segment address (type 2): base = value << 4.
path2 = _write_hex(
tmp,
[
_hex_line(0x0000, bytes([0x00, 0x10]), record_type=2),
_hex_line(0x0000, bytes([0x42])),
":00000001FF",
],
)
mem2 = wf._parse_hex_to_memory_map(path2)
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]))
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)
check("hex bad checksum rejected", False)
except wf.FirmwareImageError:
check("hex bad checksum rejected", True)
# Non-hex garbage in a record is rejected.
path4 = _write_hex(tmp, [":10000000ZZ000000000000000000000000000000000000"])
try:
wf._parse_hex_to_memory_map(path4)
check("hex garbage rejected", False)
except wf.FirmwareImageError:
check("hex garbage rejected", True)
# EOF-only file: no data records.
path5 = _write_hex(tmp, [":00000001FF"])
try:
wf.read_firmware_info(path5)
check("hex no data records", False)
except wf.FirmwareImageError as exc:
check("hex no data records", "data records" in str(exc))
# Missing file.
try:
wf.read_firmware_info(os.path.join(tmp, "nope.hex"))
check("hex missing file", False)
except wf.FirmwareImageError as exc:
check("hex missing file", "not found" in str(exc))
def test_read_firmware_info():
with tempfile.TemporaryDirectory() as tmp:
path = _write_hex(tmp, _build_struct_lines())
info = wf.read_firmware_info(path)
check("info vendor", info.vendor_id == 0xEF)
check("info product", info.product_id == 0x05)
check("info version", info.version == 5)
check("info build string", info.build_string == "TG-WV-PRO2-FW_20260902_0741")
check("info build time", info.build_time == datetime(2026, 9, 2, 7, 41))
# A build string without a timestamp parses but has no build time.
path2 = _write_hex(tmp, _build_struct_lines(build="TG-WV-PRO2-FW"))
info2 = wf.read_firmware_info(path2)
check("info build time absent", info2.build_time is None)
def test_bundled_image():
"""The shipped TG-WV-PRO2-FW.hex must parse to the known identity."""
path = wf.bundled_firmware_path()
check("bundled exists", path.is_file())
if not path.is_file():
return
info = wf.read_firmware_info(path)
check("bundled vendor", info.vendor_id == 0xEF)
check("bundled product", info.product_id == wf.PRODUCT_ID_PRO2)
check("bundled version", info.version == 5)
check("bundled build", info.build_string == "TG-WV-PRO2-FW_20260902_0741")
check("bundled build time", info.build_time == datetime(2026, 9, 2, 7, 41))
base, image = wf.read_firmware_image(path)
check("bundled base", base == 0x08000000)
check("bundled size plausible", 64 * 1024 <= len(image) <= 256 * 1024)
# The first bytes are the STM32 vector table (initial SP at 0x20006000).
check("bundled first bytes", image[:2] == bytes([0x00, 0x60]))
# ── Compatibility verdicts ────────────────────────────────────────────────────
def _img(version=5, build="TG-WV-PRO2-FW_20260902_0741",
vendor=0xEF, product=0x05) -> wf.FirmwareImageInfo:
return wf.FirmwareImageInfo(vendor, product, version, build)
def test_compatibility_verdicts():
pro2 = (wf.VENDOR_ID_THERMAL_GRIZZLY, wf.PRODUCT_ID_PRO2)
noctua = (wf.VENDOR_ID_THERMAL_GRIZZLY, wf.PRODUCT_ID_PRO2_NOCTUA)
t_new = datetime(2026, 9, 2, 7, 41)
t_old = datetime(2026, 1, 1, 0, 0)
# Version dominates.
check("verdict newer version",
wf.evaluate(_img(version=6), *pro2, 5, t_old) == wf.VERDICT_NEWER)
check("verdict downgrade version",
wf.evaluate(_img(version=4), *pro2, 5, t_new) == wf.VERDICT_DOWNGRADE)
# Equal version: build timestamp decides.
check("verdict newer build",
wf.evaluate(_img(build="TG-WV-PRO2-FW_20261001_0000"), *pro2, 5, t_old)
== wf.VERDICT_NEWER)
check("verdict downgrade build",
wf.evaluate(_img(build="TG-WV-PRO2-FW_20250101_0000"), *pro2, 5, t_new)
== wf.VERDICT_DOWNGRADE)
check("verdict same",
wf.evaluate(_img(), *pro2, 5, t_new) == wf.VERDICT_SAME)
# Unknown sides.
check("verdict unknown device version",
wf.evaluate(_img(), *pro2, None, t_new) == wf.VERDICT_UNKNOWN)
check("verdict unknown device build",
wf.evaluate(_img(), *pro2, 5, None) == wf.VERDICT_UNKNOWN)
check("verdict unknown image build",
wf.evaluate(_img(build="TG-WV-PRO2-FW"), *pro2, 5, t_new)
== wf.VERDICT_UNKNOWN)
# Product matching (with the Noctua alias).
check("verdict product mismatch",
wf.evaluate(_img(product=0x99), *pro2, 5, t_new)
== wf.VERDICT_PRODUCT_MISMATCH)
check("verdict vendor mismatch",
wf.evaluate(_img(vendor=0x12), *pro2, 5, t_new)
== wf.VERDICT_PRODUCT_MISMATCH)
check("verdict unknown device vendor",
wf.evaluate(_img(), 0, 0, 5, t_new) == wf.VERDICT_PRODUCT_MISMATCH)
check("verdict noctua alias matches pro2 image",
wf.evaluate(_img(product=0x05), *noctua, 5, t_old) == wf.VERDICT_NEWER)
# Noctua floor: an image predating 2026-09-02 never goes onto product 6.
check("verdict too old for noctua",
wf.evaluate(_img(build="TG-WV-PRO2-FW_20260801_0000"), *noctua, 5, t_old)
== wf.VERDICT_TOO_OLD_FOR_NOCTUA)
check("verdict noctua floor date ok",
wf.evaluate(_img(build="TG-WV-PRO2-FW_20260902_0741"), *noctua, 5, t_old)
== wf.VERDICT_NEWER)
check("verdict noctua no build date too old",
wf.evaluate(_img(build="TG-WV-PRO2-FW"), *noctua, 5, t_old)
== wf.VERDICT_TOO_OLD_FOR_NOCTUA)
# The floor only applies to Noctua devices: the same old image is a plain
# downgrade on a Pro II.
check("verdict pro2 old image is downgrade",
wf.evaluate(_img(build="TG-WV-PRO2-FW_20260801_0000"), *pro2, 5, t_new)
== wf.VERDICT_DOWNGRADE)
# ── dfu-util flasher (mocked subprocess) ──────────────────────────────────────
class _FakeStdout:
def __init__(self, text: str):
self._chars = list(text)
def read(self, n: int) -> str:
if not self._chars:
return ""
out = self._chars[:n]
del self._chars[:n]
return "".join(out)
class _FakeStderr:
def __init__(self, text: str):
self._text = 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:
def __init__(self, stdout: str = "", stderr: str = "", returncode: int = 0,
wait_error: Exception | None = None):
self.stdout = _FakeStdout(stdout)
self.stderr = _FakeStderr(stderr)
self.returncode = returncode
self._wait_error = wait_error
self.killed = False
def wait(self, timeout: float | None = None) -> int:
if self._wait_error is not None:
raise self._wait_error
return self.returncode
def kill(self) -> None:
self.killed = True
def test_dfu_util_version():
ok = mock.Mock(returncode=0, stdout="dfu-util 0.11\nCopyright…\n")
with mock.patch.object(wf.subprocess, "run", return_value=ok):
check("dfu-util version", wf.DfuUtilFlasher.dfu_util_version() == "dfu-util 0.11")
with mock.patch.object(wf.subprocess, "run",
side_effect=FileNotFoundError("dfu-util")):
check("dfu-util missing", wf.DfuUtilFlasher.dfu_util_version() is None)
broken = mock.Mock(returncode=1, stdout="")
with mock.patch.object(wf.subprocess, "run", return_value=broken):
check("dfu-util broken", wf.DfuUtilFlasher.dfu_util_version() is None)
def test_wait_for_dfu_device():
found = mock.Mock(returncode=0, stdout="Found DFU: [0483:df11] (STM32…)\n")
with mock.patch.object(wf.subprocess, "run", return_value=found):
check("dfu device found", wf.DfuUtilFlasher.wait_for_dfu_device(0.5))
absent = mock.Mock(returncode=0, stdout="No DFU capable devices found.\n")
with mock.patch.object(wf.subprocess, "run", return_value=absent):
check("dfu device absent", not wf.DfuUtilFlasher.wait_for_dfu_device(0.6))
def test_dfu_flash():
progress: list[float] = []
out = (
"Downloading file: /tmp/fw.bin\n"
"\r 0% |\r\n"
"\r 25% |\r\n"
"\r 50% |\r\n"
"\r100% |\r\n"
"File downloaded successfully\n"
)
with tempfile.TemporaryDirectory() as tmp:
bin_path = os.path.join(tmp, "fw.bin")
with mock.patch.object(wf.subprocess, "Popen",
return_value=_FakeProc(stdout=out, returncode=0)) as popen:
wf.DfuUtilFlasher.flash(bin_path, 0x08000000,
progress_cb=progress.append)
check("flash no error", True)
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",
"-s 0x08000000:leave", "-D", bin_path])
# Exit 74 (EX_IOERR) after a completed download is treated as success.
with mock.patch.object(wf.subprocess, "Popen",
return_value=_FakeProc(
stdout="File downloaded successfully\n",
returncode=74)):
wf.DfuUtilFlasher.flash(bin_path, 0x08000000)
check("flash exit 74 tolerated", True)
# A real failure raises with dfu-util's output.
with mock.patch.object(wf.subprocess, "Popen",
return_value=_FakeProc(
stderr="dfu-util: no DFU capable USB device found\n",
returncode=1)):
try:
wf.DfuUtilFlasher.flash(bin_path, 0x08000000)
check("flash failure raises", False)
except wf.FirmwareFlashError as exc:
check("flash failure raises", "no DFU capable USB device" in str(exc))
check("flash failure exit code", "exit 1" in str(exc))
# A hang is killed and reported as a timeout.
hung = _FakeProc(wait_error=subprocess.TimeoutExpired("dfu-util", 300))
with mock.patch.object(wf.subprocess, "Popen", return_value=hung):
try:
wf.DfuUtilFlasher.flash(bin_path, 0x08000000, timeout_s=0.1)
check("flash timeout raises", False)
except wf.FirmwareFlashError as exc:
check("flash timeout raises", "did not finish" in str(exc))
check("flash timeout kills", hung.killed)
# A missing binary is reported, not raised as OSError.
with mock.patch.object(wf.subprocess, "Popen",
side_effect=FileNotFoundError("dfu-util")):
try:
wf.DfuUtilFlasher.flash(bin_path, 0x08000000)
check("flash missing binary", False)
except wf.FirmwareFlashError as exc:
check("flash missing binary", "Could not run dfu-util" in str(exc))
# ── Bootloader command ────────────────────────────────────────────────────────
def _build_info_struct(product_name: str, build_info: str) -> bytes:
"""BuildStruct: VendorData(3) + ProductName(32) + BuildInfo(32) + NameLength(1)."""
return (
bytes([0xEF, 0x05, 5])
+ product_name.encode().ljust(32, b"\x00")
+ build_info.encode().ljust(32, b"\x00")
+ bytes([len(product_name)])
)
def test_enter_bootloader():
"""enter_bootloader sends the top-level 0xF1 command once and closes the
connection (the device re-enumerates as 0483:df11 afterwards)."""
import pty
import queue
import threading
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)
except OSError:
return
if not cmd:
return
if cmd[0] == wv.CMD_BOOTLOADER:
received.put(cmd)
continue
resp = {
wv.CMD_READ_VENDOR_DATA: bytes([0xEF, 0x05, 5]),
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", "TG-WV-PRO2-FW_20260902_0741"
),
}.get(cmd[0])
if resp:
try:
os.write(master, resp)
except OSError:
return
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())
check("boot: disconnected", not dev.connected)
try:
got = received.get(timeout=2)
check("boot: 0xF1 sent", got == b"\xF1")
except queue.Empty:
check("boot: 0xF1 sent", False)
# A second call on a closed device fails without touching the port.
check("boot: second call fails", not dev.enter_bootloader())
finally:
os.close(master)
t.join(timeout=2)
def test_hwmon_enter_bootloader():
"""The hwmon transport cannot enter the bootloader (wireviewd owns the
port, and nvcurve does not speak the daemon protocol)."""
dev = wv.WireViewHwmonDevice("/sys/class/hwmon/hwmon99")
check("hwmon enter_bootloader unsupported", dev.enter_bootloader() is False)
def main() -> int:
print("wireview firmware tests:")
test_parse_build_timestamp()
test_hex_parser()
test_read_firmware_info()
test_bundled_image()
test_compatibility_verdicts()
test_dfu_util_version()
test_wait_for_dfu_device()
test_dfu_flash()
test_enter_bootloader()
test_hwmon_enter_bootloader()
print(f"\n{PASS} passed, {FAIL} failed")
return 1 if FAIL else 0
if __name__ == "__main__":
sys.exit(main())