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/client/session.py ADDED
@@ -0,0 +1,639 @@
1
+ """PPK2 session lifecycle: open, configure, stream, tear down.
2
+
3
+ ``Session`` is a context manager; leaving the block stops the stream,
4
+ switches the DUT off and closes the port.
5
+
6
+ >>> with Session.open(port) as s:
7
+ ... s.set_mode(Mode.AMPERE)
8
+ ... s.set_source_voltage(3300)
9
+ ... s.start_measuring()
10
+ ... s.power_on()
11
+ ... s.capture(on_sample) # until on_sample returns False
12
+ """
13
+
14
+ import warnings
15
+ from collections.abc import Callable
16
+ from contextlib import suppress
17
+ from dataclasses import replace
18
+ from enum import IntEnum
19
+ from time import monotonic, sleep
20
+ from typing import Protocol
21
+
22
+ import serial
23
+
24
+ from ppk2.protocol import (
25
+ CalibrationCoefficients,
26
+ MetadataError,
27
+ Opcode,
28
+ RangeArray,
29
+ Sample,
30
+ SpikeFilter,
31
+ StreamParser,
32
+ parse_metadata,
33
+ )
34
+
35
+ _BAUD_RATE = 115_200
36
+ _READ_TIMEOUT_S = 0.1
37
+ _OPEN_SETTLE_S = 0.05
38
+ _START_BUSY_S = 0.35 # the PPK2 holds commands for 0.31 s after AVERAGE_START
39
+ _STREAM_BYTES_PER_S = 400_000 # 100,000 samples of 4 bytes
40
+ _CAUGHT_UP_BYTES = 4_000 # within 10 ms of the stream: caught up
41
+ _CATCH_UP_CAP_S = 1.5 # how long to try, at most
42
+ _METADATA_READ_TIMEOUT_S = 2.5
43
+ _QUIET_S = 0.05 # no byte for this long: the stream has ended
44
+ _QUIET_CAP_S = 0.5 # how long to wait for that, at most
45
+ _HANDSHAKE_ATTEMPTS = 3
46
+ _OPEN_ATTEMPTS = 3
47
+
48
+ #: Lowest ``REGULATOR_SET`` value the firmware accepts, in millivolts.
49
+ #: Below it the on-board LDO does not regulate cleanly.
50
+ VOLTAGE_LIMIT_HARDWARE_MIN_MV: int = 800
51
+
52
+ #: Highest voltage the on-board regulator can supply, in millivolts: a
53
+ #: hard ceiling. ``Session.set_voltage_limit`` can only lower it.
54
+ VOLTAGE_LIMIT_HARDWARE_MAX_MV: int = 5000
55
+
56
+ #: The user gains Nordic's app accepts, per range.
57
+ USER_GAIN_MIN: float = 0.9
58
+ USER_GAIN_MAX: float = 1.1
59
+
60
+
61
+ class SessionError(Exception):
62
+ """Base class for session lifecycle failures."""
63
+
64
+
65
+ class SerialIOError(SessionError):
66
+ """Underlying serial I/O failed."""
67
+
68
+
69
+ class HandshakeFailed(SessionError):
70
+ """The metadata handshake ran out of attempts.
71
+
72
+ ``attempts`` is how many were made; ``last`` describes the final
73
+ failure (write error, no END, parse error).
74
+ """
75
+
76
+ def __init__(self, attempts: int, last: str) -> None:
77
+ super().__init__(f"metadata recovery failed after {attempts} attempts; last: {last}")
78
+ self.attempts = attempts
79
+ self.last = last
80
+
81
+
82
+ class Mode(IntEnum):
83
+ """PPK2 measurement mode; the value is the wire byte.
84
+
85
+ ``AMPERE`` is the Ampere meter mode of Nordic's app: the DUT has its
86
+ own supply and the PPK2 sits in series. ``SOURCE`` is its Source
87
+ meter mode: the PPK2 supplies the DUT.
88
+ """
89
+
90
+ AMPERE = 0x01
91
+ SOURCE = 0x02
92
+
93
+
94
+ class Session:
95
+ """An open PPK2 session: the serial port plus the device's calibration.
96
+
97
+ Use it as a context manager (``with Session.open(port) as s:``) so
98
+ the teardown runs even on an exception.
99
+
100
+ One ``Session`` per thread: the serial port underneath is not safe
101
+ to share.
102
+ """
103
+
104
+ def __init__(self, port: serial.Serial, coeffs: CalibrationCoefficients) -> None:
105
+ """Wrap an already-open port and its parsed calibration.
106
+
107
+ Prefer ``Session.open``, which opens the port and runs the
108
+ handshake.
109
+
110
+ The supply voltage starts at ``coeffs.vdd_mv``, the value the
111
+ firmware reported and keeps across host disconnects: a PPK2
112
+ left at 1,800 mV starts the next session at 1,800 mV until
113
+ ``set_source_voltage`` says otherwise. Same as Nordic's app.
114
+ """
115
+ self._port = port
116
+ if not all(USER_GAIN_MIN <= g <= USER_GAIN_MAX for g in coeffs.ug):
117
+ # As Nordic's app does when it connects.
118
+ warnings.warn(
119
+ f"the PPK2 reports a user gain outside {USER_GAIN_MIN} to "
120
+ f"{USER_GAIN_MAX} ({coeffs.ug}); all five are taken as 1.0",
121
+ RuntimeWarning,
122
+ stacklevel=2,
123
+ )
124
+ coeffs = replace(coeffs, ug=(1.0, 1.0, 1.0, 1.0, 1.0))
125
+ self._coeffs = coeffs
126
+ self._vdd_mv = coeffs.vdd_mv
127
+ self._spike_filter = SpikeFilter()
128
+ self._voltage_limit_mv = VOLTAGE_LIMIT_HARDWARE_MAX_MV
129
+ self._closed = False
130
+ self._measuring = False
131
+ self._stream_started_at = 0.0
132
+ self._stream_bytes = 0 # read since start_measuring
133
+
134
+ # ── Construction ───────────────────────────────────────────────────
135
+
136
+ @classmethod
137
+ def open(cls, device: str) -> "Session":
138
+ """Open ``device`` and run the metadata handshake.
139
+
140
+ Up to 3 attempts, 0.5 s then 1.0 s apart. The retries are for
141
+ a port left stuck by another program's capture (seen on
142
+ macOS), above all one that sent ``RESET`` on close.
143
+ """
144
+ last_err: SessionError = SerialIOError("open: never attempted")
145
+ for attempt in range(_OPEN_ATTEMPTS):
146
+ try:
147
+ port, coeffs = cls._try_open_once(device)
148
+ except SessionError as exc:
149
+ last_err = exc
150
+ if attempt == _OPEN_ATTEMPTS - 1:
151
+ break
152
+ # 0.5 s then 1.0 s: 1.5 s total backoff across 3 attempts.
153
+ sleep(0.5 * (1 << attempt))
154
+ continue
155
+ else:
156
+ return cls(port=port, coeffs=coeffs)
157
+ raise last_err
158
+
159
+ @staticmethod
160
+ def _try_open_once(device: str) -> tuple[serial.Serial, CalibrationCoefficients]:
161
+ """One open + handshake attempt."""
162
+ try:
163
+ # exclusive=True: the open fails while another program
164
+ # holds the port, and others fail while this session lives.
165
+ port = serial.Serial(
166
+ device,
167
+ baudrate=_BAUD_RATE,
168
+ timeout=_READ_TIMEOUT_S,
169
+ write_timeout=_READ_TIMEOUT_S,
170
+ exclusive=True,
171
+ )
172
+ except serial.SerialException as exc:
173
+ raise SerialIOError(f"serial open: {exc}") from exc
174
+ sleep(_OPEN_SETTLE_S)
175
+ try:
176
+ _empty_serial(port)
177
+ coeffs = _recover_and_negotiate(port)
178
+ except BaseException:
179
+ # Left open, the port would keep its lock and fail the next attempt.
180
+ with suppress(Exception):
181
+ port.close()
182
+ raise
183
+ return port, coeffs
184
+
185
+ # ── Context manager protocol ───────────────────────────────────────
186
+
187
+ def __enter__(self) -> "Session":
188
+ return self
189
+
190
+ def __exit__(self, *_args: object) -> None:
191
+ self.close()
192
+
193
+ def close(self) -> None:
194
+ """Stop the stream, cut power to the DUT, wait for the stream to end, close the port.
195
+
196
+ Idempotent; errors are swallowed. No ``RESET`` is sent: it makes the
197
+ PPK2 leave USB and come back, which takes 200 to 500 ms and can
198
+ block the next session.
199
+
200
+ The port is not closed while samples still arrive. Closed right
201
+ after ``AVERAGE_STOP``, the PPK2 can miss the command and keep
202
+ streaming, and what was in flight goes to whoever opens the port
203
+ next: a client that asks for the metadata first, like Nordic's
204
+ own tools, then gets no usable answer.
205
+
206
+ DUT power does not outlive the session: the PPK2 cuts it by itself
207
+ when the port closes (it follows the DTR line), so this holds even
208
+ when the process is killed and this method never runs.
209
+ """
210
+ if self._closed:
211
+ return
212
+ self._closed = True
213
+ with suppress(serial.SerialException):
214
+ self._port.write(bytes([Opcode.AVERAGE_STOP.byte()]))
215
+ with suppress(serial.SerialException):
216
+ self._port.write(bytes([Opcode.DEVICE_RUNNING_SET.byte(), 0x00]))
217
+ self._wait_for_quiet()
218
+ with suppress(serial.SerialException):
219
+ self._port.close()
220
+
221
+ # ── Accessors ──────────────────────────────────────────────────────
222
+
223
+ def coefficients(self) -> CalibrationCoefficients:
224
+ """Per-device calibration read at session open."""
225
+ return self._coeffs
226
+
227
+ # ── Configuration ──────────────────────────────────────────────────
228
+
229
+ def set_mode(self, mode: Mode) -> None:
230
+ """Select the measurement mode.
231
+
232
+ Call it before ``start_measuring``. On the PPK2 tested, a
233
+ change sent during a stream was applied too; nothing here
234
+ relies on that.
235
+ """
236
+ self._write(bytes([Opcode.SET_POWER_MODE.byte(), int(mode)]))
237
+
238
+ def set_source_voltage(self, mv: int) -> None:
239
+ """Set the supply voltage in millivolts.
240
+
241
+ In Source meter mode this is what the PPK2 outputs. In Ampere
242
+ meter mode the regulator is inactive, but the value still feeds
243
+ the calibration: set it to the DUT's real supply voltage.
244
+
245
+ Values outside 800 to 5,000 mV are brought back to the nearest
246
+ limit; the firmware would ignore them.
247
+
248
+ Raises:
249
+ ValueError: If ``mv`` exceeds the cap set with
250
+ ``set_voltage_limit``.
251
+ SerialIOError: If the serial write fails.
252
+ """
253
+ clamped = max(VOLTAGE_LIMIT_HARDWARE_MIN_MV, min(VOLTAGE_LIMIT_HARDWARE_MAX_MV, mv))
254
+ if clamped > self._voltage_limit_mv:
255
+ raise ValueError(
256
+ f"requested {mv} mV exceeds voltage limit "
257
+ f"{self._voltage_limit_mv} mV: call set_voltage_limit "
258
+ f"first if you want to raise the ceiling"
259
+ )
260
+ wire = bytes(
261
+ [
262
+ Opcode.REGULATOR_SET.byte(),
263
+ (clamped >> 8) & 0xFF,
264
+ clamped & 0xFF,
265
+ ]
266
+ )
267
+ self._write(wire)
268
+ self._vdd_mv = clamped
269
+
270
+ def set_voltage_limit(self, mv: int) -> None:
271
+ """Cap what ``set_source_voltage`` will accept, in millivolts.
272
+
273
+ A host-side guard against typing a DUT-damaging voltage, like
274
+ the app's voltage limit ("Set max supply voltage to"). The cap
275
+ is itself kept within 800 to 5,000 mV, and it does not change a
276
+ supply voltage already above it.
277
+
278
+ Raises:
279
+ RuntimeError: If called while a stream runs, between
280
+ ``start_measuring`` and ``stop_measuring``.
281
+ """
282
+ if self._measuring:
283
+ raise RuntimeError("set_voltage_limit must be called before start_measuring()")
284
+ self._voltage_limit_mv = max(
285
+ VOLTAGE_LIMIT_HARDWARE_MIN_MV,
286
+ min(VOLTAGE_LIMIT_HARDWARE_MAX_MV, mv),
287
+ )
288
+
289
+ def voltage_limit(self) -> int:
290
+ """The cap set by ``set_voltage_limit``, in millivolts."""
291
+ return self._voltage_limit_mv
292
+
293
+ # ── Stream control ─────────────────────────────────────────────────
294
+
295
+ def start_measuring(self) -> None:
296
+ """Start the stream of samples, 100,000 per second."""
297
+ self._write(bytes([Opcode.AVERAGE_START.byte()]))
298
+ self._stream_started_at = monotonic()
299
+ self._stream_bytes = 0
300
+ self._measuring = True
301
+
302
+ def stop_measuring(self) -> None:
303
+ """Send ``AVERAGE_STOP`` and read the stream out to its end.
304
+
305
+ Left unread, the end of the stream would lead the next one: a
306
+ few milliseconds of samples from before the stop. Safe to call
307
+ when no stream is active.
308
+ """
309
+ self._write(bytes([Opcode.AVERAGE_STOP.byte()]))
310
+ self._wait_for_quiet()
311
+ self._measuring = False
312
+
313
+ # ── DUT power ──────────────────────────────────────────────────────
314
+
315
+ def power_on(self) -> None:
316
+ """Switch power to the DUT on, as the app's "Enable power output" does.
317
+
318
+ The power comes up about 1 ms after the command. With a stream
319
+ running, the stream is first read until the host has caught up
320
+ with it, which takes until about 0.9 s after ``start_measuring``.
321
+ The samples read after this call are then from the switch on, to
322
+ within about 10 ms, so a capture that follows has the boot in it
323
+ (the protocol page, Known caveats).
324
+ """
325
+ self._catch_up()
326
+ self._write(bytes([Opcode.DEVICE_RUNNING_SET.byte(), 0x01]))
327
+
328
+ def power_off(self) -> None:
329
+ """Switch power to the DUT off. Idempotent."""
330
+ self._write(bytes([Opcode.DEVICE_RUNNING_SET.byte(), 0x00]))
331
+
332
+ def drop_pending_backlog(self) -> int:
333
+ """Discard what the OS reports as waiting; return the byte count.
334
+
335
+ One read, not a loop: a running stream never goes empty, so
336
+ draining until empty would hang. It does not bring the reads up
337
+ to the present: on macOS ``in_waiting`` reports about 1 kB while
338
+ some 40 kB are queued (the protocol page, Known caveats).
339
+
340
+ Raises:
341
+ SerialIOError: If the serial read fails.
342
+ """
343
+ try:
344
+ waiting = self._port.in_waiting
345
+ if waiting:
346
+ self._stream_bytes += len(self._port.read(waiting))
347
+ except serial.SerialException as exc:
348
+ raise SerialIOError(f"serial read: {exc}") from exc
349
+ return waiting
350
+
351
+ # ── User gain override ─────────────────────────────────────────────
352
+
353
+ def set_user_gain(self, range_idx: int, gain: float) -> None:
354
+ """Override the user gain of one range for this session.
355
+
356
+ Host-side only: the calibration used by the next ``capture`` is
357
+ rebuilt with the new gain and nothing is sent. Current firmware
358
+ ignores ``SET_USER_GAINS``, and Nordic's app applies the gain
359
+ host-side too. The override is gone at ``close``.
360
+
361
+ Args:
362
+ range_idx: Which of the five measurement ranges, 0 to 4. The
363
+ app numbers them 1 to 5.
364
+ gain: The gain, from 0.9 to 1.1 as in the app.
365
+
366
+ Raises:
367
+ ValueError: If ``range_idx`` is not 0 to 4, or ``gain`` is not
368
+ from 0.9 to 1.1.
369
+ RuntimeError: If called while a stream runs, between
370
+ ``start_measuring`` and ``stop_measuring``.
371
+ """
372
+ if self._measuring:
373
+ raise RuntimeError(
374
+ "set_user_gain must be called before start_measuring(); "
375
+ "the active capture's StreamParser uses the coefficients "
376
+ "captured at init time."
377
+ )
378
+ if not 0 <= range_idx <= 4:
379
+ raise ValueError(f"range_idx must be 0 to 4, got {range_idx}")
380
+ if not USER_GAIN_MIN <= gain <= USER_GAIN_MAX:
381
+ raise ValueError(f"gain must be from {USER_GAIN_MIN} to {USER_GAIN_MAX}, got {gain}")
382
+ old_ug = self._coeffs.ug
383
+ new_ug: RangeArray = (
384
+ gain if range_idx == 0 else old_ug[0],
385
+ gain if range_idx == 1 else old_ug[1],
386
+ gain if range_idx == 2 else old_ug[2],
387
+ gain if range_idx == 3 else old_ug[3],
388
+ gain if range_idx == 4 else old_ug[4],
389
+ )
390
+ self._coeffs = replace(self._coeffs, ug=new_ug)
391
+
392
+ # ── Spike-filter settings ──────────────────────────────────────────
393
+
394
+ def set_spike_filter(
395
+ self,
396
+ *,
397
+ samples: int | None = None,
398
+ alpha: float | None = None,
399
+ alpha5: float | None = None,
400
+ ) -> None:
401
+ """Change settings of the spike filter; those not passed keep their value.
402
+
403
+ Host-side, like Nordic's app: the next ``capture`` builds its
404
+ parser with these. See ``SpikeFilter`` for what each setting does
405
+ and its limits. The change is gone at ``close``.
406
+
407
+ Raises:
408
+ ValueError: If a setting is out of range.
409
+ RuntimeError: If called while a stream runs, between
410
+ ``start_measuring`` and ``stop_measuring``.
411
+ """
412
+ if self._measuring:
413
+ raise RuntimeError(
414
+ "set_spike_filter must be called before start_measuring(); "
415
+ "the active capture's StreamParser was built with the "
416
+ "previous filter and can't switch mid-stream."
417
+ )
418
+ current = self._spike_filter
419
+ self._spike_filter = SpikeFilter(
420
+ samples=current.samples if samples is None else samples,
421
+ alpha=current.alpha if alpha is None else alpha,
422
+ alpha5=current.alpha5 if alpha5 is None else alpha5,
423
+ )
424
+
425
+ def spike_filter(self) -> SpikeFilter:
426
+ """The spike-filter settings the next ``capture`` will use."""
427
+ return self._spike_filter
428
+
429
+ # ── Capture loop ───────────────────────────────────────────────────
430
+
431
+ def capture(
432
+ self,
433
+ emit: Callable[[Sample], bool],
434
+ on_dataloss: Callable[[int], None] | None = None,
435
+ keep_going: Callable[[], bool] | None = None,
436
+ ) -> None:
437
+ """Read the stream and call ``emit`` per sample until it returns ``False``.
438
+
439
+ Args:
440
+ emit: Called with each ``Sample``; return ``False`` to stop.
441
+ It is not called again after that.
442
+ on_dataloss: Called with the running total of lost samples
443
+ whenever a read adds to it (at most once per read).
444
+ keep_going: Called after every read; return ``False`` to
445
+ stop. Without it, a PPK2 that sends nothing, or nothing
446
+ that decodes to a sample, keeps ``capture`` waiting for
447
+ ever, since ``emit`` is never called.
448
+ """
449
+ parser = StreamParser(self._coeffs, self._vdd_mv, self._spike_filter)
450
+ scratch = bytearray(4096)
451
+ stop = False
452
+
453
+ def collect(sample: Sample) -> None:
454
+ nonlocal stop
455
+ # The rest of a read is dropped once emit has said stop.
456
+ if not stop and not emit(sample):
457
+ stop = True
458
+
459
+ while not stop:
460
+ n = self._read_into(scratch)
461
+ # Asked after every read: bytes that hold no sample must not
462
+ # keep a capture going either.
463
+ if keep_going is not None and not keep_going():
464
+ return
465
+ if n == 0:
466
+ continue
467
+ before = parser.dataloss_total
468
+ parser.push_bytes(bytes(scratch[:n]), collect)
469
+ if on_dataloss is not None and parser.dataloss_total > before:
470
+ on_dataloss(parser.dataloss_total)
471
+
472
+ # ── Internals ──────────────────────────────────────────────────────
473
+
474
+ def _catch_up(self) -> None:
475
+ """Read and discard until the reads have caught up with the stream.
476
+
477
+ For 0.31 s after ``AVERAGE_START`` the PPK2 sends slowly and
478
+ holds any command it receives, and the host is level with the
479
+ stream only after about 0.9 s (measured on macOS). Caught up
480
+ means: past that first stretch, and as many bytes read as the
481
+ PPK2 has produced since ``start_measuring``, to within 10 ms.
482
+ Gives up after ``_CATCH_UP_CAP_S``. Does nothing without a
483
+ stream.
484
+ """
485
+ if not self._measuring:
486
+ return
487
+ deadline = monotonic() + _CATCH_UP_CAP_S
488
+ scratch = bytearray(4096)
489
+ while (now := monotonic()) < deadline:
490
+ elapsed = now - self._stream_started_at
491
+ behind = elapsed * _STREAM_BYTES_PER_S - self._stream_bytes
492
+ if elapsed >= _START_BUSY_S and behind <= _CAUGHT_UP_BYTES:
493
+ return
494
+ self._read_into(scratch)
495
+
496
+ def _wait_for_quiet(self) -> None:
497
+ """Read and discard until no byte arrives for ``_QUIET_S``.
498
+
499
+ Gives up after ``_QUIET_CAP_S``. Best effort: the port may
500
+ already be gone.
501
+ """
502
+ deadline = monotonic() + _QUIET_CAP_S
503
+ with suppress(Exception):
504
+ read_timeout = self._port.timeout
505
+ self._port.timeout = _QUIET_S
506
+ try:
507
+ while monotonic() < deadline and self._port.read(4096):
508
+ pass
509
+ finally:
510
+ self._port.timeout = read_timeout
511
+
512
+ def _write(self, payload: bytes) -> None:
513
+ try:
514
+ self._port.write(payload)
515
+ except serial.SerialException as exc:
516
+ raise SerialIOError(f"serial write: {exc}") from exc
517
+
518
+ def _read_into(self, buf: bytearray) -> int:
519
+ """Read up to ``len(buf)`` bytes into ``buf``; return the count, 0 on timeout."""
520
+ try:
521
+ chunk = self._port.read(len(buf))
522
+ except serial.SerialException as exc:
523
+ raise SerialIOError(f"serial read: {exc}") from exc
524
+ n = len(chunk)
525
+ if n:
526
+ buf[:n] = chunk
527
+ self._stream_bytes += n
528
+ return n
529
+
530
+
531
+ # ─── module-private helpers ────────────────────────────────────────────
532
+
533
+
534
+ def flush_input(port: serial.Serial) -> None:
535
+ """Discard buffered input, best effort.
536
+
537
+ On a port that has just dropped off USB (the device re-enumerates
538
+ after a ``RESET``), pyserial lets a bare ``termios.error`` through:
539
+ neither ``SerialException`` nor ``OSError``. The next write or read
540
+ reports the dead port properly.
541
+ """
542
+ with suppress(Exception):
543
+ port.reset_input_buffer()
544
+
545
+
546
+ def _empty_serial(port: serial.Serial) -> None:
547
+ """Drain whatever the firmware was still emitting, up to ~1 s."""
548
+ deadline = monotonic() + 1.0
549
+ while monotonic() < deadline:
550
+ try:
551
+ waiting = port.in_waiting
552
+ except (serial.SerialException, OSError):
553
+ return
554
+ if waiting == 0:
555
+ return
556
+ try:
557
+ port.read(waiting)
558
+ except serial.SerialException:
559
+ return
560
+
561
+
562
+ class BytesReader(Protocol):
563
+ """Anything with ``read(n) -> bytes``: pyserial's ``Serial``, or a test fake."""
564
+
565
+ def read(self, n: int, /) -> bytes:
566
+ """Read up to ``n`` bytes; return ``b""`` if none are ready."""
567
+ ...
568
+
569
+
570
+ def read_until_end(reader: BytesReader, total_timeout_s: float) -> bytes:
571
+ """Read until the data contains ``b"END"``, or raise ``TimeoutError``.
572
+
573
+ The metadata response can arrive split across several reads.
574
+ """
575
+ deadline = monotonic() + total_timeout_s
576
+ buf = bytearray()
577
+
578
+ while monotonic() < deadline:
579
+ chunk = reader.read(512)
580
+ if not chunk:
581
+ sleep(0.02)
582
+ continue
583
+ buf.extend(chunk)
584
+ if b"END" in buf:
585
+ return bytes(buf)
586
+
587
+ raise TimeoutError(f"no END within {total_timeout_s}s; buffered {len(buf)} bytes")
588
+
589
+
590
+ def _recover_and_negotiate(port: serial.Serial) -> CalibrationCoefficients:
591
+ """Stop any stream, reset on retries, read and parse the metadata.
592
+
593
+ Up to 3 attempts. A failed write is recorded as the failure instead
594
+ of being skipped: on a port that is stuck every write fails,
595
+ and reporting a later parse failure would hide the real cause.
596
+ """
597
+ last_failure = "(no attempts made)"
598
+
599
+ for attempt in range(_HANDSHAKE_ATTEMPTS):
600
+ # In case a stream was left running.
601
+ try:
602
+ port.write(bytes([Opcode.AVERAGE_STOP.byte()]))
603
+ except serial.SerialException as exc:
604
+ last_failure = f"write AVERAGE_STOP: {exc}"
605
+ continue
606
+ sleep(0.1)
607
+
608
+ # RESET on retries only: it makes the PPK2 drop off USB.
609
+ if attempt > 0:
610
+ try:
611
+ port.write(bytes([Opcode.RESET.byte()]))
612
+ except serial.SerialException as exc:
613
+ last_failure = f"write RESET: {exc}"
614
+ continue
615
+ sleep(0.3)
616
+
617
+ # Discard what was still arriving.
618
+ flush_input(port)
619
+ _empty_serial(port)
620
+
621
+ try:
622
+ port.write(bytes([Opcode.GET_METADATA.byte()]))
623
+ except serial.SerialException as exc:
624
+ last_failure = f"write GET_METADATA: {exc}"
625
+ continue
626
+
627
+ try:
628
+ buf = read_until_end(port, _METADATA_READ_TIMEOUT_S)
629
+ except (TimeoutError, OSError) as exc:
630
+ last_failure = f"read metadata: {exc}"
631
+ continue
632
+
633
+ try:
634
+ return parse_metadata(buf)
635
+ except MetadataError as exc:
636
+ last_failure = f"parse_metadata: {exc!r}"
637
+ continue
638
+
639
+ raise HandshakeFailed(_HANDSHAKE_ATTEMPTS, last_failure)
@@ -0,0 +1,51 @@
1
+ """Pure protocol primitives: opcodes, metadata parser, sample decoder, stream.
2
+
3
+ Stdlib-only; no I/O. The top-level ``ppk2`` package re-exports the
4
+ items you'd typically import from here.
5
+ """
6
+
7
+ from ppk2.protocol.calibration import current_micro_amps
8
+ from ppk2.protocol.metadata import (
9
+ NUM_RANGES,
10
+ CalibrationCoefficients,
11
+ InvalidValue,
12
+ MetadataError,
13
+ MissingEnd,
14
+ MissingField,
15
+ RangeArray,
16
+ parse_metadata,
17
+ )
18
+ from ppk2.protocol.opcode import Opcode
19
+ from ppk2.protocol.sample import RawSample, decode_sample, decode_sample_bytes
20
+ from ppk2.protocol.stream import (
21
+ DEFAULT_SPIKE_FILTER_ALPHA,
22
+ DEFAULT_SPIKE_FILTER_ALPHA5,
23
+ DEFAULT_SPIKE_FILTER_SAMPLES,
24
+ MAX_BUFFERED_CORRUPTED,
25
+ Sample,
26
+ SpikeFilter,
27
+ StreamParser,
28
+ )
29
+
30
+ __all__ = [
31
+ "DEFAULT_SPIKE_FILTER_ALPHA",
32
+ "DEFAULT_SPIKE_FILTER_ALPHA5",
33
+ "DEFAULT_SPIKE_FILTER_SAMPLES",
34
+ "MAX_BUFFERED_CORRUPTED",
35
+ "NUM_RANGES",
36
+ "CalibrationCoefficients",
37
+ "InvalidValue",
38
+ "MetadataError",
39
+ "MissingEnd",
40
+ "MissingField",
41
+ "Opcode",
42
+ "RangeArray",
43
+ "RawSample",
44
+ "Sample",
45
+ "SpikeFilter",
46
+ "StreamParser",
47
+ "current_micro_amps",
48
+ "decode_sample",
49
+ "decode_sample_bytes",
50
+ "parse_metadata",
51
+ ]