Kleidos API Search

In development. It changes without notice.

The Python API

The host package, kleidos_meter: every public class, method and function a program that drives the meter may use. This page is written by scripts/gen_python_api_doc.py from the sources' docstrings, and a test fails when the two differ. The package's installation and a first program are in the host package's README; the command line is the command line's reference, the panel's HTTP API the HTTP API's reference, and what each SCPI command, report key and error number means the SCPI command set.

A report comes back as its fields, text by key, as the instrument printed them, and an integer's name ends in its unit (_us, _na, _pv, _nohm).

Module Holds
kleidos_meter.client the instrument on its port
kleidos_meter.protocol the wire format, with no I/O
kleidos_meter.sim a simulated instrument
kleidos_meter.pins the pin map, its rules and a board's wiring
kleidos_meter.identity which instrument it is
kleidos_meter.registry the calibration registry
kleidos_meter.calibration_cli an instrument against the registry
kleidos_meter.calibrate the guided calibration
kleidos_meter.relay_timing the relays' times

Exported by the package

from kleidos_meter import …; everything else is imported from its module.

kleidos_meter.client

A synchronous client for the meter's SCPI protocol (docs/scpi.md).

Every exchange is one program message ending in SYSTem:ERRor:ALL?, so each answer carries its own verdict and no error is left queued for the next one; the first message of a session also clears the queue (*CLS). Stream records arriving while the client waits are kept, never mistaken for the response: the bytes of the line go through LineRouter, which tells responses, blocks and records apart however the bytes are cut.

Transport

class Transport(Protocol)

A byte pipe to the instrument: what a Meter is made on.

SerialTransport is the line, and SimulatedMeter is one too.

Transport.write

Transport.write(data: bytes) -> int

Send data.

  • data: The bytes to send.
  • returns: How many were taken.

Transport.read

Transport.read(size: int) -> bytes

Read what has arrived, waiting a moment for some.

  • size: The most bytes to return.
  • returns: What arrived, possibly nothing.

Transport.close

Transport.close() -> None

Release the pipe.

MeterError

class MeterError(message: str, errors: Sequence[ErrorEntry] = ())

The instrument refused a unit, or did not answer.

  • message: What happened, for a person.
  • errors: The instrument's errors, oldest first.
  • attribute errors: The same, as a list.

MeterError.codes

MeterError.codes -> list[int]

The error numbers.

MeterTimeout

class MeterTimeout(MeterError)

No response arrived in time.

PortBusyError

class PortBusyError(MeterError)

The port is held by another opener: serve, a QA run or another tool.

Capture

class Capture(rows: dict[int, dict[str, float]] = {}, marks: list[Mark] = [])

What a capture streamed: samples merged by timestamp, and marks.

  • rows: Each timestamp's channels and values, by microseconds since boot.
  • marks: The marks, in the order they arrived.

Capture.channel

Capture.channel(name: str) -> list[tuple[int, float]]

One channel as (t_us, value) pairs, in time order.

  • name: The channel: i_ua, v_mv, p_mw or die_c.
  • returns: Its samples; empty when the capture did not carry it.

SerialTransport

class SerialTransport(port: str, baud: int = 6000000, *, exclusive: bool = True)

The CH343 line, opened exclusively and so that the open does not reset the board.

The carrier's auto-reset circuit pulls EN low for one line state only: DTR released while RTS is still asserted (docs/carrier-board.md §7). The port is opened with the lines as the OS and pyserial leave them, then RTS is released, then DTR (docs/scpi.md, "The line"). Setting both before open() does not keep that order: pyserial applies DTR first and RTS second inside open(), which passes through the reset state.

