diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 6a42d46c..711b5e26 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -74,10 +74,11 @@ jobs: # bundle.resources picks it up. run: pyinstaller resistamet-api.spec --noconfirm --clean --distpath desktop/sidecar - - name: Smoke-test the frozen backend (handshake + /health) + - name: Smoke-test the frozen backend (handshake, /health, WebSocket upgrade) shell: python run: | - import json, subprocess, sys, time, urllib.request, os + import http.client, json, subprocess, sys, time, urllib.request, os + from urllib.parse import urlsplit exe = os.path.join("desktop", "sidecar", "resistamet-api", "resistamet-api.exe" if os.name == "nt" else "resistamet-api") proc = subprocess.Popen([exe, "--port", "0", "--simulate", "--config", "ci-config.json"], @@ -87,6 +88,18 @@ jobs: info = json.loads(line) with urllib.request.urlopen(info["url"] + "/health", timeout=10) as r: assert r.status == 200, r.status + # The desktop UI lives on this socket. uvicorn answers 404 here when + # its WebSocket implementation did not make it into the bundle. + parts = urlsplit(info["url"]) + conn = http.client.HTTPConnection(parts.hostname, parts.port, timeout=10) + conn.request("GET", "/session/events/ws?token=" + info["token"], headers={ + "Connection": "Upgrade", "Upgrade": "websocket", + "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==", + }) + status = conn.getresponse().status + conn.close() + print("websocket upgrade:", status) + assert status == 101, f"WebSocket upgrade answered {status}, not 101" proc.stdin.close() proc.wait(timeout=60) print("backend exited", proc.returncode) diff --git a/desktop/src/components/ErrorBoundary.tsx b/desktop/src/components/ErrorBoundary.tsx new file mode 100644 index 00000000..6d219c3c --- /dev/null +++ b/desktop/src/components/ErrorBoundary.tsx @@ -0,0 +1,54 @@ +// A render error must never leave an operator looking at a blank window with +// an instrument running. The measurement lives in the backend process and is +// unaffected; what the operator needs is to know that, to see what broke, and +// a way back to the Stop button. Two boundaries use this: one around the whole +// app, one around the settings dialog body so a broken section closes with the +// dialog instead of taking the measurement view with it. + +import { Component, type ErrorInfo, type ReactNode } from "react"; +import { Button, Notice } from "./ui"; + +interface Props { + children: ReactNode; + /** Where this boundary sits, for the message: "the settings dialog". */ + scope: string; + /** Offered instead of a reload when the parent can recover (close the dialog). */ + onDismiss?: (() => void) | undefined; +} + +interface State { + error: Error | null; +} + +export class ErrorBoundary extends Component { + state: State = { error: null }; + + static getDerivedStateFromError(error: Error): State { + return { error }; + } + + componentDidCatch(error: Error, info: ErrorInfo): void { + console.error(`render error in ${this.props.scope}`, error, info.componentStack); + } + + render(): ReactNode { + const { error } = this.state; + if (error === null) return this.props.children; + return ( +
+ + Display error in {this.props.scope}: {error.message}. A running measurement is unaffected: it lives in the + backend, not in this window. + +
+ {this.props.onDismiss ? ( + + ) : null} + +
+
+ ); + } +} diff --git a/desktop/src/components/dialogs/SettingsDialog.tsx b/desktop/src/components/dialogs/SettingsDialog.tsx index 7d357b46..ad699250 100644 --- a/desktop/src/components/dialogs/SettingsDialog.tsx +++ b/desktop/src/components/dialogs/SettingsDialog.tsx @@ -13,6 +13,7 @@ import type { InstrumentInfo, Profile, VisaBackend } from "../../lib/api"; import { ApiError } from "../../lib/api"; import { useSession } from "../../state/session"; import { setTheme, useUi } from "../../state/ui"; +import { ErrorBoundary } from "../ErrorBoundary"; import { FieldRow } from "../forms/SettingsForm"; import { Button, Dialog, Field, Input, Notice, Select } from "../ui"; import styles from "./dialogs.module.css"; @@ -153,85 +154,87 @@ export function SettingsDialog({ onClose }: Props) { ))}
- {error ? {error} : null} - {profile === null && !error ?
Loading…
: null} + + {error ? {error} : null} + {profile === null && !error ?
Loading…
: null} - {profile && section === "timing" - ? TIMING.map((spec) => ( - set("measurement", spec.key, v)} - disabled={running} - /> - )) - : null} + {profile && section === "timing" + ? TIMING.map((spec) => ( + set("measurement", spec.key, v)} + disabled={running} + /> + )) + : null} - {profile && section === "instrument" ? : null} + {profile && section === "instrument" ? : null} - {profile && section === "aux" - ? AUX.map((spec) => ( - set("measurement", spec.key, v)} - disabled={running} - /> - )) - : null} + {profile && section === "aux" + ? AUX.map((spec) => ( + set("measurement", spec.key, v)} + disabled={running} + /> + )) + : null} - {profile && section === "safety" - ? SAFETY.map((spec) => ( - set("measurement", spec.key, v)} - disabled={running} - /> - )) - : null} + {profile && section === "safety" + ? SAFETY.map((spec) => ( + set("measurement", spec.key, v)} + disabled={running} + /> + )) + : null} - {profile && section === "files" ? ( - <> - {FILES.map((spec) => ( - set("file", spec.key, v)} - disabled={running} - /> - ))} -
Output
- {OUTPUT.map((spec) => ( - set("output", spec.key, v)} - disabled={running} - /> - ))} - - ) : null} + {profile && section === "files" ? ( + <> + {FILES.map((spec) => ( + set("file", spec.key, v)} + disabled={running} + /> + ))} +
Output
+ {OUTPUT.map((spec) => ( + set("output", spec.key, v)} + disabled={running} + /> + ))} + + ) : null} - {section === "display" ? ( - - - - ) : null} + {section === "display" ? ( + + + + ) : null} +
diff --git a/desktop/src/components/forms/SettingsForm.tsx b/desktop/src/components/forms/SettingsForm.tsx index ac9c69cc..217a4ed7 100644 --- a/desktop/src/components/forms/SettingsForm.tsx +++ b/desktop/src/components/forms/SettingsForm.tsx @@ -30,17 +30,20 @@ export function SettingsForm({ mode, groups, values, onChange, issues = [], disa {groups.map((group) => (
{group.title} - {group.fields.map((spec) => ( - onChange(spec.key, v)} - issue={issueFor(spec.key)} - disabled={disabled} - /> - ))} + {group.fields.map((spec) => { + const overridden = spec.overriddenBy !== undefined && values[spec.overriddenBy.key] === spec.overriddenBy.when; + return ( + onChange(spec.key, v)} + issue={issueFor(spec.key)} + disabled={disabled || overridden} + /> + ); + })}
))} @@ -81,6 +84,22 @@ export function FieldRow({ spec, meta, value, onChange, issue, disabled }: RowPr ); } + if (meta.type === "string") { + // Free text: an address, a driver name, a directory. Never the numeric + // input, whose formatter would throw on a string mid-render. + return ( + + onChange(e.target.value)} + /> + + ); + } + if (meta.type === "integer") { // Counts are counts: no prefixes, no decimals. const current = typeof value === "number" ? value : ((meta.default as number | undefined) ?? 0); diff --git a/desktop/src/components/plot/LivePlot.tsx b/desktop/src/components/plot/LivePlot.tsx index 570735cd..962c0662 100644 --- a/desktop/src/components/plot/LivePlot.tsx +++ b/desktop/src/components/plot/LivePlot.tsx @@ -10,7 +10,7 @@ import { useEffect, useRef } from "react"; import uPlot, { type AlignedData, type Options, type Series } from "uplot"; import "uplot/dist/uPlot.min.css"; import { getSeries, getSamplesVersion } from "../../state/samples"; -import { engineering } from "../../lib/format"; +import { axisLabels, engineering } from "../../lib/format"; import styles from "./LivePlot.module.css"; export interface TraceSpec { @@ -70,14 +70,7 @@ export function LivePlot({ traces, mode, windowS = 0, fps = 30 }: Props) { })), ]; - const axisValues = (unit: string) => (_u: uPlot, ticks: number[]) => { - // Pick one prefix for the whole axis from the largest tick so labels - // read as a scale, not a jumble of prefixes. - const largest = ticks.reduce((m, v) => Math.max(m, Math.abs(v)), 0); - const ref = engineering(largest || 1, unit); - const factor = largest ? Number(ref.mantissa) / largest : 1; - return ticks.map((v) => (v * factor).toPrecision(4).replace(/\.?0+$/, "") + (ref.unit ? ` ${ref.unit}` : "")); - }; + const axisValues = (unit: string) => (_u: uPlot, ticks: number[]) => axisLabels(ticks, unit); const leftUnit = traces.find((t) => !t.rightAxis)?.unit ?? ""; const rightUnit = traces.find((t) => t.rightAxis)?.unit ?? ""; diff --git a/desktop/src/components/plot/XYPlot.tsx b/desktop/src/components/plot/XYPlot.tsx index 01ff2ed5..f59a2990 100644 --- a/desktop/src/components/plot/XYPlot.tsx +++ b/desktop/src/components/plot/XYPlot.tsx @@ -5,7 +5,7 @@ import { useEffect, useRef } from "react"; import uPlot, { type AlignedData, type Options } from "uplot"; import "uplot/dist/uPlot.min.css"; -import { engineering } from "../../lib/format"; +import { axisLabels } from "../../lib/format"; import styles from "./LivePlot.module.css"; export interface XYSeries { @@ -40,12 +40,7 @@ export function XYPlot({ series, xUnit, yUnit }: Props) { const gridLine = computed.getPropertyValue("--grid-line").trim() || "rgba(255,255,255,.08)"; const font = "11px " + computed.getPropertyValue("--font-mono"); - const axisValues = (unit: string) => (_u: uPlot, ticks: number[]) => { - const largest = ticks.reduce((m, v) => Math.max(m, Math.abs(v)), 0); - const ref = engineering(largest || 1, unit); - const factor = largest ? Number(ref.mantissa) / largest : 1; - return ticks.map((v) => (v * factor).toPrecision(4).replace(/\.?0+$/, "") + (ref.unit ? ` ${ref.unit}` : "")); - }; + const axisValues = (unit: string) => (_u: uPlot, ticks: number[]) => axisLabels(ticks, unit); // uPlot wants one shared x array. Series with different x sets are // merged onto the union of x values, with nulls where a series has none. diff --git a/desktop/src/lib/fields.ts b/desktop/src/lib/fields.ts index 2d696702..a6dfd88d 100644 --- a/desktop/src/lib/fields.ts +++ b/desktop/src/lib/fields.ts @@ -22,6 +22,10 @@ export interface FieldSpec { hint?: string; /** Enum labels, when the raw values are not self-explanatory. */ options?: Record; + /** The instrument ignores this field while another field has a given + * value; the row is shown disabled with `hint` so the number on screen is + * not mistaken for the number in use. */ + overriddenBy?: { key: string; when: unknown; hint: string }; } export interface FieldGroup { @@ -35,8 +39,22 @@ export const RESISTANCE_FIELDS: FieldGroup>[] = [ { title: "Source", fields: [ - { key: "res_test_current", label: "Test current", unit: "A" }, - { key: "res_voltage_compliance", label: "Voltage compliance", unit: "V" }, + // With Auto range on, the 2400's auto-ohms picks the test current per + // range and sets its own voltage limit (2.1 V seen for a 0.5 V request); + // the CSV's Current column and effective.voltage_compliance_V record + // what it chose. Bench, 2026-09-18. + { + key: "res_test_current", + label: "Test current", + unit: "A", + overriddenBy: { key: "res_auto_range", when: true, hint: "Chosen by the instrument per range while Auto range is on." }, + }, + { + key: "res_voltage_compliance", + label: "Voltage compliance", + unit: "V", + overriddenBy: { key: "res_auto_range", when: true, hint: "Set by the instrument while Auto range is on; the file records the value in force." }, + }, ], }, { diff --git a/desktop/src/lib/format.ts b/desktop/src/lib/format.ts index 678e7d40..0aecc073 100644 --- a/desktop/src/lib/format.ts +++ b/desktop/src/lib/format.ts @@ -25,15 +25,35 @@ export interface Engineering { * shown at face value: "50 mcm" is not a thing. */ const PREFIXABLE = new Set(["", "Ω", "V", "A", "W", "s", "Hz", "F", "H", "S", "Ω·cm", "S/cm"]); +/** The SI prefix a magnitude is shown with, and the factor that goes with it. */ +export function prefixFor(value: number, unit = ""): { scale: number; prefix: string } { + if (!PREFIXABLE.has(unit) || !Number.isFinite(value) || value === 0) return { scale: 1, prefix: "" }; + const magnitude = Math.abs(value); + const [scale, prefix] = PREFIXES.find(([s]) => magnitude >= s * 0.9995) ?? PREFIXES[PREFIXES.length - 1]!; + return { scale, prefix }; +} + /** Split a value into a mantissa and a prefixed unit. NaN yields "—". */ export function engineering(value: number, unit = "", digits = 4): Engineering { if (!Number.isFinite(value)) return { mantissa: "—", unit }; if (value === 0) return { mantissa: "0", unit }; - if (!PREFIXABLE.has(unit)) return { mantissa: toSignificant(value, digits), unit }; - const magnitude = Math.abs(value); - const [scale, prefix] = PREFIXES.find(([s]) => magnitude >= s * 0.9995) ?? PREFIXES[PREFIXES.length - 1]!; - const scaled = value / scale; - return { mantissa: toSignificant(scaled, digits), unit: prefix + unit }; + const { scale, prefix } = prefixFor(value, unit); + return { mantissa: toSignificant(value / scale, digits), unit: prefix + unit }; +} + +/** Axis tick labels: one prefix for the whole axis, and as many decimals as + * the tick spacing needs so neighbouring ticks never read the same. A + * resistance trace lives in the last digits (10.075 … 10.080 Ω), which four + * significant figures cannot show. */ +export function axisLabels(ticks: number[], unit = ""): string[] { + const largest = ticks.reduce((m, v) => Math.max(m, Math.abs(v)), 0); + const { scale, prefix } = prefixFor(largest || 1, unit); + const scaled = ticks.map((v) => v / scale); + let spacing = Number.POSITIVE_INFINITY; + for (let i = 1; i < scaled.length; i++) spacing = Math.min(spacing, Math.abs(scaled[i]! - scaled[i - 1]!)); + const decimals = Number.isFinite(spacing) && spacing > 0 ? Math.min(10, Math.max(0, Math.ceil(-Math.log10(spacing) - 1e-9))) : 0; + const suffix = prefix + unit ? ` ${prefix}${unit}` : ""; + return scaled.map((v) => (Math.abs(v) < 0.5 * 10 ** -decimals ? (0).toFixed(decimals) : v.toFixed(decimals)) + suffix); } export function formatEngineering(value: number, unit = "", digits = 4): string { diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx index 72914648..98660b93 100644 --- a/desktop/src/main.tsx +++ b/desktop/src/main.tsx @@ -1,10 +1,13 @@ import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; +import { ErrorBoundary } from "./components/ErrorBoundary"; import "./styles/global.css"; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( - + + + , ); diff --git a/desktop/src/state/sweep.ts b/desktop/src/state/sweep.ts index b6cad2e5..4d8cdf1d 100644 --- a/desktop/src/state/sweep.ts +++ b/desktop/src/state/sweep.ts @@ -41,6 +41,8 @@ export function resetSweep(runId: string | null): void { export function applySweepSegment(event: Event<"sweep_segment">): void { const { payload } = event; + // A replayed segment from an earlier run must not join this run's curve. + if (result.runId !== null && event.run_id && event.run_id !== result.runId) return; publish({ runId: event.run_id ?? null, segments: [ diff --git a/desktop/src/state/vdp.ts b/desktop/src/state/vdp.ts index f3baa3d4..aae95af5 100644 --- a/desktop/src/state/vdp.ts +++ b/desktop/src/state/vdp.ts @@ -33,10 +33,20 @@ export function resetVdp(runId: string | null): void { publish({ runId, geometries: [], result: null }); } +/** Events belong to the run that run_started announced. A replay after a + * reconnect can carry the previous run's geometries and result; those must + * not land on top of the run in progress. (Bench: an aborted run showed the + * previous run's complete result badged Done.) */ +function forThisRun(runId: string | null | undefined): boolean { + return state.runId === null || runId === undefined || runId === null || runId === state.runId; +} + export function applyVdpGeometry(event: Event<"vdp_geometry_complete">): void { + if (!forThisRun(event.run_id)) return; publish({ ...state, runId: event.run_id ?? state.runId, geometries: [...state.geometries, event.payload] }); } export function applyVdpResult(event: Event<"vdp_result">): void { + if (!forThisRun(event.run_id)) return; publish({ ...state, runId: event.run_id ?? state.runId, result: event.payload }); } diff --git a/desktop/src/views/sweep/SweepView.tsx b/desktop/src/views/sweep/SweepView.tsx index 0feec6a6..2e06678a 100644 --- a/desktop/src/views/sweep/SweepView.tsx +++ b/desktop/src/views/sweep/SweepView.tsx @@ -24,6 +24,13 @@ import own from "./SweepView.module.css"; const MODE: Mode = "sweep"; +/** Conservative sweeps per source, applied when the source is switched. The + * voltage set is the profile default; the current set is its mirror at the + * scale a 2400 sources into an unknown DUT without drama. */ +const SWEEP_FOR_VOLTAGE = { sweep_start: 0.0, sweep_stop: 1.0, sweep_step: 0.05, sweep_compliance: 0.1 }; +// sweep_compliance is bounded at 3 in the schema whatever the unit, so 2 V. +const SWEEP_FOR_CURRENT = { sweep_start: 0.0, sweep_stop: 1e-3, sweep_step: 50e-6, sweep_compliance: 2.0 }; + export function SweepView() { const api = useApi(); const session = useSession(); @@ -62,7 +69,25 @@ export function SweepView() { }; }, [api, ui.username, overrides]); - const onChange = useCallback((key: string, value: unknown) => setOverride(MODE, key, value), []); + // The start, stop, step and compliance numbers are in volts or amps + // depending on the source. Switching the source must not keep the numbers + // and change their meaning: a 2 V compliance would silently become 2 A. + // They reset to a conservative sweep for the new source instead, and the + // view says so until the next edit. + const [reset, setReset] = useState(null); + const onChange = useCallback( + (key: string, value: unknown) => { + if (key === "sweep_source" && value !== (overrides.sweep_source ?? "voltage")) { + const range = value === "current" ? SWEEP_FOR_CURRENT : SWEEP_FOR_VOLTAGE; + for (const [k, v] of Object.entries(range)) setOverride(MODE, k, v); + setReset(value === "current" ? "Start, stop, step and compliance reset for a current source: 0 to 1 mA in 50 µA steps, 2 V limit." : "Start, stop, step and compliance reset for a voltage source: 0 to 1 V in 50 mV steps, 100 mA limit."); + } else if (key !== "sweep_source") { + setReset(null); + } + setOverride(MODE, key, value); + }, + [overrides.sweep_source], + ); const sourceIsVoltage = (overrides.sweep_source ?? "voltage") === "voltage"; const sourceUnit = sourceIsVoltage ? "V" : "A"; @@ -121,6 +146,7 @@ export function SweepView() { {error ? {error} : null} + {reset ? {reset} : null} {running && !thisRunning ? Another run is in progress. : null} {ui.sampleName.trim() === "" && !running ? Name the sample in the top bar to enable the sweep. : null} {resolved?.hazard?.hazardous && !running ? ( diff --git a/desktop/src/views/vdp/VdpView.tsx b/desktop/src/views/vdp/VdpView.tsx index e9ed0886..604ae344 100644 --- a/desktop/src/views/vdp/VdpView.tsx +++ b/desktop/src/views/vdp/VdpView.tsx @@ -97,8 +97,13 @@ export function VdpView() { run(() => api.start({ mode: MODE, sample_name: ui.sampleName.trim(), username: ui.username!, overrides })); const measure = (p: PendingPrompt) => run(() => api.answerPrompt(p.prompt_id, "proceed")); - const done = vdp.geometries.length; - const result = vdp.result; + // What the store holds is only this run's if the run ids agree: between + // pressing Start and the run_started event, and after a replay, the store + // can still describe the previous run. + const current = status === null || status.run_id === null || vdp.runId === null || vdp.runId === status.run_id; + const geometries = current ? vdp.geometries : []; + const done = geometries.length; + const result = current ? vdp.result : null; return (
@@ -181,7 +186,7 @@ export function VdpView() { - {vdp.geometries.length === 0 ? ( + {geometries.length === 0 ? (
None yet.
) : ( @@ -194,7 +199,7 @@ export function VdpView() { - {vdp.geometries.map((g) => ( + {geometries.map((g) => (
{g.name} {g.group} diff --git a/docs/design/ni_usb_gpib_protocol.md b/docs/design/ni_usb_gpib_protocol.md index f2c1ceab..a7b56fa8 100644 --- a/docs/design/ni_usb_gpib_protocol.md +++ b/docs/design/ni_usb_gpib_protocol.md @@ -128,6 +128,14 @@ ready all three are 0x00. A single readiness query without the loop has been observed to succeed on an already-settled HS; the loop is the normative form (2.8). +Observed on GPIB-USB-HS 01CEE482 (bcdDevice 0x101), 2026-09-18: the reply +is `40 01 00 01 30 01 19 08 00 00 65` (11 bytes), i.e. byte 6 = 0x19, +byte 7 = 0x08, byte 9 = 0x00, byte 10 = 0x65, immediately after a USB +reset and unchanged afterwards. These bytes therefore vary between units +or firmware versions (0x65 = 101 matches the 1.01 of bcdDevice); only +"nonzero" carries meaning. The serial-number reply was `41 82 e4 ce 01` +(5 bytes), decoding to 0x01CEE482 as described. + ### 2.4 Model-specific extra initialisation - **HS+**: after the readiness poll, issue the three control requests @@ -388,9 +396,10 @@ Register-read reply layouts: - 1 register: `34 v0 00 00 | 35 k 00 00 [| 04 00 00 00]`, k mod 3 = 1. - 4 registers (USB-B serial read): `34 v0 v1 v2 | 34 v3 pp pp | 35 k 00 00 [| 04 00 00 00]`, where `pp` is padding of the partial final chunk - (value unverified; expect 0x00) and k mod 3 = 1. Uncertain: whether - the termination block follows the 0x35 block; request 32 bytes and - accept a shorter transfer. + (value unverified; expect 0x00) and k mod 3 = 1. Observed on the + GPIB-USB-HS (one register): the termination block does follow, the + reply is exactly `34 vv 00 00 35 01 00 00 04 00 00 00` (12 bytes). + Request 32 bytes and accept a shorter transfer. Reply sizes to expect: @@ -400,12 +409,11 @@ Reply sizes to expect: | 0x09 register write | 16 | status block (8, id 0x09) + `k 00 00 00` (k = writes completed) + `04 00 00 00` | | 0x08 register read | up to 32 | 0x34 chunks + 0x35 block (+ termination, uncertain) | | 0x07 parallel poll | up to 32 | status block (8) + result byte + padding (+ termination, uncertain) | -| 0x0a read | see 5.2 | data blocks + 28-byte trailer | +| 0x0a read | see 5.2 | data blocks + 16-byte trailer (observed; the sources implied 28) | The 12- and 16-byte reply lengths are exact and can be asserted. -Uncertain: whether the trailing 4 bytes of those replies are always -`04 00 00 00`; the arithmetic (8 + 4, 8 + 4 + 4) strongly implies it, -but the bytes have not been verified. +Observed on the GPIB-USB-HS: the trailing 4 bytes of every such reply are +`04 00 00 00`. ### 3.6 Worked hex examples @@ -435,7 +443,8 @@ IN : 0d ss ss ee cc cc 00 00 04 00 00 00 `fa ff` = -6 little-endian; byte 6 = 0x08 requests EOI; two pad bytes after the data. -**Read up to 256 bytes, EOS disabled:** +**Read up to 256 bytes, EOS disabled (OUT observed; IN as the sources +implied it, NOT what the device sends -- see the next example):** ``` OUT: 0a 00 00 fc 00 ff 00 00 09 02 00 01 0a 51 01 0a 55 00 00 00 04 00 00 00 IN : 36 41 42 43 44 45 0a xx xx xx xx xx xx xx xx xx @@ -449,9 +458,36 @@ Instrument answered `ABCDE\n` (6 bytes) with EOI. One 0x36 block; the `xx` filler after the 6 valid bytes is unspecified. Status: id 0x38, error 0, count `06 ff` = 0xff06 = 6 - 256 (250 bytes not transferred). `aa` = ADR1 register bits (ignored); `06` = valid bytes in the last data block; -`00 00` pad; then the status of the embedded 2-register write (id 0x09, -`02` = two writes completed, 3 pad bytes) and the termination block. Total -44 bytes = one 16-byte data block + 28-byte trailer. +`00 00` pad. The two blocks `09 ...` / `02 00 00 00` (status of the +embedded 2-register write) were inferred from the sources and are **not +sent** by the GPIB-USB-HS; a parser must accept their absence. + +**Read up to 256 bytes, EOS disabled -- observed on GPIB-USB-HS 01CEE482 +with a Keithley 2400 at PAD 3, 2026-09-18:** +``` +OUT: 0a 00 00 fc 00 ff 00 00 09 02 00 01 0a 51 01 0a 55 00 00 00 04 00 00 00 +IN : 37 00 4b 45 49 54 48 4c 45 59 20 49 4e 53 54 52 55 4d 45 4e 54 53 20 49 4e 43 2e 2c 4d 4f 44 45 + 37 00 4c 20 32 34 30 30 2c 31 31 37 35 36 38 30 2c 43 33 30 20 20 20 4d 61 72 20 31 37 20 32 30 + 37 00 30 36 20 30 39 3a 32 39 3a 32 39 2f 41 30 32 20 20 2f 4b 2f 4a 0a 00 00 00 00 00 00 00 00 + 38 20 20 00 52 ff ff ff + e0 16 00 00 + 04 00 00 00 +``` +112 bytes in one USB transfer (64 + 48). Payload: `KEITHLEY INSTRUMENTS +INC.,MODEL 2400,1175680,C30 Mar 17 2006 09:29:29/A02 /K/J\n` (82 +bytes) in three 30-byte 0x37 blocks, the last holding 22 valid bytes +(`16`) and then filler. Status: ibsta 0x2020 (END, CIC), error 0, count +`52 ff` = 0xff52 = 82 - 256; bytes 6-7 `ff ff`. `e0` = ADR1 with bit 7 set +(EOI seen); `00 00` pad; termination. Trailer = 16 bytes. + +Also observed (same setup): a 1-byte read (serial poll) and a 5-byte read +arrive in 0x36 blocks (`36 00 20 00 aa 55 ff ff ... | 38 00 20 00 00 00 01 +00 60 01 00 00 04 00 00 00`), so the block size depends on the request; +the filler after the valid bytes is stale data from earlier replies; ADR1 +is 0x60 without EOI. A read that times out with nothing to read returns +the bare 16-byte trailer `38 00 20 0a c0 ff ff ff e0 5e 00 00 04 00 00 00` +(error 0x0a, count 0xffc0 = 0 - 64); the last-block-count byte (`5e`) is +meaningless when there is no data block. **Register read of BSR (bus lines):** ``` @@ -477,8 +513,8 @@ IN : 01 ss ss ee 00 00 00 00 04 00 00 00 | 0 | 1 | id | echoes the instruction opcode; 0x38 for the read-data status | | 1 | 2 | ibsta | **big-endian** (byte 1 = high byte) | | 3 | 1 | error code | see 4.3; 0 = success | -| 4 | 2 | count | **little-endian**, two's complement: (transferred - requested). Bytes not transferred = (0x10000 - count) & 0xffff; bytes transferred = requested - that. 0 when everything was transferred. | -| 6 | 2 | unused | observed 0x00 0x00 | +| 4 | 2 | count | **little-endian**, two's complement: (transferred - requested). Bytes not transferred = (0x10000 - count) & 0xffff; bytes transferred = requested - that. 0 when everything was transferred. **Meaningful only in replies to 0x0a, 0x0c, 0x0d.** Observed on the GPIB-USB-HS: replies to 0x01 and 0x06 carry `aa 55` here, and replies to 0x09 and 0x0f carry the count left over from the last data operation (`ff ff` after a reset, `52 ff` after a read that transferred 82 of 256). | +| 6 | 2 | unused | observed 0x00 0x00 (sources); on the GPIB-USB-HS `ff ff` in most replies, `01 00` in a read reply that filled the requested count, `00 00` after a successful 0x0d | The same 8-byte layout is returned by control requests 0x20 and 0x21 and pushed on the interrupt endpoint. @@ -594,17 +630,24 @@ to work. may be ignored -- use ibsta END instead. 4. 1 byte: number of valid data bytes in the LAST data block (0 if none). 5. 2 bytes: 0x00 0x00. - 6. 8-byte status block, id 0x09 (status of the embedded register write). - 7. 1 byte: 0x02 (two writes completed), then 3 bytes 0x00. - 8. `04 00 00 00`. - Items 2-8 form a fixed 28-byte trailer. + 6. `04 00 00 00`. + Items 2-6 form a fixed 16-byte trailer (observed on the GPIB-USB-HS, + 2026-09-18). The sources implied two further items before the + termination block -- an 8-byte status block with id 0x09 for the + embedded register write, then `02 00 00 00` -- making 28 bytes; the + device does not send them. A parser should accept both forms. +- Block size: reads of 1 and 5 bytes arrived in 0x36 blocks, a read of up + to 256 bytes in 0x37 blocks (observed). The filler after the valid bytes + of the last block is stale data, not zeros. - Bytes actually read = (blocks - 1) × block_size + last_block_count, or - 0 if no data block. Cross-check: it must equal requested - (bytes not - transferred from the 0x38 count field). + 0 if no data block (the last-block-count byte is then meaningless). + Cross-check: it must equal requested - (bytes not transferred from the + 0x38 count field). - Host receive buffer for a requested N: ceil(N/30) 32-byte blocks (or - ceil(N/15) 16-byte blocks) plus the 28-byte trailer; request the larger - of the two, rounded up to the endpoint's max packet size. The device - ends the reply with a short packet. + ceil(N/15) 16-byte blocks) plus the trailer (size for 28 bytes, the + longer form); request the larger of the two, rounded up to the + endpoint's max packet size. The device ends the reply with a short + packet. - End conditions: ibsta END (0x2000) set in the 0x38 block means the read ended on EOI or, when `m` has 0x04, on the EOS character (NI-488.2 convention). END clear with error 0 means the count was reached. Error @@ -740,8 +783,10 @@ Presence signals attested on this adapter: the instrument. Recommended non-intrusive probe for address N (IEEE-488.1 acceptor -handshake sampled via 5.13; not bench-verified with this adapter -- -uncertain): +handshake sampled via 5.13). Bench-verified on the GPIB-USB-HS with a +Keithley 2400 at PAD 3, 2026-09-18: BSR read 0x01 (REN only) for empty +addresses and had NDAC set for address 3; the probe over 1..30 returned +exactly [3]: 1. 0x0c `3f 20+N` (UNL, LAD N). Error 5 here means the bus is empty; stop. 2. 0x06 (go to standby, ATN false). @@ -908,6 +953,38 @@ reported through the status block rather than as a USB error. driver does; their meaning is unknown. Do not omit them. 16. Absence of serial/parallel poll or SRQ handling in a known working implementation is not evidence those instructions fail. +17. **A hung adapter.** Observed on GPIB-USB-HS 01CEE482, 2026-09-18: the + adapter answered every control request normally (serial number, + readiness, status and stop), accepted bulk OUT messages on 0x02 until + about 4 KB had been queued (and about 1 KB on 0x06), then NAKed, and + never sent a byte on 0x84, 0x88 or 0x81. Nothing on the USB side + cleared it: not the stop request, the monitor mask, clear-halt, + SET_CONFIGURATION 0/1, nor a USB bus reset (which empties the + endpoint FIFOs but does not restart the firmware). Unplugging and + replugging the adapter fixed it at once. A driver should treat "the + initialisation message was accepted but no reply arrived within 2 s, + nor after a stop request" as this condition and tell the user to + power-cycle the adapter. +18. **Settle after IFC / REN before the first addressed command.** Observed + on GPIB-USB-HS 01CEE482 with a Keithley 2400 at PAD 3, 2026-09-18: with + the sequence attach -> presence probe (5.16, which addresses the + instrument and puts it in remote) -> shutdown (2.9; the chip reset drops + REN, the instrument returns to local) -> attach (IFC, REN, take control) + -> `3f 40 23`, `0d ... *IDN?` within about 1 ms, the write instruction + reported all 6 bytes transferred (the instrument's interface handshakes + in hardware) but the instrument never parsed them: the following read + timed out and the instrument logged `-420,"Query UNTERMINATED"`. It + reproduced within 1-4 iterations; without the probe (instrument never + in remote) it did not reproduce in 20. A pause of 20 ms after take + control, or after the shutdown, was already enough (10/10 each); the + driver waits 100 ms after the attach's take control and after a public + IFC pulse. The adapter also hung once (8.17) under the application at + exactly this point -- the first `0x0c` after such an attach never + answered even after the device timeout -- so a stalled handshake with an + instrument in this state may be what wedges the firmware; with the pause + in place the sequence ran 10 x (attach, probe, close, attach, `*IDN?`, + 50 x `:OUTP?`, close) with no gap and 5 more cycles through pyvisa + without incident. --- @@ -928,6 +1005,18 @@ formats are described from the device's point of view, not the programs'. | gpib_user.h (linux-gpib public API header; used only to confirm NI-488.2 ibsta bit numbers, EOS flag values and command bytes) | https://sourceforge.net/p/linux-gpib/code/HEAD/tree/trunk/linux-gpib-kernel/drivers/gpib/include/gpib_user.h?format=raw | 8680bb597a799f19ab6d96551100aa2705954eab6fd1f1e7645eb2b28def1dbc | | TNT4882 Programmer Reference Manual, NI part 370872A-01 (July 1995) | https://docs-be.ni.com/bundle/tnt4882-programmer-reference/raw/resource/enus/370872a.pdf | 11a790cc4050cb330c0a1654dca5e49ccb9d548ed5b12ab3363d9e161f79d9fb | +Bench observations: statements marked "observed on GPIB-USB-HS 01CEE482" +were recorded on 2026-09-18 from a GPIB-USB-HS (USB 3923:709b, bcdDevice +0x101, serial 01CEE482) on macOS through pyusb/libusb, with a Keithley +2400 at primary address 3 on the bus, using the clean-room driver in +`resistamet_gui/gpib_usb/` and a byte-level trace of every USB transfer. +They correct the sources in these places: the read-reply trailer is 16 +bytes (5.2, 3.5, 3.6); the count field is meaningful only after data +operations and bytes 6-7 are not zero (4.1); the termination block follows +the 0x35 block of a register-read reply (3.5); the readiness reply's +informational bytes vary by unit (2.3); the 5.16 probe works; the hung +state of 8.17 exists; and instruments need a pause after IFC/REN (8.18). + Section-level attribution: sections 1-5, 7 and 8 -- linux-gpib ni_usb_gpib.c / ni_usb_gpib.h and ni-gpib-usb-hs controller.py; register names and bit meanings in 2.6, 2.7, 3.4, 5.13 -- linux-gpib diff --git a/docs/design/tauri_backend_split.md b/docs/design/tauri_backend_split.md index f2f155cf..e358ac1d 100644 --- a/docs/design/tauri_backend_split.md +++ b/docs/design/tauri_backend_split.md @@ -995,7 +995,7 @@ MW:2014-2049; widget reads MW:1950-2012 stay). No `api.py` or session god object | **42c** | `prompt_timeout_s` on `RunRequest`; watchdog in `MeasurementSession` only | ~50 + 60 test | Add (headless-only; PySide6 path untouched) | Timeout takes the `abort()` path: output off, file finalized, `run_ended{prompt_timeout}`; a prompt answered in time cancels the watchdog; Qt path asserted to have no timeout | | **43** | `tests/test_session_e2e.py` | ~350 test | Tests | Each ported assertion mapped to its `test_e2e_simulator.py` line in the PR body; spot test deferral stated | | **44** | `ConfigManager` lock + temp-file `os.replace` | ~40 + 60 test | **Behavior** (write mechanics only; format unchanged) | Lock never held across anything but mutate+save; Windows `os.replace` semantics | -| **45** | `session/instrument_lock.py`: `fcntl.flock` / `msvcrt.locking` on `/locks/.lock`, held from before connect to after `_cleanup`, for the SMU address and the aux port; acquired in the shared run procedures, so PySide6 and the session both get it | ~120 + 100 test | **Behavior**: a second process is refused with `error{code: instrument_busy}` instead of colliding on the bus | No stale-lock logic (the OS releases on process death — stated and tested by killing a child); lock acquired *before* any VISA open and released after output-off; two-process test on the simulator; identify/Test Connection also guarded | +| **45** | `session/instrument_lock.py`: `fcntl.flock` / `msvcrt.locking` on `~/.resistamet/locks/.lock` (one place per machine, not beside the config: two processes only exclude each other if they agree on where the lock is — the first version keyed it to the config directory and the bench found two backends never contending), taken by the session before `start` answers so a refusal is synchronous, held to after `_cleanup`, for the SMU address and the aux port; acquired in the shared run procedures, so PySide6 and the session both get it | ~120 + 100 test | **Behavior**: a second process is refused with `error{code: instrument_busy}` instead of colliding on the bus | No stale-lock logic (the OS releases on process death — stated and tested by killing a child); lock acquired *before* any VISA open and released after output-off; two-process test on the simulator; identify/Test Connection also guarded | | **46** | `RunControl` accumulates paused time; duration check subtracts it (W:641, W:1089) | ~30 + 50 test | **Behavior**: a run paused across its deadline resumes and runs its remaining time | `elapsed_s`/`t_unix`/CSV elapsed unchanged (asserted); pause → wait → resume → run continues; `duration` of 0 (unlimited) unaffected | | **50a** | `api/app.py`, `routes_session.py`, token auth, API CI job, `test_session_no_qt` extended to `api` | ~220 + 150 test | Add | `pytest -rs` shows API tests ran; handlers are one-liners; binds 127.0.0.1 | | **50b** | `routes_settings.py` (users, profiles, resolve, schema, instruments) | ~170 + 120 test | Add | 409 guards: identify/resources unless idle, `gpib_address` patch during run | diff --git a/docs/design/tauri_ui_status.md b/docs/design/tauri_ui_status.md index ecfe4ad8..eee4385d 100644 --- a/docs/design/tauri_ui_status.md +++ b/docs/design/tauri_ui_status.md @@ -1,6 +1,6 @@ # Tauri Desktop UI — Status (steps 2 and 3) -**Status:** On `phase0/reviewable-baseline`, pushed, CI green +**Status:** On `phase0/reviewable-baseline`, pushed, CI green; backend bench-checked on the lab 2420 and on a 2400 over the NI USB driver; UI bench report's three blockers and five majors fixed (see `tauri_ui_bench_2026-09-18.md`) **Date:** 2026-09-17 **Depends on:** step 1 (`tauri_backend_split.md`, `tauri_backend_split_status.md`) @@ -83,16 +83,55 @@ things landed for that: afternoon on the lab laptop was a VISA library present with no GPIB driver behind it. +## Bench, lab desktop, 2026-09-18 + +The frozen Windows backend from CI run 35380847071, extracted from the msi +into a scratch folder (nothing installed), driven over an SSH tunnel against +the Keithley 2420 (serial 1230523) with a ~10 Ω DUT. The shipping PySide6 GUI +was open on the PC but idle throughout. + +| Check | Result | +|---|---| +| `--check-visa bus` from inside the bundle | NI-VISA 22.5 via `visa32.dll`; `GPIB0::24::INSTR` enumerated; NI USB driver correctly unavailable on Windows | +| Identify | IDN in 1.2 s, model 2420 with 60 V / 3.05 A / 22 W limits | +| Resistance run, defaults, 10 s | 29 samples, 10.081 Ω, spread 0.015 %, `run_ended user_stop ok`, stop latency 0.48 s | +| Stop during a 6 s settle | `run_ended user_stop ok samples=0`, no error event, stop latency 0.15 s | +| Start immediately after that stop | accepted; the lock's grace covered the previous run's cleanup | +| `/session/shutdown` mid-run | server stopped, file finalized with footer (103 rows), sleep re-enabled, then `OUTP?` = 0 asked directly over NI-VISA | + +One observation, not a regression: with **Auto-range on, the 2420's +auto-ohms chooses its own test current** (100 mA for a 10 Ω DUT on the 20 Ω +range) and the profile's 1 mA "test current" is not what flows. The SCPI is +identical in the shipping worker, so this is how the lab has always run +resistance mode; the UI should say so, or grey the field out, when +Auto-range is on. + +## The driver on a real adapter, 2026-09-18 + +GPIB-USB-HS 01CEE482 with a Keithley 2400 (serial 1175680) at primary +address 3 on this Mac. First contact found two things the specification had +wrong — the read reply's tail is 16 bytes, not 28, and the 2400 drops +addressing bytes that arrive within a millisecond of take control, which +wedged the adapter until it was power-cycled — both fixed on the bench +(`bc74095`, `beb1db1`). Through the driver: identify, three consecutive +resistance runs (99.51 Ω at 10 mA), stop mid-settle, immediate restart, +shutdown mid-run with the output confirmed off, and the compliance +detection of `1568506`. + +## The UI on the lab PC, 2026-09-18 + +Installed per-user (2.0.0-1, NSIS) and driven through WebView2's debug +port; every mode, dialog and shutdown path exercised against the 2420. +Report and punch list: `tauri_ui_bench_2026-09-18.md`. Three blockers and +five majors found and fixed the same day; the fixes were verified in the +dev UI against the simulator (and on a 2400 for compliance), not yet on the +PC. The first CI build also lacked a WebSocket implementation entirely +(`websockets` was never a declared dependency), fixed in `f5d0e29`. + ## Not yet -- **Hardware.** Nothing here has touched the 2420. The backend's stop path, - instrument lock and sidecar shutdown are the things to watch on the bench. -- **The NI USB driver on a real adapter.** Proven only against scripted - fakes. Needs the GPIB-USB-HS from laptop2 on a Mac with a 2400: attach, - `*IDN?`, a resistance run, a stop mid-settle, Scan while idle. -- **Installing the Windows build on the lab PC.** `resistamet-api - --check-visa bus` answers whether the frozen backend finds NI-VISA and the - instrument before the GUI is opened at all. +- **The UI fixes on the lab PC itself**, and the 16 minor and 12 cosmetic + items in the bench report. - **Prologix / AR488 adapters** need their `PRLGX-ASRL::…::INTFC` resource opened before the instrument address resolves; the app does not do that. - **Backend items step 2 depends on** but works around for now: the 4PP spot diff --git a/pyproject.toml b/pyproject.toml index 0bd1afb4..4b7b14f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,6 +65,7 @@ dev = [ "pytest-cov>=4.0.0", "fastapi>=0.110", "uvicorn>=0.27", + "websockets>=13", "httpx>=0.27", ] hdf5 = [ @@ -73,6 +74,8 @@ hdf5 = [ api = [ "fastapi>=0.110", "uvicorn>=0.27", + # uvicorn has no WebSocket implementation of its own. + "websockets>=13", ] # NI GPIB-USB adapters from user space (resistamet_gui/gpib_usb); needs a # libusb shared library on the machine as well. diff --git a/requirements.txt b/requirements.txt index de27032f..dbf654ab 100644 --- a/requirements.txt +++ b/requirements.txt @@ -33,6 +33,10 @@ pydantic>=2.0 # the GUI; required by the sidecar the Tauri shell will launch. fastapi>=0.110 uvicorn>=0.27 +# uvicorn speaks WebSocket only through a separately installed implementation; +# without one it answers every upgrade with 404 and the desktop UI shows +# "Reconnecting" forever. Found on the lab PC in the first frozen build. +websockets>=13 # User-space driver for NI GPIB-USB adapters (resistamet_gui/gpib_usb), the # GPIB route on a Mac where NI ships no driver. pyusb is BSD; it needs a diff --git a/resistamet-api.spec b/resistamet-api.spec index fd4d0527..02b64d30 100644 --- a/resistamet-api.spec +++ b/resistamet-api.spec @@ -23,7 +23,7 @@ import sys import tempfile from pathlib import Path -from PyInstaller.utils.hooks import copy_metadata +from PyInstaller.utils.hooks import collect_submodules, copy_metadata def _version_metadata(): @@ -126,12 +126,12 @@ a = Analysis( "uvicorn.protocols.http.h11_impl", "uvicorn.protocols.websockets", "uvicorn.protocols.websockets.auto", + # uvicorn's auto selection has moved between these two across + # releases; ship both so the pick at runtime always resolves. "uvicorn.protocols.websockets.websockets_impl", + "uvicorn.protocols.websockets.websockets_sansio_impl", "uvicorn.lifespan", "uvicorn.lifespan.on", - "websockets", - "websockets.legacy", - "websockets.legacy.server", # pydantic v2 keeps its core in a compiled module "pydantic", "pydantic_core", @@ -145,6 +145,11 @@ a = Analysis( "h5py.utils", "h5py.h5ac", "h5py._proxy", + # The WebSocket implementation uvicorn loads by name at runtime. + # Without it every upgrade is answered 404 and the desktop UI sits + # on "Reconnecting"; the whole package, so the impl uvicorn picks + # always has what it imports. + *collect_submodules("websockets"), ], hookspath=[], hooksconfig={}, diff --git a/resistamet_gui/_simulator.py b/resistamet_gui/_simulator.py index 7da66220..c08fc6ae 100644 --- a/resistamet_gui/_simulator.py +++ b/resistamet_gui/_simulator.py @@ -674,7 +674,11 @@ def _compute_read(self) -> str: ) v, i, r, comp = self._compute_one_point(source_value) baseline = _STAT_BASELINE.get(self._mode_tag(), _STAT_BASELINE["default"]) - stat = baseline | (_STAT_BIT_COMPLIANCE if comp else 0) + # The ohms function leaves the compliance bit clear even with the + # source pinned at its voltage limit (2400 and 2420, bench + # 2026-09-18); the clamped VOLT element is the only sign. + flag_compliance = comp and self._sense_func_short() != "RES" + stat = baseline | (_STAT_BIT_COMPLIANCE if flag_compliance else 0) return self._format_elements(v, i, r, stat) def _compute_sweep_read(self) -> str: diff --git a/resistamet_gui/api/routes_session.py b/resistamet_gui/api/routes_session.py index 137c3fa8..b175f014 100644 --- a/resistamet_gui/api/routes_session.py +++ b/resistamet_gui/api/routes_session.py @@ -10,6 +10,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, status from pydantic import BaseModel, Field +from ..session.instrument_lock import InstrumentBusy from ..session.manager import MeasurementSession, SessionBusy from .app import UI_ROLE, busy_as_conflict, get_session, require_token @@ -79,6 +80,9 @@ def start(body: StartRequest, request: Request, prompt_timeout_s=body.prompt_timeout_s) except SessionBusy as exc: raise busy_as_conflict(exc) + except InstrumentBusy as exc: + # Another process holds the bus. Refused now, not failed later. + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) except ValueError as exc: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) diff --git a/resistamet_gui/data_export.py b/resistamet_gui/data_export.py index 53765607..3bdb6b73 100644 --- a/resistamet_gui/data_export.py +++ b/resistamet_gui/data_export.py @@ -289,12 +289,18 @@ def build_metadata( settings: Dict[str, Any], instrument_idn: str = "", start_time: Optional[datetime] = None, - aux_columns: Optional[List[str]] = None + aux_columns: Optional[List[str]] = None, + effective: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Build metadata dictionary for export. Shared schema across all backends. ``aux_columns`` is the aux-sensor column list (sensors.aux_column_names), passed explicitly by the worker when co-logging is active. + + ``effective`` is what the instrument reported after configuration where + that differs from what was asked — the voltage limit auto-ohms imposes, + for one. ``params`` stays the request; a reader comparing the two sees + exactly what the instrument overrode. """ from .constants import __version__ @@ -395,6 +401,9 @@ def build_metadata( meta['params']['aux_sensor_address'] = measurement_settings.get('aux_address') meta['params']['aux_channels'] = list(aux_columns) if aux_columns else None + if effective: + meta['effective'] = dict(effective) + return meta diff --git a/resistamet_gui/gpib_usb/__init__.py b/resistamet_gui/gpib_usb/__init__.py index a95acbbc..2408e0ac 100644 --- a/resistamet_gui/gpib_usb/__init__.py +++ b/resistamet_gui/gpib_usb/__init__.py @@ -15,7 +15,7 @@ import logging from . import transport as _transport -from .protocol import AdapterNotReady, GpibError, GpibTimeout, NoListener, ProtocolError +from .protocol import AdapterNotReady, GpibError, GpibTimeout, NoListener, NoReply, ProtocolError from .transport import AdapterInfo, TransportError, TransportTimeout, find_adapters __all__ = [ @@ -24,6 +24,7 @@ 'GpibError', 'GpibTimeout', 'NoListener', + 'NoReply', 'ProtocolError', 'TransportError', 'TransportTimeout', diff --git a/resistamet_gui/gpib_usb/controller.py b/resistamet_gui/gpib_usb/controller.py index 90a63b09..5a38865b 100644 --- a/resistamet_gui/gpib_usb/controller.py +++ b/resistamet_gui/gpib_usb/controller.py @@ -18,6 +18,16 @@ without it reliable), so attach skips the interrupt-monitor-mask steps 4 and 6 of §2.8 and ``status()`` polls the control endpoint instead. +Bench notes (GPIB-USB-HS 01CEE482, Keithley 2400 at PAD 3, 2026-09-18): the +attach sequence, addressing, write, read, serial poll and the presence probe +all work as written. Instruments need a moment after IFC and REN before the +first addressed command (``IFC_SETTLE_S``); without it the 2400 silently +dropped the first query after a close-then-attach, and the adapter hung once +under the backend at exactly that point. The read reply's trailer is 16 bytes, not the 28 the +specification derived (see ``protocol``). The count field of a status reply +is only meaningful after 0x0a/0x0c/0x0d; other replies carry stale or marker +bytes there, which is why nothing here reads it elsewhere. + Size: this module runs a little over the 400-line guideline even with the device-level sequences moved out. What remains is the attach sequence, the three transfer primitives and the exchange/fault machinery they share; the @@ -31,7 +41,7 @@ from . import protocol as p from . import tables as t -from .protocol import AdapterNotReady, GpibError, GpibTimeout, ProtocolError, StatusBlock +from .protocol import AdapterNotReady, GpibError, GpibTimeout, NoReply, ProtocolError, StatusBlock from .transport import Transport, TransportError, TransportTimeout logger = logging.getLogger(__name__) @@ -45,6 +55,13 @@ DRAIN_WAIT_S = 0.2 #: Device timeout for bus housekeeping that has no session timeout of its own. DEFAULT_TIMEOUT_S = 3.0 +#: Pause after an IFC pulse / REN change before the first addressed command. +#: Observed on the bench: a Keithley 2400 that was in remote state, then saw +#: REN drop at shutdown and IFC + REN at the next attach, handshakes command +#: and data bytes arriving within ~1 ms in hardware but never parses them +#: (it later reports -420 Query UNTERMINATED); 20 ms was already enough. +#: This is five times that. +IFC_SETTLE_S = 0.1 #: spec gap: with the device timeout disabled (code 0xf0) §7.2 leaves the #: host wait to the application. Ten minutes; on expiry the operation is #: stopped (§5.11) and reported as a timeout. @@ -128,9 +145,17 @@ def attach(self, system_controller: bool = True) -> None: self.serial_number = self._usb_b_serial() # step 3 (USB-B) # Step 4 (monitor mask 0x0000) skipped: the interrupt endpoint is not used. # Own secondary addressing stays disabled (rows 20-22 of §2.6). - self._register_write( # step 5 - t.register_init_writes(self._own_address, system_controller, self._t1_ns), - 'register initialisation') + try: + self._register_write( # step 5 + t.register_init_writes(self._own_address, system_controller, self._t1_ns), + 'register initialisation') + except NoReply as exc: + # Seen on the bench: a hung adapter answers every control request, + # swallows bulk messages until its FIFO fills and never replies. A + # USB reset does not clear it; only a power cycle does. + raise AdapterNotReady( + '%s accepted the initialisation message but never replied: the ' + 'adapter is hung. Unplug it and plug it back in.' % self._model.name) from exc # Step 6 (monitor mask 0x10ff) skipped for the same reason. if system_controller: # step 7 self._interface_clear() @@ -138,6 +163,7 @@ def attach(self, system_controller: bool = True) -> None: # Error 5 here just means nothing is on the bus yet (§8.12). self._status_exchange(p.take_control_message(True), SHORT_WAIT_S, 'take control', tolerate=(t.ERR_NO_ACCEPTOR,)) + self._sleep(IFC_SETTLE_S) # let the instruments finish reacting to IFC/REN self._attached = True self._resync_pending = False @@ -195,6 +221,7 @@ def interface_clear(self) -> None: with self._guard(): self._ensure_attached() self._interface_clear() + self._sleep(IFC_SETTLE_S) def remote_enable(self, on: bool) -> None: with self._guard(): @@ -407,7 +434,7 @@ def _transact(self, message: bytes, reply_length: int, wait_s: float) -> bytes: try: return self._transport.bulk_in(reply_length, int(RECOVERY_WAIT_S * 1000)) except TransportTimeout as exc: - raise ProtocolError('adapter did not answer after a stop request') from exc + raise NoReply('adapter did not answer after a stop request') from exc def _exchange(self, message: bytes, reply_length: int, wait_s: float, operation: str, tolerate: Sequence[int] = ()) -> Tuple[StatusBlock, bytes]: diff --git a/resistamet_gui/gpib_usb/device_ops.py b/resistamet_gui/gpib_usb/device_ops.py index 23a34f62..8732a449 100644 --- a/resistamet_gui/gpib_usb/device_ops.py +++ b/resistamet_gui/gpib_usb/device_ops.py @@ -80,8 +80,8 @@ def find_listeners(controller: Controller, addresses: Iterable[int], a listener holds NDAC asserted while it waits for data; an empty address leaves it released. No data byte is sent to the instrument. """ - # spec gap: this NDAC probe follows IEEE-488.1 but is not bench-verified - # with this adapter; §5.16 marks it uncertain. + # Bench-verified on the GPIB-USB-HS with a Keithley 2400 at PAD 3: BSR reads + # 0x01 (REN only) for empty addresses and has NDAC set for the instrument. with controller.lock: found: List[int] = [] for pad in addresses: diff --git a/resistamet_gui/gpib_usb/protocol.py b/resistamet_gui/gpib_usb/protocol.py index 79198b8a..8565ce87 100644 --- a/resistamet_gui/gpib_usb/protocol.py +++ b/resistamet_gui/gpib_usb/protocol.py @@ -9,6 +9,14 @@ worked examples in the specification (§3.6) without hardware. Section numbers in comments refer to that specification. + +Bench notes (GPIB-USB-HS 01CEE482, 2026-09-18): every host-to-device +message here was accepted as built. Replies differed from the +specification in one place: a read reply ends in a 16-byte trailer (status, +ADR1, last-block count, pad, termination) with no embedded 0x09 status +block; ``parse_read_reply`` follows the device and tolerates the longer +form. Small reads arrive in 0x36 blocks, a 256-byte read in 0x37 blocks, +and the filler after the valid bytes is stale data. """ from dataclasses import dataclass from typing import List, Optional, Sequence, Tuple @@ -41,7 +49,13 @@ STATUS_REPLY_LENGTH = 12 REGISTER_WRITE_REPLY_LENGTH = 16 REGISTER_READ_REPLY_LENGTH = 32 -READ_REPLY_TRAILER_LENGTH = 28 +#: Observed on GPIB-USB-HS 01CEE482: status block (8) + ADR1 + last-block +#: count + 2 pad + termination (4). The specification derived 28 bytes with +#: an embedded 0x09 status block that the device does not send. +READ_REPLY_TRAILER_LENGTH = 16 +#: Receive buffers are sized for the longer, specification-derived trailer +#: so a firmware that does send the embedded status still fits. +READ_REPLY_TRAILER_MAX = 28 MAX_COMMAND_BYTES = 16 # §5.3, all models MAX_TRANSFER_BYTES = 0xFFFF # §5.1, §5.2 @@ -89,6 +103,10 @@ class ProtocolError(GpibError): """A reply did not have the shape the specification gives it.""" +class NoReply(ProtocolError): + """A message was accepted but never answered, not even after a stop request.""" + + def error_for_code(code: int, operation: str) -> GpibError: """The exception for a nonzero status-block error code (§4.3).""" message = '%s: error %d (%s)' % (operation, code, t.error_label(code)) @@ -293,8 +311,10 @@ def parse_status_reply(reply: bytes, expected_id: int) -> StatusBlock: if status.id != expected_id: raise ProtocolError('reply id 0x%02x, expected 0x%02x: %s' % (status.id, expected_id, reply.hex())) - # spec gap: the trailing 4 bytes are implied to be 04 00 00 00 but not - # verified, so they are not checked. + # Observed on the GPIB-USB-HS: the trailing 4 bytes are the termination + # block; anything else means the pipes are out of step. + if reply[8:] != TERMINATION_BLOCK: + raise ProtocolError('status reply does not end in a termination block: %s' % reply.hex()) return status @@ -320,9 +340,9 @@ def parse_register_read_reply(reply: bytes, count: int) -> List[int]: if block_id == BLOCK_REGISTER_VALUES: values.extend(reply[offset + 1:offset + 4]) elif block_id == BLOCK_REGISTER_END: - # spec gap: the meaning of the 0x35 count byte is unsettled; it is - # not used. Whether a termination block follows is also unsettled, - # so nothing after 0x35 is inspected. + # Observed on the GPIB-USB-HS: a termination block follows 0x35 + # (12 bytes for one register). spec gap: the meaning of the 0x35 + # count byte is still unsettled; it is not used. break else: raise ProtocolError('unexpected block 0x%02x in register-read reply: %s' @@ -339,9 +359,12 @@ class ReadReply: """A parsed 0x0a reply (§5.2).""" data: bytes - status: StatusBlock # id 0x38 - embedded_status: StatusBlock # id 0x09, the two AUXMR writes - adr1: int # bit 7 = EOI seen with the last byte; §5.2 says ignore + status: StatusBlock # id 0x38 + adr1: int # bit 7 = EOI seen with the last byte; §5.2 says ignore + #: The specification describes a second status block (id 0x09, for the + #: embedded register writes) after the pad bytes; the GPIB-USB-HS does not + #: send one. Kept when present, None otherwise. + embedded_status: Optional[StatusBlock] = None @property def end(self) -> bool: @@ -377,9 +400,15 @@ def parse_read_reply(reply: bytes, requested: int) -> ReadReply: % (status.id, reply.hex())) adr1 = reply[offset + 8] last_block_count = reply[offset + 9] - embedded = parse_status_block(reply, offset + 12) - if embedded.id != OP_REGISTER_WRITE: - raise ProtocolError('embedded write status id 0x%02x: %s' % (embedded.id, reply.hex())) + tail = offset + 12 + embedded: Optional[StatusBlock] = None + if len(reply) >= tail + 8 and reply[tail] == OP_REGISTER_WRITE: + # The specification's layout: the embedded register write reports + # separately before the termination block. Not seen on the HS. + embedded = parse_status_block(reply, tail) + tail += 12 + if len(reply) >= tail + 4 and reply[tail] != OP_TERMINATION: + raise ProtocolError('read reply does not end in a termination block: %s' % reply.hex()) if payloads: if any(len(p) < 15 for p in payloads[:-1]) or last_block_count > len(payloads[-1]): @@ -398,7 +427,7 @@ def read_reply_buffer_size(max_bytes: int, max_packet_size: int) -> int: """Host receive buffer for a read of ``max_bytes`` (§5.2, §8.6).""" blocks_30 = -(-max_bytes // 30) * 32 blocks_15 = -(-max_bytes // 15) * 16 - total = max(blocks_30, blocks_15) + READ_REPLY_TRAILER_LENGTH + total = max(blocks_30, blocks_15) + READ_REPLY_TRAILER_MAX return -(-total // max_packet_size) * max_packet_size diff --git a/resistamet_gui/gpib_usb/tables.py b/resistamet_gui/gpib_usb/tables.py index 07391aa3..85c00242 100644 --- a/resistamet_gui/gpib_usb/tables.py +++ b/resistamet_gui/gpib_usb/tables.py @@ -84,6 +84,9 @@ class ControlRequest: bytes.fromhex('f80100000001000000')), ) +#: Observed on GPIB-USB-HS 01CEE482 (bcdDevice 0x101): the readiness reply is +#: ``40 01 00 01 30 01 19 08 00 00 65``, i.e. bytes 6/7/10 differ from the +#: values the specification lists; nonzero still means ready. READINESS_ATTEMPTS = 50 READINESS_INTERVAL_S = 0.1 READINESS_USB_TIMEOUT_MS = 100 diff --git a/resistamet_gui/session/configure.py b/resistamet_gui/session/configure.py index 3102af72..7696b151 100644 --- a/resistamet_gui/session/configure.py +++ b/resistamet_gui/session/configure.py @@ -13,9 +13,25 @@ @dataclass(frozen=True) class ResistanceState: - """What the resistance configure step decided, read back by the loop.""" + """What the resistance configure step decided, read back by the loop. + + ``voltage_compliance_v`` is the limit the instrument reports after + configuration, not the one requested: with auto-range on, auto-ohms + sets its own. The loop detects compliance against this value, because + the ohms function never sets the compliance bit in the status word + (Keithley 2400 and 2420, bench 2026-09-18). + """ cable_null: float = 0.0 + voltage_compliance_v: float = float('inf') + + +def _read_back_float(keithley, query: str, fallback: float) -> float: + """Ask the instrument what a setting became; the request if it will not say.""" + try: + return float(keithley.query(query).strip()) + except Exception: + return float(fallback) @dataclass(frozen=True) @@ -69,9 +85,15 @@ def configure_resistance(keithley, events, measurement_settings, nplc): # Offset-compensated ohms: cancels thermoelectric EMF if measurement_settings.get('res_offset_comp', False): keithley.write(":SENS:RES:OCOM ON") + # The limit that will actually apply. Auto-ohms overrides the requested + # compliance (2.1 V seen on a 2420 that was asked for 0.5 V), and the + # status word does not report compliance in the ohms function, so the + # loop compares readings against this number. + effective_compliance = _read_back_float(keithley, ":SENS:VOLT:PROT?", voltage_compliance) # Cable null: software subtraction (2400 series lacks :SENS:RES:REL) state = ResistanceState( - cable_null=float(measurement_settings.get('res_cable_null', 0.0))) + cable_null=float(measurement_settings.get('res_cable_null', 0.0)), + voltage_compliance_v=effective_compliance) # Pull raw V and I alongside R so accuracy.py can propagate # the per-range V and I uncertainties into σ_R. The 2400's # ohms function senses V and I internally regardless of @@ -84,6 +106,10 @@ def configure_resistance(keithley, events, measurement_settings, nplc): 'Mode': 'Resistance Measurement', 'Test Current (A)': test_current, 'Voltage Compliance (V)': voltage_compliance, + # What the instrument will actually enforce. With auto range on this + # differs from the request, and auto-ohms also chooses the test + # current per range, so the Current column is the record of that. + 'Effective Voltage Compliance (V)': effective_compliance, 'Measurement Type': measurement_type, 'Resistance Auto Range': 'ON' if auto_range else 'OFF', } diff --git a/resistamet_gui/session/continuous_run.py b/resistamet_gui/session/continuous_run.py index e9765e4f..5a384efd 100644 --- a/resistamet_gui/session/continuous_run.py +++ b/resistamet_gui/session/continuous_run.py @@ -7,6 +7,7 @@ code. No Qt here. """ import logging +import math import time from datetime import datetime from pathlib import Path @@ -21,7 +22,7 @@ from ..sensors import aux_column_names, make_sensor, reading_to_columns from ..system_utils import SleepInhibitor from .control import RunStopped -from .instrument_lock import InstrumentBusy, hold_instrument +from .instrument_lock import HeldInstrument, InstrumentBusy from .configure import ( configure_four_point, configure_resistance, configure_source_i, configure_source_v, configure_sweep, @@ -48,7 +49,7 @@ class ContinuousRun: """ def __init__(self, mode, sample_name, username, settings, control, events, - safety_ack='skip', prompt_timeout_s=None): + safety_ack='skip', prompt_timeout_s=None, instrument_lock=None): if mode not in ['resistance', 'source_v', 'source_i', 'four_point', 'sweep']: raise ValueError(f"Invalid measurement mode: {mode}") self.mode = mode @@ -59,7 +60,9 @@ def __init__(self, mode, sample_name, username, settings, control, events, self._safety_ack = safety_ack #: None = wait forever (the GUI has an operator at the bench). self._prompt_timeout_s = prompt_timeout_s - self._instrument_lock = None + #: A HeldInstrument the caller already took (so its refusal was + #: synchronous), or None to take it here. Released in _cleanup either way. + self._instrument_lock = instrument_lock # Set by the configure step: the frozen per-mode state the loop reads. self._mode_state = None # Set by each delta read: the per-polarity values the row builder logs. @@ -158,6 +161,14 @@ def _open_aux_sensor(self, measurement_settings): return return True + def _effective_settings(self): + """What the instrument reported after configuration, for the file header.""" + state = self._mode_state + limit = getattr(state, 'voltage_compliance_v', None) + if limit is None or not math.isfinite(limit): + return None + return {'voltage_compliance_V': limit} + def _open_output_file(self, measurement_settings, source_value_str): """Create the exporter for this run. False on failure.""" # File setup via the configured exporter (csv / hdf5 / csv+legacy_json). @@ -180,6 +191,7 @@ def _open_output_file(self, measurement_settings, source_value_str): aux_units=self._aux_units, on_compress=self._emit_compress_status, on_large_file=self._emit_large_file_status, + effective=self._effective_settings(), ) # Hdf5Exporter does not expose them; the schema is still known # to the caller, so an empty list means "ask get_column_config". @@ -290,11 +302,12 @@ def _enter_instrument_lock(self, address): """Hold the address for this run; released in _cleanup. Taken before anything is opened, so a second process is refused rather - than allowed to interleave SCPI on the same bus. + than allowed to interleave SCPI on the same bus. A lock the caller + already holds is kept as it is. """ - manager = hold_instrument(address) - manager.__enter__() - return manager + if self._instrument_lock is not None: + return self._instrument_lock + return HeldInstrument(address) def _safety_prompt_declined(self) -> bool: """Ask before a hazardous voltage reaches the leads. True = cancel. @@ -921,11 +934,11 @@ def stop_measurement(self) -> None: self._control.finish('user_stop') def _release_instrument_lock(self) -> None: - manager = getattr(self, '_instrument_lock', None) - if manager is not None: + held = getattr(self, '_instrument_lock', None) + if held is not None: self._instrument_lock = None try: - manager.__exit__(None, None, None) + held.release() except Exception: logger.warning("failed to release the instrument lock", exc_info=True) diff --git a/resistamet_gui/session/instrument_lock.py b/resistamet_gui/session/instrument_lock.py index 9b416731..c106ed45 100644 --- a/resistamet_gui/session/instrument_lock.py +++ b/resistamet_gui/session/instrument_lock.py @@ -9,9 +9,14 @@ releases it when the holder dies, so there is no stale-lock logic to get wrong and no pid file to go out of date after a crash. -Lock files live beside the config, one per sanitized address, and are never -deleted — an empty lock file is the cheap part; deleting one while another -process holds it is how these break. +Lock files live in one place per user, ``~/.resistamet/locks``, one per +sanitized address, and are never deleted — an empty lock file is the cheap +part; deleting one while another process holds it is how these break. + +One place, not "beside the config": two processes only exclude each other if +they agree on where the lock is, and the bench showed the desktop app and a +second backend each looking beside their own config and both opening the +instrument. The bus is a property of the machine, so the lock's home is too. """ import logging import re @@ -20,8 +25,6 @@ from pathlib import Path from typing import Optional -from ..constants import CONFIG_FILE - logger = logging.getLogger(__name__) @@ -29,8 +32,13 @@ class InstrumentBusy(RuntimeError): """Another process holds this instrument.""" +def default_lock_dir() -> Path: + """Where every ResistaMet process on this machine looks for locks.""" + return Path.home() / '.resistamet' / 'locks' + + def _lock_dir(lock_dir: Optional[str] = None) -> Path: - directory = Path(lock_dir) if lock_dir else Path(CONFIG_FILE).resolve().parent / 'locks' + directory = Path(lock_dir) if lock_dir else default_lock_dir() directory.mkdir(parents=True, exist_ok=True) return directory @@ -72,6 +80,27 @@ def _release(handle) -> None: _POLL_S = 0.05 +class HeldInstrument: + """An instrument lock taken now and released later, outside a ``with``. + + For the case where the process that decides to start a run is not the + thread that runs it: the session acquires before it answers "started", + so a refusal is synchronous, and hands the held lock to the run, which + releases it at the end of cleanup. ``release`` is idempotent. + """ + + def __init__(self, address: str, lock_dir: Optional[str] = None, + wait_s: float = ACQUIRE_GRACE_S) -> None: + self.address = address + self._manager = hold_instrument(address, lock_dir, wait_s) + self.path = self._manager.__enter__() + + def release(self) -> None: + manager, self._manager = self._manager, None + if manager is not None: + manager.__exit__(None, None, None) + + @contextmanager def hold_instrument(address: str, lock_dir: Optional[str] = None, wait_s: float = ACQUIRE_GRACE_S): diff --git a/resistamet_gui/session/manager.py b/resistamet_gui/session/manager.py index 38ca0153..8111107b 100644 --- a/resistamet_gui/session/manager.py +++ b/resistamet_gui/session/manager.py @@ -26,7 +26,7 @@ from .continuous_run import ContinuousRun from .control import RunControl from .emitter import EventEmitter -from .instrument_lock import hold_instrument +from .instrument_lock import HeldInstrument, InstrumentBusy, hold_instrument from .vdp_run import VdpRun logger = logging.getLogger(__name__) @@ -98,7 +98,8 @@ def start(self, profile: Dict[str, Any], mode: str, sample_name: str, username: prompt_timeout_s: float = 900.0) -> str: """Resolve settings, then run them. Returns the run id immediately. - Raises ``SessionBusy`` unless idle and ``ValueError`` when the strict + Raises ``SessionBusy`` unless idle, ``InstrumentBusy`` when another + process holds the instrument, and ``ValueError`` when the strict resolver rejects the request — a run that cannot be described should never reach the instrument. """ @@ -110,19 +111,30 @@ def start(self, profile: Dict[str, Any], mode: str, sample_name: str, username: with self._lock: if self._state != 'idle': raise SessionBusy(f"session is {self._state}") - self._run_count += 1 - run_id = f"run-{self._run_count}" - control = RunControl() - emitter = EventEmitter(self._record, run_id=run_id, clock=self._clock) - if mode == VDP_MODE: - run = VdpRun(sample_name, username, resolved.settings, control, emitter, - safety_ack='prompt', prompt_timeout_s=prompt_timeout_s) - else: - run = ContinuousRun(mode, sample_name, username, resolved.settings, - control, emitter, safety_ack='prompt', - prompt_timeout_s=prompt_timeout_s) - thread = threading.Thread(target=self._execute, args=(run,), - name=f"resistamet-{run_id}", daemon=True) + # The instrument is taken here, before "started" is answered, so a + # bus held by another process is a refusal the caller sees, not a + # run that fails a moment later. The run releases it in cleanup. + address = resolved.settings.get('measurement', {}).get('gpib_address', '') + held = HeldInstrument(address) # raises InstrumentBusy + try: + self._run_count += 1 + run_id = f"run-{self._run_count}" + control = RunControl() + emitter = EventEmitter(self._record, run_id=run_id, clock=self._clock) + if mode == VDP_MODE: + run = VdpRun(sample_name, username, resolved.settings, control, emitter, + safety_ack='prompt', prompt_timeout_s=prompt_timeout_s, + instrument_lock=held) + else: + run = ContinuousRun(mode, sample_name, username, resolved.settings, + control, emitter, safety_ack='prompt', + prompt_timeout_s=prompt_timeout_s, + instrument_lock=held) + thread = threading.Thread(target=self._execute, args=(run,), + name=f"resistamet-{run_id}", daemon=True) + except Exception: + held.release() + raise self._state = 'running' self._run_id, self._mode = run_id, mode self._control, self._run, self._thread = control, run, thread diff --git a/resistamet_gui/session/run_files.py b/resistamet_gui/session/run_files.py index fa5f4953..42ff62e3 100644 --- a/resistamet_gui/session/run_files.py +++ b/resistamet_gui/session/run_files.py @@ -58,8 +58,12 @@ def create_base_path(data_directory, username, sample_name, mode, source_value_s def open_exporter(base_path, mode, settings, measurement_settings, username, sample_name, instrument_idn, start_time, aux_columns, aux_units, - on_compress=None, on_large_file=None): - """Build the run's exporter. Returns (exporter, primary filename).""" + on_compress=None, on_large_file=None, effective=None): + """Build the run's exporter. Returns (exporter, primary filename). + + ``effective``: settings the instrument reported back after configuration, + recorded beside the requested ones (see ``build_metadata``). + """ columns, units = get_column_config( mode, measurement_settings, aux_columns=aux_columns or None, @@ -73,6 +77,7 @@ def open_exporter(base_path, mode, settings, measurement_settings, username, sam instrument_idn=instrument_idn, start_time=datetime.fromtimestamp(start_time), aux_columns=aux_columns or None, + effective=effective, ) exporter = make_exporter( diff --git a/resistamet_gui/session/samples.py b/resistamet_gui/session/samples.py index b25d3f55..6e8fd562 100644 --- a/resistamet_gui/session/samples.py +++ b/resistamet_gui/session/samples.py @@ -37,7 +37,15 @@ def parse_resistance(parts, stat_word, hw_compliance, measurement_settings, nplc except Exception: voltage = float('nan'); current = float('nan'); value = float('nan') compliance_type = 'Voltage' - if hw_compliance: + # The ohms function does not set the compliance bit (2400 and 2420, + # bench 2026-09-18), and in manual range it reports the programmed + # current, so V/I under compliance is a wrong number that looks fine. + # Detect it the way the source modes do: the measured voltage sitting at + # the limit the instrument actually has. + comp_limit_v = getattr(mode_state, 'voltage_compliance_v', float('inf')) + if not np.isfinite(comp_limit_v) or comp_limit_v <= 0: + comp_limit_v = float(measurement_settings.get('res_voltage_compliance', float('inf')) or float('inf')) + if hw_compliance or (np.isfinite(voltage) and abs(voltage) >= comp_limit_v * 0.99): compliance_status = 'V_COMP' if not np.isfinite(value): value = float('nan') diff --git a/resistamet_gui/session/vdp_run.py b/resistamet_gui/session/vdp_run.py index 94537a65..b2533d17 100644 --- a/resistamet_gui/session/vdp_run.py +++ b/resistamet_gui/session/vdp_run.py @@ -15,7 +15,7 @@ from ..instrument import Keithley2400, humanize_connection_error from ..system_utils import SleepInhibitor from .control import RunStopped -from .instrument_lock import InstrumentBusy, hold_instrument +from .instrument_lock import HeldInstrument, InstrumentBusy from .run_files import create_base_path logger = logging.getLogger(__name__) @@ -41,7 +41,7 @@ class VdpRun: MODE = 'vdp' def __init__(self, sample_name, username, settings, control, events, - safety_ack='skip', prompt_timeout_s=None): + safety_ack='skip', prompt_timeout_s=None, instrument_lock=None): self.sample_name = sample_name self.username = username self.settings = settings @@ -49,7 +49,8 @@ def __init__(self, sample_name, username, settings, control, events, self._safety_ack = safety_ack #: None = wait forever (the GUI has an operator at the bench). self._prompt_timeout_s = prompt_timeout_s - self._instrument_lock = None + #: A HeldInstrument the caller already took, or None to take it here. + self._instrument_lock = instrument_lock self._control = control self._voltages: Dict[str, float] = {} self.keithley = None @@ -146,8 +147,8 @@ def execute(self) -> None: self.running = True address = self.settings.get('measurement', {}).get('gpib_address', '') try: - self._instrument_lock = hold_instrument(address) - self._instrument_lock.__enter__() + if self._instrument_lock is None: + self._instrument_lock = HeldInstrument(address) except InstrumentBusy as exc: self._control.finish('instrument_busy') self._events.error('instrument_busy', 'smu', str(exc)) @@ -465,11 +466,11 @@ def _compute_and_emit_result(self) -> None: logger.warning("vdP: finalize with result failed", exc_info=True) def _release_instrument_lock(self) -> None: - manager = getattr(self, '_instrument_lock', None) - if manager is not None: + held = getattr(self, '_instrument_lock', None) + if held is not None: self._instrument_lock = None try: - manager.__exit__(None, None, None) + held.release() except Exception: logger.warning("failed to release the instrument lock", exc_info=True) diff --git a/tests/test_api_sidecar.py b/tests/test_api_sidecar.py index 519703ed..6d1d10ae 100644 --- a/tests/test_api_sidecar.py +++ b/tests/test_api_sidecar.py @@ -79,6 +79,57 @@ def test_logs_go_to_stderr_not_stdout(self, tmp_path): _stop(process) +def _websocket_upgrade_status(url: str, token: str) -> int: + """Send a bare WebSocket handshake and return the HTTP status uvicorn answers. + + No client library: what is being tested is the server process's ability + to upgrade at all, which Starlette's in-process test client never asks + of uvicorn. + """ + import http.client + from urllib.parse import urlsplit + + parts = urlsplit(url) + connection = http.client.HTTPConnection(parts.hostname, parts.port, timeout=10) + try: + connection.request('GET', f"/session/events/ws?token={token}", headers={ + 'Connection': 'Upgrade', + 'Upgrade': 'websocket', + 'Sec-WebSocket-Version': '13', + 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', + }) + return connection.getresponse().status + finally: + connection.close() + + +class TestEventsWebSocket: + """The real server process must upgrade, not just serve HTTP. + + uvicorn has no WebSocket implementation of its own; without one it logs + "No supported WebSocket library detected" and answers 404. The desktop + UI then never receives an event and shows "Reconnecting" for ever, which + is exactly what the first frozen build did on the lab PC. + """ + + def test_the_server_process_accepts_the_upgrade(self, tmp_path): + process, handshake = _spawn(tmp_path) + try: + assert _websocket_upgrade_status(handshake['url'], handshake['token']) == 101 + finally: + _stop(process) + + def test_a_bad_token_is_refused_not_ignored(self, tmp_path): + process, handshake = _spawn(tmp_path) + try: + status = _websocket_upgrade_status(handshake['url'], 'wrong') + # Accepted then closed with 4401, or refused outright: either is + # the server speaking WebSocket. 404 would mean it cannot. + assert status != 404 + finally: + _stop(process) + + class TestShutdown: def test_closing_stdin_stops_the_process(self, tmp_path): """A killed parent must not leave a process holding the instrument.""" diff --git a/tests/test_gpib_usb_controller.py b/tests/test_gpib_usb_controller.py index 6fd1052a..3e2a41ec 100644 --- a/tests/test_gpib_usb_controller.py +++ b/tests/test_gpib_usb_controller.py @@ -14,7 +14,8 @@ from resistamet_gui.gpib_usb import device_ops as ops from resistamet_gui.gpib_usb import protocol as p from resistamet_gui.gpib_usb import tables as t -from resistamet_gui.gpib_usb.controller import DRAIN_WAIT_S, RECOVERY_WAIT_S, SHORT_WAIT_S, Controller +from resistamet_gui.gpib_usb.controller import (DRAIN_WAIT_S, IFC_SETTLE_S, RECOVERY_WAIT_S, SHORT_WAIT_S, + Controller) from resistamet_gui.gpib_usb.protocol import AdapterNotReady, GpibError, GpibTimeout, NoListener, ProtocolError from resistamet_gui.gpib_usb.transport import TransportError, TransportTimeout @@ -129,9 +130,10 @@ def read_reply(data: bytes, requested: int, *, end: bool = True, error: int = 0) last_count = len(data) - ((len(data) - 1) // 15) * 15 if data else 0 ibsta = 0x0100 | (t.IBSTA_END if end else 0) | (t.IBSTA_TIMO if error == t.ERR_TIMEOUT else 0) count = (len(data) - requested) & 0xFFFF + # The 16-byte trailer as the GPIB-USB-HS sends it (no embedded 0x09 block). trailer = (bytes((0x38,)) + ibsta.to_bytes(2, 'big') + bytes((error,)) - + count.to_bytes(2, 'little') + b'\x00\x00' + bytes((0, last_count, 0, 0)) - + h('09 00 00 00 00 00 00 00 02 00 00 00 04 00 00 00')) + + count.to_bytes(2, 'little') + b'\xff\xff' + + bytes((0xE0 if end else 0x60, last_count, 0, 0)) + h('04 00 00 00')) return blocks + trailer @@ -199,7 +201,56 @@ def test_readiness_poll_repeats_until_ready(self): script += [('ctrl', (0x40, 0, 0, 16), READY)] + attach_script()[2:] controller = Controller(ScriptedTransport(script), t.PID_HS, sleep=naps.append) controller.attach() - assert naps == [0.1] * 4 + assert naps == [0.1] * 4 + [IFC_SETTLE_S] + + def test_attach_settles_after_ifc_and_ren_before_any_addressing(self): + # Bench: a Keithley 2400 dropped command bytes sent within ~1 ms of IFC/REN. + events: List[str] = [] + transport = ScriptedTransport(attach_script() + address_listener() + [ + ('out', p.write_message(b'A', T3S, True)), ('in', status_reply(0x0D)), + ]) + original_out = transport.bulk_out + + def bulk_out(data, timeout_ms): + events.append('out 0x%02x' % data[0]) + original_out(data, timeout_ms) + transport.bulk_out = bulk_out # type: ignore[assignment] + controller = Controller(transport, t.PID_HS, sleep=lambda s: events.append('sleep %.1f' % s)) + controller.attach() + controller.write(22, b'A', timeout_s=3.0) + assert events == ['out 0x09', 'out 0x0f', 'out 0x09', 'out 0x01', 'sleep 0.1', 'out 0x0c', 'out 0x0d'] + + def test_no_settle_when_not_system_controller(self): + naps: List[float] = [] + script = attach_script()[:4] + script[2] = ('out', p.register_write_message(t.register_init_writes(system_controller=False))) + Controller(ScriptedTransport(script), t.PID_HS, sleep=naps.append).attach(system_controller=False) + assert naps == [] + + def test_public_interface_clear_settles_too(self): + naps: List[float] = [] + transport = ScriptedTransport(attach_script() + [ + ('out', p.interface_clear_message()), ('in', status_reply(0x0F)), + ]) + controller = Controller(transport, t.PID_HS, sleep=naps.append) + controller.attach() + controller.interface_clear() + assert naps == [IFC_SETTLE_S, IFC_SETTLE_S] + + def test_hung_adapter_is_reported_with_the_replug_message(self): + # Seen on the bench: control requests answered, init accepted, no bulk reply ever. + script = attach_script()[:3] + [ + ('in', TransportTimeout('no reply'), 16), + STOP, + ('in', TransportTimeout('still no reply'), 16), + ] + transport = ScriptedTransport(script) + controller = Controller(transport, t.PID_HS, sleep=lambda s: None) + with pytest.raises(AdapterNotReady) as info: + controller.attach() + assert 'Unplug' in str(info.value) + transport.assert_done() + assert [tm for kind, _, tm in transport.timeouts if kind == 'in'] == [SHORT_MS, int(RECOVERY_WAIT_S * 1000)] def test_never_ready_raises_after_50_polls(self): script = [('ctrl', (0x41, 0, 0, 16), SERIAL_REPLY)] @@ -399,17 +450,24 @@ def test_host_wait_expiry_on_a_write_takes_the_stop_path(self): class TestRead: - IDN_REPLY = h('36 41 42 43 44 45 0a ee ee ee ee ee ee ee ee ee' - '38 21 00 00 06 ff 00 00 aa 06 00 00 09 00 00 00 00 00 00 00 02 00 00 00 04 00 00 00') - - def test_read_ending_in_eoi_uses_the_worked_example_bytes(self): + #: The *IDN? reply as GPIB-USB-HS 01CEE482 sent it for a Keithley 2400 at PAD 3 + #: (2026-09-18): three 0x37 blocks and the 16-byte trailer. The specification's + #: worked example drew a 28-byte trailer; the device disagreed. + IDN_TEXT = b'KEITHLEY INSTRUMENTS INC.,MODEL 2400,1175680,C30 Mar 17 2006 09:29:29/A02 /K/J\n' + IDN_REPLY = h( + '37 00 4b 45 49 54 48 4c 45 59 20 49 4e 53 54 52 55 4d 45 4e 54 53 20 49 4e 43 2e 2c 4d 4f 44 45' + '37 00 4c 20 32 34 30 30 2c 31 31 37 35 36 38 30 2c 43 33 30 20 20 20 4d 61 72 20 31 37 20 32 30' + '37 00 30 36 20 30 39 3a 32 39 3a 32 39 2f 41 30 32 20 20 2f 4b 2f 4a 0a 00 00 00 00 00 00 00 00' + '38 20 20 00 52 ff ff ff e0 16 00 00 04 00 00 00') + + def test_read_ending_in_eoi_as_observed_on_the_bench(self): controller, transport = attached([ - ('out', p.command_message(bytes((0x3F, 0x20, 0x56)), T3S)), ('in', status_reply(0x0C), 12), - ('out', h('06 00 00 00 04 00 00 00')), ('in', status_reply(0x06), 12), + ('out', h('0c fd 00 fc 3f 20 43 00 04 00 00 00')), ('in', h('0c 00 6c 00 00 00 ff ff 04 00 00 00'), 12), + ('out', h('06 00 00 00 04 00 00 00')), ('in', h('06 00 20 00 aa 55 ff ff 04 00 00 00'), 12), ('out', h('0a 00 00 fc 00 ff 00 00 09 02 00 01 0a 51 01 0a 55 00 00 00 04 00 00 00')), ('in', self.IDN_REPLY, 512), ]) - assert controller.read(22, max_bytes=256, timeout_s=3.0) == (b'ABCDE\n', True) + assert controller.read(3, max_bytes=256, timeout_s=3.0) == (self.IDN_TEXT, True) transport.assert_done() def test_read_ending_on_the_count(self): diff --git a/tests/test_gpib_usb_protocol.py b/tests/test_gpib_usb_protocol.py index a1a294d8..594618be 100644 --- a/tests/test_gpib_usb_protocol.py +++ b/tests/test_gpib_usb_protocol.py @@ -126,7 +126,9 @@ def test_write_reply(self): assert status.transferred(6) == 6 assert status.tacs - def test_read_reply_abcde(self): + def test_read_reply_as_the_specification_draws_it_is_tolerated(self): + # The device disagreed with this layout (see TestObservedReplies): the + # HS sends no embedded 0x09 block. The parser still accepts the longer form. reply = h('36 41 42 43 44 45 0a ee ee ee ee ee ee ee ee ee' '38 20 00 00 06 ff 00 00' 'aa 06 00 00' @@ -137,12 +139,10 @@ def test_read_reply_abcde(self): parsed = p.parse_read_reply(reply, 256) assert parsed.data == b'ABCDE\n' assert parsed.end is True - assert parsed.status.id == 0x38 assert parsed.status.count == 0xFF06 - assert parsed.status.bytes_not_transferred == 250 assert parsed.status.transferred(256) == 6 assert parsed.adr1 == 0xAA - assert parsed.embedded_status.id == 0x09 + assert parsed.embedded_status is not None and parsed.embedded_status.id == 0x09 assert p.read_status_offset(reply) == 16 def test_register_read_bsr_reply(self): @@ -154,6 +154,68 @@ def test_take_control_reply(self): assert status.cic and status.atn +#: Captured from GPIB-USB-HS 01CEE482 with a Keithley 2400 at PAD 3, 2026-09-18. +IDN_TEXT = b'KEITHLEY INSTRUMENTS INC.,MODEL 2400,1175680,C30 Mar 17 2006 09:29:29/A02 /K/J\n' +IDN_REPLY_256 = h( + '37 00 4b 45 49 54 48 4c 45 59 20 49 4e 53 54 52 55 4d 45 4e 54 53 20 49 4e 43 2e 2c 4d 4f 44 45' + '37 00 4c 20 32 34 30 30 2c 31 31 37 35 36 38 30 2c 43 33 30 20 20 20 4d 61 72 20 31 37 20 32 30' + '37 00 30 36 20 30 39 3a 32 39 3a 32 39 2f 41 30 32 20 20 2f 4b 2f 4a 0a 00 00 00 00 00 00 00 00' + '38 20 20 00 52 ff ff ff e0 16 00 00 04 00 00 00') +#: Serial-poll read of one byte (STB 0); the 0x36 filler is stale bus data. +STB_REPLY_1 = h('36 00 20 00 aa 55 ff ff 04 00 00 00 04 00 00 00' + '38 00 20 00 00 00 01 00 60 01 00 00 04 00 00 00') +#: Count-limited read of 5 bytes out of "KEITHLEY...": no END. +KEITH_REPLY_5 = h('36 4b 45 49 54 48 ff ff 04 00 00 00 04 00 00 00' + '38 00 20 00 00 00 01 00 60 05 00 00 04 00 00 00') +#: Read of up to 64 bytes with nothing to read: device-side timeout, no data blocks. +TIMEOUT_REPLY_64 = h('38 00 20 0a c0 ff ff ff e0 5e 00 00 04 00 00 00') + + +class TestObservedReplies: + """Read replies exactly as the GPIB-USB-HS sent them (the spec derived a longer trailer).""" + + def test_idn_in_three_extended_blocks(self): + assert len(IDN_REPLY_256) == 112 + parsed = p.parse_read_reply(IDN_REPLY_256, 256) + assert parsed.data == IDN_TEXT and len(parsed.data) == 82 + assert parsed.end is True + assert parsed.status.ibsta == 0x2020 # END | CIC + assert parsed.status.error == 0 + assert parsed.status.count == 0xFF52 and parsed.status.transferred(256) == 82 + assert parsed.adr1 == 0xE0 # EOI seen + assert parsed.embedded_status is None + assert p.read_status_offset(IDN_REPLY_256) == 96 + + def test_one_byte_serial_poll_reply(self): + parsed = p.parse_read_reply(STB_REPLY_1, 1) + assert parsed.data == b'\x00' and parsed.end is False + assert parsed.status.transferred(1) == 1 + + def test_count_limited_read(self): + parsed = p.parse_read_reply(KEITH_REPLY_5, 5) + assert parsed.data == b'KEITH' and parsed.end is False + assert parsed.adr1 == 0x60 + + def test_timeout_reply_has_no_data_blocks(self): + parsed = p.parse_read_reply(TIMEOUT_REPLY_64, 64) + assert parsed.data == b'' + assert parsed.status.error == t.ERR_TIMEOUT + assert parsed.status.transferred(64) == 0 + assert p.read_status_offset(TIMEOUT_REPLY_64) == 0 + + def test_trailer_must_end_in_a_termination_block(self): + broken = bytearray(TIMEOUT_REPLY_64) + broken[12] = 0x09 + with pytest.raises(p.ProtocolError): + p.parse_read_reply(bytes(broken), 64) + + def test_status_reply_must_end_in_a_termination_block(self): + with pytest.raises(p.ProtocolError): + p.parse_status_reply(h('0c 00 78 00 00 00 ff ff 00 00 00 00'), p.OP_COMMAND) + status = p.parse_status_reply(h('0c 00 78 00 00 00 ff ff 04 00 00 00'), p.OP_COMMAND) + assert status.ibsta == 0x0078 # observed after addressing: REM | CIC | ATN | TACS + + # --------------------------------------------------------------------------- # §3.3 count encoding # --------------------------------------------------------------------------- @@ -328,8 +390,12 @@ def test_error_code_to_exception(self): # --------------------------------------------------------------------------- def read_reply(data: bytes, requested: int, *, end: bool = True, error: int = 0, - block: int = 15) -> bytes: - """Build a 0x0a reply the way the device lays it out.""" + block: int = 15, spec_layout: bool = False) -> bytes: + """Build a 0x0a reply the way the device lays it out (16-byte trailer). + + ``spec_layout`` adds the embedded 0x09 status block the specification + describes and the GPIB-USB-HS does not send. + """ payload = 15 if block == 15 else 30 blocks = [] for start in range(0, len(data), payload): @@ -343,10 +409,11 @@ def read_reply(data: bytes, requested: int, *, end: bool = True, error: int = 0, ibsta = (t.IBSTA_END if end else 0) | (t.IBSTA_TIMO if error == t.ERR_TIMEOUT else 0) count = (len(data) - requested) & 0xFFFF trailer = (bytes((0x38,)) + ibsta.to_bytes(2, 'big') + bytes((error,)) - + count.to_bytes(2, 'little') + b'\x00\x00' - + bytes((0x80 if end else 0x00, last_count, 0, 0)) - + h('09 00 00 00 00 00 00 00') + h('02 00 00 00') + h('04 00 00 00')) - return b''.join(blocks) + trailer + + count.to_bytes(2, 'little') + b'\xff\xff' + + bytes((0xE0 if end else 0x60, last_count, 0, 0))) + if spec_layout: + trailer += h('09 00 00 00 00 00 00 00') + h('02 00 00 00') + return b''.join(blocks) + trailer + h('04 00 00 00') class TestReadReplyReassembly: @@ -363,6 +430,12 @@ def test_extended_blocks(self): assert p.parse_read_reply(reply, 100).data == data assert p.read_status_offset(reply) == 64 + def test_specification_layout_still_parses(self): + data = bytes(range(20)) + reply = read_reply(data, 64, spec_layout=True) + parsed = p.parse_read_reply(reply, 64) + assert parsed.data == data and parsed.embedded_status is not None + def test_exactly_one_full_block(self): data = bytes(15) parsed = p.parse_read_reply(read_reply(data, 15, end=False), 15) @@ -374,7 +447,7 @@ def test_no_data_on_timeout(self): assert parsed.data == b'' assert parsed.status.error == t.ERR_TIMEOUT assert parsed.status.transferred(256) == 0 - assert p.read_status_offset(parsed and read_reply(b'', 256, end=False)) == 0 + assert p.read_status_offset(read_reply(b'', 256, end=False)) == 0 def test_partial_data_on_timeout(self): parsed = p.parse_read_reply(read_reply(b'ABC', 256, end=False, error=t.ERR_TIMEOUT), 256) diff --git a/tests/test_gpib_usb_visa.py b/tests/test_gpib_usb_visa.py index 35965434..1ba260e4 100644 --- a/tests/test_gpib_usb_visa.py +++ b/tests/test_gpib_usb_visa.py @@ -28,6 +28,7 @@ import resistamet_gui.gpib_usb as gpib_usb # noqa: E402 from resistamet_gui.gpib_usb import protocol as p # noqa: E402 from resistamet_gui.gpib_usb import tables as t # noqa: E402 +from resistamet_gui.gpib_usb import controller as controller_module # noqa: E402 from resistamet_gui.gpib_usb import transport, visa_session # noqa: E402 from resistamet_gui.gpib_usb.boards import BoardRegistry # noqa: E402 from resistamet_gui.gpib_usb.transport import AdapterInfo, TransportError # noqa: E402 @@ -146,13 +147,14 @@ def _write(self, data: bytes) -> bytes: def _read(self, data: bytes) -> bytes: requested = 0x10000 - int.from_bytes(data[4:6], 'little') eos_mode, eos_char = data[1], data[2] - trailer_tail = h('09 01 30 00 00 00 00 00 02 00 00 00 04 00 00 00') + # The 16-byte trailer as the real adapter sends it. + trailer_tail = h('04 00 00 00') if self.atn: - return self._status(0x38, error=2, count=-requested) + h('00 00 00 00') + trailer_tail + return self._status(0x38, error=2, count=-requested) + h('60 00 00 00') + trailer_tail instrument = self.instruments.get(self.talker) if self.talker is not None else None if instrument is None or not instrument.pending: - return (self._status(0x38, error=0x0A, count=-requested, ibsta=0x4100) - + h('00 00 00 00') + trailer_tail) + return (self._status(0x38, error=0x0A, count=-requested, ibsta=0x0020) + + h('e0 5e 00 00') + trailer_tail) source = instrument.pending if eos_mode & 0x04 and bytes((eos_char,)) in source: cut = source.index(bytes((eos_char,))) + 1 @@ -168,7 +170,7 @@ def _read(self, data: bytes) -> bytes: last_count = len(out) - ((len(out) - 1) // 15) * 15 if out else 0 status = self._status(0x38, count=len(out) - requested, ibsta=0x2100 if end else 0x0100) - return blocks + status + bytes((0x80 if end else 0, last_count, 0, 0)) + trailer_tail + return blocks + status + bytes((0xE0 if end else 0x60, last_count, 0, 0)) + trailer_tail def bulk_in(self, length: int, timeout_ms: int) -> bytes: self.bulk_in_timeouts.append(timeout_ms) @@ -246,6 +248,7 @@ def adapter(monkeypatch, session_registry, enumeration): """One fake HS at GPIB0 with a Keithley-like instrument at address 24, installed.""" sim = SimulatedAdapter({24: FakeInstrument('KEITHLEY INSTRUMENTS INC.,MODEL 2400,1234567,C30')}) monkeypatch.setattr(gpib_usb, 'available', lambda: True) + monkeypatch.setattr(controller_module, 'IFC_SETTLE_S', 0.0) # the fake needs no settle monkeypatch.setattr(visa_session, '_REGISTRY', BoardRegistry(open_transport=lambda i: sim, first_board=0)) session_registry[GPIB_INSTR] = Sentinel diff --git a/tests/test_instrument_lock.py b/tests/test_instrument_lock.py index 0917a358..e87575bb 100644 --- a/tests/test_instrument_lock.py +++ b/tests/test_instrument_lock.py @@ -94,3 +94,45 @@ def test_different_addresses_do_not_collide(tmp_path): with hold_instrument('GPIB0::24::INSTR', str(tmp_path)): with hold_instrument('ASRL6::INSTR', str(tmp_path)): pass + + +class TestWhereTheLockLives: + """Two processes exclude each other only if they look in the same place.""" + + def test_default_dir_is_per_user_not_per_working_directory(self, tmp_path, monkeypatch): + from resistamet_gui.session import instrument_lock + + monkeypatch.setattr(instrument_lock.Path, 'home', staticmethod(lambda: tmp_path)) + (tmp_path / 'a').mkdir() + (tmp_path / 'b').mkdir() + monkeypatch.chdir(tmp_path / 'a') + first = lock_path('GPIB0::24::INSTR') + monkeypatch.chdir(tmp_path / 'b') + second = lock_path('GPIB0::24::INSTR') + assert first == second == tmp_path / '.resistamet' / 'locks' / 'GPIB0__24__INSTR.lock' + + +class TestHeldInstrument: + def test_held_then_released_frees_the_address(self, tmp_path): + from resistamet_gui.session.instrument_lock import HeldInstrument + + held = HeldInstrument('GPIB0::24::INSTR', str(tmp_path)) + assert held.path == lock_path('GPIB0::24::INSTR', str(tmp_path)) + held.release() + held.release() # idempotent + with hold_instrument('GPIB0::24::INSTR', str(tmp_path)): + pass + + def test_refused_while_another_process_holds_it(self, tmp_path): + from resistamet_gui.session.instrument_lock import HeldInstrument + + script = HOLDER.format(address='GPIB0::24::INSTR', lock_dir=str(tmp_path)) + holder = subprocess.Popen([sys.executable, '-c', textwrap.dedent(script), '5'], + stdout=subprocess.PIPE, text=True) + try: + assert holder.stdout.readline().strip() == 'held' + with pytest.raises(InstrumentBusy): + HeldInstrument('GPIB0::24::INSTR', str(tmp_path), wait_s=0.2) + finally: + holder.kill() + holder.wait(timeout=5) diff --git a/tests/test_session.py b/tests/test_session.py index beca1ebb..290dbb46 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -373,3 +373,47 @@ def test_an_unpaused_run_still_stops_on_time(self, session, sink, fake_rm, profi session.start(self._timed(profile, 0.5 / 3600.0), 'source_v', 'wafer1', 'alice') assert _wait_for(lambda: session.state == 'idle', timeout=10.0) assert [e.payload['reason'] for e in sink.of_type('run_ended')] == ['duration'] + + +class TestInstrumentHeldElsewhere: + """Start refuses at once when another process holds the bus. + + The bench showed why: a second backend was told 'started', connected + anyway a moment later, and its SCPI landed in the middle of a live run. + """ + + def test_start_is_refused_synchronously(self, session, sink, fake_rm, profile, tmp_path, monkeypatch): + import subprocess, sys, textwrap + from resistamet_gui.session import instrument_lock + from resistamet_gui.session.instrument_lock import InstrumentBusy + + monkeypatch.setattr(instrument_lock, 'default_lock_dir', lambda: tmp_path / 'locks') + monkeypatch.setattr(instrument_lock, 'ACQUIRE_GRACE_S', 0.3) + holder_script = textwrap.dedent(f""" + import sys, time + from resistamet_gui.session.instrument_lock import hold_instrument + with hold_instrument('GPIB0::24::INSTR', {str(tmp_path / 'locks')!r}): + print('held', flush=True) + time.sleep(10) + """) + holder = subprocess.Popen([sys.executable, '-c', holder_script], + stdout=subprocess.PIPE, text=True) + try: + assert holder.stdout.readline().strip() == 'held' + with pytest.raises(InstrumentBusy, match='in use by another ResistaMet process'): + session.start(_four_point(profile), 'four_point', 'wafer1', 'alice') + assert session.state == 'idle' + assert sink.events == [] # nothing started, nothing reported + finally: + holder.kill() + holder.wait(timeout=5) + + def test_the_run_releases_the_lock_the_session_took(self, session, sink, fake_rm, profile, tmp_path, monkeypatch): + from resistamet_gui.session import instrument_lock + + monkeypatch.setattr(instrument_lock, 'default_lock_dir', lambda: tmp_path / 'locks') + session.start(_four_point(profile), 'four_point', 'wafer1', 'alice') + assert _wait_for(lambda: session.state == 'idle') + # Free again: a fresh hold succeeds without waiting. + with instrument_lock.hold_instrument('GPIB0::24::INSTR', wait_s=0.0): + pass diff --git a/tests/test_session_e2e.py b/tests/test_session_e2e.py index fe6d922b..24e6723f 100644 --- a/tests/test_session_e2e.py +++ b/tests/test_session_e2e.py @@ -231,3 +231,47 @@ def test_sequence_numbers_are_contiguous(self, session, profile): sink = _run_until_samples(session, profile, 'resistance', res_test_current=1e-3, res_voltage_compliance=5.0) assert [e.seq for e in sink.events] == list(range(1, len(sink.events) + 1)) + + +class TestResistanceCompliance: + """The ohms function does not raise the compliance bit; the reading has to say it. + + Bench, 2026-09-18, Keithley 2400 and 2420: with the source pinned at its + voltage limit the status word stays clear, and in manual range the CURR + element is the programmed current, so V/I is a wrong resistance that + looks like data. The simulator reproduces that, and the parser must catch + it from the measured voltage sitting at the limit. + """ + + def test_a_pinned_voltage_is_flagged_not_recorded_as_good(self, session, profile): + # 100 Ω at 10 mA wants 1 V; a 0.5 V limit pins it. + sink = _run_until_samples(session, profile, 'resistance', res_auto_range=False, + res_test_current=10e-3, res_voltage_compliance=0.5) + samples = sink.of_type('sample') + assert samples, 'no samples' + assert {s.payload['compliance'] for s in samples} == {'V_COMP'} + assert sink.of_type('compliance'), 'no compliance event' + # And the value it would have archived is indeed wrong, which is why the flag matters. + assert all(v['resistance'] < DUT_OHMS * 0.6 for v in (s.payload['values'] for s in samples)) + + def test_stop_on_compliance_ends_the_run(self, session, profile): + profile['measurement']['stop_on_compliance'] = True + session.start(profile, 'resistance', 'pinned', 'alice', + overrides={'res_auto_range': False, 'res_test_current': 10e-3, + 'res_voltage_compliance': 0.5}) + assert _wait_for(lambda: session.state == 'idle') + ended = session.sink.of_type('run_ended')[-1].payload + assert ended['reason'] == 'compliance_stop' + + def test_within_compliance_is_still_ok(self, session, profile): + sink = _run_until_samples(session, profile, 'resistance', res_auto_range=False, + res_test_current=1e-3, res_voltage_compliance=5.0) + assert {s.payload['compliance'] for s in sink.of_type('sample')} == {'OK'} + + def test_the_file_records_the_limit_the_instrument_has(self, session, profile): + sink = _run_until_samples(session, profile, 'resistance', res_auto_range=False, + res_test_current=1e-3, res_voltage_compliance=2.0) + with open(sink.of_type('run_ended')[-1].payload['path']) as handle: + comments = [line for line in handle if line.startswith('#')] + assert any('effective' in line and 'voltage_compliance_V' in line and '2.0' in line + for line in comments), comments