Kleidos API Search

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.

cd host
python3 -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
pytest
from kleidos_meter import Meter, SerialTransport
with Meter(SerialTransport("/dev/cu.usbmodemXXXX1")) as meter:
if meter.wait_ready(): # *ESR? answered with the power-on bit
print("the instrument rebooted")
print(meter.idn()) # KLEIDOS,KLEIDOS-METER,KM-0000000000,0.18.0
meter.set_profile("STATE")
print(meter.measure("CURR")) # amperes, e.g. 0.088066019
meter.start(["i_ua", "v_mv"])
...
stats = meter.stop() # FETCh:STATistics? fields

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_for_url. Meter.wait_ready() is the readiness check that page describes: a bare newline, a drain, then *ESR? with short timeouts until the instrument answers; it returns whether the power-on bit was set, so a host learns that the instrument rebooted instead of inferring it, and raises MeterTimeout when nothing answers.

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_dump(block, header), RAW or SCALed: it holds the block to its CRC-32 first (a damaged one raises ValueError), then returns a Dump whose samples are columns of integers (counts, nanoamps, one array entry per sample, so a full ring of 1,048,576 samples stays a few megabytes) from capture index start on, with the drift anchors, the marks and the trigger. Given the capture's FETCh:HEADer?, a RAW dump's counts become currents exactly as firmware/src/scale.h converts them, (counts × shunt_lsb_pv − offset_pv) × 1000 / shunt_uohm truncated toward zero, so each is the integer the SCALed dump of the same ring prints (current_nanoamps, DumpScale); Dump.t_us(index) is t0_us + index × period_us corrected by interpolating between the anchors, and Dump.nominal_t_us(index) the uncorrected timestamp a SCALed row prints. A header from another capture (another t0_us or period_us) is refused. Meter.trace() reads the header and the RAW dump in one message and decodes them; kleidos-meter relay-timing finds its edges in a decoded dump.

The command line reads the same port, checks the line first and says on stderr when the instrument had rebooted:

kleidos-meter --port /dev/cu.usbmodemXXXX1 '*IDN?' 'MEAS:CURR?'

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_meter/sim.py) is that instrument, behind the same write/read/close as a port. It resolves every header against kleidos_meter/sim_table.py, a copy of the firmware's command table (kCommands in firmware/src/console.cpp) with each command's flags and the most parameters it takes, so it refuses what the firmware refuses (D, R, C, a parameter too many); a command it does not model is listed in sim.UNDEFINED and answers -113. A test holds the copy to the firmware's table, as scripts/scpi_table.py reads it, so a command added there fails the suite until the simulator implements it or names it undefined; and the conformance suite (below) holds its reports' keys, its answers' forms and its refusals' codes to the firmware's own, on the native bridge. Its relays are the rig's two: K1 on the DUT's battery lead and K2, the bypass across the shunt, which make the firmware's four paths (shunt, both, bypass, none, relay.h pathOf) through ROUTe:LEAD, ROUTe:LEAD:CYCLe, ROUTe:BYPass and ROUTe:NULLpath (K2 then K1 on, K1 then K2 off) with the firmware's interlocks: -221 for a move under a running capture without LIVE, 110 for one that takes that capture off the DUT's current without FORCe, 109 for one that leaves the DUT with no supply without FORCe, 112 under a sampling null window, and an order that moves nothing answered whatever runs. Each move under a running capture is a mark of it (k1:open, k2:closed, a lead cycle's reclose too; past the 16 marks a move is driven unmarked), and once one has taken the shunt off the capture's current the later ones need no FORCe (the firmware's captureBypassed_). A capture, a measurement or a null is refused with 101 where the shunt does not carry the whole current (both, bypass; a null on both only), never on none, where it reads the zero a DUT without its battery draws. Every path but shunt is held 120 s and then released make-before-break, with 113, 114 or 115 by the path. It runs in two modes:

  • 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.

kleidos-meter serve --port /dev/cu.usbmodemXXXX1 # or KLEIDOS_METER_PORT
kleidos-meter serve --sim # the clock-driven simulator
kleidos-meter serve --scpi-passthrough # and a raw SCPI socket on 127.0.0.1:5025

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_RUNTIME_DIR/kleidos-meter, or kleidos-meter-<uid> in the temporary directory), readable by the user alone and named by a digest of the port's path, so the adapter's serial number in that path never becomes a file name. On start it waits until the instrument answers, prints what it is (SYSTem:INFormation?), its last reset and uptime (SYSTem:HEALth?) and anything the instrument had queued, and takes a snapshot of the capture-shaping settings: the I2C clock, the profile, the channels, the range, SENSe:CAPTure and its limit, the threshold, its hysteresis and marks, SAMPle:COUNt, the trigger's source, level, slope and pretrigger, and FORMat. A capture or a null window already open is reported and left alone. serve then holds the port until Ctrl-C or SIGTERM; on the way out it aborts an acquisition of its own still in flight, closes a window it opened (never one it found), writes back each setting a message changed that now differs from the snapshot (the I2C clock first, the profile before the channels it resets) and reads them back, releases the port and removes its note. It never sends *RST and never changes FORMat itself. A capture it started that still runs is stopped first and its run finished. It exits 0 after a clean stop, 1 when the port is held elsewhere, the panel's or the passthrough's address cannot be bound, the instrument does not answer within --ready-timeout (15 s) or the settings could not be written back (a window it did not open still runs), and 2 on a usage error (a --data-dir inside a git work tree among them). While it holds the port it serves the panel's page and its HTTP API (both below) on --bind and --http, 127.0.0.1 and 8040 by default (--http 0 takes any free port; both addresses are printed, serve: panel at http://127.0.0.1:8040/ and serve: panel API at http://127.0.0.1:8040/api/, and the panel's is written into the note). Every capture started through the API is recorded under --data-dir ($XDG_STATE_HOME/kleidos-meter/runs, printed as serve: recordings in …; below). --registry (the repository's calibration/) is the calibration registry each range's shunt is shown against, with its uncertainty (below); an override the panel writes is kept in the data directory's parent, $XDG_STATE_HOME/kleidos-meter/overrides/<serial>.json by default. --elf names the build whose firmware.elf the Calibration and health view holds the instrument's elf= to, the repository's firmware/.pio/build/meter/firmware.elf by default. A sequence that runs when serve is stopped is aborted first and its cleanup run (serve: aborting the sequence; its cleanup runs).

Every message goes through kleidos_meter.panel.executor.Executor: one thread that alone writes to and reads from the port, a FIFO of the callers' messages and one message in flight, so a response is always the answer to the message that was sent last. Callers on any thread submit() a program message and get a future of its Reply (the units, the errors, any block); each is sent with ;:SYST:ERR:ALL? appended, so its answer carries its own verdict. A message the instrument would discard is refused before anything is sent (MessageRefused): longer than 255 bytes with that suffix, a byte that is not printable ASCII or a tab, or empty. Each waits as long as its slowest unit may take (TIMEOUTS: 5 s, 10 s for a relay order, 15 s for a self-test, 20 s for ABORt, four minutes for a dump, and the firmware's bound of twice 600 s plus a second for an acquisition). After a time-out the executor gets back in step before it sends anything else: a bare newline, then an undefined header carrying a fresh number (KMSYNC<n>;:SYST:ERR:ALL?), whose -113 names it, and every response before that one is discarded as a stray line, so a late answer is never taken for the next message's. The first such sync is the readiness check; a line silent for 15 s is down, and what waits fails with LinkDown until the instrument answers a sync again. While a MEASure, READ or CALibration:SHUNt message holds the console, abort() sends ABORt at once, ahead of the FIFO (the instrument reads nothing else meanwhile); at any other time it is an ordinary message in its turn. The status (SYSTem:STATus? and SYSTem:HEALth?) is polled twice a second with no window open and once a second with one, never while polling is off (a passthrough client attached); an uptime that grew less than the time between two polls, or a new image, is a reboot. Stream records, block progress, the polls' status, a reboot, errors nobody asked for (a hold that reclosed a lead) and the line going down or up reach the listeners as events, in line order. The FIFO is bounded (64 messages, ExecutorBusy past them), so nothing on the host grows without limit.

The page

Open the address serve prints (http://127.0.0.1:8040/) in a browser. The page is kleidos_meter/panel/static/, shipped with the package and served as it is (kleidos_meter.panel.static): one HTML document at /, one stylesheet and plain ES modules below /static/, with no build step, no third-party script and no resource of another origin (a test scans every file for one, and holds every file a file refers to to the ones the package ships). The modules carry // @ts-check and JSDoc. The files are read once when serve starts, so the server never grows with requests and a path outside them is simply not found; the document goes out with its own Content-Security-Policy (its origin only for scripts, styles, images and connections, a data: image for the tab icon, nothing inline, no framing), every file with nosniff, no-store and no-referrer, behind the same Host guard as the API, and a method other than GET is 405. The stylesheet's tokens are the Kleidos web design system v2's (the two themes, the type roles, the 4 px spacing, the radii; copied from the Kleidos repository's site/assets/style.css at the commit its header names), in the reader's OS theme, dark when it states none, on the system's own faces. The page is in English.

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/kleidos_meter/panel/static/js/chart-math.js): the samples go into a ring of typed arrays sized once (262,144 samples, five minutes of STATe; the oldest are forgotten), each pixel column is drawn from its minimum to its maximum and joined to the next, one lane and one axis per unit, the marks as dashed lines with their labels, and at most 30 frames a second, drawn only when something changed. The window presets are 1 s, 10 s, 1 min and 5 min, the window follows the newest sample until a zoom or a pan holds it, and Follow live (or F, or a double click) lets it follow again. With the chart focused, Left and Right pan, Shift with them moves the crosshair, + and - zoom about it, Escape hides it; with a pointer, a drag pans, Ctrl (or a pinch) with the wheel zooms and a horizontal wheel pans. A text readout below the chart says the newest values and each lane's range in view, or the crosshair's sample, for assistive technology. A ring profile streams nothing while it runs: the view shows its fill, and once it ends the chart shows the run's trace from GET /api/runs/<run>/decimated (4,000 buckets, each with its count, mean, root mean square, minimum and maximum, weighed by its count). After a capture the view shows its statistics (FETCh:STATistics?: samples, dropped, duration, the current's mean, deviation, minimum and maximum, the bus voltage's and the power's extremes, q=). A notices list keeps the last 20 events nobody asked for (device errors, a reboot, the line, a passthrough client, events missed). In a five-minute STATe capture on the simulator the page's JavaScript heap stayed at 13 MB while the ring turned over.

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_meter.panel.http serves JSON on the standard library's threading server, one thread per request, and every message a route sends goes through the executor, behind the message in flight. What it offers is declared once in kleidos_meter.panel.schema, served as GET /api/schema: the settings (each with its query, its setter, the firmware's pattern and flags, the form its value takes), the profiles (each with its period, whether it fills the ring, and the channels it streams by default, from the simulator's copy of the firmware's profile table), the relay orders, the sequences and the routes. A test holds every header and flag the schema names to kCommands in firmware/src/console.cpp, so a command the firmware renames or whose flags change fails the host suite, and the capture-shaping guard restores from the same declaration.

