Skip to content

API reference

Every name on this page can be imported from ppk2. The text under each one comes from its docstring. See the architecture page for how the pieces fit together and how a session runs.

Discovery

find_ppk2() returns the data port of the one PPK2 attached. To get there it:

  1. lists the serial ports and keeps those with the PPK2's USB identity, 1915:C00A;
  2. groups them by USB serial number, since a PPK2 shows up as two ports;
  3. asks each port for its calibration. Only the data port answers. If none does, it asks once more after a RESET.

If nothing is found, it tries again for up to 3 seconds, because a PPK2 that was just plugged in takes a moment to appear. If several PPK2s are attached, use find_ppk2_by_serial to pick one, and list_ppk2s to see what is there.

find_ppk2

find_ppk2(
    *,
    timeout_s: float = DEFAULT_DISCOVERY_TIMEOUT_S,
    probe: ProbeFn | None = None,
) -> PortInfo

Find the single PPK2 on the bus and return its data port.

Polls for up to timeout_s seconds, so that a PPK2 just plugged in, or coming back on USB, is found.

Parameters:

Name Type Description Default
timeout_s float

Polling budget in seconds; 0 for a single pass.

DEFAULT_DISCOVERY_TIMEOUT_S
probe ProbeFn | None

Probe function to use instead of the real one (tests).

None

Raises:

Type Description
NotFound

No PPK2 on the bus.

Ambiguous

More than one PPK2; raised at once, polling cannot settle it.

DataPortNotFound

A PPK2 is there but no port answered in time.

find_ppk2_by_serial

find_ppk2_by_serial(
    usb_serial: str,
    *,
    timeout_s: float = DEFAULT_DISCOVERY_TIMEOUT_S,
    probe: ProbeFn | None = None,
) -> PortInfo

Like find_ppk2, for the PPK2 whose USB serial is exactly usb_serial.

list_ppk2s

list_ppk2s(
    *, probe: ProbeFn | None = None
) -> list[Ppk2Listing]

List connected PPK2s with the status of each port (ppk2 list).

Each device's ports are probed lowest path first, stopping at the data port: the rest are then idle and left unprobed. When nothing answers, every port is probed, which tells busy (held by another process) from idle (silent).

Parameters:

Name Type Description Default
probe ProbeFn | None

Probe function to use instead of the real one (tests).

None

PortInfo dataclass

A PPK2 and the port to talk to it on.

Attributes:

Name Type Description
device str

Device path or COM name (/dev/cu.usbmodemA1B2C3D4E5F62 on macOS, COM7 on Windows).

usb_serial str

USB serial number, the stable handle when several PPK2s are plugged in.

Ppk2Listing dataclass

One connected PPK2 and the status of each of its ports.

Attributes:

Name Type Description
usb_serial str

USB serial number of the device.

ports tuple[str, ...]

Its port paths, sorted.

data_port str | None

The path that answered the probe, or None when none did (usually another process holds the data port).

statuses dict[str, PortStatus]

Probe result per path. Paths left unprobed because an earlier one already answered are reported "idle".

DiscoveryError

Bases: Exception

Base class for port discovery failures.

NotFound

Bases: DiscoveryError

No PPK2 (USB 0x1915:0xC00A) on the bus, or none with the serial asked for.

Ambiguous

Bases: DiscoveryError

More than one PPK2 on the bus; count is how many.

Pick one with find_ppk2_by_serial.

DataPortNotFound

Bases: DiscoveryError

A PPK2 enumerated but no port answered the probe; paths lists them.

Usually another process holds the data port: Nordic's Power Profiler app keeps it open while it runs.

Session

Mode

Bases: IntEnum

PPK2 measurement mode; the value is the wire byte.

AMPERE is the Ampere meter mode of Nordic's app: the DUT has its own supply and the PPK2 sits in series. SOURCE is its Source meter mode: the PPK2 supplies the DUT.

Session

An open PPK2 session: the serial port plus the device's calibration.

Use it as a context manager (with Session.open(port) as s:) so the teardown runs even on an exception.

One Session per thread: the serial port underneath is not safe to share.

open classmethod

open(device: str) -> Session

Open device and run the metadata handshake.

