In development. It changes without notice.
kleidos-meter, the host client
A small Python client for the bench meter's SCPI protocol (the SCPI command set), and a simulated instrument that speaks the same protocol, so the client is tested without the bench. How a measuring session goes with it is in the usage guide, and how the panel is used in the panel's guide; every command is in the command line's reference and every public class and method in the Python API's reference, both generated. This page is how the package is made.
SerialTransport opens the port with the lines as the OS leaves them and then releases RTS, then DTR (docs/scpi.md, "The line"): the other order resets the instrument through the carrier's auto-reset circuit. It opens the port exclusively (pyserial's exclusive, an flock on macOS and Linux), so a second opener, a QA run or another kleidos-meter, is refused at once with PortBusyError instead of reading some of the first one's lines; exclusive=False opts out. The port may also be a pyserial URL, such as socket://127.0.0.1:5025, opened through serial.serial_
Every byte read goes through protocol.LineRouter, a pure and incremental parser: feed(bytes) returns the responses, stream records (Sample, Mark) and BlockProgress events the bytes complete, the same responses and records however the line is cut. A TRACe:DATA? block is read by its byte count wherever it opens a unit of the line, so its rows never pass for responses or records, and a line longer than 64 KiB is dropped as an Overflow instead of being held. Meter.send() is built on it, and a program that reads the line itself, such as a panel, can use it directly.
A TRACe:DATA? dump is decoded by protocol.decode_
The command line reads the same port, checks the line first and says on stderr when the instrument had rebooted:
It exits 0 when every message was answered, 1 when the port is held elsewhere, the instrument does not answer or any message goes unanswered within --timeout (each miss is a # line on stderr, and the later messages are still sent), and 2 on a usage error. A command with no query has no response, so on its own it times out: end it with a query such as SYST:ERR:ALL?.
SimulatedMeter (kleidos_
- Deterministic (SimulatedMeter(), the client's tests): time stands still; a streamed capture emits four samples per message and two at ABORt, and a ring holds 64 samples once INITiate starts it.
- Clock-driven (SimulatedMeter(clocked=True), for kleidos-meter serve --sim and the panel's tests): samples fall due at the profile's period on clock (868 a second on STATE, 14.8 on SLEEP) and read() writes them, from current_a or a waveform such as ScriptedWaveform([(0.1, 0.01), (0.1, 0.2)]). A sample that would overflow the output the reader has not taken (tx_capacity) is lost and counted in dropped=, so a slow reader costs samples, never memory. A ring fills over time with a drift anchor every 1024 samples (drift_ppm moves the anchors and the stream's timestamps), SENSe:CAPTure:LIMit, a full ring and a level trigger end their captures by themselves, a null window ends after its seconds, the relay hold runs on the clock, DIAGnostic:WATChdog:TEST reboots after the watchdog's timeout and inject_
reboot() reboots at once. A MEASure holds the console for its SAMPle:COUNt periods, as the firmware's acquisition does: the messages that arrive meanwhile wait their turn, and one whose first unit is ABORt ends it with -230 ("aborted after n of count samples"), its ABORt consumed and the rest of it run in its turn. One lock guards every entry point, so a reader thread and a writer thread can share it. In both modes a program message longer than 255 bytes is discarded with -363 and one holding a byte that is not printable ASCII with -101, as the firmware discards them, and a capture latches its range's shunt and null at INITiate, as the firmware does, stores raw counts that carry the null (a closed CALibration:ZERO window stores its offset_pv for the range, and the input's offset is taken to be what the null measured) and converts them with scale.h's integer arithmetic, so its SCALed dump, its stream and its statistics are the integers the instrument would print, and FETCh:HEADer? reports shunt_lsb_pv, shunt_uohm and offset_pv of the capture. A MEASure's acquisition is a capture too: closed at its last sample (or at ABORt's), streamed to nobody, its ring kept on a ring profile, and the one FETCh:STATistics? and FETCh:HEADer? then describe. FETCh:STATistics? counts every sample taken, of which the stream carried samples - dropped.
The panel's process: kleidos-meter serve
How to use it, what each view and sequence does, the passthrough's rules and what happens when something dies are the panel's guide; its HTTP API is the HTTP API's reference. This section is how it works.
serve is the one opener of the meter's port while it runs: it opens it exclusively, and a second opener, a second serve among them, is refused at once and told which process holds it (# the port is held by kleidos-meter serve (pid …, since …)), from a note serve leaves in the user's runtime directory ($XDG_
Every message goes through kleidos_
The page
Open the address serve prints (http://127.0.0.1:8040/) in a browser. The page is kleidos_
The status bar, always in view: the instrument's serial, its image (firmware and elf=), the capture as the status polls report it, the samples the instrument dropped and those the page lost (a lost event, or a gap between two batches' n0), the live profile's averaging in the INA228 while it is on (read from SENSe:PROFile:REPort? at the start, after each settings event that names the profile or the averaging, and after a reboot or a passthrough client), who controls the line (this panel, a passthrough client while it holds the line, a sequence while one runs) and the registry's verdict on the calibration, where the live pin map came from (default, stored, fallback) and whether its relays are verified, beside the state of the line.
The Live view picks a profile (each with its period and whether it streams or fills the ring, from /api/schema's profiles) and the channels a streamed profile carries, an optional duration and a run label; Start and Stop drive POST /api/capture/start and stop, Mark POST /api/capture/mark, and what serve or the instrument refuses is shown beside the controls with its status and error codes. The chart is the page's own, on a Canvas 2D, with its arithmetic in one module without the DOM (host/
The other views, one at a time as the page's fragment names them (#sequences, #runs, #relays, #pins, #settings, #health, #console; a view that is not shown reads nothing from the instrument), each show what serve or the instrument refuses beside the control that sent it, with its HTTP status and the instrument's error codes:
- Sequences: one card and one Run button per sequence of /api/schema, with its parameters within their bounds; the run's state, a progress bar over its total steps, its steps, its cleanup and its results, Abort, and a sequence's question in a modal <dialog> whose safe answer (cancel) has the focus and is what dismissing it sends.
- Runs: the latest 100 runs, newest first, each with the averaging it was taken with, marked when it was on, and Open, which shows it in the Live chart from GET /api/runs/<run>/decimated (every channel it holds, 4,000 buckets of count, mean, root mean square, minimum and maximum each, so a run of any length costs the page the same), and its text, csv and json exports as plain download links.
- Relays: the circuit drawn as an inline SVG from ROUTe:STATe?: the cell, the shunt between VIN+ and VIN−, Relay 1 on the DUT's battery lead and Relay 2 across the shunt, each with the GPIO that drives it and its active level, each contact closed or lifted and the wires that carry the DUT's current marked for the path (shunt, bypass, both, none), said in words beside it; the hold's countdown, read again every 10 s while it runs and the view is shown, and at once after a 113 to 116; and one card per relay order with a button per choice and a box per flag it takes. An order goes out with only the flags ticked; before one with FORCe or LIVE a dialog names what moves and the path it leaves, and the order goes out only on its confirmation. Relays 3 and 4 are shown, not wired, and disabled.
- Pins: the board drawn as an inline SVG from GET /api/pins's table, both rails with their 22 terminals, the silk and the GPIO of each, every pin marked by its state (free, in use, reserved by the board, usable with caution, conflict) in color, shape and word. The drawing is one tab stop: the arrows move between pins, Enter or Space opens a pin's <dialog> with its use and its configuration, Escape closes it. The draft is the page's own until Apply: it is judged by the firmware's rules in JavaScript (host/
kleidos_ meter/ panel/ static/ js/ pins-math.js, with no DOM, held to every line of firmware/ test/ native/ golden/ pinmap.vectors in the browser test), its conflicts are drawn on the pins and what differs from the live map is listed. Apply asks, stages and applies; Defaults asks and puts the rig's own map back; the instrument's result is shown, a revert's reason and the null-path check included. The view only shows while the instrument's pin table is another than the package's. - Settings: a row per setting of the schema with the instrument's answer and a control built from its kind, written alone with Set and read back, so a refusal lands beside it; while the setting's flags would refuse it (R with a capture or a null window running, C also until a window that ended by itself is closed, D without the INA228), or another controller holds the line, or a sequence runs, its control is disabled and says why. Below, the INA228's noise reduction, a card per profile (host/
kleidos_ meter/ panel/ static/ js/ noise.js): off, the averaging count and the shunt conversion time, with the sample period they give computed from /api/schema's profiles before anything is written; Set selects the profile when it is not the live one, turns an averaging that is on off before it writes other figures, and shows the instrument's refusal, which leaves the profile off. Each range's shunt with its source, U at k = 2, the registry's figure and the deviation, the registry's verdict, the override (a value and its uncertainty, previewed first and written only from the preview after a confirmation) with the 'not quotable' banner while a range converts with one, which the status bar repeats, and Revert to the registry. - Calibration and health: identity, with the instrument's elf= against the local build's; the reset reason, the uptime and the coils a reset released; each task's fewest free stack bytes against 512; the heap counts (allocs_
since_ main and frees_ since_ main when the image reports them, allocs_ after_ init and frees_ after_ init before, 0 for a healthy instrument) and what was allocated before app_main; the watchdog; the calibration; and on request *TST? with its bits decoded and DIAGnostic:I2C:SCAN?, both through POST /api/scpi since they act on the device. - SCPI console: program messages, one per line, through POST /api/scpi (Ctrl or Cmd with Enter sends), each written to a transcript of the last 50 with its answers and its errors.
/api/schema and the page are held together by a test: every setting, sequence (and each of its parameters) and relay order of the schema has its control in index.html (data-setting, data-noise and data-noise-setting for a setting kept per profile, data-sequence and data-param, data-relay, data-choice and data-flag), with the place its refusal is shown, and the page has no control the schema does not declare; the page also notes in its notices any it finds missing.
The panel's HTTP API
kleidos_
Every route, what it takes, what it answers and what it sends is the HTTP API's reference, written by scripts/
A report becomes an object of the same keys: a value in canonical integer form becomes a JSON integer in the unit its key names (i_na, vbus_uv, hold_s), - becomes null, and anything else stays the instrument's text, as do identifiers and versions (elf, serial, fw, cal_tag, ...) and an integer beyond 2^53, which a browser would round. A route answers 400 when the instrument queued a command error (-1xx) and 409 for an execution or device error (-2xx, -3xx, 100 and up), with the reply in the body; a value or a message refused before it was sent is 400 (a setting's value is checked for its form, never for its range: no ;, newline or stray quote can ride along), a full queue, a line that is down or a closing executor 503 with Retry-After, an answer that did not come in time 504. While another controller holds the line (Api.hold(): a client of the SCPI passthrough, below), every route that talks to the instrument answers 423 and names it, and so does a message that meets the executor's hand-over (LineHeld); the schema and the status are still served.
The panel is unauthenticated, so it guards against accidents and other web pages (kleidos_
The SCPI passthrough
--scpi-passthrough [PORT] (kleidos_
Live samples and events
GET /api/events is a Server-Sent Events stream (kleidos_
Recordings: run directories
Every capture serve owns is recorded by kleidos_
- stream.txt: the capture's stream records exactly as the instrument wrote them, one per line, in the stream's own format (TEXT or CSV, whichever FORMat was): the samples of a streamed capture, the marks of any. A thread of the run's own writes it, so a slow disk costs records counted in meta.json (stream.lost), never the line a sample.
- trace.raw: a ring capture's TRACe:DATA? RAW block, written only once its CRC-32 matched (read in one message with FETCh:HEADer? and TRACe:POINts?); a block that fails twice is kept as trace.damaged and the run says so.
- meta.json (kleidos.meter.run/
1), what makes the files self-describing: the instrument (*IDN?, SYSTem:INFormation?), every shaping setting as read at the start, the capture's FETCh:HEADer? and FETCh:STATistics? (each the unit as the instrument wrote it and its fields), what the stream and the trace hold (records, sample rows, marks, bytes, SHA-256, the first and last timestamp), the errors queued meanwhile, how it ended (stop, seconds, ended_ by_ itself, reboot, link_down, shutdown), and the host's wall clock at the start and the end, labeled as the host's (the instrument has no calendar clock). complete is true when the capture closed normally and the run holds every sample the instrument delivered: the stream's rows are samples - dropped, or the dump holds TRACe:POINts? samples.
A data directory inside a git work tree is refused, by serve and by kleidos-meter capture alike: a run carries the instrument's serial, and measurements that are filed go through the Kleidos harness, never a commit of a run directory. The exports are made from those files once and kept beside them: text and csv are stream records that protocol.parse_
A capture with no panel reuses the same recorder:
It opens the port exclusively and names a holder as serve does, writes the profile and the channels, records the capture into a run under --out (the default data directory otherwise), stops it after --seconds (a ring profile may leave it out and runs until the ring is full; Ctrl-C stops it early, and the run is finished either way), writes back the settings it changed and prints the run's directory and what it holds. It exits 0 when the run is complete and the settings were written back, 1 when the port is held elsewhere, the instrument does not answer or refuses the capture, or the run is incomplete, and 2 on a usage error.
Measurement sequences
kleidos_
The sequences, their parameters and what each one moves are docs/
A sequence ends done, failed (the step names why: an error the instrument queued, a check that did not hold, a wait that timed out, a run that is incomplete), aborted or declined (a question answered with anything but continue, or unanswered for 10 minutes), and a cleanup step that does not hold fails a sequence that was done. While one runs every other change answers 409 (sequence_
The shunt and its uncertainty
kleidos_
An override (a shunt swapped on the bench, a datasheet's figure) is taken only with its uncertainty, stated once: expanded_ppm or expanded_uohm (U at k = 2, so u = U/2) or tolerance_ppm or tolerance_
The generated references
The command line's reference is written by scripts/
- The command line: cli.SUBCOMMANDS names each subcommand's module, which has a build_
parser(), a main(argv) and an EXIT_STATUS, what each status it exits with says. Every option has a help text. The generator holds what no parser does: where to read more, and an example on the simulator with its output. tests/ test_ cli_ doc.py holds the page to the generator, each synopsis to argparse's own usage, the statuses to what each main returns and the examples to what they print. - The Python API: every public class, method and function of the modules gen_
python_ api_ doc.py lists, in the source's order, with its signature and its docstring. A new module is added to the list, or to the one of those documented elsewhere, with the reason; one in neither fails. tests/ test_ python_ api_ doc.py holds the page to the generator and the sources to the convention below.
Docstrings
The convention is the reStructuredText field style of the Kleidos firmware repository's qa/
- What has one: every module, and every public class, function, method and property of the package. A private helper has one when what it does is not plain from its name.
- Its first line says in one sentence what the thing is or does, with a final full stop (the one difference from Kleidos's, which has none). A blank line separates the rest, wrapped at 100 columns like the code.
- Its fields, last: :param name: for each parameter, a class's __init__ among them, in the class's docstring; :returns: when the value is not None; :raises Error: for each error a caller may want to catch; :ivar name: for each field of a dataclass and each public attribute. No :type: and no :rtype:: every public signature carries its hints. A property needs only its first line.
- Its marks: double backticks around a literal (a command, a path, a report key), *name* around a parameter in prose, and a role for another name (:class:, :meth:, :func:, :data:, with the full path when it is of another module), which the page turns into a link.
tests/
Testing the panel end to end
Besides each module's unit tests, five suites take the panel as a user meets it, through kleidos-meter serve's own main() on the real clock (tests/
- Contracts (tests/
test_ panel_ contract.py): one serve --sim with its passthrough and a registry that files the simulator's calibration; every route of /api/schema has a contract (what it answers, in which shape, what it leaves the instrument in), and a route added without one fails the suite. The same serve holds each class of refusal to its status (400 for a command error or a message refused unsent, 409 for an execution or device error, 403, 404, 405, 413, 421), and, with a passthrough client attached, 423 naming it on every route that talks to the instrument while the routes that send nothing are still served. - The page in a browser (tests/
test_ panel_ browser.py), headless Chromium through Python Playwright, pinned exactly in the browser extra: pip install -e '.[browser]', then python -m playwright install chromium. Without either the module skips and says which is missing, and fails with METER_ BROWSER_ REQUIRED=1, which CI's Panel (Playwright) job sets after installing both. Each test fails on a console error, an uncaught exception or a request beyond serve's own address; between them they start a live capture and see it drawn, refuse a FORCe order until its dialog is confirmed, run a sequence to done and decline one's question in its dialog, download a run's CSV and parse it, check the chart's arithmetic through the page's own chart-math.js against figures computed in Python, and hold the page's JavaScript heap flat over six seconds of the simulator's full STATE rate. The test of record walks every view in both themes at 1280 and 390 px: no error, no request beyond serve, no absolute path in any text (hidden ones, titles, names and values included) and one height of the status bar. What the module's pages run of every module of the page is measured by Chromium's own precise block coverage, through the DevTools protocol (tests/ js_ coverage.py, no new dependency), and the module's last test holds it to the floors of js_ floors.toml, which only rise: 100 % of functions and blocks of the pure modules (chart-math.js, pins-math.js), a block no test can run listed there with its reason, and for the modules that draw on the DOM two points under the least of two measured runs, the blocks they leave printed by the test. A selection of the tests (-k, a node id) skips that last test, because it covers less by its nature; V8's count gives an if with no else no block for its false side, so the figure is blocks run, not both sides of every branch. - Conformance (tests/
test_ conformance.py, tests/ conformance.py): the client suite (every parameterless query the simulator shares with kCommands, a setting written and read back, the first command errors, and every command that takes a parameter given none, a word, a number past any range, a quoted string and a negative number) run through Meter on the simulator, through a serve --sim passthrough (byte for byte the simulator's answers), through a process on standard input and output (tests/ sim_ stdio.py, a stand-in), and on the firmware's native bridge when KLEIDOS_ METER_ NATIVE_ BRIDGE names its binary (make -C firmware/ test/ native bridge): each answer reduced to its signature (the units, each report's keys, each value's form, the error codes) must be the simulator's, and of the pin map's orders and the averaging override (every count and conversion time on three profiles at three bus clocks) every byte, the errors' texts included. Without the variable that case skips and says why, and fails with METER_ BRIDGE_ REQUIRED=1, which scripts/ run_ tests.sh and the commit hook set after building the bridge. - Its documents (tests/
test_ panel_ doc.py): docs/ http-api.md is what its generator writes from the schema, docs/panel.md names every route, sequence and option there is and no other, and its examples on the simulator (serve --sim, every curl, the passthrough's client) are run and print what the page shows. - The bench (tests/
test_ panel_ bench.py, tests/ panel_ bench.py): the scenario a panel puts the meter through (HEALTH, a STATE capture whose every sample reaches the live events, NULL_RELAY, a TRACE ring whose trace.raw, decoded on the host, equals the instrument's SCALed dump read through the passthrough, the heap counts unchanged, the relays back on the shunt and FORMat TEXT) runs on serve --sim in every run, and so does its page's part in the browser tests (run_ page_ scenario: the Pins view's live map, SDA moved to a pin with no INA228 applied from the page and put back with its sentence, the live chart at 100 ms of smoothing whose readout gives the capture's FETCh:STATistics? mean, a run recorded with the INA228's averaging on and named in its meta.json). On the meter both run with --run-bench, under the bench lock, with a 10 s capture, the page in a headless Chromium (the browser extra), and require the calibration verdict applied, which the meter, filed under the placeholder KM-0000000000, reaches only through its alias in the environment or the repository's .env, which git ignores (KLEIDOS_ METER_ SERIAL_ ALIASES; every other run sets it empty, tests/ conftest.py); --bench-shots <dir> saves the Live, Pins and Calibration and health views there, each named by the date and the image's elf=:
Without --run-bench the bench case skips (talks to the meter on the bench: give --run-bench). --meter-port and --bench-lock default to KLEIDOS_
Coverage and mutants
The suite takes every branch side of every module, on Python 3.13, 3.14 and 3.15 (CI's, .python-version): branch_
Coverage says which decisions a test took, not that a test would notice them going wrong, so mutants/*.patch are small wrong changes to the package that a test must notice: the moving average's weights, centering and gap rule, the pin rules in Python and in the page, the refusals of a pin order, and what a path is cut to. Each patch says what it breaks on its # Mutant line and gives the command that must then fail on its # Kill: line, run with sh -c from the root of a copy of the tree on the Python that PYTHON names:
tests/
The development tools are pinned in the dev extra: ruff 0.17.6 (the quality kit's hook pin) and pypdf 7.2.0 (CI's, for scripts/
The Kleidos firmware repository's QA harness (qa/