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:
- lists the serial ports and keeps those with the PPK2's USB
identity,
1915:C00A; - groups them by USB serial number, since a PPK2 shows up as two ports;
- 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 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
( |
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 |
statuses |
dict[str, PortStatus]
|
Probe result per path. Paths left unprobed because an
earlier one already answered are reported |
DiscoveryError
¶
Bases: Exception
Base class for port discovery failures.
NotFound
¶
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 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
¶
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
¶
Per-device calibration read at session open.
set_mode
¶
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 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 |
SerialIOError
|
If the serial write fails. |
set_voltage_limit
¶
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
|
stop_measuring
¶
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
¶
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).
drop_pending_backlog
¶
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
¶
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 |
RuntimeError
|
If called while a stream runs, between
|
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
|
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 |
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 |
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).
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")
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
( |
alpha |
float
|
Coefficient of the moving average for ranges 0 to 3, in
|
alpha5 |
float
|
Coefficient of the moving average for range 4, in
|
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
¶
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). |
decode_sample
¶
Split a 32-bit sample word into its fields (no validation).
decode_sample_bytes
¶
Same as decode_sample, from exactly 4 little-endian bytes.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Calibration¶
parse_metadata
¶
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 |
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 |
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
|
mode |
int
|
Power mode, |
hw |
int
|
The |
ia |
int
|
The |
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 |
required |
range_idx
|
int
|
Range index, 0 to 4. |
required |
vdd_mv
|
int
|
Present supply voltage in millivolts (the last
|
required |
coeffs
|
CalibrationCoefficients
|
Per-device calibration from |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
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
¶
InvalidValue
¶
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
¶
Generic ON parameter byte. Rarely sent as an opcode of its own.
AVG_NUM_SET
class-attribute
instance-attribute
¶
Decimation count. Nordic's source marks it as not handled by the firmware, which ignores it.
TRIGGER_WINDOW_SET
class-attribute
instance-attribute
¶
Triggered-capture window size (u16 LE).
TRIGGER_INTERVAL_SET
class-attribute
instance-attribute
¶
Triggered-capture interval (u16 LE). Nordic's source marks it as not handled by the firmware.
TRIGGER_SINGLE_SET
class-attribute
instance-attribute
¶
Single-shot trigger arm.
AVERAGE_START
class-attribute
instance-attribute
¶
Start the stream: 100,000 samples per second, each a 4-byte
little-endian word, until AVERAGE_STOP.
RANGE_SET
class-attribute
instance-attribute
¶
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 backlight. The PPK2 has no LCD; Nordic's source marks it as not handled by the firmware.
DEVICE_RUNNING_SET
class-attribute
instance-attribute
¶
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
¶
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
¶
Auto-range hysteresis (downward).
SWITCH_POINT_UP
class-attribute
instance-attribute
¶
Auto-range hysteresis (upward).
SET_POWER_MODE
class-attribute
instance-attribute
¶
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
¶
User-supplied resistor calibration. No known host sends it.
SPIKE_FILTERING_ON
class-attribute
instance-attribute
¶
Enable firmware-side spike filtering.
SPIKE_FILTERING_OFF
class-attribute
instance-attribute
¶
Disable firmware-side spike filtering.
GET_METADATA
class-attribute
instance-attribute
¶
Request the per-device calibration: about 1 kB of ASCII
key: value\n lines ending with END.
RESET
class-attribute
instance-attribute
¶
Restart the firmware. The PPK2 leaves USB and comes back 200 to 500 ms later.
SET_USER_GAINS
class-attribute
instance-attribute
¶
User gain override, payload [u8 range, f32 gain]. Current
firmware accepts and ignores it.