Up to 3 attempts, 0.5 s then 1.0 s apart. The retries are for a port left stuck by another program's capture (seen on macOS), above all one that sent RESET on close.

close

close() -> None

Stop the stream, cut power to the DUT, wait for the stream to end, close the port.

Idempotent; errors are swallowed. No RESET is sent: it makes the PPK2 leave USB and come back, which takes 200 to 500 ms and can block the next session.

The port is not closed while samples still arrive. Closed right after AVERAGE_STOP, the PPK2 can miss the command and keep streaming, and what was in flight goes to whoever opens the port next: a client that asks for the metadata first, like Nordic's own tools, then gets no usable answer.

DUT power does not outlive the session: the PPK2 cuts it by itself when the port closes (it follows the DTR line), so this holds even when the process is killed and this method never runs.

coefficients

coefficients() -> CalibrationCoefficients

Per-device calibration read at session open.

set_mode

set_mode(mode: Mode) -> None

Select the measurement mode.

Call it before start_measuring. On the PPK2 tested, a change sent during a stream was applied too; nothing here relies on that.

set_source_voltage

set_source_voltage(mv: int) -> None

Set the supply voltage in millivolts.

In Source meter mode this is what the PPK2 outputs. In Ampere meter mode the regulator is inactive, but the value still feeds the calibration: set it to the DUT's real supply voltage.

Values outside 800 to 5,000 mV are brought back to the nearest limit; the firmware would ignore them.

Raises:

Type Description
ValueError

If mv exceeds the cap set with set_voltage_limit.

SerialIOError

If the serial write fails.

set_voltage_limit

set_voltage_limit(mv: int) -> None

Cap what set_source_voltage will accept, in millivolts.

A host-side guard against typing a DUT-damaging voltage, like the app's voltage limit ("Set max supply voltage to"). The cap is itself kept within 800 to 5,000 mV, and it does not change a supply voltage already above it.

Raises:

Type Description
RuntimeError

If called while a stream runs, between start_measuring and stop_measuring.

voltage_limit

voltage_limit() -> int

The cap set by set_voltage_limit, in millivolts.

start_measuring

start_measuring() -> None

Start the stream of samples, 100,000 per second.

stop_measuring

stop_measuring() -> None

Send AVERAGE_STOP and read the stream out to its end.

Left unread, the end of the stream would lead the next one: a few milliseconds of samples from before the stop. Safe to call when no stream is active.

power_on

power_on() -> None

Switch power to the DUT on, as the app's "Enable power output" does.

The power comes up about 1 ms after the command. With a stream running, the stream is first read until the host has caught up with it, which takes until about 0.9 s after start_measuring. The samples read after this call are then from the switch on, to within about 10 ms, so a capture that follows has the boot in it (the protocol page, Known caveats).

power_off

power_off() -> None

Switch power to the DUT off. Idempotent.

drop_pending_backlog

drop_pending_backlog() -> int

Discard what the OS reports as waiting; return the byte count.

One read, not a loop: a running stream never goes empty, so draining until empty would hang. It does not bring the reads up to the present: on macOS in_waiting reports about 1 kB while some 40 kB are queued (the protocol page, Known caveats).

Raises:

Type Description
SerialIOError

If the serial read fails.

set_user_gain

set_user_gain(range_idx: int, gain: float) -> None

Override the user gain of one range for this session.

Host-side only: the calibration used by the next capture is rebuilt with the new gain and nothing is sent. Current firmware ignores SET_USER_GAINS, and Nordic's app applies the gain host-side too. The override is gone at close.

Parameters:

Name Type Description Default
range_idx int

Which of the five measurement ranges, 0 to 4. The app numbers them 1 to 5.

required
gain float

The gain, from 0.9 to 1.1 as in the app.

required

Raises:

Type Description
ValueError

If range_idx is not 0 to 4, or gain is not from 0.9 to 1.1.

RuntimeError

If called while a stream runs, between start_measuring and stop_measuring.

set_spike_filter

set_spike_filter(
    *,
    samples: int | None = None,
    alpha: float | None = None,
    alpha5: float | None = None,
) -> None

Change settings of the spike filter; those not passed keep their value.

Host-side, like Nordic's app: the next capture builds its parser with these. See SpikeFilter for what each setting does and its limits. The change is gone at close.