Every route, what it takes, what it answers and what it sends is the HTTP API's reference, written by scripts/gen_http_api_doc.py from the same schema (each route's arguments and answer are declared in it too) and held to it by a test.

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_meter.panel.guards), not against a person at the machine. The Host header must name the loopback (localhost, 127.0.0.1, [::1]), otherwise 421, so a domain an attacker points at 127.0.0.1 is refused. A GET never changes the instrument: the routes that change it take POST only (a GET on one is 405), and the query route refuses a command, a query the R flag marks (it acts on the device: an acquisition, a self-test, a dump, a scan, a register read), one whose reading clears what it reads (*ESR?, SYSTem:ERRor?, the status event registers) and a header the table does not have. Every POST must carry X-Kleidos-Meter: 1 (403 otherwise), which a page of another origin cannot send without a CORS preflight; the panel approves none (no Access-Control-* header ever, OPTIONS is 405) and refuses an Origin other than the loopback's. With curl: curl -H 'X-Kleidos-Meter: 1' --data 'SYST:STAT?' http://127.0.0.1:8040/api/scpi. --bind beyond the loopback is refused unless --allow-remote is given as well; serve then warns that whoever reaches the address can move the relays, and takes any IP literal as the Host, still never a name. Bodies are at most 16 KiB with a Content-Length, at most 32 requests run at once, and an idle connection is closed after 10 s, so a client cannot make the server grow.

