Files
nvcurve/frontend/src/components/WireView/WireViewPanel.tsx
T
ARIA d9f5e34c80 feat: wireview clear fault status/log
- WireViewSerialDevice.clear_faults() sends CMD_CLEAR_FAULTS (0x0E)
  with 16-bit keep masks (0x0000 clears, 0xFFFF keeps); all port
  access is now serialized with an RLock so the poller, the
  clear-fault endpoint and the watchdog cannot interleave on the
  port mid-transaction.
- POST /api/wireview/clear-fault (serial transport only — in hwmon
  mode wireviewd owns the port and the masks are read-only); the
  sample is re-read immediately so clients see the cleared masks
  without waiting for the next poll tick.
- WireView tab: Clear buttons on the fault status/log badges.
- tests: protocol-level clear-fault tests via pty (byte-exact
  command framing, keep-mask semantics).
2026-10-05 20:08:26 +02:00

572 lines
21 KiB
TypeScript

import { 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 {
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
// full scale is 10 A (rating + headroom); red at/above the 9.2 A rating.
const PIN_RATED_A = 9.2;
const PIN_BAR_MAX_A = 10;
const FAULT_NAMES: Record<number, string> = {
0: "Chip over-temperature",
1: "Sensor over-temperature",
2: "Over-current (OCP)",
3: "Wire over-current",
4: "Over-power (OPP)",
5: "Current imbalance",
};
function decodeFaults(mask: number): string[] {
return Object.entries(FAULT_NAMES)
.filter(([bit]) => mask & (1 << Number(bit)))
.map(([, name]) => name);
}
function pluck(history: WireViewSample[], key: keyof WireViewSample): number[] {
return history.map((s) => (s[key] as number | null) ?? 0);
}
function FaultBadge({
label,
mask,
onClear,
clearing,
}: {
label: string;
mask: number;
onClear?: () => void;
clearing?: boolean;
}) {
const faults = decodeFaults(mask);
return (
<div
className={`rounded-lg p-3 border flex flex-col gap-1.5 min-w-0 ${
faults.length > 0
? "bg-red-500/10 border-red-500/40"
: "bg-zinc-900 border-zinc-800"
}`}
>
<div className="flex items-center justify-between gap-2">
<span className="text-xs text-zinc-500 uppercase tracking-wider">
{label}
</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">
{faults.map((f) => (
<span
key={f}
className="px-1.5 py-0.5 rounded bg-red-500/20 border border-red-500/40 text-red-300 text-[11px] font-medium"
>
{f}
</span>
))}
</div>
) : (
<div className="text-sm text-emerald-400 font-medium">No faults</div>
)}
</div>
);
}
function PinCard({
index,
voltage,
current,
power,
}: {
index: number;
voltage: number;
current: number;
power: number;
}) {
const loadPct = Math.min(100, (current / PIN_BAR_MAX_A) * 100);
const barColor =
current >= PIN_RATED_A
? "#f87171"
: loadPct >= 75
? "#fbbf24"
: "#34d399";
return (
<div className="bg-zinc-900 rounded-lg p-3 flex flex-col gap-1.5 min-w-0">
<div className="flex items-center justify-between">
<span className="text-xs text-zinc-500 uppercase tracking-wider">
Pin {index + 1}
</span>
<span className="text-[10px] font-mono text-zinc-600">
{current.toFixed(1)} / {PIN_RATED_A} A
</span>
</div>
<div className="grid grid-cols-3 gap-1 text-center">
<div>
<div className="text-[10px] text-zinc-600">V</div>
<div className="text-sm font-mono font-semibold text-violet-300">
{voltage.toFixed(2)}
</div>
</div>
<div>
<div className="text-[10px] text-zinc-600">A</div>
<div className="text-sm font-mono font-semibold text-cyan-300">
{current.toFixed(2)}
</div>
</div>
<div>
<div className="text-[10px] text-zinc-600">W</div>
<div className="text-sm font-mono font-semibold text-pink-300">
{power.toFixed(1)}
</div>
</div>
</div>
<div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden">
<div
className="h-full rounded-full transition-all duration-500"
style={{ width: `${loadPct}%`, backgroundColor: barColor }}
/>
</div>
</div>
);
}
function InfoItem({
label,
value,
}: {
label: string;
value: string | null | undefined;
}) {
if (!value) return null;
return (
<div className="flex flex-col gap-0.5 min-w-0">
<span className="text-xs text-zinc-500">{label}</span>
<span
className="text-sm font-mono text-zinc-200 truncate"
title={value}
>
{value}
</span>
</div>
);
}
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";
async function refreshFirmware() {
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]);
// 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]);
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.
await api.wireviewClearFault(
which === "status" ? 0x0000 : 0xffff,
which === "log" ? 0x0000 : 0xffff,
);
toast.success(
which === "status" ? "Fault status cleared" : "Fault log cleared",
);
} catch (err) {
toast.error(
err instanceof Error ? err.message : "Failed to clear fault",
);
} finally {
setClearing(null);
}
}
if (!sample) {
return (
<div className="bg-zinc-900 rounded-lg p-10 text-center text-zinc-500 flex flex-col items-center gap-2">
<div className="text-lg font-medium text-zinc-400">
WireView Pro II not connected
</div>
<div className="text-sm">
Plug in the device — the tab appears automatically once it is
detected.
</div>
</div>
);
}
const psuCap = sample.psu_capability_w > 0 ? sample.psu_capability_w : 600;
return (
<div className="flex flex-col gap-4 w-full">
{/* ── Header ─────────────────────────────────────────────────── */}
<div className="bg-zinc-900 rounded-lg p-4 border border-zinc-800 flex flex-wrap items-center gap-x-6 gap-y-2">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-emerald-400" />
<span className="text-lg font-semibold text-zinc-100">
{info?.device_name ?? "WireView Pro II"}
</span>
</div>
<span className="text-sm font-mono text-zinc-400">
{info?.hw_rev ? `HW ${info.hw_rev}` : ""}
{info?.firmware_version ? ` · FW ${info.firmware_version}` : ""}
</span>
<span className="text-sm font-mono text-zinc-400">
PSU {psuCap} W
</span>
<span className="text-xs font-mono text-zinc-600 ml-auto">
{info?.transport === "hwmon"
? `hwmon: ${info.port}`
: `serial: ${info?.port ?? ""}`}
</span>
</div>
{/* ── Main gauges ────────────────────────────────────────────── */}
<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">
12 VHPWR Connector
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-3">
<GaugeCard
label="Total Power"
value={fmt.watts(sample.power_total_w, 1)}
history={pluck(history, "power_total_w")}
color="#f472b6"
max={psuCap}
/>
<GaugeCard
label="Total Current"
value={`${sample.current_total_a.toFixed(2)} A`}
history={pluck(history, "current_total_a")}
color="#38bdf8"
max={(psuCap / 12) * 1.1}
/>
<GaugeCard
label="Avg Voltage"
value={`${sample.voltage_avg_v.toFixed(3)} V`}
history={pluck(history, "voltage_avg_v")}
color="#a78bfa"
max={13}
/>
<GaugeCard
label="Fan Duty"
value={fmt.pct(sample.fan_duty_pct)}
history={pluck(history, "fan_duty_pct")}
color="#fb923c"
max={100}
/>
</div>
</div>
{/* ── Per-pin ────────────────────────────────────────────────── */}
<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">
Per-Pin Readings
</div>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mt-3">
{sample.pins.map((pin, i) => (
<PinCard
key={i}
index={i}
voltage={pin.voltage_v}
current={pin.current_a}
power={pin.power_w}
/>
))}
</div>
</div>
{/* ── Temperatures ───────────────────────────────────────────── */}
<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">
Temperatures
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-3">
<GaugeCard
label="Temp In"
value={fmt.celsius(sample.temp_in_c, 1)}
history={pluck(history, "temp_in_c")}
color="#f87171"
max={90}
/>
<GaugeCard
label="Temp Out"
value={fmt.celsius(sample.temp_out_c, 1)}
history={pluck(history, "temp_out_c")}
color="#fb923c"
max={90}
/>
<GaugeCard
label="Ext Sensor 1"
value={fmt.celsius(sample.temp_ext1_c, 1)}
history={pluck(history, "temp_ext1_c")}
color="#fbbf24"
max={90}
/>
<GaugeCard
label="Ext Sensor 2"
value={fmt.celsius(sample.temp_ext2_c, 1)}
history={pluck(history, "temp_ext2_c")}
color="#a78bfa"
max={90}
/>
</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}
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">
Device
</div>
<div className="grid grid-cols-2 gap-x-6 gap-y-3 mt-3">
<InfoItem label="Hardware Revision" value={info?.hw_rev} />
<InfoItem label="Firmware" value={info?.firmware_version} />
<InfoItem label="Build" value={info?.build} />
<InfoItem label="UID" value={info?.uid} />
<InfoItem label="Transport" value={info?.transport} />
<InfoItem label="Port" value={info?.port} />
</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 * 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>
);
}