Raises:

Type Description
ValueError

If a setting is out of range.

RuntimeError

If called while a stream runs, between start_measuring and stop_measuring.

spike_filter

spike_filter() -> SpikeFilter

The spike-filter settings the next capture will use.

capture

capture(
    emit: Callable[[Sample], bool],
    on_dataloss: Callable[[int], None] | None = None,
    keep_going: Callable[[], bool] | None = None,
) -> None

Read the stream and call emit per sample until it returns False.

Parameters:

Name Type Description Default
emit Callable[[Sample], bool]

Called with each Sample; return False to stop. It is not called again after that.

required
on_dataloss Callable[[int], None] | None

Called with the running total of lost samples whenever a read adds to it (at most once per read).

None
keep_going Callable[[], bool] | None

Called after every read; return False to stop. Without it, a PPK2 that sends nothing, or nothing that decodes to a sample, keeps capture waiting for ever, since emit is never called.

None

SessionError

Bases: Exception

Base class for session lifecycle failures.

SerialIOError

Bases: SessionError

Underlying serial I/O failed.

HandshakeFailed

Bases: SessionError

The metadata handshake ran out of attempts.

attempts is how many were made; last describes the final failure (write error, no END, parse error).

VOLTAGE_LIMIT_HARDWARE_MIN_MV module-attribute

VOLTAGE_LIMIT_HARDWARE_MIN_MV: int = 800

VOLTAGE_LIMIT_HARDWARE_MAX_MV module-attribute

VOLTAGE_LIMIT_HARDWARE_MAX_MV: int = 5000

USER_GAIN_MIN module-attribute

USER_GAIN_MIN: float = 0.9

USER_GAIN_MAX module-attribute

USER_GAIN_MAX: float = 1.1

Samples and stream parser

StreamParser is what a capture runs on. Give it the bytes of each read, and it calls your function once per sample. It also:

  • keeps the alignment when a read ends in the middle of a word;
  • follows the counter of the samples, and puts a placeholder where one was lost;
  • applies the spike filter.

One call to push_bytes can produce no sample, one per word, or more. It produces none when the bytes do not complete a word, or when a sample is held back. It produces several when held samples are released, or when placeholders fill a gap.

The parser does not care where the bytes come from. For example, this decodes the stream stored with the tests, with the calibration stored next to it:

from pathlib import Path

from ppk2 import StreamParser, parse_metadata

coeffs = parse_metadata(Path("tests/fixtures/metadata.raw").read_bytes())
parser = StreamParser(coeffs, vdd_mv=3300)

currents: list[float] = []
parser.push_bytes(
    Path("tests/fixtures/stream_poweron.bin").read_bytes(),
    lambda sample: currents.append(sample.current_micro_amps),
)
print(f"{len(currents)} samples, mean {sum(currents) / len(currents):.2f} µA")
600 samples, mean 5205.55 µA

Sample dataclass

One calibrated, filtered sample.

Attributes:

Name Type Description
current_micro_amps float

Current in microamperes. NaN marks a lost sample: counter sync was not recovered in time.

logic int

Digital inputs D0 to D7 (bit 0 is D0); 0 for a lost sample.

SpikeFilter dataclass

Settings of the spike filter applied after a range change.

The same three settings as the spike filter of Nordic's app, with the app's defaults. The app numbers the ranges 1 to 5; here they are 0 to 4, as in the stream.

Attributes:

Name Type Description
samples int

How many samples after a range change are smoothed (>= 0). The app's "Samples to smooth". A larger value smooths a transient more and follows a real change of level later.

alpha float

Coefficient of the moving average for ranges 0 to 3, in [0, 1]. The app's "Coefficient for range 1-4".

alpha5 float

Coefficient of the moving average for range 4, in [0, 1]. The app's "Coefficient for range 5". This is the top range, 50 mA to 1 A in the PPK2 user guide, and it gets the heavier smoothing.

StreamParser

Turns the PPK2 byte stream into Sample objects; one per capture.

Reads need not land on 4-byte boundaries: up to 3 trailing bytes are kept and prepended to the next push_bytes call. The reads seen on the bench have come back aligned. The remainder is for those that do not: another system, a read that times out in the middle of a word, a test.

push_bytes

