feat: wireview firmware check + DFU flash, fault clearing, pin-imbalance gauge #19

Merged
Pakobbix merged 4 commits from feat/wireview-firmware-flash-faults into main 2026-10-05 18:40:35 +00:00
8 changed files with 111 additions and 55 deletions
Showing only changes of commit 6e87dcf862 - Show all commits

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). \ > **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. \ > **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.) \ > **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. \ > **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. > 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 `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 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] > [!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. > 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: 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; - `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 ## Pin current imbalance warning
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { api } from "../../api/client.js"; import { api } from "../../api/client.js";
import { ConfirmDialog } from "../common/ConfirmDialog.js"; import { ConfirmDialog } from "../common/ConfirmDialog.js";
@@ -203,7 +203,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
flash.state === "waiting" || flash.state === "waiting" ||
flash.state === "flashing"; flash.state === "flashing";
async function refreshFirmware() { const refreshFirmware = useCallback(async () => {
try { try {
setFirmware(await api.wireviewFirmware()); setFirmware(await api.wireviewFirmware());
setFirmwareError(null); setFirmwareError(null);
@@ -212,7 +212,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
err instanceof Error ? err.message : "Failed to load firmware state", err instanceof Error ? err.message : "Failed to load firmware state",
); );
} }
} }, []);
const hasSample = sample !== null; const hasSample = sample !== null;
// Fetch the firmware check when a device appears (the panel early-returns // 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). // body (rule false-positive on async fetch).
// eslint-disable-next-line react-hooks/set-state-in-effect // eslint-disable-next-line react-hooks/set-state-in-effect
if (hasSample) refreshFirmware(); if (hasSample) refreshFirmware();
}, [hasSample]); }, [hasSample, refreshFirmware]);
// After a flash the device reboots and re-enumerates; re-check once it is // After a flash the device reboots and re-enumerates; re-check once it is
// back so the verdict reflects the new firmware. // back so the verdict reflects the new firmware.
@@ -232,7 +232,7 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
refreshFirmware(); refreshFirmware();
}, 3000); }, 3000);
return () => clearTimeout(t); return () => clearTimeout(t);
}, [flash.state]); }, [flash.state, refreshFirmware]);
async function startFlash(override: boolean) { async function startFlash(override: boolean) {
setConfirming(null); setConfirming(null);
@@ -253,10 +253,10 @@ export function WireViewPanel({ info, sample, history, flash }: Props) {
setClearing(which); setClearing(which);
try { try {
// Keep-mask semantics: 0x0000 clears, 0xFFFF keeps. // Keep-mask semantics: 0x0000 clears, 0xFFFF keeps.
await api.wireviewClearFault( const clear = 0x0000, keep = 0xffff;
which === "status" ? 0x0000 : 0xffff, const statusMask = which === "status" ? clear : keep;
which === "log" ? 0x0000 : 0xffff, const logMask = which === "status" ? keep : clear;
); await api.wireviewClearFault(statusMask, logMask);
toast.success( toast.success(
which === "status" ? "Fault status cleared" : "Fault log cleared", 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"> <div className="flex items-center justify-between text-xs text-zinc-400">
<span>{flash.status || "Starting…"}</span> <span>{flash.status || "Starting…"}</span>
<span className="font-mono"> <span className="font-mono">
{Math.round(flash.progress * 100)}% {Math.round((flash.progress ?? 0) * 100)}%
</span> </span>
</div> </div>
<div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden"> <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 = export type WireViewWsMessage =
| { type: "unavailable" } | { 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
type: "firmware"; // match the WS message shape; keep in sync with WireViewFlashProgress.
state: WireViewFlashProgress["state"]; | ({ type: "firmware" } &
progress: number; Pick<WireViewFlashProgress, "state" | "progress" | "status">);
status: string;
};
+30 -17
View File
@@ -25,8 +25,7 @@ from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel from pydantic import BaseModel
from . import __version__ from . import __version__, auth
from . import auth
from .config import Config, default_config, tls_enabled from .config import Config, default_config, tls_enabled
from .hal.dashboard import get_dashboard_info from .hal.dashboard import get_dashboard_info
from .hal.fans import ( from .hal.fans import (
@@ -540,6 +539,11 @@ async def lifespan(app: FastAPI):
# ── WireView Pro II detection ───────────────────────────────────────────── # ── WireView Pro II detection ─────────────────────────────────────────────
# Independent of GPU discovery: the tab appears whenever the connector # Independent of GPU discovery: the tab appears whenever the connector
# monitor is attached, and the watchdog handles hot-plug afterwards. # 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: try:
await _wireview_connect() await _wireview_connect()
except Exception as exc: except Exception as exc:
@@ -1929,10 +1933,9 @@ async def api_wireview_clear_fault(req: WireViewClearFaultRequest):
# ── WireView Pro II firmware (check + DFU flash) ───────────────────────────── # ── WireView Pro II firmware (check + DFU flash) ─────────────────────────────
def _wireview_device_firmware(device) -> tuple[int | None, str | None]: def _device_firmware_version(info: dict) -> tuple[int | None, str | None]:
"""(version, build string) of the connected device, version None when """(version, build string) from a device info dict, version None when
unparsable.""" unparsable."""
info = device.info()
try: try:
version = int(info["firmware_version"]) version = int(info["firmware_version"])
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -2021,8 +2024,10 @@ async def api_wireview_firmware():
device_version: int | None = None device_version: int | None = None
device_build: str | None = None device_build: str | None = None
device_info = None
if device is not 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. # Re-read the bundled image: it may have been swapped on disk.
image = None image = None
@@ -2035,13 +2040,12 @@ async def api_wireview_firmware():
image_error = str(exc) image_error = str(exc)
verdict = None verdict = None
if image is not None and device is not None: if image is not None and device_info is not None:
info = device.info()
verdict = await _run( verdict = await _run(
evaluate, evaluate,
image, image,
info["vendor_id"], device_info["vendor_id"],
info["product_id"], device_info["product_id"],
device_version, device_version,
parse_build_timestamp(device_build), 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.", 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: try:
image = await _run(read_firmware_info, bundled_firmware_path()) image = await _run(read_firmware_info, image_path)
except FirmwareImageError as exc: except FirmwareImageError as exc:
raise HTTPException( raise HTTPException(
status_code=500, status_code=500,
detail=f"Could not parse the bundled firmware image: {exc}", detail=f"Could not parse the bundled firmware image: {exc}",
) from exc ) from exc
info = device.info() info = await _run(device.info)
device_version, device_build = await _run(_wireview_device_firmware, device) device_version, device_build = _device_firmware_version(info)
verdict = await _run( verdict = await _run(
evaluate, evaluate,
image, image,
@@ -2121,12 +2131,12 @@ async def api_wireview_firmware_flash(req: WireViewFirmwareFlashRequest):
) )
if verdict == VERDICT_PRODUCT_MISMATCH: if verdict == VERDICT_PRODUCT_MISMATCH:
raise HTTPException( raise HTTPException(
status_code=409, status_code=400,
detail="The bundled firmware does not match this device. Nothing was flashed.", detail="The bundled firmware does not match this device. Nothing was flashed.",
) )
if verdict == VERDICT_TOO_OLD_FOR_NOCTUA: if verdict == VERDICT_TOO_OLD_FOR_NOCTUA:
raise HTTPException( raise HTTPException(
status_code=409, status_code=400,
detail=( detail=(
"The bundled firmware predates Noctua Edition support and cannot be " "The bundled firmware predates Noctua Edition support and cannot be "
"flashed to this device. Nothing was flashed." "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: if verdict in (VERDICT_DOWNGRADE, VERDICT_SAME) and not req.override:
raise HTTPException( raise HTTPException(
status_code=409, status_code=400,
detail=( detail=(
"The bundled firmware is not newer than the device firmware. " "The bundled firmware is not newer than the device firmware. "
"Retry with override=true to flash anyway." "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()) wv["flash_task"] = asyncio.create_task(_wireview_firmware_flash())
return {"ok": True} return {"ok": True}
+3
View File
@@ -66,6 +66,9 @@ CMD_READ_BUILD_INFO = 0x0D
# STM32 DFU bootloader (USB 0483:df11) for firmware flashing. # STM32 DFU bootloader (USB 0483:df11) for firmware flashing.
CMD_BOOTLOADER = 0xF1 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 SCREEN_RESUME_UPDATES = 0xF1
# ── Wire layout ─────────────────────────────────────────────────────────────── # ── Wire layout ───────────────────────────────────────────────────────────────
+32 -15
View File
@@ -147,13 +147,13 @@ def read_firmware_info(hex_path: str | Path) -> FirmwareImageInfo:
if not mem: if not mem:
raise FirmwareImageError("HEX file does not contain data records.") raise FirmwareImageError("HEX file does not contain data records.")
build_struct = min(mem) + BUILD_STRUCT_OFFSET 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 ( if (
build_struct + VENDOR_ID_OFFSET_IN_BUILD_STRUCT not in mem build_struct + VENDOR_ID_OFFSET_IN_BUILD_STRUCT not in mem
or build_struct + PRODUCT_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.") 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_string: str | None = None
build_info_base = build_struct + BUILD_INFO_OFFSET_IN_BUILD_STRUCT build_info_base = build_struct + BUILD_INFO_OFFSET_IN_BUILD_STRUCT
@@ -390,36 +390,53 @@ class DfuUtilFlasher:
raise FirmwareFlashError(f"Could not run dfu-util: {exc}") from exc raise FirmwareFlashError(f"Could not run dfu-util: {exc}") from exc
stdout_parts: list[str] = [] stdout_parts: list[str] = []
stderr_parts: list[str] = []
def _read_stdout() -> None: def _read_stdout() -> None:
# dfu-util redraws its progress bar with '\r', so read # dfu-util redraws its progress bar with '\r', so track the
# char-by-char and surface the latest percentage as it arrives. # 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] = [] line: list[str] = []
while True: while True:
ch = proc.stdout.read(1) # type: ignore[union-attr] chunk = proc.stdout.read(256) # type: ignore[union-attr]
if ch == "": if chunk == "":
break break
stdout_parts.append(ch) stdout_parts.append(chunk)
if ch in "\r\n": for ch in chunk:
m = _PROGRESS_RE.search("".join(line)) if ch in "\r\n":
if m and progress_cb is not None: m = _PROGRESS_RE.search("".join(line))
progress_cb(min(100, max(0, int(m.group(1)))) / 100.0) if m and progress_cb is not None:
line = [] progress_cb(min(100, max(0, int(m.group(1)))) / 100.0)
else: line = []
line.append(ch) 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) reader = threading.Thread(target=_read_stdout, daemon=True)
stderr_reader = threading.Thread(target=_read_stderr, daemon=True)
reader.start() reader.start()
stderr_reader.start()
try: try:
proc.wait(timeout=timeout_s) proc.wait(timeout=timeout_s)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
proc.kill() proc.kill()
reader.join(timeout=5) reader.join(timeout=5)
stderr_reader.join(timeout=5)
raise FirmwareFlashError( raise FirmwareFlashError(
f"dfu-util did not finish within {timeout_s:.0f}s." f"dfu-util did not finish within {timeout_s:.0f}s."
) from None ) from None
reader.join(timeout=5) 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) stdout = "".join(stdout_parts)
downloaded = "File downloaded successfully" in (stdout + stderr) 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__), "..")) 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 as wv # noqa: E402
from nvcurve import wireview_firmware as wf # noqa: E402 from nvcurve import wireview_firmware as wf # noqa: E402
@@ -36,6 +41,10 @@ def check(name: str, cond: bool) -> None:
else: else:
FAIL += 1 FAIL += 1
print(f" FAIL {name}") 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: 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}) check("hex segment address", mem2 == {0x100: 0x42})
# A bad checksum must be rejected — a corrupt image must never flash. # 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 = _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]) path3 = _write_hex(tmp, [bad])
try: try:
wf._parse_hex_to_memory_map(path3) wf._parse_hex_to_memory_map(path3)
@@ -281,8 +292,10 @@ class _FakeStderr:
def __init__(self, text: str): def __init__(self, text: str):
self._text = text self._text = text
def read(self) -> str: def read(self, n: int | None = None) -> str:
return self._text # The flasher drains stderr in a read() loop until EOF.
out, self._text = self._text, ""
return out
class _FakeProc: class _FakeProc:
@@ -341,7 +354,12 @@ def test_dfu_flash():
wf.DfuUtilFlasher.flash(bin_path, 0x08000000, wf.DfuUtilFlasher.flash(bin_path, 0x08000000,
progress_cb=progress.append) progress_cb=progress.append)
check("flash no error", True) 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] args = popen.call_args.args[0]
check("flash args", check("flash args",
args == ["dfu-util", "-d 0483:df11", "-a", "0", args == ["dfu-util", "-d 0483:df11", "-a", "0",
@@ -410,8 +428,12 @@ def test_enter_bootloader():
master, slave = pty.openpty() master, slave = pty.openpty()
slave_path = os.ttyname(slave) slave_path = os.ttyname(slave)
received: queue.Queue = queue.Queue() received: queue.Queue = queue.Queue()
reader_started = threading.Event()
def run(): 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: while True:
try: try:
cmd = os.read(master, 1) cmd = os.read(master, 1)
@@ -439,6 +461,9 @@ def test_enter_bootloader():
t = threading.Thread(target=run, daemon=True) t = threading.Thread(target=run, daemon=True)
t.start() t.start()
try: 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) dev = wv.WireViewSerialDevice(slave_path)
check("boot: connect", dev.connect()) check("boot: connect", dev.connect())
check("boot: enter", dev.enter_bootloader()) check("boot: enter", dev.enter_bootloader())