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/cli/signals.py ADDED
@@ -0,0 +1,46 @@
1
+ """Route termination signals to ``SystemExit`` so the session teardown runs.
2
+
3
+ ``kill <pid>`` (SIGTERM) or a closed terminal (SIGHUP) would otherwise
4
+ end the process without unwinding the ``with`` stack: no
5
+ ``AVERAGE_STOP`` is sent and the PPK2 keeps streaming into a dead
6
+ session, which wedges the next open. Raising ``SystemExit`` from the
7
+ handler unwinds the context managers instead, same as a Ctrl-C stop.
8
+ """
9
+
10
+ import signal
11
+ from collections.abc import Callable, Generator
12
+ from contextlib import contextmanager, suppress
13
+ from types import FrameType
14
+
15
+ # Matches `signal.signal`'s handler union: the SIG_DFL / SIG_IGN
16
+ # sentinels or a Python callable.
17
+ _SignalHandler = Callable[[int, FrameType | None], object] | int | None
18
+
19
+
20
+ @contextmanager
21
+ def signals_to_systemexit(*names: str) -> Generator[None, None, None]:
22
+ """Route the named signals (e.g. ``"SIGTERM"``) to ``SystemExit`` for the block.
23
+
24
+ The exit code is the conventional ``128 + signum``; the previous
25
+ handlers come back on exit. A signal that cannot be installed is
26
+ skipped: a name this OS lacks (no ``SIGHUP`` on Windows), or a call
27
+ off the main thread, where ``signal.signal`` raises ``ValueError``.
28
+ """
29
+
30
+ def _raise(signum: int, _frame: FrameType | None) -> None:
31
+ raise SystemExit(128 + signum)
32
+
33
+ previous: dict[int, _SignalHandler] = {}
34
+ for name in names:
35
+ sig = getattr(signal, name, None)
36
+ if sig is None:
37
+ continue # not on this OS
38
+ # signal.signal raises ValueError off the main thread.
39
+ with suppress(ValueError):
40
+ previous[sig] = signal.signal(sig, _raise)
41
+ try:
42
+ yield
43
+ finally:
44
+ for sig, handler in previous.items():
45
+ with suppress(ValueError, OSError):
46
+ signal.signal(sig, handler)
ppk2/cli/trace.py ADDED
@@ -0,0 +1,60 @@
1
+ """The file ``capture`` and ``run`` write their samples to."""
2
+
3
+ from math import isnan
4
+ from pathlib import Path
5
+ from typing import TextIO
6
+
7
+ from ppk2.cli.csv import CSV_HEADER, write_csv_row
8
+ from ppk2.cli.ppk2file import Ppk2FileWriter
9
+
10
+ SAMPLE_RATE_HZ = 100_000
11
+
12
+ #: What a lost sample is recorded as, in µA, with its digital inputs
13
+ #: low: the value Nordic's app records for it.
14
+ #: A made-up reading, which pulls sums and means towards 0.2 µA.
15
+ LOST_SAMPLE_UA = 0.2
16
+ _SAMPLE_PERIOD_MS = 1000.0 / SAMPLE_RATE_HZ # 0.01
17
+
18
+
19
+ class TraceFile:
20
+ """A capture on disk: a ``.ppk2`` session file, or the 11-column CSV.
21
+
22
+ The name decides: ``.ppk2``, in any case, or anything else for CSV.
23
+ A lost sample (NaN) keeps its place in time and is recorded as
24
+ ``LOST_SAMPLE_UA`` with its digital inputs low, as Nordic's app
25
+ records it.
26
+ """
27
+
28
+ def __init__(self, path: Path) -> None:
29
+ self.is_ppk2 = path.suffix.lower() == ".ppk2"
30
+ self._ppk2 = Ppk2FileWriter(path) if self.is_ppk2 else None
31
+ self._csv: TextIO | None = None
32
+ if self._ppk2 is None:
33
+ self._csv = path.open("w", encoding="utf-8")
34
+ self._csv.write(f"{CSV_HEADER}\n")
35
+ self._slot = 0
36
+
37
+ def __enter__(self) -> "TraceFile":
38
+ return self
39
+
40
+ def __exit__(self, *_args: object) -> None:
41
+ self.close()
42
+
43
+ def add(self, current_ua: float, logic: int) -> None:
44
+ """Append one sample; NaN marks a lost one."""
45
+ if isnan(current_ua):
46
+ current_ua, logic = LOST_SAMPLE_UA, 0
47
+ if self._ppk2 is not None:
48
+ self._ppk2.add(current_ua, logic)
49
+ elif self._csv is not None:
50
+ # From the sample index: a running sum of 0.01 drifts and,
51
+ # after some 40 minutes, repeats a timestamp.
52
+ write_csv_row(self._csv, self._slot * _SAMPLE_PERIOD_MS, current_ua, logic)
53
+ self._slot += 1
54
+
55
+ def close(self) -> None:
56
+ """Complete the file. Safe to call twice."""
57
+ if self._ppk2 is not None:
58
+ self._ppk2.close()
59
+ if self._csv is not None and not self._csv.closed:
60
+ self._csv.close()
@@ -0,0 +1,50 @@
1
+ """Sync host driver: port discovery and the session state machine.
2
+
3
+ Depends on ``ppk2.protocol`` and ``serial`` (pyserial).
4
+ """
5
+
6
+ from ppk2.client.discovery import (
7
+ DEFAULT_DISCOVERY_TIMEOUT_S,
8
+ Ambiguous,
9
+ DataPortNotFound,
10
+ DiscoveryError,
11
+ NotFound,
12
+ PortInfo,
13
+ Ppk2Listing,
14
+ find_ppk2,
15
+ find_ppk2_by_serial,
16
+ list_ppk2s,
17
+ )
18
+ from ppk2.client.session import (
19
+ USER_GAIN_MAX,
20
+ USER_GAIN_MIN,
21
+ VOLTAGE_LIMIT_HARDWARE_MAX_MV,
22
+ VOLTAGE_LIMIT_HARDWARE_MIN_MV,
23
+ HandshakeFailed,
24
+ Mode,
25
+ SerialIOError,
26
+ Session,
27
+ SessionError,
28
+ )
29
+
30
+ __all__ = [
31
+ "DEFAULT_DISCOVERY_TIMEOUT_S",
32
+ "USER_GAIN_MAX",
33
+ "USER_GAIN_MIN",
34
+ "VOLTAGE_LIMIT_HARDWARE_MAX_MV",
35
+ "VOLTAGE_LIMIT_HARDWARE_MIN_MV",
36
+ "Ambiguous",
37
+ "DataPortNotFound",
38
+ "DiscoveryError",
39
+ "HandshakeFailed",
40
+ "Mode",
41
+ "NotFound",
42
+ "PortInfo",
43
+ "Ppk2Listing",
44
+ "SerialIOError",
45
+ "Session",
46
+ "SessionError",
47
+ "find_ppk2",
48
+ "find_ppk2_by_serial",
49
+ "list_ppk2s",
50
+ ]
@@ -0,0 +1,515 @@
1
+ """PPK2 port discovery.
2
+
3
+ A PPK2 shows up as two USB serial ports with identical
4
+ descriptors; only one, the data port, speaks the protocol. Discovery:
5
+
6
+ 1. List the serial ports and keep those with the PPK2's USB VID/PID
7
+ (Nordic ``0x1915`` / ``0xC00A``).
8
+ 2. Group them by USB serial number. More than one device means the
9
+ caller must pick one with ``find_ppk2_by_serial``.
10
+ 3. Find the data port by probing, lowest path first (the usual hit):
11
+ open, stop any stream, request the metadata, wait for ``END``. The
12
+ data port answers; the other port opens but stays silent; a port
13
+ held by another process (typically Nordic's Power Profiler app)
14
+ does not open at all.
15
+ 4. If nothing answered, probe once more with a reset: the last resort
16
+ for a PPK2 the plain probe cannot reach.
17
+
18
+ The probe runs inside the polling loop, so a device that has only half
19
+ enumerated is probed again on the next tick.
20
+ """
21
+
22
+ from collections import defaultdict
23
+ from collections.abc import Callable
24
+ from contextlib import suppress
25
+ from dataclasses import dataclass
26
+ from time import monotonic, sleep
27
+ from typing import Literal
28
+
29
+ import serial
30
+ import serial.tools.list_ports
31
+
32
+ from ppk2.client.session import flush_input, read_until_end
33
+ from ppk2.protocol import MetadataError, Opcode, parse_metadata
34
+
35
+ #: Default polling budget for ``find_ppk2``, in seconds: long enough for
36
+ #: a PPK2 to come back on USB after a ``RESET``.
37
+ DEFAULT_DISCOVERY_TIMEOUT_S = 3.0
38
+
39
+ #: What a probe found on one port: the data port answers the metadata
40
+ #: request, the other port is idle, a port held elsewhere is busy.
41
+ PortStatus = Literal["data", "idle", "busy"]
42
+
43
+ #: A port-probe function: ``probe_port`` or a test double.
44
+ ProbeFn = Callable[[str], PortStatus]
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class PortInfo:
49
+ """A PPK2 and the port to talk to it on.
50
+
51
+ Attributes:
52
+ device: Device path or COM name
53
+ (``/dev/cu.usbmodemA1B2C3D4E5F62`` on macOS, ``COM7`` on
54
+ Windows).
55
+ usb_serial: USB serial number, the stable handle when several
56
+ PPK2s are plugged in.
57
+ """
58
+
59
+ device: str
60
+ usb_serial: str
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Ppk2Listing:
65
+ """One connected PPK2 and the status of each of its ports.
66
+
67
+ Attributes:
68
+ usb_serial: USB serial number of the device.
69
+ ports: Its port paths, sorted.
70
+ data_port: The path that answered the probe, or ``None`` when none
71
+ did (usually another process holds the data port).
72
+ statuses: Probe result per path. Paths left unprobed because an
73
+ earlier one already answered are reported ``"idle"``.
74
+ """
75
+
76
+ usb_serial: str
77
+ ports: tuple[str, ...]
78
+ data_port: str | None
79
+ statuses: dict[str, PortStatus]
80
+
81
+
82
+ class DiscoveryError(Exception):
83
+ """Base class for port discovery failures."""
84
+
85
+
86
+ class NotFound(DiscoveryError):
87
+ """No PPK2 (USB ``0x1915:0xC00A``) on the bus, or none with the serial asked for."""
88
+
89
+ def __init__(self, message: str | None = None) -> None:
90
+ super().__init__(message or "no PPK2 found (USB 1915:C00A): plug one in or check the cable")
91
+
92
+
93
+ class Ambiguous(DiscoveryError):
94
+ """More than one PPK2 on the bus; ``count`` is how many.
95
+
96
+ Pick one with ``find_ppk2_by_serial``.
97
+ """
98
+
99
+ def __init__(self, count: int) -> None:
100
+ super().__init__(
101
+ f"{count} physical PPK2 devices found; pass --serial <usb-serial> to pick one"
102
+ )
103
+ self.count = count
104
+
105
+
106
+ class DataPortNotFound(DiscoveryError):
107
+ """A PPK2 enumerated but no port answered the probe; ``paths`` lists them.
108
+
109
+ Usually another process holds the data port: Nordic's Power Profiler
110
+ app keeps it open while it runs.
111
+ """
112
+
113
+ def __init__(self, paths: tuple[str, ...]) -> None:
114
+ super().__init__(
115
+ f"could not identify the PPK2 data port: none of {list(paths)} answered "
116
+ "GET_METADATA; close the nRF Connect Power Profiler if it is open, "
117
+ "or pass --port to select the port explicitly"
118
+ )
119
+ self.paths = paths
120
+
121
+
122
+ def find_ppk2(
123
+ *,
124
+ timeout_s: float = DEFAULT_DISCOVERY_TIMEOUT_S,
125
+ probe: ProbeFn | None = None,
126
+ ) -> PortInfo:
127
+ """Find the single PPK2 on the bus and return its data port.
128
+
129
+ Polls for up to ``timeout_s`` seconds, so that a PPK2
130
+ just plugged in, or coming back on USB, is found.
131
+
132
+ Args:
133
+ timeout_s: Polling budget in seconds; 0 for a single pass.
134
+ probe: Probe function to use instead of the real one (tests).
135
+
136
+ Raises:
137
+ NotFound: No PPK2 on the bus.
138
+ Ambiguous: More than one PPK2; raised at once, polling cannot
139
+ settle it.
140
+ DataPortNotFound: A PPK2 is there but no port answered in time.
141
+ """
142
+ return _poll_until_found(timeout_s, find_group_in, probe)
143
+
144
+
145
+ def find_ppk2_by_serial(
146
+ usb_serial: str,
147
+ *,
148
+ timeout_s: float = DEFAULT_DISCOVERY_TIMEOUT_S,
149
+ probe: ProbeFn | None = None,
150
+ ) -> PortInfo:
151
+ """Like ``find_ppk2``, for the PPK2 whose USB serial is exactly ``usb_serial``."""
152
+ return _poll_until_found(
153
+ timeout_s,
154
+ lambda ports: find_group_in_by_serial(ports, usb_serial),
155
+ probe,
156
+ )
157
+
158
+
159
+ def list_ppk2s(*, probe: ProbeFn | None = None) -> list[Ppk2Listing]:
160
+ """List connected PPK2s with the status of each port (``ppk2 list``).
161
+
162
+ Each device's ports are probed lowest path first, stopping at the data
163
+ port: the rest are then idle and left unprobed. When nothing answers,
164
+ every port is probed, which tells ``busy`` (held by another process)
165
+ from ``idle`` (silent).
166
+
167
+ Args:
168
+ probe: Probe function to use instead of the real one (tests).
169
+ """
170
+ quick, recover = resolve_probes(probe)
171
+ return build_listings(enumerate_ports(), quick, recover)
172
+
173
+
174
+ # ─── building blocks ───────────────────────────────────────────────────
175
+ #
176
+ # The pieces the functions above are made of. Importable, but not part
177
+ # of the public API.
178
+
179
+
180
+ #: Nordic Semiconductor's USB vendor ID.
181
+ PPK2_VID: int = 0x1915
182
+
183
+ #: PPK2's USB product ID.
184
+ PPK2_PID: int = 0xC00A
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class RawPort:
189
+ """The fields of a pyserial port entry that discovery uses."""
190
+
191
+ device: str
192
+ vid: int | None
193
+ pid: int | None
194
+ serial_number: str | None
195
+
196
+
197
+ def enumerate_ports() -> list[RawPort]:
198
+ """Snapshot the serial ports as ``RawPort`` rows."""
199
+ out: list[RawPort] = []
200
+ for port in serial.tools.list_ports.comports():
201
+ out.append(
202
+ RawPort(
203
+ device=port.device,
204
+ vid=port.vid,
205
+ pid=port.pid,
206
+ serial_number=port.serial_number,
207
+ )
208
+ )
209
+ return out
210
+
211
+
212
+ def looks_like_ppk2(port: RawPort) -> bool:
213
+ """Whether the port has the PPK2's USB VID/PID.
214
+
215
+ The same selector as Nordic's app, and more reliable than product
216
+ strings (empty on Windows, varying across firmware on Linux). Both
217
+ ports of a PPK2 match: telling them apart is the probe's job.
218
+ """
219
+ return port.vid == PPK2_VID and port.pid == PPK2_PID
220
+
221
+
222
+ def group_ppk2s(ports: list[RawPort]) -> dict[str, list[str]]:
223
+ """Group PPK2 candidates by USB serial number; drop entries with no serial."""
224
+ by_serial: dict[str, list[str]] = defaultdict(list)
225
+ for port in ports:
226
+ if not looks_like_ppk2(port):
227
+ continue
228
+ if port.serial_number is None:
229
+ continue
230
+ by_serial[port.serial_number].append(port.device)
231
+ return dict(by_serial)
232
+
233
+
234
+ def find_group_in(ports: list[RawPort]) -> tuple[str, tuple[str, ...]]:
235
+ """Pick the single PPK2's ``(usb_serial, sorted port paths)`` from ``ports``.
236
+
237
+ Raises:
238
+ NotFound: No PPK2-shaped device in ``ports``.
239
+ Ambiguous: More than one distinct USB serial.
240
+ """
241
+ groups = group_ppk2s(ports)
242
+ if not groups:
243
+ raise NotFound
244
+ if len(groups) > 1:
245
+ raise Ambiguous(len(groups))
246
+ serial_str, paths = next(iter(groups.items()))
247
+ return serial_str, tuple(sorted(paths))
248
+
249
+
250
+ def find_group_in_by_serial(ports: list[RawPort], usb_serial: str) -> tuple[str, tuple[str, ...]]:
251
+ """Pick ``(usb_serial, sorted port paths)`` for an exact USB-serial match.
252
+
253
+ Raises:
254
+ NotFound: No PPK2 with that serial in ``ports``.
255
+ """
256
+ groups = group_ppk2s(ports)
257
+ paths = groups.get(usb_serial)
258
+ if paths is None:
259
+ if not groups:
260
+ raise NotFound
261
+ raise NotFound(f"no PPK2 with serial {usb_serial}: attached {', '.join(sorted(groups))}")
262
+ return usb_serial, tuple(sorted(paths))
263
+
264
+
265
+ # ─── active data-port probe ────────────────────────────────────────────
266
+
267
+ _PROBE_BAUD = 115_200
268
+ _PROBE_READ_TIMEOUT_S = 0.1
269
+ _PROBE_SETTLE_S = 0.1 # let AVERAGE_STOP take effect before draining
270
+ _PROBE_DRAIN_S = 0.3 # budget for flushing a still-streaming backlog
271
+ _PROBE_METADATA_TIMEOUT_S = 1.0 # accumulate-until-END budget
272
+ _RECOVER_REENUM_S = 1.0 # ride out the post-RESET USB CDC re-enumeration
273
+ _RECOVER_OPEN_RETRY_S = 2.0 # ride out the post-kill CDC lock-release lag
274
+ _RECOVER_METADATA_TIMEOUT_S = 2.5 # mirror _METADATA_READ_TIMEOUT_S
275
+
276
+
277
+ def probe_port(device: str) -> PortStatus:
278
+ """Classify one port by probing it once, without ``RESET``.
279
+
280
+ Open, send ``AVERAGE_STOP`` (a live stream would garble the answer),
281
+ let it settle, drain the input, request the metadata and wait up to
282
+ ~1 s for a parseable response. The port is closed before returning.
283
+
284
+ Returns:
285
+ ``"data"`` if it answered with metadata, ``"idle"`` if it opened
286
+ but stayed silent (the other port), ``"busy"`` if it would not
287
+ open (almost always held by another process).
288
+ """
289
+ try:
290
+ # exclusive=True (POSIX flock): a port held by a lock-respecting
291
+ # process, such as a live capture from this package, classifies
292
+ # as busy instead of being opened a second time.
293
+ port = serial.Serial(
294
+ device,
295
+ baudrate=_PROBE_BAUD,
296
+ timeout=_PROBE_READ_TIMEOUT_S,
297
+ write_timeout=_PROBE_READ_TIMEOUT_S,
298
+ exclusive=True,
299
+ )
300
+ except (serial.SerialException, OSError):
301
+ return "busy"
302
+ try:
303
+ port.write(bytes([Opcode.AVERAGE_STOP.byte()]))
304
+ sleep(_PROBE_SETTLE_S)
305
+ flush_input(port)
306
+ _drain_input(port, _PROBE_DRAIN_S)
307
+ port.write(bytes([Opcode.GET_METADATA.byte()]))
308
+ buf = read_until_end(port, _PROBE_METADATA_TIMEOUT_S)
309
+ parse_metadata(buf)
310
+ except (OSError, MetadataError):
311
+ # SerialException and TimeoutError are both OSError: a port that
312
+ # opens but does not answer is the other port.
313
+ return "idle"
314
+ else:
315
+ return "data"
316
+ finally:
317
+ with suppress(serial.SerialException, OSError):
318
+ port.close()
319
+
320
+
321
+ def probe_port_recover(device: str) -> PortStatus:
322
+ """Probe one port with a reset first: the last resort after a plain probe.
323
+
324
+ ``RESET`` makes the device drop off USB and re-enumerate (~200-500 ms
325
+ on macOS), which kills the open port, so this takes two opens: stop +
326
+ ``RESET``, close, wait, reopen, then request the metadata with the
327
+ session's 2.5 s budget. The device path survives the re-enumeration
328
+ (it derives from the USB serial). Both opens retry for a while: right
329
+ after a killed session the CDC driver can refuse opens for a second
330
+ or two.
331
+
332
+ A ``RESET`` fired and abandoned wedges the next opener, which is why
333
+ ``Session.close`` never sends one. Here the sender waits it out: do
334
+ not remove the wait or the reopen retry.
335
+ """
336
+ port = _open_with_retry(device, _RECOVER_OPEN_RETRY_S)
337
+ if port is None:
338
+ return "busy"
339
+ try:
340
+ with suppress(serial.SerialException, OSError):
341
+ port.write(bytes([Opcode.AVERAGE_STOP.byte()]))
342
+ sleep(_PROBE_SETTLE_S)
343
+ port.write(bytes([Opcode.RESET.byte()]))
344
+ finally:
345
+ with suppress(serial.SerialException, OSError):
346
+ port.close()
347
+ sleep(_RECOVER_REENUM_S)
348
+
349
+ port = _open_with_retry(device, _RECOVER_OPEN_RETRY_S)
350
+ if port is None:
351
+ return "busy"
352
+ try:
353
+ flush_input(port)
354
+ _drain_input(port, _PROBE_DRAIN_S)
355
+ port.write(bytes([Opcode.GET_METADATA.byte()]))
356
+ buf = read_until_end(port, _RECOVER_METADATA_TIMEOUT_S)
357
+ parse_metadata(buf)
358
+ except (OSError, MetadataError):
359
+ return "idle"
360
+ else:
361
+ return "data"
362
+ finally:
363
+ with suppress(serial.SerialException, OSError):
364
+ port.close()
365
+
366
+
367
+ def _open_with_retry(device: str, budget_s: float) -> serial.Serial | None:
368
+ """Open ``device`` exclusively, retrying failures up to ``budget_s``."""
369
+ deadline = monotonic() + budget_s
370
+ while True:
371
+ try:
372
+ return serial.Serial(
373
+ device,
374
+ baudrate=_PROBE_BAUD,
375
+ timeout=_PROBE_READ_TIMEOUT_S,
376
+ write_timeout=_PROBE_READ_TIMEOUT_S,
377
+ exclusive=True,
378
+ )
379
+ except (serial.SerialException, OSError):
380
+ if monotonic() >= deadline:
381
+ return None
382
+ sleep(0.25)
383
+
384
+
385
+ def _drain_input(port: serial.Serial, budget_s: float) -> None:
386
+ """Read and discard whatever is in the input buffer, up to ``budget_s``."""
387
+ deadline = monotonic() + budget_s
388
+ while monotonic() < deadline:
389
+ try:
390
+ waiting = port.in_waiting
391
+ except (serial.SerialException, OSError):
392
+ return
393
+ if waiting == 0:
394
+ return
395
+ try:
396
+ port.read(waiting)
397
+ except (serial.SerialException, OSError):
398
+ return
399
+ sleep(0.02)
400
+
401
+
402
+ def probe_data_port(
403
+ paths: tuple[str, ...],
404
+ probe: ProbeFn,
405
+ recover_probe: ProbeFn | None = None,
406
+ ) -> str | None:
407
+ """Return the first path, lowest first, that answers the probe, else ``None``.
408
+
409
+ If the quick pass finds nothing and ``recover_probe`` is given, the
410
+ paths get a second pass with it.
411
+ """
412
+ for path in sorted(paths):
413
+ if probe(path) == "data":
414
+ return path
415
+ if recover_probe is not None:
416
+ for path in sorted(paths):
417
+ if recover_probe(path) == "data":
418
+ return path
419
+ return None
420
+
421
+
422
+ def classify_ports(
423
+ paths: tuple[str, ...],
424
+ probe: ProbeFn,
425
+ recover_probe: ProbeFn | None = None,
426
+ ) -> dict[str, PortStatus]:
427
+ """Probe ``paths`` in order until one is the data port; mark the rest idle.
428
+
429
+ Stopping at the data port keeps the usual case to one port opened.
430
+ When nothing answers, every path has been probed, which tells ``busy``
431
+ from ``idle``; with ``recover_probe``, the paths then get a second
432
+ pass, idle ones first (the likelier data port), then busy ones (a port
433
+ just released by a killed process also reads as busy; one truly held
434
+ stays busy).
435
+ """
436
+ statuses: dict[str, PortStatus] = {}
437
+ for path in paths:
438
+ statuses[path] = probe(path)
439
+ if statuses[path] == "data":
440
+ break
441
+ for path in paths:
442
+ statuses.setdefault(path, "idle")
443
+ if recover_probe is not None and "data" not in statuses.values():
444
+ by_priority = [p for p in paths if statuses[p] == "idle"] + [
445
+ p for p in paths if statuses[p] == "busy"
446
+ ]
447
+ for path in by_priority:
448
+ statuses[path] = recover_probe(path)
449
+ if statuses[path] == "data":
450
+ break
451
+ return statuses
452
+
453
+
454
+ def build_listings(
455
+ ports: list[RawPort],
456
+ probe: ProbeFn,
457
+ recover_probe: ProbeFn | None = None,
458
+ ) -> list[Ppk2Listing]:
459
+ """Build ``Ppk2Listing`` rows from a port snapshot and a probe."""
460
+ out: list[Ppk2Listing] = []
461
+ for usb_serial, paths in sorted(group_ppk2s(ports).items()):
462
+ ordered = tuple(sorted(paths))
463
+ statuses = classify_ports(ordered, probe, recover_probe)
464
+ data_port = next((p for p in ordered if statuses[p] == "data"), None)
465
+ out.append(
466
+ Ppk2Listing(
467
+ usb_serial=usb_serial,
468
+ ports=ordered,
469
+ data_port=data_port,
470
+ statuses=statuses,
471
+ )
472
+ )
473
+ return out
474
+
475
+
476
+ def resolve_probes(probe: ProbeFn | None) -> tuple[ProbeFn, ProbeFn | None]:
477
+ """The real probe pair by default; an injected probe alone, without escalation."""
478
+ if probe is None:
479
+ return probe_port, probe_port_recover
480
+ return probe, None
481
+
482
+
483
+ def _poll_until_found(
484
+ timeout_s: float,
485
+ try_find: "_GroupFindFn",
486
+ probe: ProbeFn | None,
487
+ ) -> PortInfo:
488
+ """Enumerate and probe every 250 ms until a data port is found or time runs out.
489
+
490
+ ``Ambiguous`` is raised at once: polling cannot settle it. A device
491
+ not found yet, or found but not answering yet, is tried again.
492
+ """
493
+ quick, recover = resolve_probes(probe)
494
+ deadline = monotonic() + timeout_s
495
+ while True:
496
+ ports = enumerate_ports()
497
+ try:
498
+ serial_str, paths = try_find(ports)
499
+ except Ambiguous:
500
+ raise
501
+ except DiscoveryError:
502
+ if monotonic() >= deadline:
503
+ raise
504
+ else:
505
+ device = probe_data_port(paths, quick, recover)
506
+ if device is not None:
507
+ return PortInfo(device=device, usb_serial=serial_str)
508
+ if monotonic() >= deadline:
509
+ raise DataPortNotFound(paths)
510
+ # 250 ms: easy on IOKit/udev, and a re-enumeration shows up
511
+ # within a tick or two.
512
+ sleep(0.25)
513
+
514
+
515
+ _GroupFindFn = Callable[[list[RawPort]], tuple[str, tuple[str, ...]]]