push_bytes(
    buf: bytes, emit: Callable[[Sample], None]
) -> None

Feed bytes from a serial read; call emit for each sample they complete.

One call can emit nothing (bytes short of a word, or a sample held back for resync) or several samples per word (held samples released, or placeholders for a lost gap).

Raw samples

RawSample dataclass

One sample frame after bit extraction: no calibration, no validation.

Attributes:

Name Type Description
adc_14 int

Raw 14-bit ADC reading (0 to 16,383).

range int

Auto-range index. Healthy firmware emits 0 to 4; 5 and up means the parse is misaligned.

counter int

6-bit per-sample counter, incrementing mod 64.

logic int

Digital inputs D0 to D7 in one byte (bit 0 is D0).

range_valid

range_valid() -> bool

Whether the range index is one of the five real ranges.

pin

pin(pin: int) -> bool

Whether digital input pin (0 to 7) was high; pin wraps modulo 8.

decode_sample

decode_sample(raw: int) -> RawSample

Split a 32-bit sample word into its fields (no validation).

decode_sample_bytes

decode_sample_bytes(buf: bytes) -> RawSample

Same as decode_sample, from exactly 4 little-endian bytes.

Raises:

Type Description
ValueError

If buf is not 4 bytes long.

Calibration

parse_metadata

parse_metadata(buf: bytes) -> CalibrationCoefficients

Parse a full GET_METADATA response into calibration coefficients.

Tolerant of unknown keys, END with or without a newline, spaces around the :, missing VDD/mode (see CalibrationCoefficients), and bytes before the text: the end of a stream that was not read out, up to 1 kB of samples, can come glued in front of the response. The parse starts at the first key, Calibrated.

Strict on missing calibration fields and on malformed values. A blank slot (-nan) takes the default Nordic's app uses for it.

Raises:

Type Description
MissingEnd

If buf has no END terminator.

MissingField

If a calibration key is absent.

InvalidValue

If a present field's value cannot be parsed.

CalibrationCoefficients dataclass

Per-device calibration, plus the VDD and mode the firmware reported.

Every coefficient is mandatory: a defaulted calibration value would corrupt every sample, so parse_metadata raises MissingField instead. VDD and mode describe the device's present state, not its calibration, and some firmware revisions omit them: those two get defaults.

Attributes:

Name Type Description
calibrated bool

The Calibrated value as reported. Not interpreted: a PPK2 that reports False still carries a full set of coefficients, and they are used.

r RangeArray

Per-range resistance (Ω, virtual).

gs RangeArray

Per-range gain slope (quadratic term).

gi RangeArray

Per-range gain intercept (linear term).

o RangeArray

Per-range ADC offset (16-bit-equivalent counts).

s RangeArray

Per-range VDD-dependent linear slope.

i RangeArray

Per-range VDD-dependent linear intercept.

ug RangeArray

Per-range user gain (default 1.0).

vdd_mv int

Supply voltage in millivolts, 800 to 5,000: the last REGULATOR_SET. It survives host disconnects: a PPK2 left at 1,800 mV reports it on the next open. 3,300 when the firmware omits it.

mode int

Power mode, 1 Ampere meter or 2 Source meter; anything else raises InvalidValue. Ampere meter, the passive mode, when the firmware omits it.

hw int

The HW value as reported. Not interpreted.

ia int

The IA value as reported. Not interpreted.

current_micro_amps

current_micro_amps(
    adc_14: int,
    range_idx: int,
    vdd_mv: int,
    coeffs: CalibrationCoefficients,
) -> float

Convert one raw ADC reading into microamperes.

Parameters:

Name Type Description Default
adc_14 int

14-bit ADC value, straight from RawSample.adc_14 (the *4 rescale happens here).

required
range_idx int

Range index, 0 to 4.

required
vdd_mv int

Present supply voltage in millivolts (the last REGULATOR_SET). Needed in Ampere meter mode too.

required
coeffs CalibrationCoefficients

Per-device calibration from parse_metadata.

required

Raises:

Type Description
IndexError

If range_idx is above 4.

MetadataError

Bases: Exception

Base class for metadata-parse failures.

MissingEnd

Bases: MetadataError

Buffer did not contain the END terminator.

The caller's accumulating-read loop has a bug.

