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 +100 -0
- ppk2/__main__.py +5 -0
- ppk2/cli/__init__.py +3 -0
- ppk2/cli/commands/__init__.py +23 -0
- ppk2/cli/commands/capture.py +270 -0
- ppk2/cli/commands/convert.py +119 -0
- ppk2/cli/commands/discover.py +14 -0
- ppk2/cli/commands/list_devices.py +45 -0
- ppk2/cli/commands/metadata.py +36 -0
- ppk2/cli/commands/power.py +63 -0
- ppk2/cli/commands/run.py +162 -0
- ppk2/cli/csv.py +67 -0
- ppk2/cli/main.py +276 -0
- ppk2/cli/ppk2file.py +179 -0
- ppk2/cli/signals.py +46 -0
- ppk2/cli/trace.py +60 -0
- ppk2/client/__init__.py +50 -0
- ppk2/client/discovery.py +515 -0
- ppk2/client/session.py +639 -0
- ppk2/protocol/__init__.py +51 -0
- ppk2/protocol/calibration.py +51 -0
- ppk2/protocol/metadata.py +320 -0
- ppk2/protocol/opcode.py +110 -0
- ppk2/protocol/sample.py +61 -0
- ppk2/protocol/stream.py +375 -0
- ppk2/py.typed +0 -0
- ppk2_lib-0.1.0.dist-info/METADATA +164 -0
- ppk2_lib-0.1.0.dist-info/RECORD +32 -0
- ppk2_lib-0.1.0.dist-info/WHEEL +4 -0
- ppk2_lib-0.1.0.dist-info/entry_points.txt +2 -0
- ppk2_lib-0.1.0.dist-info/licenses/LICENSE-APACHE +202 -0
- ppk2_lib-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Per-sample current calibration.
|
|
2
|
+
|
|
3
|
+
``current_micro_amps`` turns one raw ADC count into microamperes, given
|
|
4
|
+
the range, the per-device coefficients, and the present supply voltage.
|
|
5
|
+
It is stateless and computes the same formula as Nordic's ``getAdcResult``;
|
|
6
|
+
the spike filter that follows a range change lives in the stream
|
|
7
|
+
parser.
|
|
8
|
+
|
|
9
|
+
Regression-tested against a sample word from a real PPK2 with its
|
|
10
|
+
captured coefficients: ``0x015c0097`` gives ``5.302145379685201`` µA.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from ppk2.protocol.metadata import CalibrationCoefficients
|
|
14
|
+
|
|
15
|
+
# The firmware's ADC scaling: a 1.8 V reference over 2^14 * 10 (the
|
|
16
|
+
# 14-bit count, with *10 of internal headroom).
|
|
17
|
+
_ADC_MULT: float = 1.8 / 163_840.0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def current_micro_amps(
|
|
21
|
+
adc_14: int,
|
|
22
|
+
range_idx: int,
|
|
23
|
+
vdd_mv: int,
|
|
24
|
+
coeffs: CalibrationCoefficients,
|
|
25
|
+
) -> float:
|
|
26
|
+
"""Convert one raw ADC reading into microamperes.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
adc_14: 14-bit ADC value, straight from ``RawSample.adc_14``
|
|
30
|
+
(the *4 rescale happens here).
|
|
31
|
+
range_idx: Range index, 0 to 4.
|
|
32
|
+
vdd_mv: Present supply voltage in millivolts (the last
|
|
33
|
+
``REGULATOR_SET``). Needed in Ampere meter mode too.
|
|
34
|
+
coeffs: Per-device calibration from ``parse_metadata``.
|
|
35
|
+
|
|
36
|
+
Raises:
|
|
37
|
+
IndexError: If ``range_idx`` is above 4.
|
|
38
|
+
"""
|
|
39
|
+
r = range_idx
|
|
40
|
+
|
|
41
|
+
# Measured voltage over the range's resistance: the current before correction, in amperes.
|
|
42
|
+
counts = float(adc_14) * 4.0 - coeffs.o[r]
|
|
43
|
+
raw_amps = counts * (_ADC_MULT / coeffs.r[r])
|
|
44
|
+
|
|
45
|
+
# The per-range correction: a quadratic in the raw current, plus a
|
|
46
|
+
# term that follows the supply voltage.
|
|
47
|
+
vdd_volts = float(vdd_mv) / 1000.0
|
|
48
|
+
amps = coeffs.ug[r] * (
|
|
49
|
+
raw_amps * (coeffs.gs[r] * raw_amps + coeffs.gi[r]) + coeffs.s[r] * vdd_volts + coeffs.i[r]
|
|
50
|
+
)
|
|
51
|
+
return amps * 1e6
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
r"""Per-device calibration metadata returned by ``GET_METADATA`` (0x19).
|
|
2
|
+
|
|
3
|
+
The response is about 1 kB of ASCII ``key: value\n`` lines ending with a
|
|
4
|
+
literal ``END``. It can arrive split across reads: accumulate until
|
|
5
|
+
``END`` is in the buffer, then call ``parse_metadata``.
|
|
6
|
+
|
|
7
|
+
Regression-tested against ``tests/fixtures/metadata.raw``, a real
|
|
8
|
+
response captured from a PPK2.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from math import isfinite, isnan
|
|
13
|
+
|
|
14
|
+
# Five measurement ranges, fixed across the PPK2 line.
|
|
15
|
+
NUM_RANGES = 5
|
|
16
|
+
|
|
17
|
+
# One value per range; a fixed-length tuple, so pyright checks the count.
|
|
18
|
+
RangeArray = tuple[float, float, float, float, float]
|
|
19
|
+
|
|
20
|
+
# The response starts with this key; what precedes it is not metadata.
|
|
21
|
+
_FIRST_KEY = b"Calibrated"
|
|
22
|
+
|
|
23
|
+
# What Nordic's Power Profiler app assumes for a slot the device left
|
|
24
|
+
# blank (the firmware prints ``-nan`` for one): nominal resistances,
|
|
25
|
+
# unit gains, no offsets.
|
|
26
|
+
_BLANK_DEFAULTS: dict[str, RangeArray] = {
|
|
27
|
+
"R": (1031.64, 101.65, 10.15, 0.94, 0.043),
|
|
28
|
+
"GS": (1.0, 1.0, 1.0, 1.0, 1.0),
|
|
29
|
+
"GI": (1.0, 1.0, 1.0, 1.0, 1.0),
|
|
30
|
+
"O": (0.0, 0.0, 0.0, 0.0, 0.0),
|
|
31
|
+
"S": (0.0, 0.0, 0.0, 0.0, 0.0),
|
|
32
|
+
"I": (0.0, 0.0, 0.0, 0.0, 0.0),
|
|
33
|
+
"UG": (1.0, 1.0, 1.0, 1.0, 1.0),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class CalibrationCoefficients:
|
|
39
|
+
"""Per-device calibration, plus the VDD and mode the firmware reported.
|
|
40
|
+
|
|
41
|
+
Every coefficient is mandatory: a defaulted calibration value would
|
|
42
|
+
corrupt every sample, so ``parse_metadata`` raises ``MissingField``
|
|
43
|
+
instead. ``VDD`` and ``mode`` describe the device's present state,
|
|
44
|
+
not its calibration, and some firmware revisions omit them: those
|
|
45
|
+
two get defaults.
|
|
46
|
+
|
|
47
|
+
Attributes:
|
|
48
|
+
calibrated: The ``Calibrated`` value as reported. Not
|
|
49
|
+
interpreted: a PPK2 that reports ``False`` still carries a
|
|
50
|
+
full set of coefficients, and they are used.
|
|
51
|
+
r: Per-range resistance (Ω, virtual).
|
|
52
|
+
gs: Per-range gain slope (quadratic term).
|
|
53
|
+
gi: Per-range gain intercept (linear term).
|
|
54
|
+
o: Per-range ADC offset (16-bit-equivalent counts).
|
|
55
|
+
s: Per-range VDD-dependent linear slope.
|
|
56
|
+
i: Per-range VDD-dependent linear intercept.
|
|
57
|
+
ug: Per-range user gain (default 1.0).
|
|
58
|
+
vdd_mv: Supply voltage in millivolts, 800 to 5,000: the last
|
|
59
|
+
``REGULATOR_SET``. It survives host disconnects: a PPK2
|
|
60
|
+
left at 1,800 mV reports it on the next open. 3,300 when
|
|
61
|
+
the firmware omits it.
|
|
62
|
+
mode: Power mode, ``1`` Ampere meter or ``2`` Source meter;
|
|
63
|
+
anything else raises ``InvalidValue``. Ampere meter, the
|
|
64
|
+
passive mode, when the firmware omits it.
|
|
65
|
+
hw: The ``HW`` value as reported. Not interpreted.
|
|
66
|
+
ia: The ``IA`` value as reported. Not interpreted.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
calibrated: bool
|
|
70
|
+
r: RangeArray
|
|
71
|
+
gs: RangeArray
|
|
72
|
+
gi: RangeArray
|
|
73
|
+
o: RangeArray
|
|
74
|
+
s: RangeArray
|
|
75
|
+
i: RangeArray
|
|
76
|
+
ug: RangeArray
|
|
77
|
+
vdd_mv: int
|
|
78
|
+
mode: int
|
|
79
|
+
hw: int
|
|
80
|
+
ia: int
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class MetadataError(Exception):
|
|
84
|
+
"""Base class for metadata-parse failures."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class MissingEnd(MetadataError):
|
|
88
|
+
"""Buffer did not contain the ``END`` terminator.
|
|
89
|
+
|
|
90
|
+
The caller's accumulating-read loop has a bug.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class MissingField(MetadataError):
|
|
95
|
+
"""A required key was absent; ``field`` names it (e.g. ``R[3]``)."""
|
|
96
|
+
|
|
97
|
+
def __init__(self, field: str) -> None:
|
|
98
|
+
super().__init__(f"missing required metadata field: {field}")
|
|
99
|
+
self.field = field
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class InvalidValue(MetadataError):
|
|
103
|
+
"""A field's value could not be parsed; ``value`` is the raw text."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, field: str, value: str) -> None:
|
|
106
|
+
super().__init__(f"invalid value for {field}: {value!r}")
|
|
107
|
+
self.field = field
|
|
108
|
+
self.value = value
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def parse_metadata(buf: bytes) -> CalibrationCoefficients:
|
|
112
|
+
r"""Parse a full ``GET_METADATA`` response into calibration coefficients.
|
|
113
|
+
|
|
114
|
+
Tolerant of unknown keys, ``END`` with or without a newline, spaces
|
|
115
|
+
around the ``:``, missing ``VDD``/``mode`` (see
|
|
116
|
+
``CalibrationCoefficients``), and bytes before the text: the end
|
|
117
|
+
of a stream that was not read out, up to 1 kB of samples, can come
|
|
118
|
+
glued in front of the response. The parse starts at the first key,
|
|
119
|
+
``Calibrated``.
|
|
120
|
+
|
|
121
|
+
Strict on missing calibration fields and on malformed values. A
|
|
122
|
+
blank slot (``-nan``) takes the default Nordic's app uses for it.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
MissingEnd: If ``buf`` has no ``END`` terminator.
|
|
126
|
+
MissingField: If a calibration key is absent.
|
|
127
|
+
InvalidValue: If a present field's value cannot be parsed.
|
|
128
|
+
"""
|
|
129
|
+
start = buf.find(_FIRST_KEY)
|
|
130
|
+
if start > 0:
|
|
131
|
+
buf = buf[start:]
|
|
132
|
+
text = buf.decode("utf-8", errors="replace")
|
|
133
|
+
|
|
134
|
+
partial = _Partial()
|
|
135
|
+
saw_end = False
|
|
136
|
+
|
|
137
|
+
for raw_line in text.split("\n"):
|
|
138
|
+
line = raw_line.strip()
|
|
139
|
+
if not line:
|
|
140
|
+
continue
|
|
141
|
+
if line == "END":
|
|
142
|
+
saw_end = True
|
|
143
|
+
break
|
|
144
|
+
kv = _split_kv(line)
|
|
145
|
+
if kv is None:
|
|
146
|
+
# Lines without `:` are silently skipped (forward-compat).
|
|
147
|
+
continue
|
|
148
|
+
key, value = kv
|
|
149
|
+
partial.assign(key, value)
|
|
150
|
+
|
|
151
|
+
if not saw_end:
|
|
152
|
+
raise MissingEnd("no END terminator in metadata buffer")
|
|
153
|
+
|
|
154
|
+
return partial.finish()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ─── internals ─────────────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _split_kv(line: str) -> tuple[str, str] | None:
|
|
161
|
+
"""Split a line on the first ``:``; return ``(key, value)`` trimmed."""
|
|
162
|
+
if ":" not in line:
|
|
163
|
+
return None
|
|
164
|
+
k, _, v = line.partition(":")
|
|
165
|
+
return k.strip(), v.strip()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
_PER_RANGE_PREFIXES = ("R", "GS", "GI", "O", "S", "I", "UG")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _split_keyed_index(key: str) -> tuple[str, int] | None:
|
|
172
|
+
"""Split a per-range key into prefix + numeric suffix.
|
|
173
|
+
|
|
174
|
+
Examples: ``"R0" -> ("R", 0)``, ``"GS4" -> ("GS", 4)``, ``"HW" -> None``,
|
|
175
|
+
``"Calibrated" -> None``.
|
|
176
|
+
"""
|
|
177
|
+
# Walk back from the end while digits, then take the suffix.
|
|
178
|
+
suffix_start = len(key)
|
|
179
|
+
while suffix_start > 0 and key[suffix_start - 1].isdigit():
|
|
180
|
+
suffix_start -= 1
|
|
181
|
+
if suffix_start == 0 or suffix_start == len(key):
|
|
182
|
+
return None
|
|
183
|
+
prefix = key[:suffix_start]
|
|
184
|
+
try:
|
|
185
|
+
idx = int(key[suffix_start:])
|
|
186
|
+
except ValueError:
|
|
187
|
+
return None
|
|
188
|
+
return prefix, idx
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class _Partial:
|
|
192
|
+
"""Mutable accumulator: ``assign`` fills it, ``finish`` seals it."""
|
|
193
|
+
|
|
194
|
+
def __init__(self) -> None:
|
|
195
|
+
self.calibrated: bool | None = None
|
|
196
|
+
self.r: list[float | None] = [None] * NUM_RANGES
|
|
197
|
+
self.gs: list[float | None] = [None] * NUM_RANGES
|
|
198
|
+
self.gi: list[float | None] = [None] * NUM_RANGES
|
|
199
|
+
self.o: list[float | None] = [None] * NUM_RANGES
|
|
200
|
+
self.s: list[float | None] = [None] * NUM_RANGES
|
|
201
|
+
self.i: list[float | None] = [None] * NUM_RANGES
|
|
202
|
+
self.ug: list[float | None] = [None] * NUM_RANGES
|
|
203
|
+
self.vdd_mv: int | None = None
|
|
204
|
+
self.mode: int | None = None
|
|
205
|
+
self.hw: int | None = None
|
|
206
|
+
self.ia: int | None = None
|
|
207
|
+
|
|
208
|
+
def assign(self, key: str, value: str) -> None:
|
|
209
|
+
keyed = _split_keyed_index(key)
|
|
210
|
+
if keyed is not None:
|
|
211
|
+
prefix, idx = keyed
|
|
212
|
+
if prefix not in _PER_RANGE_PREFIXES:
|
|
213
|
+
# An unknown array: ignored.
|
|
214
|
+
return
|
|
215
|
+
if idx >= NUM_RANGES:
|
|
216
|
+
# A sixth range and beyond: ignored.
|
|
217
|
+
return
|
|
218
|
+
slot = self._slot_for(prefix)
|
|
219
|
+
try:
|
|
220
|
+
parsed = float(value)
|
|
221
|
+
except ValueError as exc:
|
|
222
|
+
raise InvalidValue(f"{prefix}[{idx}]", value) from exc
|
|
223
|
+
if isnan(parsed):
|
|
224
|
+
# A slot the device left blank: the app's default, as
|
|
225
|
+
# the app does. A NaN kept here would turn every sample
|
|
226
|
+
# of that range into NaN.
|
|
227
|
+
parsed = _BLANK_DEFAULTS[prefix][idx]
|
|
228
|
+
elif not isfinite(parsed):
|
|
229
|
+
raise InvalidValue(f"{prefix}[{idx}]", value)
|
|
230
|
+
slot[idx] = parsed
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
# Scalar keys. Names match the wire-format exactly (PPK2 firmware
|
|
234
|
+
# is case-sensitive: `VDD` upper, `mode` lower).
|
|
235
|
+
if key == "Calibrated":
|
|
236
|
+
if value == "0":
|
|
237
|
+
self.calibrated = False
|
|
238
|
+
elif value == "1":
|
|
239
|
+
self.calibrated = True
|
|
240
|
+
else:
|
|
241
|
+
raise InvalidValue("Calibrated", value)
|
|
242
|
+
elif key == "HW":
|
|
243
|
+
try:
|
|
244
|
+
self.hw = int(value)
|
|
245
|
+
except ValueError as exc:
|
|
246
|
+
raise InvalidValue("HW", value) from exc
|
|
247
|
+
elif key == "IA":
|
|
248
|
+
try:
|
|
249
|
+
self.ia = int(value)
|
|
250
|
+
except ValueError as exc:
|
|
251
|
+
raise InvalidValue("IA", value) from exc
|
|
252
|
+
elif key == "VDD":
|
|
253
|
+
try:
|
|
254
|
+
self.vdd_mv = int(value)
|
|
255
|
+
except ValueError as exc:
|
|
256
|
+
raise InvalidValue("VDD", value) from exc
|
|
257
|
+
elif key == "mode":
|
|
258
|
+
try:
|
|
259
|
+
parsed_mode = int(value)
|
|
260
|
+
except ValueError as exc:
|
|
261
|
+
raise InvalidValue("mode", value) from exc
|
|
262
|
+
if parsed_mode not in (1, 2):
|
|
263
|
+
raise InvalidValue("mode", value)
|
|
264
|
+
self.mode = parsed_mode
|
|
265
|
+
# Unknown scalar key (e.g. VERSION_OUT): forward-compat, drop.
|
|
266
|
+
|
|
267
|
+
def _slot_for(self, prefix: str) -> list[float | None]:
|
|
268
|
+
# Mapping kept explicit so pyright knows every branch returns
|
|
269
|
+
# a typed list (no Any fallback).
|
|
270
|
+
if prefix == "R":
|
|
271
|
+
return self.r
|
|
272
|
+
if prefix == "GS":
|
|
273
|
+
return self.gs
|
|
274
|
+
if prefix == "GI":
|
|
275
|
+
return self.gi
|
|
276
|
+
if prefix == "O":
|
|
277
|
+
return self.o
|
|
278
|
+
if prefix == "S":
|
|
279
|
+
return self.s
|
|
280
|
+
if prefix == "I":
|
|
281
|
+
return self.i
|
|
282
|
+
if prefix == "UG":
|
|
283
|
+
return self.ug
|
|
284
|
+
raise AssertionError(f"unreachable: caller already filtered prefix={prefix!r}")
|
|
285
|
+
|
|
286
|
+
def finish(self) -> CalibrationCoefficients:
|
|
287
|
+
if self.calibrated is None:
|
|
288
|
+
raise MissingField("Calibrated")
|
|
289
|
+
if self.hw is None:
|
|
290
|
+
raise MissingField("HW")
|
|
291
|
+
if self.ia is None:
|
|
292
|
+
raise MissingField("IA")
|
|
293
|
+
# VDD and mode are state, not calibration, and may be absent:
|
|
294
|
+
# then 3300 mV and Ampere meter mode.
|
|
295
|
+
return CalibrationCoefficients(
|
|
296
|
+
calibrated=self.calibrated,
|
|
297
|
+
r=_seal("R", self.r),
|
|
298
|
+
gs=_seal("GS", self.gs),
|
|
299
|
+
gi=_seal("GI", self.gi),
|
|
300
|
+
o=_seal("O", self.o),
|
|
301
|
+
s=_seal("S", self.s),
|
|
302
|
+
i=_seal("I", self.i),
|
|
303
|
+
ug=_seal("UG", self.ug),
|
|
304
|
+
vdd_mv=self.vdd_mv if self.vdd_mv is not None else 3300,
|
|
305
|
+
mode=self.mode if self.mode is not None else 1,
|
|
306
|
+
hw=self.hw,
|
|
307
|
+
ia=self.ia,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _seal(prefix: str, arr: list[float | None]) -> RangeArray:
|
|
312
|
+
"""Turn a filled 5-slot list into a ``RangeArray``; ``MissingField`` on a gap."""
|
|
313
|
+
out: list[float] = []
|
|
314
|
+
for idx, value in enumerate(arr):
|
|
315
|
+
if value is None:
|
|
316
|
+
raise MissingField(f"{prefix}[{idx}]")
|
|
317
|
+
out.append(value)
|
|
318
|
+
# Unpack into a fixed 5-tuple so pyright sees the exact RangeArray length.
|
|
319
|
+
a, b, c, d, e = out
|
|
320
|
+
return (a, b, c, d, e)
|
ppk2/protocol/opcode.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Wire opcodes.
|
|
2
|
+
|
|
3
|
+
Each opcode is one byte sent to the PPK2. The values are those of
|
|
4
|
+
Nordic's Power Profiler app (``pc-nrfconnect-ppk`` v4.4.1,
|
|
5
|
+
``src/constants.ts``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from enum import IntEnum
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Opcode(IntEnum):
|
|
12
|
+
"""Single-byte opcode; the enum value is the wire byte.
|
|
13
|
+
|
|
14
|
+
``Opcode.AVERAGE_START == 0x06``. ``byte()`` says the same thing at
|
|
15
|
+
call sites.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
TRIGGER_SET = 0x01
|
|
19
|
+
"""Generic ON parameter byte. Rarely sent as an opcode of its own."""
|
|
20
|
+
|
|
21
|
+
AVG_NUM_SET = 0x02
|
|
22
|
+
"""Decimation count. Nordic's source marks it as not handled by the
|
|
23
|
+
firmware, which ignores it."""
|
|
24
|
+
|
|
25
|
+
TRIGGER_WINDOW_SET = 0x03
|
|
26
|
+
"""Triggered-capture window size (u16 LE)."""
|
|
27
|
+
|
|
28
|
+
TRIGGER_INTERVAL_SET = 0x04
|
|
29
|
+
"""Triggered-capture interval (u16 LE). Nordic's source marks it as
|
|
30
|
+
not handled by the firmware."""
|
|
31
|
+
|
|
32
|
+
TRIGGER_SINGLE_SET = 0x05
|
|
33
|
+
"""Single-shot trigger arm."""
|
|
34
|
+
|
|
35
|
+
AVERAGE_START = 0x06
|
|
36
|
+
"""Start the stream: 100,000 samples per second, each a 4-byte
|
|
37
|
+
little-endian word, until ``AVERAGE_STOP``."""
|
|
38
|
+
|
|
39
|
+
AVERAGE_STOP = 0x07
|
|
40
|
+
"""Stop the sample stream."""
|
|
41
|
+
|
|
42
|
+
RANGE_SET = 0x08
|
|
43
|
+
"""Manual measurement-range override (u8, 0 to 4). Rarely used, the
|
|
44
|
+
firmware auto-ranges. Nordic's source marks it as not handled by
|
|
45
|
+
the firmware."""
|
|
46
|
+
|
|
47
|
+
LCD_SET = 0x09
|
|
48
|
+
"""LCD backlight. The PPK2 has no LCD; Nordic's source marks it as
|
|
49
|
+
not handled by the firmware."""
|
|
50
|
+
|
|
51
|
+
DEVICE_RUNNING_SET = 0x0C
|
|
52
|
+
"""Power to the DUT: payload ``0x01`` on, ``0x00`` off. The app's "Enable power output".
|
|
53
|
+
|
|
54
|
+
Applied about 1 ms after it is sent, with or without a stream. One
|
|
55
|
+
sent within 0.31 s of ``AVERAGE_START`` is held until then (the
|
|
56
|
+
protocol page, Known caveats).
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
REGULATOR_SET = 0x0D
|
|
60
|
+
"""Supply voltage in Source meter mode: ``[0x0D, mV >> 8, mV & 0xff]``
|
|
61
|
+
(big-endian), 800 to 5,000 mV.
|
|
62
|
+
|
|
63
|
+
In Ampere meter mode the regulator is inactive, but the calibration
|
|
64
|
+
still uses the last value sent (see ``current_micro_amps``).
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
SWITCH_POINT_DOWN = 0x0E
|
|
68
|
+
"""Auto-range hysteresis (downward)."""
|
|
69
|
+
|
|
70
|
+
SWITCH_POINT_UP = 0x0F
|
|
71
|
+
"""Auto-range hysteresis (upward)."""
|
|
72
|
+
|
|
73
|
+
SET_POWER_MODE = 0x11
|
|
74
|
+
"""Measurement mode: payload ``0x01`` Ampere meter, ``0x02`` Source meter.
|
|
75
|
+
|
|
76
|
+
Nordic also names this byte ``TriggerExtToggle``, an
|
|
77
|
+
external-trigger function that shares it; this library only uses it
|
|
78
|
+
to set the mode.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
RES_USER_SET = 0x12
|
|
82
|
+
"""User-supplied resistor calibration. No known host sends it."""
|
|
83
|
+
|
|
84
|
+
SPIKE_FILTERING_ON = 0x15
|
|
85
|
+
"""Enable firmware-side spike filtering."""
|
|
86
|
+
|
|
87
|
+
SPIKE_FILTERING_OFF = 0x16
|
|
88
|
+
"""Disable firmware-side spike filtering."""
|
|
89
|
+
|
|
90
|
+
GET_METADATA = 0x19
|
|
91
|
+
"""Request the per-device calibration: about 1 kB of ASCII
|
|
92
|
+
``key: value\\n`` lines ending with ``END``."""
|
|
93
|
+
|
|
94
|
+
RESET = 0x20
|
|
95
|
+
"""Restart the firmware. The PPK2 leaves USB and comes back 200 to
|
|
96
|
+
500 ms later."""
|
|
97
|
+
|
|
98
|
+
SET_USER_GAINS = 0x25
|
|
99
|
+
"""User gain override, payload ``[u8 range, f32 gain]``. Current
|
|
100
|
+
firmware accepts and ignores it."""
|
|
101
|
+
|
|
102
|
+
def byte(self) -> int:
|
|
103
|
+
"""Return the single byte sent on the wire for this opcode."""
|
|
104
|
+
return int(self)
|
|
105
|
+
|
|
106
|
+
# No @override: it lives in typing from 3.12 or in typing_extensions,
|
|
107
|
+
# and this layer is stdlib-only on 3.11.
|
|
108
|
+
def __repr__(self) -> str: # pyright: ignore[reportImplicitOverride]
|
|
109
|
+
"""Show the value in hex: these are wire bytes."""
|
|
110
|
+
return f"<{self.__class__.__name__}.{self.name}: 0x{self.value:02X}>"
|
ppk2/protocol/sample.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Sample-frame bit extraction.
|
|
2
|
+
|
|
3
|
+
Each PPK2 sample is a 4-byte little-endian word::
|
|
4
|
+
|
|
5
|
+
bits 0-13 ADC (14-bit raw count; *4 to rescale to 16-bit
|
|
6
|
+
before the calibration formula)
|
|
7
|
+
bits 14-16 RANGE (auto-range selector, 0-4; 5-7 = misaligned parse)
|
|
8
|
+
bit 17 reserved (read as 0; don't assert on it)
|
|
9
|
+
bits 18-23 COUNTER (6-bit, mod 64; what the stream parser
|
|
10
|
+
resyncs on)
|
|
11
|
+
bits 24-31 LOGIC (D0..D7; bit 0 = D0)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class RawSample:
|
|
19
|
+
"""One sample frame after bit extraction: no calibration, no validation.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
adc_14: Raw 14-bit ADC reading (0 to 16,383).
|
|
23
|
+
range: Auto-range index. Healthy firmware emits 0 to 4; 5 and up
|
|
24
|
+
means the parse is misaligned.
|
|
25
|
+
counter: 6-bit per-sample counter, incrementing mod 64.
|
|
26
|
+
logic: Digital inputs D0 to D7 in one byte (bit 0 is D0).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
adc_14: int
|
|
30
|
+
range: int
|
|
31
|
+
counter: int
|
|
32
|
+
logic: int
|
|
33
|
+
|
|
34
|
+
def range_valid(self) -> bool:
|
|
35
|
+
"""Whether the range index is one of the five real ranges."""
|
|
36
|
+
return self.range <= 4
|
|
37
|
+
|
|
38
|
+
def pin(self, pin: int) -> bool:
|
|
39
|
+
"""Whether digital input ``pin`` (0 to 7) was high; ``pin`` wraps modulo 8."""
|
|
40
|
+
return ((self.logic >> (pin & 0x7)) & 1) != 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def decode_sample(raw: int) -> RawSample:
|
|
44
|
+
"""Split a 32-bit sample word into its fields (no validation)."""
|
|
45
|
+
return RawSample(
|
|
46
|
+
adc_14=raw & 0x3FFF,
|
|
47
|
+
range=(raw >> 14) & 0x07,
|
|
48
|
+
counter=(raw >> 18) & 0x3F,
|
|
49
|
+
logic=(raw >> 24) & 0xFF,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def decode_sample_bytes(buf: bytes) -> RawSample:
|
|
54
|
+
"""Same as ``decode_sample``, from exactly 4 little-endian bytes.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
ValueError: If ``buf`` is not 4 bytes long.
|
|
58
|
+
"""
|
|
59
|
+
if len(buf) != 4:
|
|
60
|
+
raise ValueError(f"expected 4 bytes, got {len(buf)}")
|
|
61
|
+
return decode_sample(int.from_bytes(buf, "little"))
|