ppk2-lib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ppk2/__init__.py ADDED
@@ -0,0 +1,100 @@
1
+ """Python library + CLI for Nordic's Power Profiler Kit II (PPK2).
2
+
3
+ Three layers:
4
+
5
+ - ``ppk2.protocol``: pure wire-protocol primitives, stdlib-only.
6
+ - ``ppk2.client``: sync host driver on top of ``pyserial``.
7
+ - ``ppk2.cli``: the ``ppk2`` binary, internal to the package.
8
+
9
+ For library use, import from this top level:
10
+
11
+ >>> from ppk2 import StreamParser, parse_metadata, Sample # protocol layer
12
+ >>> from ppk2 import Session, find_ppk2 # client layer
13
+ """
14
+
15
+ from ppk2.client import (
16
+ USER_GAIN_MAX,
17
+ USER_GAIN_MIN,
18
+ VOLTAGE_LIMIT_HARDWARE_MAX_MV,
19
+ VOLTAGE_LIMIT_HARDWARE_MIN_MV,
20
+ Ambiguous,
21
+ DataPortNotFound,
22
+ DiscoveryError,
23
+ HandshakeFailed,
24
+ Mode,
25
+ NotFound,
26
+ PortInfo,
27
+ Ppk2Listing,
28
+ SerialIOError,
29
+ Session,
30
+ SessionError,
31
+ find_ppk2,
32
+ find_ppk2_by_serial,
33
+ list_ppk2s,
34
+ )
35
+ from ppk2.protocol import (
36
+ DEFAULT_SPIKE_FILTER_ALPHA,
37
+ DEFAULT_SPIKE_FILTER_ALPHA5,
38
+ DEFAULT_SPIKE_FILTER_SAMPLES,
39
+ MAX_BUFFERED_CORRUPTED,
40
+ NUM_RANGES,
41
+ CalibrationCoefficients,
42
+ InvalidValue,
43
+ MetadataError,
44
+ MissingEnd,
45
+ MissingField,
46
+ Opcode,
47
+ RangeArray,
48
+ RawSample,
49
+ Sample,
50
+ SpikeFilter,
51
+ StreamParser,
52
+ current_micro_amps,
53
+ decode_sample,
54
+ decode_sample_bytes,
55
+ parse_metadata,
56
+ )
57
+
58
+ __version__ = "0.1.0"
59
+
60
+ __all__ = [
61
+ "DEFAULT_SPIKE_FILTER_ALPHA",
62
+ "DEFAULT_SPIKE_FILTER_ALPHA5",
63
+ "DEFAULT_SPIKE_FILTER_SAMPLES",
64
+ "MAX_BUFFERED_CORRUPTED",
65
+ "NUM_RANGES",
66
+ "USER_GAIN_MAX",
67
+ "USER_GAIN_MIN",
68
+ "VOLTAGE_LIMIT_HARDWARE_MAX_MV",
69
+ "VOLTAGE_LIMIT_HARDWARE_MIN_MV",
70
+ "Ambiguous",
71
+ "CalibrationCoefficients",
72
+ "DataPortNotFound",
73
+ "DiscoveryError",
74
+ "HandshakeFailed",
75
+ "InvalidValue",
76
+ "MetadataError",
77
+ "MissingEnd",
78
+ "MissingField",
79
+ "Mode",
80
+ "NotFound",
81
+ "Opcode",
82
+ "PortInfo",
83
+ "Ppk2Listing",
84
+ "RangeArray",
85
+ "RawSample",
86
+ "Sample",
87
+ "SerialIOError",
88
+ "Session",
89
+ "SessionError",
90
+ "SpikeFilter",
91
+ "StreamParser",
92
+ "__version__",
93
+ "current_micro_amps",
94
+ "decode_sample",
95
+ "decode_sample_bytes",
96
+ "find_ppk2",
97
+ "find_ppk2_by_serial",
98
+ "list_ppk2s",
99
+ "parse_metadata",
100
+ ]
ppk2/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Entry point for ``python -m ppk2``: the same ``main`` as the ``ppk2`` binary."""
2
+
3
+ from ppk2.cli.main import main
4
+
5
+ main()
ppk2/cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """The ``ppk2`` binary, built on Typer. Internal: nothing here is re-exported."""
2
+
3
+ __all__: list[str] = []
@@ -0,0 +1,23 @@
1
+ """Per-subcommand modules for the ``ppk2`` CLI.
2
+
3
+ ``resolve_device``, shared by all of them, turns the ``--serial`` /
4
+ ``--port`` flag pair into a device path.
5
+ """
6
+
7
+ from ppk2 import Mode, find_ppk2, find_ppk2_by_serial
8
+
9
+ #: The modes under the names of Nordic's app, for messages.
10
+ MODE_LABELS: dict[int, str] = {Mode.AMPERE: "Ampere meter", Mode.SOURCE: "Source meter"}
11
+
12
+
13
+ def resolve_device(serial: str | None, port: str | None) -> str:
14
+ """Resolve the data-port path from the ``--serial``/``--port`` flags.
15
+
16
+ ``--port`` wins and skips discovery and the probe: the caller says
17
+ they know the path. Otherwise discovery runs, scoped to ``--serial``
18
+ when given.
19
+ """
20
+ if port is not None:
21
+ return port
22
+ info = find_ppk2_by_serial(serial) if serial else find_ppk2()
23
+ return info.device
@@ -0,0 +1,270 @@
1
+ """``ppk2 capture``: stream the current trace to a CSV or ``.ppk2`` file."""
2
+
3
+ import signal
4
+ import sys
5
+ from collections.abc import Callable, Iterable
6
+ from contextlib import ExitStack, suppress
7
+ from math import isfinite, isnan
8
+ from pathlib import Path
9
+ from time import monotonic
10
+ from types import FrameType
11
+
12
+ import typer
13
+
14
+ from ppk2 import USER_GAIN_MAX, USER_GAIN_MIN, Mode, Sample, Session
15
+ from ppk2.cli.commands import MODE_LABELS, resolve_device
16
+ from ppk2.cli.csv import noise_floor, vdd_to_mv
17
+ from ppk2.cli.signals import signals_to_systemexit
18
+ from ppk2.cli.trace import SAMPLE_RATE_HZ as _SAMPLE_RATE_HZ
19
+ from ppk2.cli.trace import TraceFile
20
+
21
+ _PROGRESS_INTERVAL_S = 1.0
22
+
23
+ #: Cumulative data-loss count at which we first emit a mid-stream
24
+ #: warning. Matches ``DATALOSS_THRESHOLD`` in Nordic's app.
25
+ _DATALOSS_WARN_THRESHOLD = 500
26
+
27
+ #: Post-capture watchdog: a realized stream rate below this fraction of
28
+ #: 100 kSPS (on captures longer than 0.5 s) means the host lost
29
+ #: samples, and charge or timing figures taken from the file are off.
30
+ _RATE_WATCHDOG_FRACTION = 0.95
31
+
32
+ #: How long past ``--seconds`` a capture waits for samples that are late.
33
+ _LATE_GRACE_S = 1.0
34
+
35
+
36
+ def capture(
37
+ serial: str | None,
38
+ port: str | None,
39
+ out: Path,
40
+ seconds: float,
41
+ vdd: float,
42
+ source: bool,
43
+ user_gain_specs: Iterable[str] = (),
44
+ ) -> None:
45
+ """Open a session, stream samples for ``seconds``, write them to ``out``.
46
+
47
+ The 11-column CSV, or a ``.ppk2`` session file when ``out`` ends in ``.ppk2``.
48
+ """
49
+ # Parse the gains first: a malformed flag should fail before the
50
+ # (slow) hardware discovery, not after.
51
+ user_gains = [parse_user_gain_spec(spec) for spec in user_gain_specs]
52
+ if not (isfinite(seconds) and round(seconds * _SAMPLE_RATE_HZ) >= 1):
53
+ raise typer.BadParameter(
54
+ f"{seconds} is not a duration: give at least one sample, 0.00001 s",
55
+ param_hint="--seconds",
56
+ )
57
+ mv = vdd_to_mv(vdd)
58
+ device = resolve_device(serial, port)
59
+ mode = Mode.SOURCE if source else Mode.AMPERE
60
+
61
+ sys.stderr.write(f"opening session ({MODE_LABELS[mode]} mode, vdd={mv} mV)\n")
62
+ if user_gains:
63
+ gains_repr = ", ".join(f"r{r}={g:.4f}" for r, g in user_gains)
64
+ sys.stderr.write(f" user-gain overrides: {gains_repr}\n")
65
+ sys.stderr.write(f"capturing {seconds:.2f} s -> {out} (Ctrl-C to stop early)\n")
66
+ sys.stderr.flush()
67
+
68
+ out.parent.mkdir(parents=True, exist_ok=True)
69
+
70
+ stop_requested = _SigintFlag()
71
+
72
+ # SIGTERM/SIGHUP raise SystemExit inside this block, so a `kill` or
73
+ # a closed terminal unwinds it like a Ctrl-C: the session tears
74
+ # down and the output file is completed.
75
+ with ExitStack() as stack:
76
+ stack.enter_context(stop_requested)
77
+ stack.enter_context(signals_to_systemexit("SIGTERM", "SIGHUP"))
78
+
79
+ with Session.open(device) as session:
80
+ # Opened once the PPK2 answers: a capture that cannot start
81
+ # leaves an earlier file of the same name alone.
82
+ trace = stack.enter_context(TraceFile(out))
83
+ session.set_mode(mode)
84
+ session.set_source_voltage(mv)
85
+ for range_idx, gain in user_gains:
86
+ session.set_user_gain(range_idx, gain)
87
+ session.start_measuring()
88
+ session.power_on()
89
+
90
+ n_samples = 0
91
+ n_dataloss = 0 # NaN placeholders from the stream parser's data-loss path
92
+ sum_ua = 0.0
93
+ last_progress = monotonic()
94
+ started = monotonic()
95
+ # The capture ends on a number of samples, so that the
96
+ # trace holds the seconds asked for. The clock ends it only
97
+ # when the samples do not come.
98
+ target = round(seconds * _SAMPLE_RATE_HZ)
99
+ deadline = started + seconds + _LATE_GRACE_S
100
+ dataloss_warned = False
101
+
102
+ def on_dataloss(total: int) -> None:
103
+ nonlocal dataloss_warned
104
+ if dataloss_warned or total < _DATALOSS_WARN_THRESHOLD:
105
+ return
106
+ dataloss_warned = True
107
+ sys.stderr.write(
108
+ f" warning: {total} samples lost so far, near sample "
109
+ f"{n_samples + n_dataloss}. Likely cause: the USB cable, a hub or a "
110
+ "busy computer. The capture goes on; each lost sample is recorded "
111
+ "as 0.2 µA, as in Nordic's app.\n"
112
+ )
113
+ sys.stderr.flush()
114
+
115
+ def emit(s: Sample) -> bool:
116
+ nonlocal n_samples, n_dataloss, sum_ua, last_progress
117
+ if stop_requested.flag:
118
+ return False
119
+ # NaN is a lost sample: 0.2 µA in the file, as in
120
+ # Nordic's app, and left out of the mean printed here.
121
+ ua = noise_floor(s.current_micro_amps)
122
+ trace.add(ua, s.logic)
123
+ if isnan(ua):
124
+ n_dataloss += 1
125
+ else:
126
+ n_samples += 1
127
+ sum_ua += ua
128
+
129
+ now = monotonic()
130
+ if now - last_progress >= _PROGRESS_INTERVAL_S:
131
+ mean = sum_ua / n_samples if n_samples else 0.0
132
+ elapsed = now - started
133
+ sys.stderr.write(
134
+ f" [{elapsed:5.1f}s] {n_samples:>10} samples mean {mean:>7.2f} µA\n"
135
+ )
136
+ sys.stderr.flush()
137
+ last_progress = now
138
+
139
+ return n_samples + n_dataloss < target and monotonic() < deadline
140
+
141
+ # The trace starts about 10 ms before power-on (Known
142
+ # caveats in docs/measure/protocol.md).
143
+ session.drop_pending_backlog()
144
+ session.capture(
145
+ emit,
146
+ on_dataloss=on_dataloss,
147
+ # A silent PPK2 never reaches emit: the clock and
148
+ # Ctrl-C are checked here too.
149
+ keep_going=lambda: not stop_requested.flag and monotonic() < deadline,
150
+ )
151
+ # Taken here: shutting the session down takes a tenth of a
152
+ # second that is not capture time.
153
+ wall = monotonic() - started
154
+
155
+ with suppress(Exception):
156
+ session.power_off()
157
+ with suppress(Exception):
158
+ session.stop_measuring()
159
+
160
+ # Complete the file before saying so, with the signal handlers
161
+ # still in place: a second Ctrl-C must not cut the write short.
162
+ trace.close()
163
+ # The stream rate counts lost samples too: they took their time.
164
+ n_total = n_samples + n_dataloss
165
+ rate = n_total / wall if wall > 0 else 0.0
166
+ if stop_requested.flag:
167
+ done = ".ppk2 written" if trace.is_ppk2 else "CSV flushed"
168
+ sys.stderr.write(f"interrupted: {done}\n")
169
+ suffix = ", stopped by Ctrl-C" if stop_requested.flag else ""
170
+ sys.stderr.write(
171
+ f"captured {n_samples} samples over {wall:.2f} s ({rate:.0f} Hz){suffix}\n"
172
+ )
173
+ if n_dataloss > 0:
174
+ sys.stderr.write(
175
+ f" warning: {n_dataloss} samples lost "
176
+ f"({100.0 * n_dataloss / n_total:.3f} % of the stream), "
177
+ "each recorded as 0.2 µA, as in Nordic's app\n"
178
+ )
179
+ if wall > 0.5 and n_total > 0 and rate < _RATE_WATCHDOG_FRACTION * _SAMPLE_RATE_HZ:
180
+ sys.stderr.write(
181
+ f"WARNING: stream rate {rate:.0f} Hz is "
182
+ f"{100.0 * rate / _SAMPLE_RATE_HZ:.1f} % of {_SAMPLE_RATE_HZ} Hz "
183
+ f"({n_total} samples in {wall:.2f} s): samples were lost without "
184
+ "being counted; do not rely on the duration or the charge of this capture.\n"
185
+ )
186
+ sys.stderr.flush()
187
+
188
+ if stop_requested.flag:
189
+ # 130 is the standard Bash SIGINT exit code. The output is
190
+ # completed as the block unwinds: shorter, but valid.
191
+ raise typer.Exit(code=130)
192
+ if n_total == 0:
193
+ sys.stderr.write(
194
+ "error: no samples captured: check the PPK2 mode and the DUT's power\n"
195
+ )
196
+ sys.stderr.flush()
197
+ raise typer.Exit(code=1)
198
+ if n_total < target:
199
+ # The clock ended it: the file is kept, and is not what was asked for.
200
+ sys.stderr.write(
201
+ f"error: capture ended with {n_total} of {target} samples: "
202
+ "the PPK2 stopped sending, or the computer did not keep up\n"
203
+ )
204
+ sys.stderr.flush()
205
+ raise typer.Exit(code=1)
206
+
207
+
208
+ def parse_user_gain_spec(spec: str) -> tuple[int, float]:
209
+ """Parse one ``--user-gain RANGE:GAIN`` token into ``(range_idx, gain)``.
210
+
211
+ Raises:
212
+ typer.BadParameter: If it is not ``RANGE:GAIN``, the range is not
213
+ 0-4, or the gain is not from 0.9 to 1.1.
214
+ """
215
+ label = "--user-gain"
216
+ parts = spec.split(":")
217
+ if len(parts) != 2:
218
+ raise typer.BadParameter(
219
+ f"{label} expects RANGE:GAIN (got '{spec}'); example: --user-gain 2:1.05",
220
+ param_hint=label,
221
+ )
222
+ range_str, gain_str = parts[0].strip(), parts[1].strip()
223
+ try:
224
+ range_idx = int(range_str)
225
+ except ValueError as exc:
226
+ raise typer.BadParameter(
227
+ f"{label} range must be an integer from 0 to 4 (got '{range_str}')",
228
+ param_hint=label,
229
+ ) from exc
230
+ if not 0 <= range_idx <= 4:
231
+ raise typer.BadParameter(
232
+ f"{label} range must be from 0 to 4 (got {range_idx})",
233
+ param_hint=label,
234
+ )
235
+ try:
236
+ gain = float(gain_str)
237
+ except ValueError as exc:
238
+ raise typer.BadParameter(
239
+ f"{label} gain must be a float (got '{gain_str}')",
240
+ param_hint=label,
241
+ ) from exc
242
+ # The range of Nordic's app. NaN fails the comparison too.
243
+ if not USER_GAIN_MIN <= gain <= USER_GAIN_MAX:
244
+ raise typer.BadParameter(
245
+ f"{label} gain must be from {USER_GAIN_MIN} to {USER_GAIN_MAX} (got '{gain_str}')",
246
+ param_hint=label,
247
+ )
248
+ return range_idx, gain
249
+
250
+
251
+ # What `signal.signal` returns: SIG_DFL / SIG_IGN or a Python callable.
252
+ _SignalHandler = Callable[[int, FrameType | None], object] | int | None
253
+
254
+
255
+ class _SigintFlag:
256
+ """A SIGINT handler that sets ``flag``; the previous handler comes back on exit."""
257
+
258
+ def __init__(self) -> None:
259
+ self.flag = False
260
+ self._prev: _SignalHandler = signal.SIG_DFL
261
+
262
+ def __enter__(self) -> "_SigintFlag":
263
+ def _handler(_signum: int, _frame: FrameType | None) -> None:
264
+ self.flag = True
265
+
266
+ self._prev = signal.signal(signal.SIGINT, _handler)
267
+ return self
268
+
269
+ def __exit__(self, *_args: object) -> None:
270
+ signal.signal(signal.SIGINT, self._prev)
@@ -0,0 +1,119 @@
1
+ """``ppk2 convert``: rewrite a CSV capture as a ``.ppk2`` session file."""
2
+
3
+ import gzip
4
+ import struct
5
+ import sys
6
+ from itertools import chain, islice, pairwise
7
+ from pathlib import Path
8
+ from typing import NoReturn, TextIO
9
+
10
+ import typer
11
+
12
+ from ppk2.cli.ppk2file import SAMPLE_RATES, Ppk2FileWriter
13
+ from ppk2.cli.trace import LOST_SAMPLE_UA
14
+
15
+ # Rows read ahead to find the sample period: enough to hold two
16
+ # neighbouring samples even where some were lost.
17
+ _ROWS_FOR_RATE = 64
18
+
19
+
20
+ def convert(src: Path, dst: Path) -> None:
21
+ """Rewrite the CSV capture ``src`` (plain or ``.gz``) as the ``.ppk2`` file ``dst``.
22
+
23
+ The sample rate is the smallest step between the first timestamps.
24
+ A ``.ppk2`` has no timestamps, so a jump in those of the CSV is
25
+ filled: one frame of ``LOST_SAMPLE_UA`` per missing row, as Nordic's
26
+ app records a lost sample, and the rest of the trace stays where it
27
+ was in time.
28
+
29
+ On any error nothing is written, and an existing ``dst`` is kept.
30
+ """
31
+ try:
32
+ count, rate, lost = _convert(src, dst)
33
+ except UnicodeDecodeError:
34
+ _fail(f"{src}: not a text file")
35
+ except EOFError:
36
+ _fail(f"{src}: the compressed file is cut short")
37
+ except OSError as exc:
38
+ _fail(f"{exc.filename or src}: {exc.strerror or exc}")
39
+
40
+ note = ""
41
+ if lost:
42
+ note = (
43
+ ", 1 missing row filled with 0.2 µA"
44
+ if lost == 1
45
+ else f", {lost} missing rows filled with 0.2 µA"
46
+ )
47
+ sys.stderr.write(f"wrote {dst}: {count} samples at {rate} S/s ({count / rate:.2f} s){note}\n")
48
+
49
+
50
+ def _convert(src: Path, dst: Path) -> tuple[int, int, int]:
51
+ """Do the conversion; return (samples written, rate, lost samples among them)."""
52
+ with _open_text(src) as rows:
53
+ columns = rows.readline().strip().split(",")
54
+ if "Timestamp(ms)" not in columns or "Current(uA)" not in columns:
55
+ _fail(f"{src}: needs the Timestamp(ms) and Current(uA) columns")
56
+ i_time = columns.index("Timestamp(ms)")
57
+ i_current = columns.index("Current(uA)")
58
+ i_logic = columns.index("D0-D7") if "D0-D7" in columns else None
59
+
60
+ head = list(islice(rows, _ROWS_FOR_RATE))
61
+ try:
62
+ times = [float(line.split(",")[i_time]) for line in head if line.strip()]
63
+ except (ValueError, IndexError):
64
+ _fail(f"{src}: cannot read the timestamps of the first rows")
65
+ if not times:
66
+ _fail(f"{src}: no samples")
67
+ step_ms = min((b - a for a, b in pairwise(times) if b > a), default=0.01)
68
+ rate = round(1000.0 / step_ms)
69
+ if rate not in SAMPLE_RATES:
70
+ _fail(f"{src}: {step_ms:g} ms between samples is not a rate the app supports")
71
+ t0 = times[0]
72
+
73
+ dst.parent.mkdir(parents=True, exist_ok=True)
74
+ logic_of: dict[str, int] = {} # "10000000" (D0 leftmost) -> 0x01
75
+ lost = 0
76
+ out = Ppk2FileWriter(dst, rate)
77
+ try:
78
+ for row, line in enumerate(chain(head, rows), start=2):
79
+ if not line.strip():
80
+ continue
81
+ fields = line.split(",")
82
+ try:
83
+ slot = round((float(fields[i_time]) - t0) * rate / 1000.0)
84
+ current = float(fields[i_current])
85
+ logic = 0
86
+ if i_logic is not None:
87
+ bits = fields[i_logic].strip()
88
+ logic = logic_of.get(bits, -1)
89
+ if logic < 0:
90
+ logic = logic_of[bits] = int(bits[::-1], 2)
91
+ except (ValueError, IndexError):
92
+ _fail(f"{src}: malformed row at line {row}")
93
+ if slot < out.count:
94
+ _fail(f"{src}: timestamps go back at line {row}")
95
+ if slot - out.count > rate:
96
+ _fail(f"{src}: timestamps jump by over a second at line {row}")
97
+ for _ in range(slot - out.count):
98
+ out.add(LOST_SAMPLE_UA, 0)
99
+ lost += 1
100
+ try:
101
+ out.add(current, logic)
102
+ except (OverflowError, struct.error):
103
+ _fail(f"{src}: current out of range at line {row}")
104
+ except BaseException:
105
+ out.discard()
106
+ raise
107
+ out.close()
108
+ return out.count, rate, lost
109
+
110
+
111
+ def _open_text(path: Path) -> TextIO:
112
+ if path.suffix == ".gz":
113
+ return gzip.open(path, "rt", encoding="utf-8")
114
+ return path.open(encoding="utf-8")
115
+
116
+
117
+ def _fail(message: str) -> NoReturn:
118
+ sys.stderr.write(f"error: {message}\n")
119
+ raise typer.Exit(code=1)
@@ -0,0 +1,14 @@
1
+ """``ppk2 discover``: print the data-port device path of the plugged-in PPK2."""
2
+
3
+ import typer
4
+
5
+ from ppk2.cli.commands import resolve_device
6
+
7
+
8
+ def discover(serial: str | None, port: str | None) -> None:
9
+ """Resolve the PPK2 and print its data-port device path to stdout.
10
+
11
+ With ``--port`` the path is echoed back as given, with no discovery
12
+ and no probe, so scripts can pass the flag to every subcommand.
13
+ """
14
+ typer.echo(resolve_device(serial, port))
@@ -0,0 +1,45 @@
1
+ """``ppk2 list``: enumerate connected PPK2s and mark each port's probe status."""
2
+
3
+ import typer
4
+
5
+ from ppk2 import list_ppk2s
6
+ from ppk2.client.discovery import PortStatus
7
+
8
+ _STATUS_TAGS: dict[PortStatus, str] = {
9
+ "data": "[data port]",
10
+ "idle": "[idle]",
11
+ "busy": "[busy: held by another process?]",
12
+ }
13
+
14
+
15
+ def list_devices(mask_serial: bool = False) -> None:
16
+ """Print one block per physical PPK2 with each port's probe status.
17
+
18
+ Exit code 0 when every enumerated device has an identified data
19
+ port; 1 when none is plugged in or when a device's data port could
20
+ not be identified (typically because another process holds it).
21
+
22
+ With ``mask_serial`` only the last four characters of each serial
23
+ number are printed, in the port paths too: for a screenshot or a
24
+ recording.
25
+ """
26
+ devices = list_ppk2s()
27
+ if not devices:
28
+ typer.echo("no PPK2 found")
29
+ raise typer.Exit(code=1)
30
+ unidentified = False
31
+ for dev in devices:
32
+ serial = dev.usb_serial
33
+ masked = "*" * (len(serial) - 4) + serial[-4:] if mask_serial else serial
34
+ typer.echo(f"PPK2 serial={masked}")
35
+ for path in dev.ports:
36
+ shown = path.replace(serial, masked) if serial else path
37
+ typer.echo(f" {shown} {_STATUS_TAGS[dev.statuses[path]]}")
38
+ if dev.data_port is None:
39
+ unidentified = True
40
+ typer.echo(
41
+ " (data port not identified: close the nRF Connect Power "
42
+ "Profiler if it's open, else pass --port)"
43
+ )
44
+ if unidentified:
45
+ raise typer.Exit(code=1)
@@ -0,0 +1,36 @@
1
+ """``ppk2 metadata``: print the per-device calibration coefficients."""
2
+
3
+ import typer
4
+
5
+ from ppk2 import CalibrationCoefficients, Session
6
+ from ppk2.cli.commands import MODE_LABELS, resolve_device
7
+ from ppk2.cli.signals import signals_to_systemexit
8
+
9
+
10
+ def metadata(serial: str | None, port: str | None) -> None:
11
+ """Open a session, read metadata, format-print to stdout, then teardown."""
12
+ device = resolve_device(serial, port)
13
+ with signals_to_systemexit("SIGTERM", "SIGHUP"), Session.open(device) as session:
14
+ coeffs = session.coefficients()
15
+ _print_coefficients(coeffs)
16
+
17
+
18
+ def _print_coefficients(c: CalibrationCoefficients) -> None:
19
+ """Render the coefficient block as a human-readable table."""
20
+ mode_name = MODE_LABELS.get(c.mode, "unknown")
21
+ typer.echo(f"Calibrated: {'true' if c.calibrated else 'false'}")
22
+ typer.echo(f"HW: {c.hw}")
23
+ typer.echo(f"IA: {c.ia}")
24
+ typer.echo(f"VDD: {c.vdd_mv} mV")
25
+ typer.echo(f"mode: {c.mode} ({mode_name})")
26
+ for name, arr in (
27
+ ("R ", c.r),
28
+ ("GS", c.gs),
29
+ ("GI", c.gi),
30
+ ("O ", c.o),
31
+ ("S ", c.s),
32
+ ("I ", c.i),
33
+ ("UG", c.ug),
34
+ ):
35
+ formatted = ", ".join(f"{v: 16.6e}" for v in arr)
36
+ typer.echo(f"{name}: [{formatted}]")
@@ -0,0 +1,63 @@
1
+ """``ppk2 power on|off``: switch power to the DUT, optionally holding it on."""
2
+
3
+ import signal
4
+ import sys
5
+ from enum import StrEnum
6
+
7
+ from ppk2 import Mode, Session
8
+ from ppk2.cli.commands import resolve_device
9
+ from ppk2.cli.csv import vdd_to_mv
10
+ from ppk2.cli.signals import signals_to_systemexit
11
+
12
+
13
+ class PowerState(StrEnum):
14
+ """``on`` / ``off`` argument shape for ``ppk2 power``."""
15
+
16
+ ON = "on"
17
+ OFF = "off"
18
+
19
+
20
+ def power(
21
+ serial: str | None,
22
+ port: str | None,
23
+ state: PowerState,
24
+ hold: bool,
25
+ vdd: float,
26
+ source: bool,
27
+ ) -> None:
28
+ """Open a session, switch the power, optionally block until SIGINT, then close."""
29
+ mv = vdd_to_mv(vdd)
30
+ device = resolve_device(serial, port)
31
+ mode = Mode.SOURCE if source else Mode.AMPERE
32
+
33
+ # SIGTERM/SIGHUP -> SystemExit so a kill still cuts the power and
34
+ # closes the port on the way out.
35
+ with signals_to_systemexit("SIGTERM", "SIGHUP"), Session.open(device) as session:
36
+ session.set_mode(mode)
37
+ session.set_source_voltage(mv)
38
+ if state is PowerState.ON:
39
+ session.power_on()
40
+ if hold:
41
+ _hold_until_sigint()
42
+ # Without --hold the power goes off as the session closes.
43
+ else:
44
+ session.power_off()
45
+
46
+
47
+ def _hold_until_sigint() -> None:
48
+ """Block until SIGINT, then return so the caller can clean up."""
49
+ received = False
50
+
51
+ def _handler(_signum: int, _frame: object) -> None:
52
+ nonlocal received
53
+ received = True
54
+
55
+ prev = signal.signal(signal.SIGINT, _handler)
56
+ try:
57
+ sys.stderr.write("ppk2: holding power on; Ctrl-C to release\n")
58
+ sys.stderr.flush()
59
+ signal.pause() # blocks until any signal; our handler unblocks SIGINT
60
+ if not received:
61
+ sys.stderr.write("ppk2: woke from pause without SIGINT, exiting anyway\n")
62
+ finally:
63
+ signal.signal(signal.SIGINT, prev)