The SCPI passthrough

kleidos-meter serve --port /dev/cu.usbmodemXXXX1 --scpi-passthrough # 127.0.0.1:5025
kleidos-meter --port socket://127.0.0.1:5025 '*IDN?' 'SYST:ERR:ALL?' # any tool, meanwhile

--scpi-passthrough [PORT] (kleidos_meter.panel.passthrough) lets a QA run or a CLI tool reach the meter while serve holds the port: it listens on 127.0.0.1 only, port 5025 unless it names one (0 takes any free port; the address is printed, serve: SCPI passthrough at socket://127.0.0.1:5025, and written into the holder's note, so a tool refused the port is told where to go instead), and gives the line to one TCP client at a time, byte for byte in both directions: serve adds no error query, no sync and no line of its own, and the client opens socket://127.0.0.1:5025 as it would open the port (SerialTransport takes the URL). A second client is refused at once: its connection is closed with nothing written. Attaching puts the panel on hold, stops the status poll and waits up to 5 s for the message in flight and those queued; it is refused (the connection closed, serve printing why) while a measurement sequence runs, while the recorder's capture runs, while a window serve opened is open (a window it found open when it started is no obstacle), or when the line does not go quiet or the instrument does not answer. Before the line is handed over serve writes back the capture-shaping settings it changed, so the client finds them as serve found them. While a client is attached the panel is a monitor: the executor's thread still reads the port, hands every chunk to the client's queue and then routes its stream records to the live events (the page shows the client's captures; the responses are the client's alone), every route that talks to the instrument answers 423 and names the client, and nothing is polled. The serial reader never waits on the client: the instrument's bytes queue for a writer thread of the client's own, and a client that lets more than 8 MiB pile up (it stopped reading while the instrument streams) is disconnected, and how many bytes it lost is printed, logged and published. When the client closes, is dropped, or serve stops, the executor takes the line back with a bare newline (which ends any message the client left unfinished) and a KMSYNC sync whose answer discards every response before it, reads SYSTem:STATus? again, releases the hold and polls at once; a capture or null window the client left open is printed (serve: the client left a stream window open ...), shown in the status as foreign_window and left open on the way out, as a window serve found is. The settings the client changed are the client's: serve writes back only what serve changed.

Live samples and events

GET /api/events is a Server-Sent Events stream (kleidos_meter.panel.live). Every 100 ms a samples event carries the samples that arrived since the last, as columns of integers in the device's units: t_us, and for each channel the batch holds its thousandths as an integer named by its unit (i_na for i_ua, v_uv for v_mv, p_uw for p_mw, die_mc for die_c), null in a row that lacks it; n0 is the first row's index among the rows of the capture serve started last and count the rows, so a page sees at once whether it missed one. The TEXT format's line per channel is merged into one row per timestamp, and a row goes out only once it holds every channel of the row before it (or the next timestamp, a mark or the capture's end closes it), however long the line pauses between its lines. Beside them: mark (a mark record, in its place among the batches), status (kind poll with the status poll's reports, link, reboot, capture from the recorder, settings when a message that changes capture-shaping settings is written, whoever sent it (changed names them, at most one per batch), passthrough when a passthrough client attaches, is refused or detaches, and hello, the first event of a stream, with the last poll, capture and passthrough state), error (device errors no caller asked for, a line overflow, a recorder failure), sequence (the sequence runner's state at each change: a step started or ended, a question, the cleanup, the outcome) and ring (a ring capture's fill and a dump's progress). A stream that reads more slowly than the line delivers is never waited for: the events sit in a ring of at most 600 events and 16 MiB, encoded once for every stream, and one that fell behind the ring gets a lost event (events, and samples, the sample rows among them) and goes on from the oldest kept. An event's id is <epoch>-<seq>-<rows>, so a browser that reconnects with Last-Event-ID resumes right after it, or learns exactly how many samples it missed; an id of an earlier serve resumes at the newest event, with the loss unknown (null). At most 8 streams are served at once (503 past them), outside the 32 request slots; a stream's socket holds at most 64 KiB for a reader that has not taken it, and one that takes nothing for 30 s is closed. The executor's thread only appends to the open batch under a short lock, so a stalled page costs itself events, never the line a sample, and the host's memory stays bounded.