The open takes an exclusive lock on the port by default (pyserial's exclusive, an flock on POSIX; Windows ports are exclusive anyway): a second opener would otherwise read some of the lines meant for the first, and both would lose them. A port another process holds is refused at once with PortBusyError.

port may also be a pyserial URL (socket://127.0.0.1:5025, the passthrough of kleidos-meter serve; loop:// in tests), opened through serial.serial_for_url; the control lines are then whatever the URL's handler makes of them.

  • port: The device node, or a pyserial URL.
  • baud: The line rate, 6,000,000 on the bench.
  • exclusive: Lock the port against every other opener.
  • raises PortBusyError: When another opener holds the port.

SerialTransport.write

SerialTransport.write(data: bytes) -> int

Write data and wait until it has left.

  • data: The bytes to send.
  • returns: How many were written.

SerialTransport.read

SerialTransport.read(size: int) -> bytes

Read up to size bytes, waiting at most the port's 50 ms timeout.

  • size: The most bytes to return.
  • returns: What arrived, possibly nothing.

SerialTransport.close

SerialTransport.close() -> None

Close the port, which releases its lock.

Meter

class Meter(transport: Transport, *, clock: Callable[[], float] = time.monotonic)

The instrument.

A method raises MeterError, with the instrument's errors, when the instrument refuses what it sent, and MeterTimeout when no response comes; send returns whatever was answered, and close_zero the errors. It is a context manager that closes the transport, and closes nothing else: a capture or a null window left open, or a relay off its rest, stays so.

  • transport: Its byte pipe.
  • clock: The monotonic clock timeouts are measured on.
  • attribute capture: What the last capture started here streamed.

Meter.close

Meter.close() -> None

Release the transport.

Meter.drain

Meter.drain(*, quiet: float = 0.1, limit: float = 1.0) -> int

Discard what the line holds: read until it has been silent for quiet.

A running capture never goes silent, so the drain also ends after limit seconds.

  • quiet: How long the line must be silent, seconds.
  • limit: The longest the drain may take, seconds.
  • returns: How many bytes were discarded, counting none for events already routed.

Meter.wait_ready

Meter.wait_ready(*, timeout: float = 15.0, attempt: float = 0.25) -> bool

Wait until the instrument answers, and say whether it had rebooted.

A bare newline ends any partial line the instrument holds, the line is drained, then *ESR? is asked with short timeouts until it answers: the instrument discards what arrives while it boots (the boot runs a PSRAM test first), so the first queries may go unanswered. *ESR? reads and clears the Standard Event register, so the power-on bit is reported once, to this call. The line is drained again after the answer, so that a late reply to an earlier attempt is not taken for the response to the next message.

  • timeout: How long to wait for the first answer, seconds.
  • attempt: How long each *ESR? waits, seconds.
  • returns: True when the power-on bit (128) was set: the instrument rebooted since its Standard Event register was last read.
  • raises MeterTimeout: When no attempt was answered within timeout.
  • raises MeterError: When *ESR? was answered with no number.

Meter.send

Meter.send(message: str, *, timeout: float = 8.0) -> Response

Send one program message and return its response line.

Stream records routed before the response are kept in capture; whatever was routed after it waits for the next call.

  • message: The program message, without its newline.
  • timeout: How long to wait for the response, seconds.
  • returns: The response line, its units and any block.
  • raises MeterTimeout: When no response arrives within timeout.

Meter.exchange

Meter.exchange(
units: Sequence[str],
*,
timeout: float = 8.0,
raise_errors: bool = True,
) -> tuple[list[str], list[ErrorEntry], bytes | None]

Send units plus SYSTem:ERRor:ALL? as one message.

The first message of a session starts with *CLS, so that an error queued before it is not taken for one of its own.

  • units: The message's units, in order, each from the root.
  • timeout: How long to wait for the response, seconds.
  • raise_errors: Raise the instrument's errors, rather than return them.
  • returns: The query responses, the errors, and a block if one came.
  • raises MeterError: When a unit was refused and raise_errors.
  • raises MeterTimeout: When no response arrives within timeout.

Meter.query

Meter.query(query: str, *, timeout: float = 8.0) -> str

Ask one query and return its response unit.

  • query: The query.
  • timeout: How long to wait for the response, seconds.
  • returns: Its response, empty when it answered only a block.
  • raises MeterError: When it was refused.

Meter.report

Meter.report(query: str, *, timeout: float = 8.0) -> dict[str, str]

Ask one report query and return its fields.

  • query: The query, of a key=value report (docs/scpi.md).
  • timeout: How long to wait for the response, seconds.
  • returns: The report's fields, as text.
  • raises MeterError: When it was refused.

Meter.idn

Meter.idn() -> str

*IDN?.

  • returns: The four fields, comma-separated: parse_idn splits them.

Meter.info

Meter.info() -> dict[str, str]

SYSTem:INFormation?.

  • returns: What the instrument is: its chip, shunt, calibration, image, serial.

Meter.status

Meter.status() -> dict[str, str]

SYSTem:STATus?.

  • returns: What it is doing: the window open, the profile, the range, the counts.

Meter.calibration

Meter.calibration() -> dict[str, str]

CALibration:DATA?.

  • returns: Its working copy of the calibration: the shunt, the nulls, the tag.

Meter.heap

Meter.heap() -> dict[str, str]

DIAGnostic:HEAP? (0.7.0 and later): heap use since the boot settled.

allocs_after_init and frees_after_init are 0 on a firmware that allocates nothing in its steady state; maint_allocs and maint_frees count what calibration saves and I2C clock changes allocated inside ESP-IDF. The zero-allocation image appends pre_main_allocs, pre_main_frees (what ESP-IDF allocated before app_main), allocs_since_main and frees_since_main (0 on a healthy image); an older one reports no such keys.

  • returns: The report's fields.

Meter.watchdog

Meter.watchdog() -> dict[str, str]

DIAGnostic:WATChdog? (0.14.0): the task watchdog as the instrument runs it.

console and sampler are 1 when that task's subscription was accepted, panic is 1 when a starved task reboots the instrument, and stalls counts the captures the console found taking no sample.

  • returns: The report's fields.

Meter.set_profile

Meter.set_profile(name: str) -> dict[str, str]

Select a profile.

  • name: TRACE, STATE, SLEEP or BURST, or its short form.
  • returns: SENSe:PROFile:REPort?'s fields.
  • raises MeterError: When it was refused: a window is open, or no such profile.

Meter.set_range_index

Meter.set_range_index(index: int) -> dict[str, str]

Select the INA228's range by its ADCRANGE.

  • index: 0, ±163.84 mV, or 1, ±40.96 mV.
  • returns: SENSe:CURRent:RANGe:REPort?'s fields.
  • raises MeterError: When it was refused: a window is open, or no such range.

Meter.pins

Meter.pins(*, pending: bool = False) -> dict[str, str]

SYSTem:PINS?: the live pin map, or with pending the staged one.

  • pending: Ask SYSTem:PINS:PENDing? instead: the staged map and its verdict, valid and, when 0, problem and at.
  • returns: The report's fields: each role's GPIO, the address, the boot clock, the pulls and the relays' levels, then src, verified and table (the board table's digest), as docs/scpi.md has them.

Meter.stage

Meter.stage(**changes: int | str | None) -> dict[str, str]

Stage a pin map: the staged map with changes, judged and not applied.

A role (sda, scl, alert, relay1, relay2) takes a GPIO or None; pull_sda, pull_scl and pull_alert take up or off; relay1_active and relay2_active high or low; addr an address, 0x40 to 0x4F, or 0 or auto for a scan; scl_hz the bus clock at boot. Nothing on the board changes until apply. meter.stage(sda=18, scl=21) stages the bus on GPIO18 and GPIO21; the returned valid says whether the rules take it.

  • changes: The fields to change, keyed as pins names them.
  • returns: SYSTem:PINS:PENDing?'s fields after the change.
  • raises ValueError: On a key the map does not have.
  • raises MeterError: When the instrument refused a unit.

Meter.apply

Meter.apply() -> tuple[dict[str, str], list[ErrorEntry]]

SYSTem:PINS:APPLy: make the staged map the live one, proved, or keep the last.

The instrument brings the map up and proves the INA228 on it; a map it cannot prove is reverted with one error (117), and one it refuses changes nothing: result=refused with its error for a relay not at rest or a map the rules refuse, and only the error (-221, 112) under a window, which the order's flags refuse before it runs. None of them raises.

  • returns: SYSTem:PINS:RESult?'s fields (result is ok, reverted or refused, or the last apply's after a window's refusal) and the errors the order queued.

Meter.pins_defaults

Meter.pins_defaults() -> tuple[dict[str, str], list[ErrorEntry]]

SYSTem:PINS:DEFault: the rig's map back, with apply's checks.

It needs no INA228: the way back from a map that left none.

  • returns: SYSTem:PINS:RESult?'s fields and the errors the order queued.

Meter.measure

Meter.measure(function: str = 'CURR', *, timeout: float = 30.0) -> float

MEASure:<function>?: one acquisition, its mean in base units.

It configures the function first, and takes SAMPle:COUNt samples.

  • function: CURR, VOLT, POW, ENER or TEMP.
  • timeout: How long to wait for the answer, seconds: longer than the sample count times the profile's period.
  • returns: Amperes, volts, watts, joules over the window, or degrees Celsius.
  • raises MeterError: When it was refused.

Meter.start

Meter.start(channels: Sequence[str] = ()) -> dict[str, str]

Choose the channels, start a capture, and return its header.

capture starts empty; a streamed capture's records fill it as the responses that follow are read.

  • channels: The stream channels, i_ua, v_mv, p_mw and die_c among them; the profile's own when empty.
  • returns: FETCh:HEADer?'s fields.
  • raises MeterError: When the capture was refused.
  • raises KeyError: For a channel that is none of the four.

Meter.start_statistics

Meter.start_statistics() -> dict[str, str]

Start a statistics-only capture (SENSe:CAPTure STATistics, 0.10.0).

Nothing is streamed and the ring is untouched; stop returns the statistics. The setting stays: set_capture puts it back.

  • returns: The capture's header.
  • raises MeterError: When the capture was refused.

Meter.set_capture

Meter.set_capture(statistics_only: bool) -> None

SENSe:CAPTure DATA|STATistics: what the next INITiate keeps.

  • statistics_only: The statistics alone, rather than the samples too.

Meter.set_threshold

Meter.set_threshold(amps: float | None, hysteresis: float = 0.0) -> None

The current level the statistics count against.

  • amps: The level, amperes; None for OFF.
  • hysteresis: How far below it the count falls back, amperes.
  • raises MeterError: When a value is outside the instrument's range.

Meter.self_test

Meter.self_test() -> int

*TST?: the instrument's self-test.

  • returns: 0 when every part passed, else one bit per part (docs/scpi.md).

Meter.health

Meter.health() -> dict[str, str]

SYSTem:HEALth?: the reset reason, the image, the stacks and the counts.

  • returns: The report's fields.

Meter.batches

Meter.batches() -> dict[str, str]

FETCh:STATistics:BATCh?: the last closed capture's batch means.

  • returns: The report's fields.

Meter.stop

Meter.stop(*, timeout: float = 20.0) -> dict[str, str]

Close the capture and return its statistics.

  • timeout: How long to wait, seconds.
  • returns: FETCh:STATistics?'s fields.
  • raises MeterError: When no window was open (111), or an error was queued.

Meter.mark

Meter.mark(label: str) -> Mark

Mark the running capture.

  • label: The mark's label.
  • returns: The mark record the instrument emitted.
  • raises MeterError: When it was refused, or no mark record came.

Meter.zero

Meter.zero(seconds: int) -> dict[str, str]

Open a null window on the live range and profile.

  • seconds: How long, 1 to 600.
  • returns: CALibration:ZERO:RESult?'s fields, the window running.
  • raises MeterError: When it was refused.

Meter.close_zero

Meter.close_zero(*, timeout: float = 20.0) -> tuple[dict[str, str], list[ErrorEntry]]

Close the null window.

  • timeout: How long to wait, seconds.
  • returns: Its result, and any errors: a null out of bounds is not stored (102, 106) and is returned, not raised.

Meter.set_reference

Meter.set_reference(ohms: float) -> None

CALibration:SHUNt:REFerence: the reference resistor's value.

  • ohms: Ohms, 1 to 4000.

Meter.shunt_point

Meter.shunt_point(*, timeout: float = 60.0) -> dict[str, str]

CALibration:SHUNt: one point of the shunt on the live range.

The reference must be in place of the DUT (calibration/README.md).

  • timeout: How long the acquisition may take, seconds.
  • returns: CALibration:SHUNt:RESult?'s fields.
  • raises MeterError: When it was refused.

Meter.set_shunt

Meter.set_shunt(ohms: float, tag: str) -> dict[str, str]

Store a measured shunt and its tag, as the instrument's working copy.

The registry is the calibration: kleidos-meter calibration restore is how the copy is written from it.

  • ohms: The shunt, ohms.
  • tag: The calibration tag.
  • returns: CALibration:DATA?'s fields.
  • raises MeterError: When it was refused.

Meter.dump

Meter.dump(*, raw: bool = True, timeout: float = 180.0) -> list[str]

TRACe:DATA?: the ring's rows.

  • raw: RAW counts, rather than SCALed currents.
  • timeout: How long the whole dump may take, seconds.
  • returns: The block's lines, its opening and closing rows among them.
  • raises MeterError: When no block came, or it arrived damaged.

Meter.trace

Meter.trace(*, timeout: float = 240.0) -> Dump

The ring, decoded: FETCh:HEADer? and TRACe:DATA? RAW in one message.

The header is read in the same message as the dump, so both describe the same capture, and the raw counts become currents exactly as the instrument converts them (decode_dump).

  • timeout: Seconds the whole answer may take; a full ring at 6 Mbaud takes about 20.
  • returns: The decoded dump.
  • raises MeterError: When no block came, or it arrived damaged.

kleidos_meter.protocol

The wire format of the meter's SCPI protocol (docs/scpi.md), with no I/O.

Splitting messages and responses into units, the error queue's entries, the key=value reports, the stream records, the definite-length block, the ring dump that block carries (decode_dump), and the LineRouter that turns the bytes of the line, however they are cut, into responses, stream records and block progress.

split_outside_quotes

split_outside_quotes(text: str, separator: str) -> list[str]

Split text at every separator outside a quoted string.

  • text: What to split.
  • separator: One character, not a quote.
  • returns: Its pieces, in order, unstripped.

split_units

split_units(text: str) -> list[str]

Split a message or a response at every ; outside a quoted string.

  • text: A program message or a response line.
  • returns: Its units, in order, unstripped.

parse_fields

parse_fields(report: str) -> dict[str, str]

Return the key=value tokens of a report unit.

  • report: The report.
  • returns: Its fields, as text.

ErrorEntry

class ErrorEntry(code: int, text: str)

One entry of the instrument's error queue.

  • code: The error's number: negative for a standard one, positive for the instrument's own (docs/scpi.md).
  • text: Its text: the standard one, a ; and the firmware's reason.

ErrorEntry.standard

ErrorEntry.standard -> str

The standard text, before the ;.

ErrorEntry.detail

ErrorEntry.detail -> str

The firmware's reason, after the ; (empty when there is none).

parse_errors

parse_errors(unit: str) -> list[ErrorEntry]

Return the errors of a SYSTem:ERRor[:ALL]? answer, 0 left out.

  • unit: The answer.
  • returns: The errors, oldest first; empty when there are none.

Sample

class Sample(t_us: int, values: dict[str, float], line: str = '')

One streamed sample: its timestamp and the channels it carries.

  • t_us: The sample's timestamp, microseconds since the instrument booted.
  • values: Each channel's value, in its unit (i_ua microamps, ...).
  • line: The record as the instrument wrote it, without its newline; empty for a sample that was not read from a line. It takes no part in comparisons.

Mark

class Mark(label: str, index: int, t_us: int, line: str = '')

One mark: a label at a sample index.

  • label: The mark's label.
  • index: The sample index it marks.
  • t_us: That sample's timestamp.
  • line: The record as the instrument wrote it, as Sample.line.

parse_record

parse_record(line: str) -> Sample | Mark | None

Parse one stream record, TEXT or CSV.

A TEXT sample carries one channel per line; the caller merges lines of one timestamp if it wants rows.

  • line: One line of the stream, without its newline.
  • returns: The sample or the mark; None for any other line.

block_header

block_header(data: bytes) -> tuple[int, int] | None

Read a definite-length block's header at the start of data.

  • data: Bytes that start with #.
  • returns: (header length, payload length), or None until enough bytes are there.
  • raises ValueError: When data starts with # but is no definite block.

quote

quote(text: str) -> str

Write text as a SCPI string parameter.

  • text: The string.
  • returns: It in double quotes, each one inside it doubled.

check_dump

check_dump(block: bytes) -> bool | None

Hold a TRACe:DATA? block to the CRC-32 its closing row carries (0.11.0).

The closing row is METER_DUMP_END crc32=<8 hex> bytes=<n>: the IEEE CRC-32 (zlib.crc32) of the block's first n bytes, every row before it. A block from an older image ends in a bare METER_DUMP_END.

  • block: The block's bytes, as TRAC:DATA? delivered them.
  • returns: True when the CRC matches, None when the block carries none.
  • raises ValueError: When it carries one and the bytes do not match it.

current_nanoamps

current_nanoamps(counts: int, shunt_lsb_pv: int, offset_pv: int, shunt_uohm: int) -> int

The current of one raw count, as scale::currentNanoamps computes it.

(counts x shunt_lsb_pv - offset_pv) x 1000 / shunt_uohm, in 64-bit integers, the division truncated toward zero as C++ truncates it: the LSB of the capture's range, the null it subtracted and the shunt it converted with, so the result is the integer the instrument printed (firmware/src/scale.h). A shunt of 0 gives 0, as the firmware's guard does.

  • counts: The sample's raw 20-bit VSHUNT count, as a RAW row has it.
  • shunt_lsb_pv: The range's VSHUNT LSB, picovolts.
  • offset_pv: The zero-current null the capture subtracted, picovolts.
  • shunt_uohm: The shunt the capture converted with, micro-ohms.
  • returns: The current, nanoamps.

parse_thousandths

parse_thousandths(text: str) -> int

Read a value formatThousandths wrote back into its integer.

  • text: A v= value, a sign, digits, a point and three decimals.
  • returns: The value in thousandths of its unit (nanoamps for i_ua).
  • raises ValueError: When text is not that shape.

format_thousandths

format_thousandths(value: int) -> str

Write value thousandths as scale::formatThousandths does: three decimals.

The inverse of parse_thousandths: 88066019 is 88066.019, -500 is -0.500.

  • value: A value in thousandths of its unit.
  • returns: Its text, a sign only when negative.

DumpScale

class DumpScale(shunt_lsb_pv: int, offset_pv: int, shunt_uohm: int)

What a capture converted its raw counts with, from its FETCh:HEADer?.

  • shunt_lsb_pv: The range's VSHUNT LSB, picovolts.
  • offset_pv: The null the capture subtracted, picovolts.
  • shunt_uohm: The shunt the capture converted with, micro-ohms: the range's applied value, whose ratio to the nominal 100,000 is the correction scale.h applies.

DumpScale.from_header

DumpScale.from_header(header: Mapping[str, str] | str) -> DumpScale

The scale a FETCh:HEADer? report states.

shunt_lsb_pv is read when the report has it, else derived from range (SHUNT_LSB_PV).

  • header: The report, as text or as parse_fields returns it.
  • returns: The capture's scale.
  • raises ValueError: When shunt_uohm, offset_pv or both of shunt_lsb_pv and a known range are missing or not integers.

DumpScale.nanoamps

DumpScale.nanoamps(counts: int) -> int

The current of raw counts, as current_nanoamps computes it.

  • counts: A raw 20-bit VSHUNT count.
  • returns: The current, nanoamps.

Anchor

class Anchor(index: int, t_us: int)

A drift anchor: the real timestamp of one sample index (A row).

  • index: The capture's sample index.
  • t_us: When that sample was taken, microseconds since boot.

Trigger

class Trigger(index: int, t_us: int)

Where a level trigger fired (T row).

  • index: The capture's sample index it fired at.
  • t_us: That sample's timestamp, microseconds since boot.

DumpMark

class DumpMark(index: int, label: str)

A mark as a dump writes it (K row): a label at an index, no time.

  • index: The capture's sample index the mark was taken at.
  • label: Its label.

RawRow

class RawRow(index: int, counts: tuple[int, ...])

A RAW row: up to sixteen raw counts from an index on (R row).

  • index: The capture's index of the first count.
  • counts: The raw 20-bit counts, in index order.

ScaledRow

class ScaledRow(t_us: int, nanoamps: int)

A SCALed row: one sample's current at its implicit timestamp.

  • t_us: t0_us + index x period_us, as the row prints it.
  • nanoamps: The current the instrument computed, nanoamps.

parse_dump_row

parse_dump_row(row: str) -> DumpRow | None

Read one row of a TRACe:DATA? block's body.

  • row: One line of the block, its newline removed.
  • returns: The row, or None for the opening and closing rows and any other line.
  • raises ValueError: When the row has a body row's prefix and a bad field.

DumpSample

class DumpSample(index: int, t_us: int, counts: int | None, nanoamps: int | None)

One sample of a decoded dump, as Dump.samples yields it.

  • index: The capture's sample index.
  • t_us: Its timestamp, interpolated between the drift anchors.
  • counts: Its raw count (None from a SCALed dump).
  • nanoamps: Its current (None from a RAW dump decoded with no header).

Dump

class Dump(
raw: bool,
count: int,
t0_us: int,
period_us: int,
first: int,
start: int,
counts: array[int] | None,
nanoamps: array[int] | None,
anchors: tuple[Anchor, ...],
marks: tuple[Mark, ...],
trigger: Trigger | None,
trig_n: int | None,
crc_checked: bool,
)

A TRACe:DATA? block, decoded by decode_dump.

The samples are held as columns, one integer per sample in an array.array, so a full ring of 1,048,576 samples takes a few megabytes rather than a Python object each.

  • raw: Whether the block was RAW (else SCALed).
  • count: The samples it carries, count= of its opening row.
  • t0_us: The capture's start, microseconds since boot.
  • period_us: The capture's nominal period, microseconds.
  • first: The capture index of the ring's oldest sample (first=, else 0).
  • start: The capture index of the first sample dumped.
  • counts: The raw counts, in index order (None from a SCALed dump).
  • nanoamps: The currents, in index order: computed from the counts by the header's DumpScale, or read from a SCALed dump's rows; None from a RAW dump decoded with no header.
  • anchors: The drift anchors, in index order.
  • marks: The marks, in index order, each timed by t_us.
  • trigger: Where a level trigger fired (its T row), or None.
  • trig_n: The index a level trigger fired at, from the opening row's trig_n=, which a partial dump carries even when it holds no T row.
  • crc_checked: Whether the closing row carried a CRC (and it matched).

Dump.indices

Dump.indices -> range

The capture indices of the samples dumped, in order.

Dump.nominal_t_us

Dump.nominal_t_us(index: int) -> int

The implicit timestamp a SCALed row prints: t0_us + index x period_us.

  • index: A capture sample index.
  • returns: Microseconds since boot, uncorrected for drift.

Dump.t_us

Dump.t_us(index: int) -> int

The timestamp of sample index, corrected by the drift anchors.

Between two anchors it is interpolated linearly, rounded to the nearest microsecond; before the first and after the last it runs on from the nearest anchor at the nominal period; with no anchor it is nominal_t_us.

  • index: A capture sample index, inside the dump or not.
  • returns: Microseconds since boot.

Dump.timestamps

Dump.timestamps() -> array[int]

t_us of every sample dumped.

  • returns: Microseconds since boot, in index order.

Dump.samples

Dump.samples() -> Iterator[DumpSample]

Every sample dumped, in index order.

  • returns: The samples, made as they are asked for.

Dump.counts_between

Dump.counts_between(first: int, last: int) -> list[int]

The raw counts of indices first to last - 1 that the dump holds.

  • first: The first capture index wanted.
  • last: One past the last capture index wanted.
  • returns: The counts of the indices in both the range and the dump, in order.
  • raises ValueError: On a SCALed dump, which holds no counts.

decode_dump

decode_dump(block: bytes, header: Mapping[str, str] | str | None = None) -> Dump

Decode a TRACe:DATA? block, RAW or SCALed (docs/scpi.md).

The block is held to its CRC first (check_dump). A RAW block's counts are converted with the capture's FETCh:HEADer? when header is given, exactly as scale.h converts them (DumpScale), so every current is the integer the instrument's SCALed dump of the same ring prints; a SCALed block's currents are read from its rows. Timestamps are the capture's t0_us and period, corrected between the drift anchors (Dump.t_us).

  • block: The block's payload, as TRACe:DATA? delivered it.
  • header: The capture's FETCh:HEADer? report, as text or fields, or None to leave a RAW dump's currents out.
  • returns: The decoded dump.
  • raises ValueError: When the CRC does not match, the opening row is missing or malformed, a row is malformed, the samples are not contiguous, their number is not count=, or header belongs to another capture (its t0_us or period_us differ) or lacks the scale.

Response

class Response(units: list[str], blocks: list[bytes] = [])

One response line: its units, and the blocks it carried.

A block is not one of the units: a TRACe:DATA? unit takes no place in units, so the units are the answers of the message's other queries, in order.

  • units: The line's units, a block's place left out.
  • blocks: The payloads of its definite-length blocks, in order.

Response.block

Response.block -> bytes | None

The line's first block, or None when it carried none.

BlockProgress

class BlockProgress(received: int, total: int)

How much of the definite-length block being read has arrived.

  • received: Payload bytes read so far.
  • total: The payload's length, from the block's header.

Overflow

class Overflow(discarded: int)

A line longer than the router's limit, given up whole.

  • discarded: How many bytes were dropped, its \n included.

LineRouter

class LineRouter(max_line: int = MAX_LINE)

Turn the bytes of the line into responses, stream records and block progress.

Pure and incremental: feed takes the bytes in whatever pieces they arrive and returns the events they complete, the same responses and records for any cut (only the number of BlockProgress events depends on it). A line is a stream record when parse_record reads it as one, else a response; an empty line is nothing. A definite-length block starts at a # that begins a unit of a response line, at the line's start or after a ; outside a quoted string, and is read by its byte count, so its rows, their newlines and anything else in it are never taken for the line's text (docs/scpi.md, "Responses"). A # whose header is malformed is text.

  • max_line: The longest line held, in bytes, before it is given up as an Overflow; a block's payload does not count.

LineRouter.reset

LineRouter.reset() -> None

Forget every byte held and any line or block in progress.

LineRouter.held

LineRouter.held -> int

How many bytes the router holds that no event has accounted for yet.

LineRouter.feed

LineRouter.feed(data: bytes) -> list[RouterEvent]

Take the next bytes of the line.

  • data: Bytes as the line delivered them, any length, empty included.
  • returns: The events they complete, in line order.

kleidos_meter.sim

A simulated instrument: the meter's SCPI protocol over an in-memory pipe.

It implements the framing exactly as the firmware does (units, root paths, long and short forms, the error queue, a response line per message, stream records outside responses, the definite-length block) and resolves every header against a copy of the firmware's command table (sim_table), with its flags: a command the simulator does not model is in UNDEFINED and answers -113 as an unknown header does. A DUT drawing a fixed current at a fixed voltage stands behind it, or a scripted waveform (ScriptedWaveform).

The board has a wiring (Wiring, the rig's by default) and the instrument a pin map (0.18.0): the INA228 answers only on a map whose bus is where the wiring has it, so SYSTem:PINS:APPLy proves a staged map on the wiring and reverts one it cannot prove, as the firmware does; a saved map survives SimulatedMeter.reboot, and one whose bus no longer answers falls back at boot. The averaging override (SENSe:AVERage) changes each profile's word and period, and with noise_a the samples carry a noise that falls with the square root of the samples averaged.

Two modes:

  • Deterministic (the default): time stands still. A streamed capture emits four samples per program message and two more at ABORt, a ring holds 64 samples as soon as INITiate starts it, and a statistics-only capture counts 64. The client's tests are written against this mode.
  • Clock-driven (clocked=True, for kleidos-meter serve --sim and the panel's tests): samples are due at the profile's period on SimulatedMeter.clock, and SimulatedMeter.read emits them as they fall due. A streamed sample that would overflow the output buffer (tx_capacity bytes the reader has not taken) is lost and counted in dropped=, as the instrument counts a line it could not write. A ring fills over time with a drift anchor every 1024 samples and ends by itself when full; SENSe:CAPTure:LIMit and a level trigger end their captures by themselves; a null window ends after its seconds; the relay hold runs in real time; DIAGnostic:WATChdog:TEST reboots after the watchdog's timeout; SimulatedMeter.inject_reboot reboots now. A MEASure holds the console for its SAMPle:COUNt periods: what arrives meanwhile waits, and a message whose first unit is ABORt ends it with -230, as the firmware's acquisition does. FETCh:STATistics? reports the samples taken, of which the stream carried samples - dropped.

Every entry point takes one lock, so a reader thread and a writer thread can share an instance.

ScriptedWaveform

class ScriptedWaveform(steps: Sequence[tuple[float, float]], *, repeat: bool = True)

A piecewise-constant current the simulated DUT draws, repeated.

  • steps: (seconds, amperes) pairs, in order.
  • repeat: Start again after the last step; otherwise hold its level.
  • raises ValueError: With no step, or a step that is not positive.

ScriptedWaveform.period_us

ScriptedWaveform.period_us -> int

One pass through every step, microseconds.

SimulatedMeter

class SimulatedMeter(
current_a: float = 0.0886,
voltage_v: float = 4.064,
*,
clocked: bool = False,
waveform: Callable[[int], float] | None = None,
ring_capacity: int = RING_CAPACITY,
tx_capacity: int = 1 << 18,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], None] = time.sleep,
wiring: pins.Wiring = pins.RIG_WIRING,
noise_a: float = 0.0,
)

The instrument, behind write/read/close like a serial port.

  • current_a: What the DUT draws, amperes, when no waveform is given.
  • voltage_v: What it sees, volts.
  • clocked: Run on clock (the module's "Clock-driven" mode).
  • waveform: The DUT's current at a device time in microseconds; the clock-driven mode samples it, the deterministic mode ignores it.
  • ring_capacity: The ring's size, RING_CAPACITY by default.
  • tx_capacity: The bytes of output the clock-driven mode holds for the reader before a streamed sample is dropped.
  • clock: The monotonic clock, seconds.
  • sleep: How the clock-driven read waits.
  • wiring: Where the board's parts are (Wiring): the rig's by default. A map whose bus is not the wiring's finds no INA228, and one whose relays are not its fails the null-path check.
  • noise_a: The RMS noise, amperes, of each clock-driven sample a profile takes with its own ADC_CONFIG; the averaging override divides it by the square root of the samples it averages for each one (count times shunt conversion time, over the profile's own). 0, the default, keeps every sample exactly the DUT's current.

SimulatedMeter.serial

SimulatedMeter.serial -> str

*IDN?'s serial: the digest of the MAC, or 0.

SimulatedMeter.image

SimulatedMeter.image -> str

identity.h kImageName: meter from 0.8.0, which has one image.

Set firmware below 0.8.0 to model an older image: then meter drove the HW-316 bypass and meter_relay2 the Relay 2 Click.

SimulatedMeter.t_us

SimulatedMeter.t_us -> int

Microseconds since boot: the clock's in the clock-driven mode.

SimulatedMeter.running

SimulatedMeter.running -> bool

Whether a window samples now (Sampler::running).

SimulatedMeter.window_open

SimulatedMeter.window_open -> bool

Whether a window is open, ended by itself or not (captureOpen).

SimulatedMeter.range_shunt_ohm

SimulatedMeter.range_shunt_ohm(index: int) -> float

The shunt range index converts with: its own value or the common one.

  • index: 0 or 1.
  • returns: Ohms.

SimulatedMeter.current_at

SimulatedMeter.current_at(t_us: int) -> float

What the DUT draws at device time t_us.

  • t_us: Microseconds since boot.
  • returns: Amperes.

SimulatedMeter.write

SimulatedMeter.write(data: bytes) -> int

Take data as the line delivers it: every newline ends a message.

  • data: The bytes.
  • returns: How many were taken: all of them.

SimulatedMeter.reboot

SimulatedMeter.reboot(writes: int = 0) -> None

Power-cycle: settings to their defaults, the power-on bit set.

What lives in RAM is lost (the open and the last capture, the ring, the results, the error queue, the status registers); the calibration is kept, as NVS keeps it.

  • writes: How many writes the booting instrument discards.

SimulatedMeter.inject_reboot

SimulatedMeter.inject_reboot(reason: str = 'panic', *, writes: int = 0) -> None

Reboot now for reason, as a panic or a watchdog would.

A coil the reset found energized is released and reported, as the firmware's boot does (error 116 and reset_released).

  • reason: What SYSTem:HEALth? then names, esp_reset_reason()'s word.
  • writes: How many writes the booting instrument discards.

SimulatedMeter.read

SimulatedMeter.read(size: int) -> bytes

Up to size bytes of output; the clock-driven mode waits for some.

  • size: The most bytes to return.
  • returns: What the instrument has written, possibly nothing.

SimulatedMeter.close

SimulatedMeter.close() -> None

Nothing to release.

SimulatedMeter.chip_up

SimulatedMeter.chip_up -> bool

Whether the INA228 answers: fitted (device_ready) and on the live map's bus.

SimulatedMeter.operation_condition

SimulatedMeter.operation_condition() -> int

STATus:OPERation:CONDition?: calibrating or measuring, now.

  • returns: The register.

SimulatedMeter.questionable_condition

SimulatedMeter.questionable_condition() -> int

STATus:QUEStionable:CONDition?: the open or last capture's doubts, now.

  • returns: The register.

SimulatedMeter.status_byte

SimulatedMeter.status_byte() -> int

*STB?: the summaries of the queue and the three registers.

  • returns: The byte.

SimulatedMeter.path

SimulatedMeter.path -> str

How the DUT's battery is fed, from K1 and K2 (relay.h pathOf).

SimulatedMeter.shunt_bypassed

SimulatedMeter.shunt_bypassed -> bool

Whether the shunt does not carry the DUT's whole current: both or bypass.

kleidos_meter.pins

The pin map: the board's table, a map, the rules it must keep, and a board's wiring.

The board is board_pins.json, the copy scripts/gen_pin_table.py writes from firmware/board/pins.toml beside the firmware's pin_table.h: every terminal of both rails, its class (free, caution, reserved), what each of the five roles needs, the default map and the table's digest, which SYSTem:PINS? names as table.

A PinMap gives each role (the INA228's SDA, SCL and ALERT, Relay 1 and Relay 2) one GPIO or none, each bus and alert pin its pull, each relay the level that energizes it, the INA228's address (0 for a scan, auto) and the bus clock at boot, keyed as SYSTem:PINS? names them.

validate_map is pinmap::validate() (firmware/src/pinmap.h) in Python: the first rule a map breaks, role by role, then the address and the clock. It is held to the firmware's verdicts by firmware/test/native/golden/pinmap.vectors, every line of which the host tests run through it.

A Wiring is where a board really has its parts: which pads the INA228's bus and ALERT reach, its strap address, and which pads drive each relay's input at which level. The simulator stands on one, and prove, relay_check and boot say what an instrument finds when it brings a map up on it: whether the INA228 answers and its self-test passes, whether a null-path check passes, and which map a boot runs with (a stored bus that does not answer falls back to the default bus when its pads are free).

address_of

address_of(word: str) -> int

An address as a report or the table writes it: auto is 0, else the number.

  • word: auto, or a number in a form int reads with base 0 (0x41).
  • returns: The address, or ADDRESS_AUTO.
  • raises ValueError: When word is neither.

address_text

address_text(address: int) -> str

An address as SYSTem:PINS? writes it.

  • address: The address, or ADDRESS_AUTO.
  • returns: auto, or 0x and two hex digits.

PinMap

class PinMap(
sda: int | None,
scl: int | None,
alert: int | None,
addr: int,
scl_hz: int,
pull_sda: str,
pull_scl: str,
pull_alert: str,
relay1: int | None,
relay1_active: str,
relay2: int | None,
relay2_active: str,
)

A pin map, keyed as SYSTem:PINS? names its twelve fields.

  • sda: The INA228's SDA pad, or None.
  • scl: Its SCL pad, or None.
  • alert: Its ALERT pad, or None.
  • addr: Its address, or ADDRESS_AUTO for a scan.
  • scl_hz: The bus clock at boot, Hz.
  • pull_sda: SDA's internal pull, up or off.
  • pull_scl: SCL's.
  • pull_alert: ALERT's.
  • relay1: Relay 1's pad (the DUT's battery lead), or None.
  • relay1_active: The level that energizes it, high or low.
  • relay2: Relay 2's pad (the shunt bypass), or None.
  • relay2_active: Its level.

PinMap.from_words

PinMap.from_words(words: Mapping[str, str]) -> PinMap

A map from its twelve fields as a report writes them (none, auto, numbers).

  • words: At least the twelve keys of KEYS; others are ignored, so a SYSTem:PINS? or SYSTem:PINS:PENDing? report reads whole.
  • returns: The map.
  • raises KeyError: When a key is missing.
  • raises ValueError: When a number does not read.

PinMap.words

PinMap.words() -> dict[str, str]

The twelve fields as SYSTem:PINS? writes them.

  • returns: Each key's word, in the report's order.

PinMap.text

PinMap.text() -> str

The map as SYSTem:PINS? writes it.

  • returns: The twelve key=value fields: sda=4 scl=5 ....

PinMap.pin

PinMap.pin(role: str) -> int | None

A role's GPIO.

  • role: One of ROLES.
  • returns: Its GPIO, or None.

PinMap.held

PinMap.held(gpio: int) -> bool

Whether a role holds a GPIO.

  • gpio: The GPIO.
  • returns: True when one of the five roles has it.

PinMap.relays

PinMap.relays() -> tuple[tuple[int | None, str], ...]

The relays as a null-path check depends on them.

  • returns: Relay 1's pad and active level, then Relay 2's.

PinMap.bus

PinMap.bus() -> tuple[int | None, int | None, int]

The bus as the INA228's answer depends on it.

  • returns: SDA's pad, SCL's and the address.

validate_map

validate_map(pins: PinMap, board: Mapping[str, Any] = BOARD) -> Verdict | None

The first rule pins breaks on board, as pinmap::validate() finds it.

Role by role, in the table's order: no pin (missing), no GPIO of the chip (no_pin), a reserved pin (reserved), a pin at or above the role's limit (too_high), a pin an earlier role holds (shared, at the later role); then an address that is neither auto nor in the strap space (address) and a clock outside the I2C master's range (clock).

  • pins: The map.
  • board: The board's table, BOARD by default (a test plants others).
  • returns: The problem's word and the key it is at, or None for a valid map.

typed_change

typed_change(key: str, value: object) -> int | str | None

A change of one field of a map, typed for stage_units.

The form is checked, never the range: whether a GPIO, an address or a clock is one the board takes is the map's rules' to say.

  • key: A field of KEYS.
  • value: A person's word (none, auto, up, 0x41, any case), or the number itself, or None for a role with no GPIO.
  • returns: The typed value.
  • raises ValueError: Saying what the field takes.

stage_units

stage_units(staged: PinMap, changes: Mapping[str, int | str | None]) -> list[str]

The units that stage changes over staged, in the map's order.

A role's pull or level is staged with its GPIO, so a change of one of the two sends the other as it is staged.

  • staged: The staged map the changes are made to.
  • changes: Fields of KEYS and their typed values.
  • returns: SYSTem:PINS:STAGe, ADDRess and CLOCk units, as sent.

verdict_text

verdict_text(verdict: Verdict | None) -> str

A verdict as SYSTem:PINS:PENDing? ends.

  • verdict: validate_map's finding, or None.
  • returns: valid=1 problem=- at=-, or valid=0 and the problem and the key.

Wiring

class Wiring(
sda: int,
scl: int,
alert: int,
address: int,
relay1: int,
relay1_active: str,
relay2: int,
relay2_active: str,
)

Where a board's parts really are: the pads each one is wired to.

  • sda: The pad the INA228's SDA reaches.
  • scl: The pad its SCL reaches.
  • alert: The pad its ALERT reaches.
  • address: Its strap address, 0x40 to 0x4F.
  • relay1: The pad that drives Relay 1's input.
  • relay1_active: The level that energizes Relay 1's module.
  • relay2: The pad that drives Relay 2's input.
  • relay2_active: Its module's level.

Wiring.parse

Wiring.parse(text: str) -> Wiring

A wiring from key=value pairs, comma-separated, over RIG_WIRING.

sda=18,addr=0x41 is the rig with the INA228's SDA on GPIO18 and its address strapped to 0x41; an empty text is the rig. The keys are the fields' (addr is address's short form), a pad a number, an address a number in any base int reads, a level high or low.

  • text: The pairs.
  • returns: The wiring.
  • raises ValueError: On a pair that is not key=value, an unknown key, a value that does not read, or an address outside the strap space.

Wiring.text

Wiring.text() -> str

The wiring as parse reads it.

  • returns: Every field as key=value, comma-separated.

wiring_argument

wiring_argument(text: str) -> Wiring

--sim-wiring's pairs, as Wiring.parse reads them, for a command line.

  • text: The pairs.
  • returns: The wiring.
  • raises argparse.ArgumentTypeError: Saying why the pairs do not read.

Proof

class Proof(answered: bool, tst: int, reason: str)

What bringing a map up on a board finds.

  • answered: Whether the INA228 answered on the map's bus and address.
  • tst: The self-test's bits the map sets (TST_NO_CHIP, TST_ALERT); 0 when it passes.
  • reason: - when it passes, else no_chip or alert: SYSTem:PINS:RESult?'s reason.

Proof.passed

Proof.passed -> bool

Whether every part passed: the map may be kept.

answers

answers(pins: PinMap, wiring: Wiring, *, fitted: bool = True) -> bool

Whether the INA228 answers on pins' bus: its pads, and its address or a scan.

  • pins: The map.
  • wiring: The board.
  • fitted: Whether the board has an INA228 that answers at all.
  • returns: True when the bus pads are the wiring's and the address is its or a scan.

prove

prove(pins: PinMap, wiring: Wiring, *, fitted: bool = True) -> Proof

Bring pins up on wiring: the INA228's answer, then its ALE wire.

A relay pad has no proof but its own read-back, which a pad always passes: a relay on the wrong pad is found by relay_check only.

  • pins: The map.
  • wiring: The board.
  • fitted: Whether the board has an INA228 that answers at all.
  • returns: What the bring-up found.

rest_state

rest_state(pins: PinMap, wiring: Wiring) -> tuple[bool, bool]

What pins' relays, released, do to the board's parts on wiring.

A relay is released by driving its pad to the level that is not its active one; a part whose pad a relay of the map drives at the level that energizes it is energized at rest. A part no relay drives stays released (its pin is parked toward release, or has no wire).

  • pins: The map.
  • wiring: The board.
  • returns: Whether Relay 1's part opens the lead, and whether Relay 2's part closes the bypass, with every relay of pins released.

relay_check

relay_check(pins: PinMap, wiring: Wiring) -> str | None

Which check of ROUTe:NULLpath ON fails on wiring with pins' relays.

Relay 2 closes first: on the wrong pad, or driven at the wrong level, the bypass takes no current (bypass, error 103), and driving Relay 1's part at its level it opens the lead, which leaves the shunt nothing (lost, 103 too); then Relay 1 opens, and on the wrong pad or level the shunt still conducts (lead, 104).

  • pins: The map.
  • wiring: The board.
  • returns: bypass, lost, lead, or None when both pass.

Boot

class Boot(pins: PinMap, src: str, problem: str | None = None)

The map a boot runs with.

  • pins: The map.
  • src: Where it came from: default, stored or fallback.
  • problem: What the boot announces as an error, or None.

boot_map

boot_map(
stored: PinMap | None,
wiring: Wiring,
*,
fitted: bool = True,
board: Mapping[str, Any] = BOARD,
) -> Boot

The map a boot takes from the stored record, on wiring.

No record, or one the table refuses, is the default map. A stored map whose bus answers is taken as it is (its ALERT and relays are never second-guessed: nothing tells a wrong pad from an absent part). One whose bus is the default's has nothing to fall back to. Another whose bus does not answer falls back to the default bus (pads, address, clock and pulls) when no other role of it holds the default bus pads, and keeps the record; otherwise it is taken with no INA228, and the console is the way back (SYSTem:PINS:DEFault).

  • stored: The stored map, or None for no record.
  • wiring: The board.
  • fitted: Whether the board has an INA228 that answers at all.
  • board: The board's table.
  • returns: The map, its source and what to announce.

kleidos_meter.identity

Which instrument this is: the serial *IDN? reports, derived as the firmware derives it.

The serial (firmware 0.4.0 and later) is KM- and ten hex digits, the first five bytes of SHA-256("kleidos-meter-serial-v1" || MAC) over the ESP32-S3's factory eFuse MAC (firmware/src/identity.h): a name that survives a full flash erase, and a pseudonym rather than the MAC, which never enters a tracked file.

Because a serial is a digest a search can undo, no real one is tracked (calibration/README.md, "Identity"): the registry files the bench instrument under a placeholder of the serial's shape. The instrument still reports its own serial, so a host maps it to the one the registry files it under through an alias it reads only from what git ignores: the environment variable ALIAS_VARIABLE, or else that key in the repository's .env (load_aliases). Its value is pairs <reported>=<filed>, separated by commas or white space.

serial_from_mac

serial_from_mac(mac: bytes) -> str

The instrument's serial, as the firmware derives it from its factory MAC.

  • mac: The six bytes of the ESP32-S3's eFuse MAC.
  • returns: KM- and ten hex digits.
  • raises ValueError: When mac is not six bytes.

parse_idn

parse_idn(text: str) -> dict[str, str]

*IDN?'s four fields.

  • text: The answer.
  • returns: manufacturer, model, serial and firmware, each empty when the answer has no such field.

version_tuple

version_tuple(text: str) -> tuple[int, ...]

A version as numbers, to compare with another.

  • text: "0.4.0".
  • returns: (0, 4, 0); () for anything unreadable.

parse_aliases

parse_aliases(text: str) -> dict[str, str]

The alias map written in text: pairs <reported>=<filed>.

The pairs are separated by commas or white space, and each side is a serial of either case, kept upper case as the firmware reports it. No message names a serial: an alias's whole point is that its left side is private, so a mistake is named by the pair's place.

  • text: The value of ALIAS_VARIABLE.
  • returns: Each reported serial and the serial the registry files it under.
  • raises ValueError: When a pair is not two serials joined by =, or one reported serial is given two filed ones.

load_aliases

load_aliases(
environment: Mapping[str, str] | None = None,
dotenv: Path = DOTENV,
) -> dict[str, str]

The alias map: ALIAS_VARIABLE in the environment, else in dotenv.

The environment's value wins even when empty, which turns off one the .env holds. Neither present is no alias.

  • environment: The variables, os.environ when None.
  • dotenv: The .env, which git ignores, read when the environment has none.
  • returns: parse_aliases of the value found.
  • raises ValueError: As parse_aliases.

kleidos_meter.registry

The calibration registry: the instrument's calibration, kept in this repository.

The registry under calibration/ is the calibration; the instrument's NVS is a working copy of it, which a full flash erase loses (calibration/README.md). This module reads the registry, checks it (schemas, arithmetic, coherence), builds the one file other tools read (calibration/index.json), picks the calibration that holds on a date, and compares an instrument's working copy with it.

Layout:

calibration/schemas/*.schema.json the three file formats
calibration/configurations/<id>.json a bill of the parts that set the measurement
calibration/instruments/<serial>.json one instrument: its configuration and its events
calibration/records/... the Markdown record and raw log of each event
calibration/index.json generated by scripts/check_calibration_registry.py

Resistances are integers in nano-ohms, relative terms integers in ppm, as on the wire. Nothing here talks to an instrument; calibration_cli does.

validate

validate(
instance: Any,
schema: dict[str, Any],
root: dict[str, Any] | None = None,
path: str = '$',
) -> list[str]

Check instance against schema, the subset of JSON Schema the registry uses.

The keywords understood: $ref (to #/$defs/...), type, const, enum, properties, required, additionalProperties (false or a schema), items, minItems, maxItems, minimum, maximum, minLength, pattern, oneOf and allOf. An unknown keyword is an error in the schema, not silence.

  • instance: The value, as json.loads returns it.
  • schema: The schema, or the part of it that applies here.
  • root: The whole schema a $ref is read in; schema by default.
  • path: Where instance is in the document, for the messages.
  • returns: One message per failure, each naming the path of the value.

Registry

class Registry(
read: Callable[[str], str | None],
listing: Callable[[str], list[str]],
schemas: dict[str, dict[str, Any]],
configurations: dict[str, dict[str, Any]],
instruments: dict[str, dict[str, Any]],
load_errors: list[str] = [],
)

The registry's files, read from a directory or from a git revision.

  • read: Returns the text of a path relative to calibration/, or None when there is no such file.
  • listing: Returns the file names (not paths) in a directory relative to calibration/.
  • schemas: The three file formats, by name.
  • configurations: The configurations, by id.
  • instruments: The instruments, by serial.
  • load_errors: What could not be read.

Registry.from_directory

Registry.from_directory(root: Path = ROOT) -> Registry

The registry as the working tree holds it.

  • root: The calibration/ directory.
  • returns: The registry, read; what could not be is in load_errors.

Registry.from_git

Registry.from_git(repository: Path, revision: str) -> Registry

The registry as revision of repository holds it (git show).

  • repository: A clone of this repository.
  • revision: A commit, a tag or a branch.
  • returns: The registry, read; what could not be is in load_errors.

Registry.load

Registry.load() -> None

Read the schemas, the configurations and the instruments.

Registry.configuration_at

Registry.configuration_at(instrument: dict[str, Any], event_id: str) -> str | None

The configuration instrument was in at event event_id: its last change before it.

Event ids sort in the order things happened (YYYY-MM-DD-NN), so a change filed later on the same day as a calibration is not the configuration that calibration was taken in.

  • instrument: The instrument's file.
  • event_id: The event.
  • returns: The configuration's id, or None when no change precedes the event.

accepted_calibrations

accepted_calibrations(instrument: dict[str, Any]) -> list[dict[str, Any]]

The instrument's accepted calibrations, oldest first.

  • instrument: The instrument's file.
  • returns: Their events.

windows

windows(
instrument: dict[str, Any],
recalibration_days: Callable[[str], int],
) -> list[dict[str, Any]]

Each accepted calibration with the dates it holds between.

A calibration holds from the day it was taken until the first of: the day the next accepted one was taken, a hardware change that voids it, and its configuration's recalibration interval. valid_until is the first day it no longer holds.

  • instrument: The instrument's file.
  • recalibration_days: The interval of a configuration, by its id.
  • returns: event, valid_from and valid_until of each, oldest first.

budget_problems

budget_problems(event: dict[str, Any]) -> list[str]

Recompute an accepted calibration's arithmetic.

  • event: The calibration's event.
  • returns: One message per disagreement.

window_problems

window_problems(event: dict[str, Any], configuration: dict[str, Any]) -> list[str]

An accepted calibration against its configuration's limits.

  • event: The calibration's event.
  • configuration: The configuration's file.
  • returns: One message per limit passed.

normalized_error

normalized_error(first: dict[str, Any], second: dict[str, Any], range_name: str) -> float

E = |R_2 − R_1| / √(U_1² + U_2²) between two calibrations, on one range.

  • first: The earlier calibration's event.
  • second: The later one's.
  • range_name: "0" or "1".
  • returns: The figure: above 1, the two do not agree within their uncertainties.

check

check(registry: Registry) -> tuple[list[str], list[str]]

Every check of the registry over its files alone: schemas, arithmetic, coherence.

  • registry: The registry.
  • returns: (problems, flags): a problem fails the check; a flag is reported and does not (an instrument that sits apart from its group).

sense_core

sense_core(configuration: dict[str, Any]) -> str

The pair that sets the measurement: the breakout and the shunt.

  • configuration: The configuration's file.
  • returns: Their two ids, joined.

sense_groups

sense_groups(registry: Registry) -> dict[str, dict[str, Any]]

Instruments of the same sense core, compared.

Two shunts of one part may differ by its tolerance, so the test is membership, not agreement: from three instruments on, one further than three scaled median absolute deviations from the median is flagged. The scale is never taken below the largest expanded uncertainty among the members: instruments that agree to within their own calibrations are not apart, and a group where most members share one value (a MAD of zero) still flags the one that does not. The group's mean offset from nominal is reported whatever the count.

  • registry: The registry.
  • returns: Each group's instruments, mean_offset_ppm, compared and flags, by its core and range.

image_problem

image_problem(firmware: dict[str, Any], image: str, version: str) -> tuple[str, str] | None

Whether an instrument's image= and firmware version fit a configuration.

firmware is a configuration's firmware object, or the index summary, which carries the same three keys: image and min_version, and image_aliases, the other names the same rig's image has had, each from its own version (from 0.8.0 the one image meter drives the Relay 2 Click that meter_relay2 drove before), and an optional max_version, the last version whose image of that name is this configuration's (the HW-316 rig's meter ends at 0.7.0).

  • firmware: What the configuration asks for.
  • image: The instrument's image=.
  • version: Its firmware version.
  • returns: None when the pair fits; ("image", <the names accepted>) when the image is none of them, or is one of them past its last version; ("version", <the lowest version>) when it is one of them, too old.

configuration_summary

configuration_summary(configuration: dict[str, Any]) -> dict[str, Any]

What an instrument reports that can be checked against its configuration.

  • configuration: The configuration's file.
  • returns: Its entry in the index.

build_index

build_index(registry: Registry) -> dict[str, Any]

The one file QA reads: each instrument's calibrations, windows resolved.

  • registry: The registry.
  • returns: The index, as calibration/index.json holds it.

dump_index

dump_index(index: dict[str, Any]) -> str

The index as it is committed: sorted keys, two-space indent, one final newline.

  • index: The index.
  • returns: Its text.

select

select(index: dict[str, Any], serial: str, on: dt.date) -> tuple[str, dict[str, Any] | None]

The calibration that holds for serial on on.

  • index: The index.
  • serial: The instrument's serial.
  • on: The day.
  • returns: (status, entry): unregistered (no such instrument, or no accepted calibration), expired (the newest one ended on or before on), or applied with the entry.

Verdict

class Verdict(
status: str,
serial: str,
entry: dict[str, Any] | None = None,
differences: list[str] = [],
warnings: list[str] = [],
aliased: bool = False,
)

What verify concluded about an instrument and the registry.

  • status: One of compare's statuses.
  • serial: The instrument's serial as the registry files it: the one it reports, or the one an alias maps that to.
  • entry: The calibration's entry in the index, when there is one.
  • differences: What differs from the registry, a sentence each.
  • warnings: What to see to, a sentence each.
  • aliased: Whether an alias mapped the serial the instrument reports to serial (load_aliases).

Verdict.ok

Verdict.ok -> bool

Whether the instrument's working copy is the registry's.

compare

compare(
index: dict[str, Any],
idn: str,
info: dict[str, str],
cal: dict[str, str],
on: dt.date,
aliases: Mapping[str, str] | None = None,
) -> Verdict

Compare an instrument with the registry.

Statuses, in the order they are judged: unregistered (no serial, an unknown one, firmware too old to report one), configuration_mismatch (the image, the bypass part or the INA228 is not what the registry says this instrument is), expired, working_copy_lost (its calibration at factory defaults: shunt_measured=0), working_copy_differs, applied.

The serial the instrument reports is looked up as aliases maps it, when it does, and the verdict names the serial the registry files: the one it reports is never in it then. An unknown serial no alias maps says how to name one.

  • index: The index.
  • idn: The instrument's *IDN?.
  • info: Its SYSTem:INFormation?'s fields.
  • cal: Its CALibration:DATA?'s fields.
  • on: The day.
  • aliases: Each reported serial and the serial the registry files it under (load_aliases); None for none.
  • returns: The verdict.

restore_messages

restore_messages(entry: dict[str, Any]) -> list[str]

The program messages that write entry's working copy to an instrument.

The common value first (it clears any per-range one), then range 1's own when it differs; the tag, the date and the VBUS side. Never a null: nulls are session state.

  • entry: The calibration's entry in the index.
  • returns: The messages, in order.

scale

scale(entry: dict[str, Any], range_index: int, device_shunt_uohm: int) -> float

The factor that rescales a current computed with the device's shunt to the registry's.

I = I_device × (device shunt) / applied is exact, because the device computes I = V / R with the copy the capture header repeats.

  • entry: The calibration's entry in the index.
  • range_index: 0 or 1.
  • device_shunt_uohm: The shunt the capture's header names, micro-ohms.
  • returns: The factor.

file_digest

file_digest(text: str) -> str

The sha256 an event records for a filed text.

  • text: The text.
  • returns: Its digest, hexadecimal.

iter_problems

iter_problems(problems: Iterable[str]) -> str

The problems, one per line.

  • problems: The messages.
  • returns: A text of them.

kleidos_meter.calibration_cli

The instrument against the calibration registry: verify it, or restore its working copy.

The registry in this repository is the calibration; the instrument's NVS holds a working copy, which a full flash erase loses (calibration/README.md).

Usage:

kleidos-meter calibration verify --port "$KLEIDOS_METER_PORT" # device vs registry
kleidos-meter calibration restore --port "$KLEIDOS_METER_PORT" # registry -> device
kleidos-meter calibration verify --port ... --rev <commit> # at a pinned commit
kleidos-meter calibration verify --sim # simulated

verify exits 0 when the working copy is the registry's (status applied), 3 otherwise; --json prints the verdict for a script. restore writes the shunt of each range, the tag, the date and the VBUS side of the calibration that holds today, reads them back and verifies; it never writes a null, which is session state. It refuses an instrument the registry does not know, or one whose image, bypass part or INA228 is not the configuration the registry files it under.

The registry files the bench instrument under a placeholder serial, since no real serial is tracked (calibration/README.md, "Identity"). Name the serial it reports in KLEIDOS_METER_SERIAL_ALIASES, in the environment or in the repository's .env, which git ignores (load_aliases): both commands then look it up, and print it, as the serial the registry files.

Instrument

class Instrument(Protocol)

What verify and restore ask of an instrument: a Meter, or the panel's link through its executor (kleidos_meter.panel.settings.InstrumentLink).

Instrument.idn

Instrument.idn() -> str

*IDN?.

  • returns: Its answer.

Instrument.info

Instrument.info() -> dict[str, str]

SYSTem:INFormation?.

  • returns: Its fields.

Instrument.calibration

Instrument.calibration() -> dict[str, str]

CALibration:DATA?.

  • returns: Its fields.

Instrument.exchange

Instrument.exchange(units: Sequence[str]) -> tuple[list[str], list[ErrorEntry], bytes | None]

Send units as one message.

  • units: The message's units.
  • returns: The query responses, the errors, and a block if one came.
  • raises MeterError: When one is refused (MeterError).

load_index

load_index(root: Path = ROOT, revision: str | None = None) -> dict[str, Any]

The index, from the working tree or from revision of the repository.

At a revision it is read with git show, so a dirty or newer checkout cannot leak into what a verification compares against. In the working tree it is rebuilt from the sources, so an index not yet regenerated after an edit is not trusted either.

  • root: The calibration/ directory.
  • revision: A git revision to read it at, or None for the working tree.
  • returns: The index.
  • raises SystemExit: When revision holds no index.

identify

identify(meter: Instrument) -> tuple[str, dict[str, str], dict[str, str]]

Ask the instrument what it is and what calibration it holds.

  • meter: The instrument.
  • returns: *IDN?, and the fields of SYSTem:INFormation? and CALibration:DATA?.

verify

verify(
meter: Instrument,
index: dict[str, Any],
on: dt.date,
aliases: Mapping[str, str] | None = None,
) -> Verdict

Compare the instrument with the registry on on.

  • meter: The instrument.
  • index: The registry's index.
  • on: The day.
  • aliases: The serial aliases (load_aliases).
  • returns: The verdict.

describe

describe(verdict: Verdict) -> list[str]

The verdict, as lines for a person.

  • verdict: The verdict.
  • returns: Its lines.

restore

restore(
meter: Instrument,
index: dict[str, Any],
on: dt.date,
*,
ask: Callable[[str], str] = input,
say: Callable[[str], None] = print,
aliases: Mapping[str, str] | None = None,
) -> Verdict

Write the registry's working copy to the instrument and verify it.

  • meter: The instrument.
  • index: The registry's index.
  • on: The day.
  • ask: Shows the confirmation and returns the answer.
  • say: Prints a line.
  • aliases: The serial aliases (load_aliases).
  • returns: The verdict after the restore (or before it, when nothing was written: the copy was already right, or the instrument is refused).

ask_terminal

ask_terminal(prompt: str) -> str

Ask on the terminal; an end of input is a no, not a traceback.

  • prompt: The question.
  • returns: The answer.

kleidos_meter.calibrate

The shunt calibration, step by step, with the owner at the bench; it files a registry event.

The method is calibration/README.md "The shunt, two points": the DUT is replaced by the 100 Ω ±0.01 % reference resistor, one current crosses both, and the instrument reads the drop across the shunt on its shunt channel and, with VBUS on the reference's top lead, the drop across the reference on its bus channel (CALibration:SHUNt). The two points are the two ADC ranges at that one current.

What 2026-11-20 taught is built in (calibration/records/2026-11-20.md):

  • the reference's joints are screwed, never twisted or clipped, and the tool asks before it measures;
  • the nulls are taken hands-free with K1 open (ROUTe:LEAD OPEN,FORCe), before and after the points, on the SLEEP profile;
  • the points are taken in blocks in the order range 0, 1, 1, 0, which takes a steady drift out of the range split;
  • a closure gate compares the first and the last block of each range, and a null-closure gate each range's closing null with its opening one: a joint that drifts fails the session instead of being stored.

The acceptance window comes from the instrument's configuration in the registry, not from constants here. An accepted session, once confirmed, is written to the instrument as its working copy and read back; then the event is appended to calibration/instruments/<serial>.json, its record and raw SCPI log are filed under calibration/records/<serial>/, and the index is regenerated. A refused session writes nothing to the instrument and is filed as refused, because it is knowledge. Nothing is committed.

An instrument the registry files under a placeholder (no real serial is tracked, calibration/README.md, "Identity") is found, recorded and filed under the serial KLEIDOS_METER_SERIAL_ALIASES maps its own to (load_aliases), and the raw log, which holds its *IDN?, is filed with the serial it reports replaced by that one.

Usage:

kleidos-meter calibrate --port "$KLEIDOS_METER_PORT"
kleidos-meter calibrate --port ... --configuration mjkdz-r100-relay2click # a first one
kleidos-meter calibrate --sim --yes --registry /tmp/registry # simulated

ppm_apart

ppm_apart(first: float, second: float) -> float

How far two resistances are apart, in parts per million of their mean.

  • first: One.
  • second: The other, in the same unit.
  • returns: The figure; 1,000,000 when either is not positive.

mean

mean(values: list[int] | list[float]) -> float

The mean of values.

  • values: One or more.
  • returns: Their mean.

sample_sd

sample_sd(values: list[int] | list[float]) -> float

The sample standard deviation of values.

  • values: The values.
  • returns: The figure; 0 for fewer than two.

Point

class Point(
range: int,
nano_ohm: int,
check: str,
die_mc: int | None,
vsh_nv: int,
fields: dict[str, str],
)

One CALibration:SHUNt:RESult?.

  • range: The range it was taken on.
  • nano_ohm: The shunt it read, nano-ohms.
  • check: The instrument's own check=.
  • die_mc: The die's temperature, millidegrees, when it was reported.
  • vsh_nv: The drop across the shunt, nanovolts.
  • fields: The report it was read from.

Point.from_fields

Point.from_fields(fields: dict[str, str]) -> Point

The point a report states.

  • fields: CALibration:SHUNt:RESult?'s fields.
  • returns: The point.

Block

class Block(range: int, points: list[Point] = [])

Consecutive points on one range.

  • range: The range.
  • points: Its points, in the order they were taken.

Block.mean_nohm

Block.mean_nohm -> float

The mean of its points, nano-ohms.

Result

class Result(
checks: list[tuple[str, str, bool]] = [],
ranges: dict[str, dict[str, Any]] = {},
split_ppm: int = 0,
budget: list[dict[str, Any]] = [],
u_c_ppm: int = 0,
coverage_k: float = 2.0,
expanded_ppm: int = 0,
applied_nohm: int = 0,
)

The gates, each with what it measured and whether it held, and the figures.

  • checks: Each gate's name, what it measured and whether it held.
  • ranges: Each range's points, mean, scatter and nulls, by its name.
  • split_ppm: How far the two ranges' means are apart.
  • budget: The uncertainty's terms.
  • u_c_ppm: The combined standard uncertainty.
  • coverage_k: The coverage factor.
  • expanded_ppm: The expanded uncertainty.
  • applied_nohm: The shunt the session gives, nano-ohms.

Result.accepted

Result.accepted -> bool

Whether there were gates and every one held.

Result.add

Result.add(name: str, measured: str, ok: bool) -> None

File one gate.

  • name: What it asks.
  • measured: What was measured.
  • ok: Whether it held.

Result.failed

Result.failed() -> list[str]

The gates that did not hold.

  • returns: Each one's name and what it measured.

judge

judge(
blocks: list[Block],
nulls_before: list[dict[str, str]],
nulls_after: list[dict[str, str]],
configuration: dict[str, Any],
reference: dict[str, Any],
*,
coverage_k: float = 2.0,
temperature_bound_c: float = REFERENCE_TEMPERATURE_BOUND_C,
) -> Result

Apply every gate to a session, and compute its figures and its budget.

  • blocks: The points, in the order they were taken.
  • nulls_before: Each range's opening null, its result's fields.
  • nulls_after: Each range's closing null.
  • configuration: The instrument's configuration, whose limits apply.
  • reference: The reference resistor, as REFERENCES describes one.
  • coverage_k: The coverage factor.
  • temperature_bound_c: How far the reference's temperature may be from its nominal one, degrees Celsius.
  • returns: The gates and the figures.

TeeTransport

class TeeTransport(inner: Transport)

A transport that keeps the SCPI exchange: what was sent and what came back.

  • inner: The transport it stands before.
  • attribute lines: The exchange, a message or a response a line.

TeeTransport.write

TeeTransport.write(data: bytes) -> int

Send data, and keep it.

  • data: The bytes to send.
  • returns: How many the inner transport took.

TeeTransport.read

TeeTransport.read(size: int) -> bytes

Read from the inner transport, and keep what came.

  • size: The most bytes to return.
  • returns: What arrived, possibly nothing.

TeeTransport.close

TeeTransport.close() -> None

Close the inner transport.

TeeTransport.text

TeeTransport.text() -> str

The exchange so far.

  • returns: Its lines, what was sent behind >>.

Refused

class Refused(Exception)

The session cannot start: the instrument, its configuration or the bench is not ready.

Session

class Session(
meter: Meter,
*,
root: Path = ROOT,
configuration: str | None = None,
reference: dict[str, Any] | None = None,
ask: Callable[[str], str] = input,
say: Callable[[str], None] = print,
sleep: Callable[[float], None] = time.sleep,
null_seconds: int = NULL_SECONDS,
samples: int = SAMPLES,
points_per_block: int = POINTS_PER_BLOCK,
now: Callable[[], dt.datetime] = lambda: dt.datetime.now().astimezone(),
transcript: TeeTransport | None = None,
aliases: Mapping[str, str] | None = None,
)

The guided flow of one calibration.

  • meter: The instrument.
  • root: The registry's directory, which the session is filed in.
  • configuration: The configuration of an instrument's first calibration.
  • reference: The reference resistor, as REFERENCES describes one.
  • ask: Shows a prompt and returns the answer.
  • say: Prints a line.
  • sleep: Waits out a null, seconds.
  • null_seconds: How long each null is.
  • samples: The samples of one point.
  • points_per_block: The points of one block.
  • now: The time, with its zone.
  • transcript: The transport that keeps the exchange, filed as the raw log.
  • aliases: The serial aliases (load_aliases).
  • attribute result: The gates and figures, once run judged them.
  • attribute stored: Whether the working copy was written.

Session.step

Session.step(text: str) -> None

Say what the person at the bench does next, and wait until it is done.

  • text: The step.

Session.null

Session.null(index: int) -> dict[str, str]

One null on range index, hands-free: K1 opens, so nothing crosses the shunt.

  • index: 0 or 1.
  • returns: The null's result.
  • raises RuntimeError: When the instrument refused it.

Session.prepare

Session.prepare() -> None

Know the instrument and its configuration, or refuse before anything is measured.

  • raises Refused: When the instrument, its configuration or its image does not fit.

Session.run

Session.run() -> Result

Run the session: the nulls, the points, the gates and, once confirmed, the copy.

Nothing is filed: file does.

  • returns: The gates and the figures.
  • raises Refused: When it could not start.
  • raises RuntimeError: When a null was refused, or the instrument did not keep the working copy.

Session.device_block

Session.device_block() -> dict[str, Any]

The working copy an accepted session writes.

  • returns: The shunt of each range, the tag, the date and the VBUS side.

Session.event_id

Session.event_id() -> str

The id the session is filed under: its day and the next number of it.

  • returns: YYYY-MM-DD-NN.

Session.record

Session.record(event_id: str) -> str

The Markdown record of this session.

  • event_id: The id it is filed under.
  • returns: Its text.

Session.event

Session.event(event_id: str, record: dict[str, Any], raw_log: dict[str, Any]) -> dict[str, Any]

The registry event of this session.

  • event_id: The id it is filed under.
  • record: The record's path and digest.
  • raw_log: The raw log's path and digest.
  • returns: The event.

Session.file

Session.file() -> tuple[Path, list[str]]

Append the event, file its record and log, and regenerate the index.

  • returns: The record's path, and the registry check's problems (none expected).

kleidos_meter.relay_timing

Measure the relays' operate and release times through the shunt (0.13.0).

kleidos-meter relay-timing runs a TRACE ring capture, moves one relay under it with LIVE (so each move is a mark at the sample index of its drive), dumps the ring around each mark and finds where the current steps: the delay from the mark to the step is the contact's operate or release time, at the ring's 280 us resolution. Each move is repeated, and the record states every delay, their spread and the step each was found from, so that a weak step (a DUT drawing tens of microamps against TRACE's per-sample noise) shows as what it is.

A move is a pair of orders that brings the rig back to path=shunt:

  • k1: ROUTe:LEAD OPEN,FORCe,LIVE then ROUTe:LEAD CLOSe,LIVE (the DUT loses its battery for --hold ms; it must have another supply or tolerate it);
  • k2: ROUTe:BYPass ON,FORCe,LIVE then ROUTe:BYPass OFF,LIVE.

The step is located by the least-squares split of the samples from the mark to the next order: the index that best divides them into two levels. The window ends at the next mark of the relay, and never later than --hold after its own: the next order, or the tool's ABORt, comes no sooner. The last move has no next mark, so the hold is all that bounds it; before, its window ran 2,000 samples (560 ms) on, and on 2026-11-21 it reached a move the instrument drove unmarked (below) and split there (docs/relay-timing.md).

The instrument keeps 16 marks a capture (TRACe:MARK and LIVE moves, docs/scpi.md error 105), and a LIVE move past them is still driven, unmarked. A move is two marks, so --repeats is refused above MAX_REPEATS.

Edge

class Edge(
relay: str,
order: str,
mark_index: int,
step_index: int,
delay_us: int,
before_counts: float,
after_counts: float,
contrast: float,
)

One move of one contact, found in the ring.

  • relay: k1 or k2.
  • order: The mark's label: the relay and the state it was ordered to.
  • mark_index: The sample index of the drive.
  • step_index: The sample index of the step.
  • delay_us: From one to the other, microseconds.
  • before_counts: The mean raw count before the step.
  • after_counts: The mean raw count after it.
  • contrast: The step against the noise: the two means' difference over the samples' own standard deviation.

split

split(values: list[float]) -> tuple[int, float, float, float]

The least-squares split of values into two levels.

  • values: The series.
  • returns: (index, mean before, mean after, contrast): the first sample of the second level, the two means and the step over the pooled standard deviation. A series too short to split returns index 0.

counts_between

counts_between(rows: list[str], first: int, last: int) -> list[float]

The raw counts of indices first to last - 1 in a RAW dump's rows.

Each R row is read by parse_dump_row; a whole block is decoded by decode_dump, as measure does.

  • rows: The dump's lines.
  • first: The first capture index wanted.
  • last: One past the last capture index wanted.
  • returns: The counts, in index order.

refusal

refusal(repeats: int, hold_ms: int) -> str | None

Why repeats moves held hold_ms each cannot be measured.

  • repeats: The moves.
  • hold_ms: The time between a move's two orders, milliseconds.
  • returns: The reason, or None when they can.

measure

measure(
meter: Meter,
relay: str,
repeats: int,
hold_ms: int,
*,
pause: Callable[[float], None] = time.sleep,
) -> list[Edge]

Move relay repeats times under one TRACE capture and find each edge.

  • meter: The instrument.
  • relay: k1 or k2.
  • repeats: The moves.
  • hold_ms: The time between a move's two orders, milliseconds.
  • pause: Waits, seconds.
  • returns: The edges, two a move, in order.
  • raises ValueError: repeats is not 1 to MAX_REPEATS (a move past the instrument's 16 marks would be driven unmarked), or hold_ms is not positive (it bounds every edge's window). Nothing is sent.

summarize

summarize(edges: list[Edge]) -> dict[str, Any]

Per order: every delay, the median, the spread, the weakest step.

  • edges: The edges.
  • returns: n, delays_us, median_us, min_us, max_us and min_contrast of each order, by its label.

Back to the top