MissingField

Bases: MetadataError

A required key was absent; field names it (e.g. R[3]).

InvalidValue

Bases: MetadataError

A field's value could not be parsed; value is the raw text.

Commands

A command is one byte. The value of each member is the byte that goes on the wire. See the protocol page for what the PPK2 does with them.

Opcode

Bases: IntEnum

Single-byte opcode; the enum value is the wire byte.

Opcode.AVERAGE_START == 0x06. byte() says the same thing at call sites.

TRIGGER_SET class-attribute instance-attribute

TRIGGER_SET = 1

Generic ON parameter byte. Rarely sent as an opcode of its own.

AVG_NUM_SET class-attribute instance-attribute

AVG_NUM_SET = 2

Decimation count. Nordic's source marks it as not handled by the firmware, which ignores it.

TRIGGER_WINDOW_SET class-attribute instance-attribute

TRIGGER_WINDOW_SET = 3

Triggered-capture window size (u16 LE).

TRIGGER_INTERVAL_SET class-attribute instance-attribute

TRIGGER_INTERVAL_SET = 4

Triggered-capture interval (u16 LE). Nordic's source marks it as not handled by the firmware.

TRIGGER_SINGLE_SET class-attribute instance-attribute

TRIGGER_SINGLE_SET = 5

Single-shot trigger arm.

AVERAGE_START class-attribute instance-attribute

AVERAGE_START = 6

Start the stream: 100,000 samples per second, each a 4-byte little-endian word, until AVERAGE_STOP.

AVERAGE_STOP class-attribute instance-attribute

AVERAGE_STOP = 7

Stop the sample stream.

RANGE_SET class-attribute instance-attribute

RANGE_SET = 8

Manual measurement-range override (u8, 0 to 4). Rarely used, the firmware auto-ranges. Nordic's source marks it as not handled by the firmware.

LCD_SET class-attribute instance-attribute

LCD_SET = 9

LCD backlight. The PPK2 has no LCD; Nordic's source marks it as not handled by the firmware.

DEVICE_RUNNING_SET class-attribute instance-attribute

DEVICE_RUNNING_SET = 12

Power to the DUT: payload 0x01 on, 0x00 off. The app's "Enable power output".

Applied about 1 ms after it is sent, with or without a stream. One sent within 0.31 s of AVERAGE_START is held until then (the protocol page, Known caveats).

REGULATOR_SET class-attribute instance-attribute

REGULATOR_SET = 13

Supply voltage in Source meter mode: [0x0D, mV >> 8, mV & 0xff] (big-endian), 800 to 5,000 mV.

In Ampere meter mode the regulator is inactive, but the calibration still uses the last value sent (see current_micro_amps).

SWITCH_POINT_DOWN class-attribute instance-attribute

SWITCH_POINT_DOWN = 14

Auto-range hysteresis (downward).

SWITCH_POINT_UP class-attribute instance-attribute

SWITCH_POINT_UP = 15

Auto-range hysteresis (upward).

SET_POWER_MODE class-attribute instance-attribute

SET_POWER_MODE = 17

Measurement mode: payload 0x01 Ampere meter, 0x02 Source meter.

Nordic also names this byte TriggerExtToggle, an external-trigger function that shares it; this library only uses it to set the mode.

RES_USER_SET class-attribute instance-attribute

RES_USER_SET = 18

User-supplied resistor calibration. No known host sends it.

SPIKE_FILTERING_ON class-attribute instance-attribute

SPIKE_FILTERING_ON = 21

Enable firmware-side spike filtering.

SPIKE_FILTERING_OFF class-attribute instance-attribute

SPIKE_FILTERING_OFF = 22

Disable firmware-side spike filtering.

GET_METADATA class-attribute instance-attribute

GET_METADATA = 25

Request the per-device calibration: about 1 kB of ASCII key: value\n lines ending with END.

RESET class-attribute instance-attribute

RESET = 32

Restart the firmware. The PPK2 leaves USB and comes back 200 to 500 ms later.

SET_USER_GAINS class-attribute instance-attribute

SET_USER_GAINS = 37

User gain override, payload [u8 range, f32 gain]. Current firmware accepts and ignores it.

byte

byte() -> int

Return the single byte sent on the wire for this opcode.