Recordings: run directories

Every capture serve owns is recorded by kleidos_meter.panel.recorder into a directory of its own under the data directory, named <UTC start>-<profile>-<6 hex> (for example 20261122T151054Z-STATE-b8cd36), readable by the user alone:

  • 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_record reads as it reads the instrument's own (a streamed run's export in its own format is stream.txt byte for byte; a ring run's rows come from the dump, timed by its drift anchors, each mark before the sample it marks), and json (kleidos.meter.export/1) carries the run's meta.json, its marks and its columns (t_us, i_na, ...), written a column at a time so a million samples are never held as objects.

A capture with no panel reuses the same recorder:

kleidos-meter capture --profile STATE --seconds 10 --port /dev/cu.usbmodemXXXX1
kleidos-meter capture --profile SLEEP --seconds 600 --channels CURR,VOLT --out ~/runs
kleidos-meter capture --profile TRACE --sim # a ring: until it is full

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_meter.panel.sequences runs the measurement sequences the panel offers as one button each, one at a time, on a thread of their own, through the executor and the recorder (a capture a sequence takes is a run like any other, labeled sequence <name>). Each is data in kleidos_meter.panel.steps: the parameters a person may set (each with its default and bounds, served in /api/schema), the steps (send a message, ask a query and keep its report, check a field of it, wait, wait until a report's field reads a value, ask a question, start, wait for, stop and mark a capture, verify or restore the calibration) and a cleanup that runs whatever happened: a step that failed, an abort (POST /api/sequences/abort or POST /api/abort), a question declined, serve stopping. The cleanup stops a capture the sequence started that still runs, closes a null window it opened, puts the relays back on the shunt (ROUTe:NULLpath OFF, which recloses K1 and opens K2 from any path, make-before-break) and checks path=shunt, and gives the I2C clock back what the sequence found; the instrument's hold puts the relays back 120 s after a host that died before it could. The panel never sends FORCe or LIVE on its own: the sequences that need FORCe (NULL_LEAD, COLD_BOOT) ask first, and go on only on continue.

The sequences, their parameters and what each one moves are docs/panel.md, "What each sequence moves".

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_running) but POST /api/abort and the sequence's own answer and abort; reads are served. A sequence is refused while a capture runs or a window serve did not open is open (409), and for a parameter it does not take or out of its bounds (400).

The shunt and its uncertainty

