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.
@@ -0,0 +1,162 @@
1
+ """``ppk2 run``: run a command with the DUT powered, optionally capturing the trace."""
2
+
3
+ import os
4
+ import signal
5
+ import subprocess
6
+ import sys
7
+ import threading
8
+ from contextlib import suppress
9
+ from pathlib import Path
10
+
11
+ import typer
12
+
13
+ from ppk2 import Mode, Sample, Session
14
+ from ppk2.cli.commands import MODE_LABELS, resolve_device
15
+ from ppk2.cli.csv import noise_floor, vdd_to_mv
16
+ from ppk2.cli.signals import signals_to_systemexit
17
+ from ppk2.cli.trace import TraceFile
18
+
19
+ #: How long a child gets to end after SIGTERM before it is killed.
20
+ _CHILD_GRACE_S = 5.0
21
+
22
+
23
+ def run(
24
+ serial: str | None,
25
+ port: str | None,
26
+ cmd: list[str],
27
+ out: Path | None,
28
+ vdd: float,
29
+ source: bool,
30
+ ) -> int:
31
+ """Spawn ``cmd`` with the DUT powered, optionally writing the trace to ``out``.
32
+
33
+ Returns the child's exit code so the caller can forward it.
34
+ """
35
+ if not cmd:
36
+ typer.echo("ppk2: run requires a command after `--`", err=True)
37
+ return 2
38
+
39
+ mv = vdd_to_mv(vdd)
40
+ device = resolve_device(serial, port)
41
+ mode = Mode.SOURCE if source else Mode.AMPERE
42
+
43
+ sys.stderr.write(f"opening session ({MODE_LABELS[mode]} mode, vdd={mv} mV)\n")
44
+ sys.stderr.flush()
45
+
46
+ trace: TraceFile | None = None
47
+ try:
48
+ # SIGTERM/SIGHUP -> SystemExit: a kill or closed terminal unwinds
49
+ # this stack so the session tears down and the file is completed.
50
+ with signals_to_systemexit("SIGTERM", "SIGHUP"), Session.open(device) as session:
51
+ if out is not None:
52
+ # Opened once the PPK2 answers: a run that cannot start
53
+ # leaves an earlier file of the same name alone.
54
+ out.parent.mkdir(parents=True, exist_ok=True)
55
+ trace = TraceFile(out)
56
+ session.set_mode(mode)
57
+ session.set_source_voltage(mv)
58
+ session.start_measuring()
59
+ session.power_on()
60
+ session.drop_pending_backlog()
61
+
62
+ stop_event = threading.Event()
63
+ reader_thread = threading.Thread(
64
+ target=_drain_samples,
65
+ args=(session, trace, stop_event),
66
+ name="ppk2-capture",
67
+ daemon=True,
68
+ )
69
+ reader_thread.start()
70
+
71
+ try:
72
+ exit_code = spawn_and_wait(cmd)
73
+ finally:
74
+ stop_event.set()
75
+ reader_thread.join(timeout=5.0)
76
+
77
+ with suppress(Exception):
78
+ session.power_off()
79
+ with suppress(Exception):
80
+ session.stop_measuring()
81
+ finally:
82
+ if trace is not None:
83
+ trace.close()
84
+
85
+ sys.stderr.write(f"child exit code: {exit_code}\n")
86
+ return exit_code
87
+
88
+
89
+ def spawn_and_wait(cmd: list[str]) -> int:
90
+ """Run ``cmd`` in its own session, forward signals, return its exit code.
91
+
92
+ In its own process group the child does not get the terminal's
93
+ Ctrl-C: this wrapper does, forwards ``SIGINT`` to the child's group,
94
+ waits, and returns its code. Otherwise both would race for the same
95
+ signal and the PPK2 teardown could interleave with the child's
96
+ shutdown.
97
+
98
+ A missing executable returns 127 and a signal-killed child
99
+ ``128 + N``, as a shell would. When this wrapper is terminated
100
+ (``SystemExit`` from SIGTERM or SIGHUP), the child's group gets
101
+ SIGTERM, then SIGKILL after ``_CHILD_GRACE_S``.
102
+ """
103
+ try:
104
+ proc = subprocess.Popen(cmd, start_new_session=True)
105
+ except FileNotFoundError:
106
+ sys.stderr.write(f"error: command not found: {cmd[0]}\n")
107
+ sys.stderr.flush()
108
+ return 127
109
+ try:
110
+ return _shell_exit_code(proc.wait())
111
+ except KeyboardInterrupt:
112
+ with suppress(ProcessLookupError):
113
+ os.killpg(os.getpgid(proc.pid), signal.SIGINT)
114
+ return _shell_exit_code(proc.wait())
115
+ except SystemExit:
116
+ # SIGTERM or SIGHUP to this wrapper: the child must not outlive
117
+ # the power it runs on.
118
+ with suppress(ProcessLookupError):
119
+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
120
+ try:
121
+ proc.wait(timeout=_CHILD_GRACE_S)
122
+ except subprocess.TimeoutExpired:
123
+ with suppress(ProcessLookupError):
124
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
125
+ proc.wait()
126
+ raise
127
+
128
+
129
+ def _shell_exit_code(returncode: int) -> int:
130
+ """Map ``Popen.wait()``'s ``-N`` (killed by signal N) to shell-style ``128 + N``."""
131
+ return 128 - returncode if returncode < 0 else returncode
132
+
133
+
134
+ def _drain_samples(
135
+ session: Session,
136
+ trace: TraceFile | None,
137
+ stop_event: threading.Event,
138
+ ) -> None:
139
+ """Run ``Session.capture`` until ``stop_event`` is set; write to ``trace`` if given.
140
+
141
+ The stream is drained even when nothing is written: the firmware
142
+ cannot pause it. A serial failure is reported on stderr, never
143
+ swallowed: a dead reader truncates the trace and leaves the stream
144
+ undrained, and the operator needs to know.
145
+ """
146
+
147
+ def emit(s: Sample) -> bool:
148
+ if stop_event.is_set():
149
+ return False
150
+ if trace is not None:
151
+ # Real values pass through the app's 0.2 µA clamp first.
152
+ trace.add(noise_floor(s.current_micro_amps), s.logic)
153
+ return True
154
+
155
+ try:
156
+ session.capture(emit, keep_going=lambda: not stop_event.is_set())
157
+ except Exception as exc:
158
+ sys.stderr.write(
159
+ f"ppk2: capture reader stopped ({exc}): the trace is incomplete "
160
+ "and the stream is no longer being drained\n"
161
+ )
162
+ sys.stderr.flush()
ppk2/cli/csv.py ADDED
@@ -0,0 +1,67 @@
1
+ """CSV output in the 11-column format of Nordic's Power Profiler app.
2
+
3
+ Timestamp(ms),Current(uA),D0-D7,D0,D1,D2,D3,D4,D5,D6,D7
4
+ 0,2.846,10000000,1,0,0,0,0,0,0,0
5
+ 0.01,2.715,10000000,1,0,0,0,0,0,0,0
6
+
7
+ - The timestamp is ``%.2f`` with trailing zeros and a trailing point
8
+ trimmed: ``0``, ``0.01``, ``0.1``, ``10``.
9
+ - ``D0-D7`` is an 8-character bit string with **D0 leftmost**.
10
+ - The ``D0``..``D7`` columns repeat each bit as 0 or 1.
11
+ """
12
+
13
+ from math import isfinite
14
+ from typing import TextIO
15
+
16
+ import typer
17
+
18
+ from ppk2.client.session import VOLTAGE_LIMIT_HARDWARE_MAX_MV, VOLTAGE_LIMIT_HARDWARE_MIN_MV
19
+
20
+ CSV_HEADER = "Timestamp(ms),Current(uA),D0-D7,D0,D1,D2,D3,D4,D5,D6,D7"
21
+
22
+
23
+ def noise_floor(current_ua: float) -> float:
24
+ """The noise-floor clamp of Nordic's app: anything below 0.2 µA becomes 0.
25
+
26
+ As the app does, negative noise included. It applies before both
27
+ the file and the running mean. NaN (a lost sample) passes through.
28
+ """
29
+ return 0.0 if current_ua < 0.2 else current_ua
30
+
31
+
32
+ def fmt_ts(t_ms: float) -> str:
33
+ """Format a millisecond timestamp the way Nordic's app does.
34
+
35
+ ``%.2f``, then trailing zeros and a trailing point trimmed, so the
36
+ column matches the app's export character for character.
37
+ """
38
+ s = f"{t_ms:.2f}"
39
+ trimmed = s.rstrip("0").rstrip(".")
40
+ return trimmed if trimmed else "0"
41
+
42
+
43
+ def fmt_logic_d0d7(logic: int) -> str:
44
+ """Format the logic byte as the app's 8-character ``D0-D7`` field, D0 leftmost."""
45
+ return "".join("1" if (logic >> i) & 1 else "0" for i in range(8))
46
+
47
+
48
+ def write_csv_row(out: TextIO, t_ms: float, current_ua: float, logic: int) -> None:
49
+ """Write one row in the 11-column format.
50
+
51
+ ``TraceFile`` turns a lost sample (NaN) into 0.2 µA before it gets here.
52
+ """
53
+ ts = fmt_ts(t_ms)
54
+ d_str = fmt_logic_d0d7(logic)
55
+ bits = ",".join(str((logic >> i) & 1) for i in range(8))
56
+ out.write(f"{ts},{current_ua:.3f},{d_str},{bits}\n")
57
+
58
+
59
+ def vdd_to_mv(vdd: float) -> int:
60
+ """Convert ``--vdd`` volts to millivolts, kept within the regulator's 800 to 5,000 mV.
61
+
62
+ Raises:
63
+ typer.BadParameter: If ``vdd`` is not a finite number.
64
+ """
65
+ if not isfinite(vdd):
66
+ raise typer.BadParameter(f"{vdd} is not a voltage", param_hint="--vdd")
67
+ return max(VOLTAGE_LIMIT_HARDWARE_MIN_MV, min(VOLTAGE_LIMIT_HARDWARE_MAX_MV, round(vdd * 1000)))
ppk2/cli/main.py ADDED
@@ -0,0 +1,276 @@
1
+ """The ``ppk2`` Typer app and its error mapping.
2
+
3
+ ``main`` is the entry point of the ``ppk2`` binary and of
4
+ ``python -m ppk2``. It wraps the app so that the expected failures (no
5
+ device, wedged handshake, serial I/O) exit with a one-line message
6
+ instead of a traceback.
7
+ """
8
+
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Annotated
12
+
13
+ import serial
14
+ import typer
15
+
16
+ from ppk2 import DiscoveryError, SessionError
17
+ from ppk2.cli.commands import capture as _capture
18
+ from ppk2.cli.commands import convert as _convert
19
+ from ppk2.cli.commands import discover as _discover
20
+ from ppk2.cli.commands import list_devices as _list_devices
21
+ from ppk2.cli.commands import metadata as _metadata
22
+ from ppk2.cli.commands import power as _power
23
+ from ppk2.cli.commands import run as _run
24
+
25
+ app = typer.Typer(
26
+ name="ppk2",
27
+ help="Command-line frontend for Nordic's Power Profiler Kit II.",
28
+ no_args_is_help=True,
29
+ add_completion=False,
30
+ )
31
+
32
+ _SerialOption = Annotated[
33
+ str | None,
34
+ typer.Option(
35
+ "--serial",
36
+ help="USB serial number of one PPK2. Needed when several are attached.",
37
+ ),
38
+ ]
39
+ _PortOption = Annotated[
40
+ str | None,
41
+ typer.Option(
42
+ "--port",
43
+ help=(
44
+ "Path of the PPK2's data port, for example /dev/cu.usbmodemA1B2C3D4E5F62. "
45
+ "Skips the search for it."
46
+ ),
47
+ ),
48
+ ]
49
+ _VddOption = Annotated[
50
+ float,
51
+ typer.Option(
52
+ "--vdd",
53
+ help=(
54
+ "DUT supply voltage in volts. Source meter mode: what the PPK2 "
55
+ "outputs. Ampere meter mode: only feeds the calibration, so give "
56
+ "the DUT's real supply voltage. Kept between 0.8 and 5.0."
57
+ ),
58
+ ),
59
+ ]
60
+ _SourceOption = Annotated[
61
+ bool,
62
+ typer.Option(
63
+ "--source",
64
+ help=(
65
+ "Use Source meter mode (the PPK2 supplies the DUT) instead of "
66
+ "the default, Ampere meter mode."
67
+ ),
68
+ ),
69
+ ]
70
+
71
+
72
+ @app.command()
73
+ def version() -> None:
74
+ """Print the package version and exit."""
75
+ from ppk2 import __version__
76
+
77
+ typer.echo(__version__)
78
+
79
+
80
+ @app.command()
81
+ def discover(serial: _SerialOption = None, port: _PortOption = None) -> None:
82
+ """Print the path of the PPK2's data port."""
83
+ _discover.discover(serial, port)
84
+
85
+
86
+ @app.command("list")
87
+ def list_(
88
+ mask_serial: Annotated[
89
+ bool,
90
+ typer.Option("--mask-serial", help="Print only the last four characters of each serial."),
91
+ ] = False,
92
+ ) -> None:
93
+ """List connected PPK2s and mark each serial port: data port, idle or busy."""
94
+ _list_devices.list_devices(mask_serial)
95
+
96
+
97
+ @app.command()
98
+ def metadata(serial: _SerialOption = None, port: _PortOption = None) -> None:
99
+ """Print the per-device calibration coefficients."""
100
+ _metadata.metadata(serial, port)
101
+
102
+
103
+ @app.command()
104
+ def power(
105
+ state: Annotated[
106
+ _power.PowerState,
107
+ typer.Argument(case_sensitive=False, help="`on` powers the DUT; `off` cuts its power."),
108
+ ],
109
+ serial: _SerialOption = None,
110
+ port: _PortOption = None,
111
+ hold: Annotated[
112
+ bool,
113
+ typer.Option("--hold", help="Keep the power on until Ctrl-C (only meaningful with `on`)."),
114
+ ] = False,
115
+ vdd: _VddOption = 3.3,
116
+ source: _SourceOption = False,
117
+ ) -> None:
118
+ """Switch power to the DUT on or off, like the app's Enable power output.
119
+
120
+ Power lasts only while the command runs: use --hold to keep it on.
121
+ """
122
+ _power.power(serial, port, state, hold, vdd, source)
123
+
124
+
125
+ @app.command()
126
+ def capture(
127
+ out: Annotated[
128
+ Path,
129
+ typer.Option(
130
+ "--out",
131
+ "-o",
132
+ help="Output path: a CSV, or a Power Profiler session file if it ends in .ppk2.",
133
+ ),
134
+ ],
135
+ serial: _SerialOption = None,
136
+ port: _PortOption = None,
137
+ seconds: Annotated[
138
+ float,
139
+ typer.Option("--seconds", "-s", help="Capture duration in seconds."),
140
+ ] = 30.0,
141
+ vdd: _VddOption = 3.3,
142
+ source: _SourceOption = False,
143
+ user_gain: Annotated[
144
+ list[str] | None,
145
+ typer.Option(
146
+ "--user-gain",
147
+ help=(
148
+ "Per-range user gain override, RANGE:GAIN, with RANGE from 0 to 4 "
149
+ "(the app numbers the ranges 1 to 5). Repeatable; "
150
+ "for example --user-gain 2:1.05 --user-gain 4:0.98. GAIN from 0.9 to 1.1. "
151
+ "Applied on the computer: nothing is sent to the PPK2."
152
+ ),
153
+ ),
154
+ ] = None,
155
+ ) -> None:
156
+ """Capture the trace to a CSV file (the app's export format) or to a .ppk2 file."""
157
+ _capture.capture(serial, port, out, seconds, vdd, source, user_gain or ())
158
+
159
+
160
+ @app.command()
161
+ def convert(
162
+ src: Annotated[Path, typer.Argument(help="CSV capture, plain or .gz.")],
163
+ dst: Annotated[Path, typer.Argument(help="Output .ppk2 path.")],
164
+ ) -> None:
165
+ """Convert a CSV capture to a .ppk2 file for Nordic's Power Profiler app."""
166
+ _convert.convert(src, dst)
167
+
168
+
169
+ @app.command(
170
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
171
+ )
172
+ def run(
173
+ ctx: typer.Context,
174
+ serial: _SerialOption = None,
175
+ port: _PortOption = None,
176
+ out: Annotated[
177
+ Path | None,
178
+ typer.Option(
179
+ "--out",
180
+ "-o",
181
+ help="Optional trace output: a CSV, or a session file if the name ends in .ppk2.",
182
+ ),
183
+ ] = None,
184
+ vdd: _VddOption = 3.3,
185
+ source: _SourceOption = False,
186
+ ) -> None:
187
+ """Run a command with the DUT powered, optionally capturing the trace.
188
+
189
+ The command goes after `--`: ppk2 run --source --vdd 3.3 -- west flash
190
+ """
191
+ cmd = list(ctx.args)
192
+ exit_code = _run.run(serial, port, cmd, out, vdd, source)
193
+ if exit_code != 0:
194
+ raise typer.Exit(code=exit_code)
195
+
196
+
197
+ # ─── top-level error mapping ────────────────────────────────────────────
198
+
199
+ #: Hint appended when a serial failure carries errno 16 (EBUSY): the
200
+ #: port is held by another process, in practice Nordic's app.
201
+ _ERRNO16_HINT = " (close the nRF Connect Power Profiler, or whatever else holds the port)"
202
+
203
+
204
+ def errno16_in_chain(exc: BaseException) -> bool:
205
+ """Whether ``exc`` or anything in its cause/context chain is EBUSY (errno 16)."""
206
+ seen: set[int] = set()
207
+ current: BaseException | None = exc
208
+ while current is not None and id(current) not in seen:
209
+ seen.add(id(current))
210
+ if isinstance(current, OSError) and current.errno == 16:
211
+ return True
212
+ current = current.__cause__ or current.__context__
213
+ return False
214
+
215
+
216
+ def dispatch(argv: list[str] | None = None) -> int:
217
+ """Run the app and map failures to an exit code and one line on stderr.
218
+
219
+ Typer keeps its own handling of usage errors (exit 2) and of Ctrl-C
220
+ inside a command (exit 130): those arrive here as ``SystemExit`` and
221
+ pass through. Added here, so that the library's expected failures
222
+ never show a traceback:
223
+
224
+ - ``DiscoveryError`` / ``SessionError`` -> ``error: …``, exit 1.
225
+ - Serial I/O errors -> ``error: serial I/O failed …``, exit 1.
226
+ - Either gets a close-the-Power-Profiler hint when errno 16 (the port
227
+ is held by another process) is in the cause chain.
228
+
229
+ A Ctrl-C during a capture does not come through here: the capture
230
+ command handles it itself (CSV flushed, exit 130).
231
+
232
+ Args:
233
+ argv: Arguments without the program name; ``sys.argv[1:]`` when
234
+ ``None``.
235
+
236
+ Returns:
237
+ The process exit code.
238
+ """
239
+ try:
240
+ app(args=argv, prog_name="ppk2")
241
+ except SystemExit as exc:
242
+ # Typer's standalone exit path: success (0), usage errors (2),
243
+ # typer.Exit codes, and Ctrl-C inside a command (130).
244
+ return _systemexit_code(exc)
245
+ except KeyboardInterrupt:
246
+ # An interrupt outside a command: Typer handles those inside.
247
+ sys.stderr.write("interrupted\n")
248
+ return 130
249
+ except (DiscoveryError, SessionError) as exc:
250
+ hint = _ERRNO16_HINT if errno16_in_chain(exc) else ""
251
+ sys.stderr.write(f"error: {exc}{hint}\n")
252
+ return 1
253
+ except serial.SerialException as exc:
254
+ hint = _ERRNO16_HINT if errno16_in_chain(exc) else ""
255
+ sys.stderr.write(f"error: serial I/O failed ({exc}){hint}\n")
256
+ return 1
257
+ except OSError as exc:
258
+ # The output file: a folder that cannot be written, a full disk.
259
+ sys.stderr.write(f"error: {exc.filename or 'output'}: {exc.strerror or exc}\n")
260
+ return 1
261
+ return 0
262
+
263
+
264
+ def _systemexit_code(exc: SystemExit) -> int:
265
+ """Normalize ``SystemExit.code`` to an int, mirroring ``sys.exit`` semantics."""
266
+ if exc.code is None:
267
+ return 0
268
+ if isinstance(exc.code, int):
269
+ return exc.code
270
+ sys.stderr.write(f"{exc.code}\n")
271
+ return 1
272
+
273
+
274
+ def main() -> None:
275
+ """Console-script entry point: run ``dispatch`` and exit with its code."""
276
+ raise SystemExit(dispatch())
ppk2/cli/ppk2file.py ADDED
@@ -0,0 +1,179 @@
1
+ """``.ppk2`` session files, as saved and loaded by Nordic's Power Profiler app.
2
+
3
+ A ``.ppk2`` file is a zip of three files (the app's README, "File
4
+ format", and its source at v4.4.1):
5
+
6
+ - ``session.raw``: 6 bytes per sample. The current in µA as a
7
+ little-endian float32, then a big-endian uint16 with two bits per
8
+ digital channel (``01`` low, ``10`` high), D0 in the lowest pair.
9
+ - ``minimap.raw``: JSON min/max envelope of the whole trace, at most
10
+ 10 000 points; the app draws its overview strip from it.
11
+ - ``metadata.json``: sample rate and format version.
12
+
13
+ Nordic gives no guarantee that the format stays the same.
14
+ """
15
+
16
+ import errno
17
+ import json
18
+ import struct
19
+ import sys
20
+ import zipfile
21
+ from math import isnan
22
+ from pathlib import Path
23
+
24
+ #: Sample rates the app can replay.
25
+ SAMPLE_RATES = (1, 10, 100, 1_000, 10_000, 100_000)
26
+
27
+ _FORMAT_VERSION = 2
28
+ _MINIMAP_POINTS = 10_000
29
+ _MINIMAP_FLOOR_NA = 200.0 # the app floors its overview there, for a log axis
30
+
31
+
32
+ def _bit_pairs(logic: int) -> int:
33
+ """Spread 8 logic bits over 16: ``01`` for a low channel, ``10`` for a high one."""
34
+ return sum(1 << (2 * ch + ((logic >> ch) & 1)) for ch in range(8))
35
+
36
+
37
+ # One frame is the current then the bit pairs. The pairs are big-endian
38
+ # on disk, so the table stores them byte-swapped for the little-endian pack.
39
+ _FRAME = struct.Struct("<fH")
40
+ _PAIRS = tuple(int.from_bytes(_bit_pairs(b).to_bytes(2, "big"), "little") for b in range(256))
41
+
42
+
43
+ class _Minimap:
44
+ """Min/max envelope that halves its resolution each time it fills up.
45
+
46
+ Keeps the same books as the app's own overview buffer, so the saved
47
+ state is what the app would have written for the same samples.
48
+ """
49
+
50
+ def __init__(self) -> None:
51
+ self._lo: list[list[float]] = [] # [time in µs, current in nA]
52
+ self._hi: list[list[float]] = []
53
+ self._per_point = 1 # samples folded into each point
54
+ self._in_last = 0 # samples in the newest point so far
55
+
56
+ def add(self, current_ua: float, t_us: float) -> None:
57
+ if self._in_last == 0:
58
+ self._lo.append([t_us, sys.float_info.max])
59
+ self._hi.append([t_us, -sys.float_info.max])
60
+ lo, hi = self._lo[-1], self._hi[-1]
61
+
62
+ self._in_last += 1
63
+ weight = 1.0 / self._in_last
64
+ lo[0] = hi[0] = t_us * weight + lo[0] * (1.0 - weight)
65
+
66
+ na = current_ua * 1000.0
67
+ if na < _MINIMAP_FLOOR_NA:
68
+ na = _MINIMAP_FLOOR_NA
69
+ if not isnan(na): # a lost sample has no value to fold in
70
+ lo[1] = min(lo[1], na)
71
+ hi[1] = max(hi[1], na)
72
+
73
+ if self._in_last == self._per_point:
74
+ self._in_last = 0
75
+ if len(self._lo) == _MINIMAP_POINTS:
76
+ self._fold()
77
+
78
+ def _fold(self) -> None:
79
+ """Merge neighbouring points pairwise."""
80
+ self._per_point *= 2
81
+ self._lo = [
82
+ [(a[0] + b[0]) / 2, min(a[1], b[1])]
83
+ for a, b in zip(self._lo[::2], self._lo[1::2], strict=True)
84
+ ]
85
+ self._hi = [
86
+ [(a[0] + b[0]) / 2, max(a[1], b[1])]
87
+ for a, b in zip(self._hi[::2], self._hi[1::2], strict=True)
88
+ ]
89
+
90
+ def to_json(self) -> dict[str, object]:
91
+ return {
92
+ "lastElementFoldCount": self._in_last,
93
+ "data": {
94
+ "length": len(self._lo),
95
+ "min": [{"x": x, "y": y} for x, y in self._lo],
96
+ "max": [{"x": x, "y": y} for x, y in self._hi],
97
+ },
98
+ "maxNumberOfElements": _MINIMAP_POINTS,
99
+ "numberOfTimesToFold": self._per_point,
100
+ }
101
+
102
+
103
+ class Ppk2FileWriter:
104
+ """Write a stream of samples to a ``.ppk2`` file; use as a context manager.
105
+
106
+ Leaving the block writes the file, even on an exception: an
107
+ interrupted capture still yields a valid, shorter session. The file
108
+ appears only once it is complete, and not at all for a capture with
109
+ no sample. Until then the frames are in ``<name>.frames`` next to
110
+ it, and stay there if the file cannot be completed.
111
+ """
112
+
113
+ def __init__(self, path: Path, samples_per_second: int = 100_000) -> None:
114
+ if samples_per_second not in SAMPLE_RATES:
115
+ raise ValueError(f"unsupported sample rate {samples_per_second} (app: {SAMPLE_RATES})")
116
+ self._path = path
117
+ self._rate = samples_per_second
118
+ # Frames go to a scratch file first, so the zip knows its size up front.
119
+ self._frames_path = path.with_name(path.name + ".frames")
120
+ if self._frames_path.exists():
121
+ # What a run that failed left behind is all that is left of
122
+ # it: not overwritten.
123
+ raise FileExistsError(
124
+ errno.EEXIST,
125
+ "left by a run that did not finish: move or delete it",
126
+ str(self._frames_path),
127
+ )
128
+ self._raw = self._frames_path.open("wb")
129
+ self._minimap = _Minimap()
130
+ self._closed = False
131
+ #: Samples written so far, lost ones included.
132
+ self.count = 0
133
+
134
+ def __enter__(self) -> "Ppk2FileWriter":
135
+ return self
136
+
137
+ def __exit__(self, *_args: object) -> None:
138
+ self.close()
139
+
140
+ def add(self, current_ua: float, logic: int) -> None:
141
+ """Append one sample. NaN is stored as it is: TraceFile replaces it before."""
142
+ if current_ua < 0.2:
143
+ current_ua = 0.0 # the app reads anything below 0.2 µA as zero
144
+ self._raw.write(_FRAME.pack(current_ua, _PAIRS[logic & 0xFF]))
145
+ self._minimap.add(current_ua, self.count * 1e6 / self._rate)
146
+ self.count += 1
147
+
148
+ def discard(self) -> None:
149
+ """Give up: write no file and drop the frames."""
150
+ if self._closed:
151
+ return
152
+ self._closed = True
153
+ self._raw.close()
154
+ self._frames_path.unlink(missing_ok=True)
155
+
156
+ def close(self) -> None:
157
+ """Zip the three files, move the result into place, remove the scratch file."""
158
+ if self._closed:
159
+ return
160
+ self._closed = True
161
+ self._raw.close()
162
+ if self.count == 0:
163
+ self._frames_path.unlink(missing_ok=True)
164
+ return
165
+ metadata = {
166
+ "metadata": {"samplesPerSecond": self._rate},
167
+ "formatVersion": _FORMAT_VERSION,
168
+ }
169
+ partial = self._path.with_name(self._path.name + ".part")
170
+ try:
171
+ with zipfile.ZipFile(partial, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
172
+ zf.write(self._frames_path, "session.raw")
173
+ zf.writestr("minimap.raw", json.dumps(self._minimap.to_json()))
174
+ zf.writestr("metadata.json", json.dumps(metadata))
175
+ partial.replace(self._path)
176
+ except BaseException:
177
+ partial.unlink(missing_ok=True) # the frames file stays: nothing is lost
178
+ raise
179
+ self._frames_path.unlink(missing_ok=True)