kleidos_meter.panel.settings shows each range's shunt as the instrument converts with it (CALibration:DATA?), beside the figure the calibration registry files for it: the applied value, its standard uncertainty u and U = k·u at k = 2, in ppm and in micro-ohms (for KM-0000000000 on both ranges 100116 µΩ, u = 424 ppm, U = 848 ppm, ±84.898 µΩ, as calibration/records/2026-11-20.md states it), the event, its validity and its record, the deviation from it, and the registry's verdict on the instrument (registry.compare). A range's source says what it converts with: registry (the registry's applied value), override, nominal (no measured shunt: a flashed instrument, until calibration restore) or device (a value nobody filed, with no uncertainty). The view is quotable only when the verdict is applied and no range converts with an override.

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_uohm (a rectangular limit t, so u = t/√3, GUM 4.3.7); one without, or with two, is refused before anything is sent. GET /api/settings/shunt/preview shows what it would write, its figures, its deviation from the registry's value and the normalized error between the two (E = |R_2 − R_1| / √(U_1² + U_2²)), and sends only queries; POST /api/settings/shunt with "confirm": true writes it (SENS:CURR:SHUN:RANG<n> <ohms>, to the micro-ohm; a value the instrument refuses is answered 409 with its error unchanged, and kept nowhere) and keeps it in $XDG_STATE_HOME/kleidos-meter/overrides/<serial>.json (by default) beside the data directory, never in this repository, readable by the user alone. While a range converts with it the view carries the banner "Not quotable", until POST /api/calibration/restore writes the registry's copy back and removes the file.

The generated references

The command line's reference is written by scripts/gen_cli_doc.py and the Python API's reference by scripts/gen_python_api_doc.py; run either after a change to what it reads, or with --check to see whether the page is stale.

  • 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/CONTRIBUTING-docstrings.md (native Sphinx fields, no Napoleon), so the same reader serves both:

  • 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/test_python_api_doc.py fails on a public name of any module with no docstring, and, in the modules of the page, on a parameter, a returned value or a field with no field of its own, a field that names what is not there, and a signature without its hints.

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/panel_harness.py):

  • 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=:
.venv/bin/python -m pytest -q -W error tests/test_panel_bench.py --run-bench \
--meter-port "$KLEIDOS_METER_PORT" --bench-lock <lock file> [--bench-shots <dir>]

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_METER_PORT and KLEIDOS_METER_LOCK, the names the repository's own bench suite (tests/bench) takes; a lock another process already holds for this run is named by KLEIDOS_METER_LOCK_PID. No other test sees the port: the suite takes KLEIDOS_METER_PORT out of the environment once the option has read it (tests/conftest.py), so a test run from a shell that exports it never opens the instrument.

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_floors.toml holds each module to the share measured, and fail_under in pyproject.toml holds the total, so neither falls. A side only a race between threads decides is staged by a test (a held read, a barrier, an injected clock), never left to a lucky run.

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:

cp -R . /tmp/meter-mutant && cd /tmp/meter-mutant
git apply host/mutants/HO10-pathtail.patch
PYTHON=$OLDPWD/host/.venv/bin/python sh -c "$(sed -n 's/^# Kill: //p' host/mutants/HO10-pathtail.patch)"

tests/test_mutants.py holds that every patch still applies, changes the package alone and names tests that exist; a change that moves a mutant's lines writes its patch again.

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/check_metadata.py); Playwright 1.65.2 in the browser extra, apart because its browser is a separate download. A warning in the suite is a failure (filterwarnings = ["error"]), and a run with --cov (as scripts/run_tests.sh makes it) fails below the measured total in [tool.coverage.report] fail_under, which a change may raise and never lower; branch_floors.toml then holds each module's share of its branch sides to a floor of its own (scripts/test_report.py --gate), the panel's at 90 % or more, and a floor only rises either.

The Kleidos firmware repository's QA harness (qa/tools/power_campaign.py, MeterLink) is the client the measurements are taken with; it speaks this protocol on its own, and this package is the reference for any other host.

Back to the top