embeddedci-openhtf 2.0.1__tar.gz → 2.2.0__tar.gz

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.
Files changed (28) hide show
  1. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/CHANGELOG.md +15 -0
  2. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/PKG-INFO +45 -8
  3. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/README.md +43 -6
  4. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/pyproject.toml +2 -2
  5. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/__init__.py +6 -0
  6. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/analog.py +61 -4
  7. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/plug.py +40 -15
  8. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/_fake.py +12 -2
  9. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_analog.py +30 -0
  10. embeddedci_openhtf-2.2.0/tests/test_docs_coverage.py +62 -0
  11. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_e2e_openhtf.py +21 -0
  12. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_persistent.py +37 -3
  13. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/.gitignore +0 -0
  14. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/LICENSE +0 -0
  15. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/examples/analog_loopback.py +0 -0
  16. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/examples/flash_and_boot.py +0 -0
  17. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/examples/serial_smoke.py +0 -0
  18. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/examples/station.py +0 -0
  19. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/measurements.py +0 -0
  20. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/phases.py +0 -0
  21. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/pins.py +0 -0
  22. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/src/embeddedci_openhtf/power.py +0 -0
  23. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/conftest.py +0 -0
  24. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_measurements.py +0 -0
  25. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_phases.py +0 -0
  26. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_pins.py +0 -0
  27. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_plug.py +0 -0
  28. {embeddedci_openhtf-2.0.1 → embeddedci_openhtf-2.2.0}/tests/test_power.py +0 -0
@@ -1,5 +1,20 @@
1
1
  # Changelog — `embeddedci-openhtf`
2
2
 
3
+ ## 2.2.0
4
+
5
+ - Persistent plugs (`benchpod_plug(..., persistent=True)`) are pooled by their connection
6
+ settings (the connection and the `BenchPod` keyword arguments) instead of by plug class. Two
7
+ `benchpod_plug` calls for the same pod now share one connection (a pod serves one client at a
8
+ time), and a plug whose OpenHTF conf or environment changes gets a connection that matches.
9
+
10
+ ## 2.1.0
11
+
12
+ - 4-20 mA terminals: `current_out_phase` (and the `current_out` helper) holds a current on the
13
+ output (J9), and `current_in_phase` reads the loop current on the input (J8) and records it
14
+ as `current_in_a` with an optional `(low, high)` limit. Both work in amps.
15
+ `signal_generate_phase` and `dac_replay_phase` accept `dac_path="current_out"`. Needs
16
+ `embeddedci` 2.4 and firmware 3.4.0.
17
+
3
18
  ## 2.0.1
4
19
 
5
20
  - Docs: LA channels are 1-14 on BenchPod v3 pods with firmware 3.1+ (LA13/LA14), which
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: embeddedci-openhtf
3
- Version: 2.0.1
3
+ Version: 2.2.0
4
4
  Summary: OpenHTF plug for driving an EmbeddedCI BenchPod directly over TCP or serial (no cloud)
5
5
  Project-URL: Homepage, https://embeddedci.com
6
6
  Project-URL: Repository, https://github.com/embeddedci-com/embeddedci-python
@@ -18,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Topic :: Software Development :: Testing
20
20
  Requires-Python: >=3.10
21
- Requires-Dist: embeddedci<3,>=2.1
21
+ Requires-Dist: embeddedci<3,>=2.4
22
22
  Requires-Dist: openhtf>=1.6
23
23
  Provides-Extra: dev
24
24
  Requires-Dist: pytest>=7.0; extra == 'dev'
@@ -183,10 +183,28 @@ def boot_and_rail(test, bench):
183
183
  test.measurements.rail_v = bench.power_status().rail(1).bus_voltage # volts
184
184
  ```
185
185
 
186
+ `flash_ok_measurement(name="flash_ok")` and `uart_matched_measurement(name="boot_ok")` are the
187
+ matching declarations, so a custom flash phase needs no hand-written measurement:
188
+
189
+ ```python
190
+ from embeddedci_openhtf import flash_ok_measurement, record_flash
191
+
192
+ @htf.measures(flash_ok_measurement())
193
+ @htf.plug(bench=bench)
194
+ def flash(test, bench):
195
+ result = bench.flash(file="fw.elf", target="target/stm32f4x.cfg",
196
+ swclk=11, swdio=12, nreset=True, check=False)
197
+ record_flash(test, result) # sets flash_ok and attaches openocd.log
198
+ ```
199
+
200
+ The recorders never raise on a bad result: they record the failing value, so the measurement (not
201
+ an exception) decides the phase outcome, and the OpenOCD or UART output is always attached.
202
+
186
203
  ### Analog steps
187
204
 
188
205
  The pod's DAC output and ADC input are exposed as phases (and low-level helpers).
189
- Every analog quantity is in **volts**; limits are `(low, high)` volts.
206
+ Every analog quantity is in **volts**; limits are `(low, high)` volts. The two 4-20 mA
207
+ terminals work in **amps**.
190
208
 
191
209
  ```python
192
210
  import openhtf as htf
@@ -209,6 +227,9 @@ test = htf.Test(
209
227
  # a calibrated DC level and a single averaged reading
210
228
  dac_output_phase(bench, path="5v", volts=2.5),
211
229
  adc_read_phase(bench, source="ext", v_range=(2.4, 2.6)), # records ext_v
230
+ # 4-20 mA: hold 12 mA on the output (J9), read a loop on the input (J8)
231
+ current_out_phase(bench, current=0.012),
232
+ current_in_phase(bench, current_range=(0.0119, 0.0121)), # records current_in_a
212
233
  )
213
234
  ```
214
235
 
@@ -216,14 +237,15 @@ test = htf.Test(
216
237
  | --- | --- |
217
238
  | `adc_capture_phase`, `loopback_measure_phase` | `<prefix>_mean_v`, `_pp_v`, `_rms_v`, `_min_v`, `_max_v` (V); samples attached as `adc.json` (`counts` + `volts`) |
218
239
  | `adc_read_phase` | `<source>_v` (V) |
240
+ | `current_in_phase` | `current_in_a` (A): the loop current on the 4-20 mA input (J8) |
219
241
  | `control_loop_phase` | `control_loop_v` (DAC code), `control_loop_i` (ADC code) |
220
- | `signal_generate_phase`, `dac_output_phase`, `dac_replay_phase` | log only |
242
+ | `signal_generate_phase`, `dac_output_phase`, `current_out_phase`, `dac_replay_phase` | log only |
221
243
 
222
244
  Notes:
223
245
 
224
246
  - `source` routes the ADC: `"ext"` (front SMA — the default, and the input the
225
247
  capture volts are calibrated for), `"cal1"` / `"cal2"` (the 5 V / 12 V DAC looped back
226
- internally), `"amp"`; `source=None` leaves the routing alone.
248
+ internally), `"current_in"`; `source=None` leaves the routing alone.
227
249
  - Starting a waveform or a DC output re-applies that DAC path, which opens the internal
228
250
  `cal1`/`cal2` loopback relays. Route the ADC **after** starting the DAC —
229
251
  `loopback_measure_phase` does this for you.
@@ -233,12 +255,19 @@ Notes:
233
255
  `replay_waveform` helpers) switch the pod to the gateware image they need — loop or deep replay —
234
256
  automatically (~3 s, logged); pass `switch_image=False` to fail instead. A switch resets the FPGA,
235
257
  so start waveforms, UART sessions and I2C sensor emulation after it.
258
+ - The 4-20 mA output (J9) is loop powered: it needs an external **floating** loop supply (8 V
259
+ plus 20 mA times the loop resistance, 30 V at most), and nothing in the loop may touch pod
260
+ ground, also not through a DUT that shares a ground with the pod. Do not wire J9 straight to
261
+ J8. The pod cannot see whether current flows. It shares the DAC with the voltage outputs:
262
+ `current_out_phase` switches them off, and a voltage waveform also moves the loop.
263
+ `signal_generate_phase` and `dac_replay_phase` take `dac_path="current_out"` for a waveform in
264
+ amps. Needs firmware 3.4.0.
236
265
  - Use a TCP connection. The STM32 pod's USB serial console is a text shell without a JSON
237
266
  mode, so over serial only `power_phase`, status and the LA voltage work; flashing, UART,
238
267
  analog and replay phases need TCP (or the cloud).
239
268
 
240
269
  The low-level helpers take a connected `BenchPod` or the injected plug:
241
- `signal_generate`, `signal_stop`, `analog_path`, `dac_output`, `adc_read`,
270
+ `signal_generate`, `signal_stop`, `analog_path`, `dac_output`, `current_out`, `adc_read`,
242
271
  `adc_capture`, `replay`, `replay_waveform`, `control_loop`, `fpga_image`.
243
272
 
244
273
  ### Pins, GPIO and timing
@@ -309,8 +338,10 @@ def ripple_under_load(test, bench):
309
338
  By default the plug opens a connection per `Test.execute()` and closes it at
310
339
  teardown. On a station cycling many DUTs back-to-back, pass `persistent=True` to
311
340
  keep **one** connection open across executions (re-checked with a ping each run,
312
- reconnected if it dropped). Reuse the *same* plug class for every execution, and
313
- close it once at the end:
341
+ reconnected if it dropped). Persistent plugs are pooled by their connection settings (the
342
+ connection and the `BenchPod` keyword arguments), so two `benchpod_plug(..., persistent=True)`
343
+ calls for the same pod share one connection, and a plug whose OpenHTF conf or environment changes
344
+ gets a connection that matches. Close them once at the end:
314
345
 
315
346
  ```python
316
347
  import openhtf as htf
@@ -329,6 +360,12 @@ finally:
329
360
  close_persistent_benchpods() # also runs automatically at process exit
330
361
  ```
331
362
 
363
+ `benchpod_plug(connection=None, *, persistent=False, health_check=True, **pod_kwargs)` returns a
364
+ `BenchPodPlug` subclass with those values as class attributes (`connection`, `persistent`,
365
+ `health_check`, `pod_kwargs`). `health_check=False` skips the ping before a pooled connection is
366
+ reused. Inside a phase, `bench.pod` is the connected `BenchPod`; any other attribute the plug does
367
+ not have is looked up on it, which is why `bench.power_on()` works.
368
+
332
369
  ## Examples
333
370
 
334
371
  * [`examples/flash_and_boot.py`](examples/flash_and_boot.py) — flash over SWD then
@@ -157,10 +157,28 @@ def boot_and_rail(test, bench):
157
157
  test.measurements.rail_v = bench.power_status().rail(1).bus_voltage # volts
158
158
  ```
159
159
 
160
+ `flash_ok_measurement(name="flash_ok")` and `uart_matched_measurement(name="boot_ok")` are the
161
+ matching declarations, so a custom flash phase needs no hand-written measurement:
162
+
163
+ ```python
164
+ from embeddedci_openhtf import flash_ok_measurement, record_flash
165
+
166
+ @htf.measures(flash_ok_measurement())
167
+ @htf.plug(bench=bench)
168
+ def flash(test, bench):
169
+ result = bench.flash(file="fw.elf", target="target/stm32f4x.cfg",
170
+ swclk=11, swdio=12, nreset=True, check=False)
171
+ record_flash(test, result) # sets flash_ok and attaches openocd.log
172
+ ```
173
+
174
+ The recorders never raise on a bad result: they record the failing value, so the measurement (not
175
+ an exception) decides the phase outcome, and the OpenOCD or UART output is always attached.
176
+
160
177
  ### Analog steps
161
178
 
162
179
  The pod's DAC output and ADC input are exposed as phases (and low-level helpers).
163
- Every analog quantity is in **volts**; limits are `(low, high)` volts.
180
+ Every analog quantity is in **volts**; limits are `(low, high)` volts. The two 4-20 mA
181
+ terminals work in **amps**.
164
182
 
165
183
  ```python
166
184
  import openhtf as htf
@@ -183,6 +201,9 @@ test = htf.Test(
183
201
  # a calibrated DC level and a single averaged reading
184
202
  dac_output_phase(bench, path="5v", volts=2.5),
185
203
  adc_read_phase(bench, source="ext", v_range=(2.4, 2.6)), # records ext_v
204
+ # 4-20 mA: hold 12 mA on the output (J9), read a loop on the input (J8)
205
+ current_out_phase(bench, current=0.012),
206
+ current_in_phase(bench, current_range=(0.0119, 0.0121)), # records current_in_a
186
207
  )
187
208
  ```
188
209
 
@@ -190,14 +211,15 @@ test = htf.Test(
190
211
  | --- | --- |
191
212
  | `adc_capture_phase`, `loopback_measure_phase` | `<prefix>_mean_v`, `_pp_v`, `_rms_v`, `_min_v`, `_max_v` (V); samples attached as `adc.json` (`counts` + `volts`) |
192
213
  | `adc_read_phase` | `<source>_v` (V) |
214
+ | `current_in_phase` | `current_in_a` (A): the loop current on the 4-20 mA input (J8) |
193
215
  | `control_loop_phase` | `control_loop_v` (DAC code), `control_loop_i` (ADC code) |
194
- | `signal_generate_phase`, `dac_output_phase`, `dac_replay_phase` | log only |
216
+ | `signal_generate_phase`, `dac_output_phase`, `current_out_phase`, `dac_replay_phase` | log only |
195
217
 
196
218
  Notes:
197
219
 
198
220
  - `source` routes the ADC: `"ext"` (front SMA — the default, and the input the
199
221
  capture volts are calibrated for), `"cal1"` / `"cal2"` (the 5 V / 12 V DAC looped back
200
- internally), `"amp"`; `source=None` leaves the routing alone.
222
+ internally), `"current_in"`; `source=None` leaves the routing alone.
201
223
  - Starting a waveform or a DC output re-applies that DAC path, which opens the internal
202
224
  `cal1`/`cal2` loopback relays. Route the ADC **after** starting the DAC —
203
225
  `loopback_measure_phase` does this for you.
@@ -207,12 +229,19 @@ Notes:
207
229
  `replay_waveform` helpers) switch the pod to the gateware image they need — loop or deep replay —
208
230
  automatically (~3 s, logged); pass `switch_image=False` to fail instead. A switch resets the FPGA,
209
231
  so start waveforms, UART sessions and I2C sensor emulation after it.
232
+ - The 4-20 mA output (J9) is loop powered: it needs an external **floating** loop supply (8 V
233
+ plus 20 mA times the loop resistance, 30 V at most), and nothing in the loop may touch pod
234
+ ground, also not through a DUT that shares a ground with the pod. Do not wire J9 straight to
235
+ J8. The pod cannot see whether current flows. It shares the DAC with the voltage outputs:
236
+ `current_out_phase` switches them off, and a voltage waveform also moves the loop.
237
+ `signal_generate_phase` and `dac_replay_phase` take `dac_path="current_out"` for a waveform in
238
+ amps. Needs firmware 3.4.0.
210
239
  - Use a TCP connection. The STM32 pod's USB serial console is a text shell without a JSON
211
240
  mode, so over serial only `power_phase`, status and the LA voltage work; flashing, UART,
212
241
  analog and replay phases need TCP (or the cloud).
213
242
 
214
243
  The low-level helpers take a connected `BenchPod` or the injected plug:
215
- `signal_generate`, `signal_stop`, `analog_path`, `dac_output`, `adc_read`,
244
+ `signal_generate`, `signal_stop`, `analog_path`, `dac_output`, `current_out`, `adc_read`,
216
245
  `adc_capture`, `replay`, `replay_waveform`, `control_loop`, `fpga_image`.
217
246
 
218
247
  ### Pins, GPIO and timing
@@ -283,8 +312,10 @@ def ripple_under_load(test, bench):
283
312
  By default the plug opens a connection per `Test.execute()` and closes it at
284
313
  teardown. On a station cycling many DUTs back-to-back, pass `persistent=True` to
285
314
  keep **one** connection open across executions (re-checked with a ping each run,
286
- reconnected if it dropped). Reuse the *same* plug class for every execution, and
287
- close it once at the end:
315
+ reconnected if it dropped). Persistent plugs are pooled by their connection settings (the
316
+ connection and the `BenchPod` keyword arguments), so two `benchpod_plug(..., persistent=True)`
317
+ calls for the same pod share one connection, and a plug whose OpenHTF conf or environment changes
318
+ gets a connection that matches. Close them once at the end:
288
319
 
289
320
  ```python
290
321
  import openhtf as htf
@@ -303,6 +334,12 @@ finally:
303
334
  close_persistent_benchpods() # also runs automatically at process exit
304
335
  ```
305
336
 
337
+ `benchpod_plug(connection=None, *, persistent=False, health_check=True, **pod_kwargs)` returns a
338
+ `BenchPodPlug` subclass with those values as class attributes (`connection`, `persistent`,
339
+ `health_check`, `pod_kwargs`). `health_check=False` skips the ping before a pooled connection is
340
+ reused. Inside a phase, `bench.pod` is the connected `BenchPod`; any other attribute the plug does
341
+ not have is looked up on it, which is why `bench.power_on()` works.
342
+
306
343
  ## Examples
307
344
 
308
345
  * [`examples/flash_and_boot.py`](examples/flash_and_boot.py) — flash over SWD then
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "embeddedci-openhtf"
7
- version = "2.0.1"
7
+ version = "2.2.0"
8
8
  description = "OpenHTF plug for driving an EmbeddedCI BenchPod directly over TCP or serial (no cloud)"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -23,7 +23,7 @@ classifiers = [
23
23
  "Topic :: Software Development :: Testing",
24
24
  ]
25
25
  dependencies = [
26
- "embeddedci>=2.1,<3",
26
+ "embeddedci>=2.4,<3",
27
27
  "openhtf>=1.6",
28
28
  ]
29
29
 
@@ -32,6 +32,9 @@ from .analog import (
32
32
  analog_path,
33
33
  control_loop,
34
34
  control_loop_phase,
35
+ current_in_phase,
36
+ current_out,
37
+ current_out_phase,
35
38
  dac_output,
36
39
  dac_output_phase,
37
40
  dac_replay_phase,
@@ -78,6 +81,8 @@ __all__ = [
78
81
  "boot_banner_phase",
79
82
  "signal_generate_phase",
80
83
  "dac_output_phase",
84
+ "current_out_phase",
85
+ "current_in_phase",
81
86
  "adc_read_phase",
82
87
  "adc_capture_phase",
83
88
  "loopback_measure_phase",
@@ -98,6 +103,7 @@ __all__ = [
98
103
  "signal_stop",
99
104
  "analog_path",
100
105
  "dac_output",
106
+ "current_out",
101
107
  "adc_read",
102
108
  "adc_capture",
103
109
  "replay",
@@ -1,13 +1,14 @@
1
1
  """Analog stimulus/acquisition helpers for OpenHTF phases.
2
2
 
3
3
  The BenchPod's analog front end is a DAC output (routed to the 3V3/5V/12V SMA paths) and a
4
- 16-bit ADC input (front SMA, internal DAC loopbacks, amps terminal). These helpers and phase
4
+ 16-bit ADC input (front SMA, internal DAC loopbacks, 4-20 mA measurement terminal). These helpers and phase
5
5
  factories wrap the :class:`~embeddedci.benchpod.BenchPod` analog API and turn its results into
6
6
  OpenHTF measurements.
7
7
 
8
- **Units are volts, seconds and hertz**, exactly as in the ``embeddedci`` SDK: ``amplitude`` /
8
+ **Units are volts, amps, seconds and hertz**, exactly as in the ``embeddedci`` SDK: ``amplitude`` /
9
9
  ``offset`` / ``volts`` are volts, ``duration`` / ``settle`` are seconds, ``freq_hz`` /
10
10
  ``sample_rate_hz`` are hertz, and every recorded analog measurement is in volts (units ``"V"``).
11
+ The two 4-20 mA terminals work in **amps** (``current``, units ``"A"``): 0.012 is 12 mA.
11
12
  Invalid arguments raise :class:`ValueError`.
12
13
 
13
14
  The ``bench`` argument to every helper is a connected :class:`~embeddedci.benchpod.BenchPod`
@@ -38,6 +39,7 @@ from embeddedci.benchpod import (
38
39
  AnalogPathState,
39
40
  Capture,
40
41
  ControlLoopHandle,
42
+ CurrentOutput,
41
43
  DacHandle,
42
44
  DacOutput,
43
45
  DacOutputPath,
@@ -61,6 +63,7 @@ __all__ = [
61
63
  "signal_stop",
62
64
  "analog_path",
63
65
  "dac_output",
66
+ "current_out",
64
67
  "adc_read",
65
68
  "adc_capture",
66
69
  "replay",
@@ -70,6 +73,8 @@ __all__ = [
70
73
  # phase factories
71
74
  "signal_generate_phase",
72
75
  "dac_output_phase",
76
+ "current_out_phase",
77
+ "current_in_phase",
73
78
  "adc_read_phase",
74
79
  "adc_capture_phase",
75
80
  "loopback_measure_phase",
@@ -81,7 +86,7 @@ __all__ = [
81
86
  _Range = Optional[Tuple[float, float]]
82
87
 
83
88
  #: ADC source -> the named analog path that routes it.
84
- _ADC_SOURCE_PATH: Dict[str, str] = {"ext": "adc_ext", "cal1": "cal1", "cal2": "cal2", "amp": "amp"}
89
+ _ADC_SOURCE_PATH: Dict[str, str] = {"ext": "adc_ext", "cal1": "cal1", "cal2": "cal2", "current_in": "current_in"}
85
90
 
86
91
 
87
92
  # -- low-level helpers (operate on a BenchPod or BenchPodPlug) ---------------
@@ -119,8 +124,18 @@ def dac_output(bench: Any, path: DacOutputPath, *, volts: Optional[float] = None
119
124
  return bench.dac_output(path, volts=volts)
120
125
 
121
126
 
127
+ def current_out(bench: Any, current: float) -> CurrentOutput:
128
+ """Hold ``current`` (amps, 0.004 to 0.020) on the 4-20 mA output, terminal J9. Returns a
129
+ :class:`~embeddedci.benchpod.CurrentOutput` (``current`` actually held, ``code``, the range).
130
+
131
+ The output is loop powered: it needs an external **floating** loop supply on J9, and nothing
132
+ in the loop may touch pod ground. It shares the DAC with the voltage outputs, which this
133
+ switches off. See :meth:`BenchPod.current_out <embeddedci.benchpod.BenchPod.current_out>`."""
134
+ return bench.current_out(current)
135
+
136
+
122
137
  def adc_read(bench: Any, source: AdcSource = "ext") -> AdcReading:
123
- """Route an ADC ``source`` (``ext``/``cal1``/``cal2``/``amp``) and return one calibrated
138
+ """Route an ADC ``source`` (``ext``/``cal1``/``cal2``/``current_in``) and return one calibrated
124
139
  :class:`~embeddedci.benchpod.AdcReading` (``voltage`` in volts, ``count``). ``ext`` applies
125
140
  the front-SMA divider, so ``voltage`` is the true SMA voltage."""
126
141
  return bench.adc_read(source)
@@ -249,6 +264,48 @@ def dac_output_phase(plug: type, *, path: DacOutputPath, volts: Optional[float]
249
264
  return _out
250
265
 
251
266
 
267
+ def current_out_phase(plug: type, *, current: float, name: str = "current_out") -> object:
268
+ """A setup phase that holds ``current`` (amps) on the 4-20 mA output, terminal J9, e.g. to
269
+ feed a DUT's loop input a known level. ``current=0.004`` returns the loop to its live zero.
270
+
271
+ The output needs an external floating loop supply; the pod cannot see whether current
272
+ flows, so pair this with a measurement on the DUT. It stays held after the phase."""
273
+ if not 0 < float(current) < 1:
274
+ raise ValueError(f"current is in amps (0.004 to 0.020), got {current!r}")
275
+
276
+ @htf.PhaseOptions(name=name)
277
+ @htf.plug(bench=plug)
278
+ def _out(test, bench):
279
+ out = current_out(bench, current)
280
+ test.logger.info("4-20 mA output -> %.3f mA (code %d)", out.current * 1000.0, out.code)
281
+
282
+ return _out
283
+
284
+
285
+ def current_in_phase(plug: type, *, current_range: _Range = None,
286
+ name: str = "current_in") -> object:
287
+ """A phase that reads the 4-20 mA input, terminal J8, and records the loop current as
288
+ ``current_in_a`` (amps). Pass ``current_range=(low, high)`` in amps for a pass/fail limit,
289
+ e.g. ``(0.0119, 0.0121)`` for 12 mA ± 0.1 mA."""
290
+ _check_range("current_range", current_range)
291
+ meas = htf.Measurement("current_in_a").with_units("A")
292
+ if current_range is not None:
293
+ meas = meas.in_range(current_range[0], current_range[1])
294
+
295
+ @htf.PhaseOptions(name=name)
296
+ @htf.measures(meas)
297
+ @htf.plug(bench=plug)
298
+ def _rd(test, bench):
299
+ r = adc_read(bench, "current_in")
300
+ if r.current is None:
301
+ raise RuntimeError("this pod's firmware does not report the loop current on current_in; "
302
+ "update the firmware")
303
+ test.measurements["current_in_a"] = r.current
304
+ test.logger.info("4-20 mA input = %.3f mA (%.4f V across 249 ohm)", r.current * 1000.0, r.voltage)
305
+
306
+ return _rd
307
+
308
+
252
309
  def adc_read_phase(plug: type, *, source: AdcSource = "ext", v_range: _Range = None,
253
310
  name: str = "adc_read") -> object:
254
311
  """A phase that routes an ADC ``source`` and records the calibrated reading as
@@ -54,6 +54,7 @@ station that cycles many DUTs back-to-back, pass ``persistent=True`` to
54
54
  :func:`benchpod_plug` to keep one connection open across executions (re-checked
55
55
  with a ping each run and reconnected if it dropped); close it explicitly with
56
56
  :func:`close_persistent_benchpods` (also run automatically at process exit).
57
+ Persistent plugs with the same connection settings share one connection.
57
58
 
58
59
  Unknown attribute access proxies to the underlying
59
60
  :class:`~embeddedci.benchpod.BenchPod`, so ``bench.flash(...)`` /
@@ -67,7 +68,7 @@ import atexit
67
68
  import os
68
69
  import threading
69
70
  from types import MappingProxyType
70
- from typing import Any, Dict, Mapping, Optional
71
+ from typing import Any, Dict, Hashable, Mapping, Optional
71
72
 
72
73
  import openhtf as htf
73
74
  from openhtf.plugs import BasePlug
@@ -105,12 +106,36 @@ htf.conf.declare(
105
106
  default_value=None,
106
107
  )
107
108
 
108
- # Process-wide pool of persistent connections, keyed by the bound plug class (one
109
- # per benchpod_plug(persistent=True) call). Survives across test executions.
110
- _PERSISTENT_POOL: Dict[type, BenchPod] = {}
109
+ # Process-wide pool of persistent connections, keyed by the connection settings (the connection
110
+ # and the BenchPod keywords, see _pool_key). Plugs with the same settings share one connection,
111
+ # which a pod that serves one client at a time needs, and a plug whose settings change (an OpenHTF
112
+ # conf value, an env var) gets a connection that matches them. Survives across test executions.
113
+ _PERSISTENT_POOL: Dict[Hashable, BenchPod] = {}
111
114
  _PERSISTENT_LOCK = threading.Lock()
112
115
 
113
116
 
117
+ def _key_part(value: Any) -> Hashable:
118
+ """A hashable stand-in for one setting: the value itself when hashable and plain, its
119
+ contents for a dict, list or set (a wiring map), and its identity for any other object (an
120
+ injected transport, a Wiring), which is the same pod only when it is the same object."""
121
+ if value is None or isinstance(value, (bool, int, float, str, bytes)):
122
+ return value
123
+ if isinstance(value, Mapping):
124
+ return ("map", tuple(sorted((str(k), _key_part(v)) for k, v in value.items())))
125
+ if isinstance(value, (list, tuple)):
126
+ return ("seq", tuple(_key_part(v) for v in value))
127
+ if isinstance(value, (set, frozenset)):
128
+ return ("set", tuple(sorted(repr(_key_part(v)) for v in value)))
129
+ if isinstance(value, os.PathLike):
130
+ return ("path", os.fspath(value))
131
+ return ("obj", id(value))
132
+
133
+
134
+ def _pool_key(conn: Optional[str], pod_kwargs: Mapping[str, Any]) -> Hashable:
135
+ """The pool key for a connection and its BenchPod keywords."""
136
+ return (conn, tuple(sorted((k, _key_part(v)) for k, v in pod_kwargs.items())))
137
+
138
+
114
139
  def _conf_value(name: str) -> Any:
115
140
  """The OpenHTF conf value for ``name``, or ``None`` when it has none."""
116
141
  try:
@@ -138,12 +163,13 @@ def close_persistent_benchpods() -> None:
138
163
  atexit.register(close_persistent_benchpods)
139
164
 
140
165
 
141
- def _acquire_persistent(cls: type, conn: Optional[str],
142
- pod_kwargs: Mapping[str, Any], health_check: bool) -> BenchPod:
143
- """Return the pooled connection for ``cls``, opening (or reopening, if a
166
+ def _acquire_persistent(conn: Optional[str], pod_kwargs: Mapping[str, Any],
167
+ health_check: bool) -> BenchPod:
168
+ """Return the pooled connection for these settings, opening (or reopening, if a
144
169
  health-check ping fails) it as needed."""
170
+ key = _pool_key(conn, pod_kwargs)
145
171
  with _PERSISTENT_LOCK:
146
- pod = _PERSISTENT_POOL.get(cls)
172
+ pod = _PERSISTENT_POOL.get(key)
147
173
  if pod is not None and health_check:
148
174
  try:
149
175
  pod.ping() # cheap liveness check; reconnect if the link died
@@ -153,10 +179,10 @@ def _acquire_persistent(cls: type, conn: Optional[str],
153
179
  except Exception:
154
180
  pass
155
181
  pod = None
156
- _PERSISTENT_POOL.pop(cls, None)
182
+ _PERSISTENT_POOL.pop(key, None)
157
183
  if pod is None:
158
184
  pod = BenchPod(conn, **pod_kwargs)
159
- _PERSISTENT_POOL[cls] = pod
185
+ _PERSISTENT_POOL[key] = pod
160
186
  return pod
161
187
 
162
188
 
@@ -214,8 +240,7 @@ class BenchPodPlug(BasePlug):
214
240
  pod_kwargs.setdefault("la_voltage", float(benchpod_la_voltage))
215
241
  if cls.persistent:
216
242
  #: The connected SDK client (shared, kept open across executions).
217
- self.pod: BenchPod = _acquire_persistent(
218
- cls, conn, pod_kwargs, cls.health_check)
243
+ self.pod: BenchPod = _acquire_persistent(conn, pod_kwargs, cls.health_check)
219
244
  else:
220
245
  # Direct TCP/serial connections never lease.
221
246
  self.pod = BenchPod(conn, **pod_kwargs)
@@ -258,9 +283,9 @@ def benchpod_plug(connection: Optional[str] = None, *, persistent: bool = False,
258
283
  @htf.plug(bench=benchpod_plug("/dev/ttyACM0"))
259
284
  def phase(test, bench): ...
260
285
 
261
- Set ``persistent=True`` to keep one connection open across test executions
262
- (reuse the *same* returned class for every ``Test.execute()`` so they share
263
- it); see :func:`close_persistent_benchpods`. Extra keyword args are forwarded
286
+ Set ``persistent=True`` to keep one connection open across test executions;
287
+ persistent plugs with the same connection and keyword arguments share it,
288
+ whichever ``benchpod_plug`` call made them. See :func:`close_persistent_benchpods`. Extra keyword args are forwarded
264
289
  to ``BenchPod(...)``: ``la_voltage=`` (volts), ``wiring=`` (a dict, a
265
290
  ``.json``/``.toml`` path or a :class:`~embeddedci.benchpod.Wiring`, which then
266
291
  supplies the channels, baud and power rail a phase leaves out), ``timeout=``
@@ -73,6 +73,8 @@ class FakeTransport(Transport):
73
73
  self.closed = False
74
74
  #: Capabilities the fake pod reports (the SDK gates GPIO, triggers and power profiles).
75
75
  self.caps = ["la", "la_pins", "gpio_read", "capture_trigger", "power_profile"]
76
+ #: Loop current the fake 4-20 mA input (current_in) reads, in microamps.
77
+ self.loop_ua = 12000
76
78
  # LA pin ownership, as the firmware keeps it.
77
79
  self.function = {la: "none" for la in range(1, 15)}
78
80
  self.mode: Dict[int, Any] = {la: None for la in range(1, 15)}
@@ -123,10 +125,18 @@ class FakeTransport(Transport):
123
125
  "code": 128 if has_v else -1}
124
126
  if cmd == "generate":
125
127
  return {"cotrig": bool(req.get("on_capture", False))}
128
+ if cmd == "current_out":
129
+ rng = {"min_ua": 4016, "max_ua": 20078}
130
+ if "ua" not in req:
131
+ return rng
132
+ return {"ua": max(4016, req["ua"]), "code": max(0, round((req["ua"] - 4015.686) / 0.245098)), **rng}
126
133
  if cmd == "adc_read":
127
134
  src = req.get("source", "ext")
128
- return {"source": src, "mv": 12034 if src == "ext" else 2502, "count": 63049,
129
- "span": 3}
135
+ reply = {"source": src, "mv": 12034 if src == "ext" else 2502, "count": 63049,
136
+ "span": 3}
137
+ if src == "current_in":
138
+ reply.update(mv=2988, offset_mv=4, ua=self.loop_ua)
139
+ return reply
130
140
  if cmd == "dac_control_loop":
131
141
  return {"armed": True, "k": req.get("k"), "vmin": req.get("vmin"),
132
142
  "vmax": req.get("vmax"), "tick_div": req.get("tick_div"), "curve_pts": 256}
@@ -18,6 +18,9 @@ from embeddedci_openhtf import (
18
18
  benchpod_plug,
19
19
  control_loop,
20
20
  control_loop_phase,
21
+ current_in_phase,
22
+ current_out,
23
+ current_out_phase,
21
24
  dac_output,
22
25
  dac_output_phase,
23
26
  fpga_image,
@@ -255,6 +258,33 @@ def test_dac_output_helper_returns_typed_result():
255
258
  assert tx.commands[-1] == {"cmd": "dac_out", "path": "off"}
256
259
 
257
260
 
261
+ # -- the 4-20 mA terminals -----------------------------------------------------------------
262
+
263
+ def test_current_out_phase_holds_amps():
264
+ tx = FakeTransport()
265
+ tx.caps.append("current_out")
266
+ rec = _run(current_out_phase(benchpod_plug(transport=tx), current=0.012))
267
+ assert rec.outcome == tr.Outcome.PASS
268
+ assert tx.commands[-1] == {"cmd": "current_out", "ua": 12000}
269
+ out = current_out(benchpod_plug(transport=tx)(), 0.020)
270
+ assert out.current == pytest.approx(0.020) and out.max_current == pytest.approx(0.020078)
271
+ with pytest.raises(ValueError, match="amps"):
272
+ current_out_phase(benchpod_plug(transport=tx), current=12) # milliamps by mistake
273
+
274
+
275
+ def test_current_in_phase_records_amps_and_applies_the_limit():
276
+ tx = FakeTransport()
277
+ rec = _run(current_in_phase(benchpod_plug(transport=tx), current_range=(0.0119, 0.0121)))
278
+ assert rec.outcome == tr.Outcome.PASS
279
+ assert tx.commands[-1] == {"cmd": "adc_read", "source": "current_in"}
280
+ assert _value(_phase(rec, "current_in"), "current_in_a") == pytest.approx(0.012)
281
+ tx.loop_ua = 3200 # a transmitter fault level
282
+ rec = _run(current_in_phase(benchpod_plug(transport=tx), current_range=(0.0119, 0.0121)))
283
+ assert rec.outcome == tr.Outcome.FAIL
284
+ with pytest.raises(ValueError, match="current_range"):
285
+ current_in_phase(benchpod_plug(transport=tx), current_range=(0.02, 0.004))
286
+
287
+
258
288
  def test_adc_read_phase_records_volts():
259
289
  tx = FakeTransport()
260
290
  rec = _run(adc_read_phase(benchpod_plug(transport=tx), source="ext", v_range=(11.0, 13.0)))
@@ -0,0 +1,62 @@
1
+ """Every public name of embeddedci-openhtf is documented in its README.
2
+
3
+ Covers ``embeddedci_openhtf.__all__``, the public attributes and methods of ``BenchPodPlug``, and
4
+ the OpenHTF conf keys the plug declares. Each must appear inside a code span or code block of
5
+ ``README.md``. A name left out on purpose goes in ``ALLOWLIST`` with the reason.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Dict, List, Set
14
+
15
+ import embeddedci_openhtf
16
+ from embeddedci_openhtf import plug as plug_module
17
+
18
+ README = Path(__file__).resolve().parents[1] / "README.md"
19
+
20
+ #: name -> why it is not in the README.
21
+ ALLOWLIST: Dict[str, str] = {
22
+ "tearDown": "OpenHTF plug lifecycle hook, called by OpenHTF, not by users",
23
+ "__version__": "standard package metadata",
24
+ }
25
+
26
+
27
+ def _code_text() -> str:
28
+ text = README.read_text(encoding="utf-8")
29
+ fenced = re.compile(r"^```.*?^```", re.M | re.S)
30
+ return "\n".join(fenced.findall(text) + re.findall(r"`([^`\n]+)`", fenced.sub("", text)))
31
+
32
+
33
+ def public_names() -> Set[str]:
34
+ names = set(embeddedci_openhtf.__all__)
35
+ for name, value in vars(embeddedci_openhtf.BenchPodPlug).items():
36
+ if not name.startswith("_") and (inspect.isfunction(value) or not callable(value)):
37
+ names.add(name)
38
+ names.add("pod") # set per instance in __init__
39
+ source = inspect.getsource(plug_module)
40
+ names.update(re.findall(r"htf\.conf\.declare\(\s*\"(\w+)\"", source))
41
+ return names
42
+
43
+
44
+ def _missing() -> List[str]:
45
+ text = _code_text()
46
+ return sorted(n for n in public_names() if n not in ALLOWLIST
47
+ and not re.search(r"(?<!\w)" + re.escape(n) + r"(?!\w)", text))
48
+
49
+
50
+ def test_names_are_found():
51
+ assert {"BenchPodPlug", "benchpod_plug", "persistent", "benchpod_timeout"} <= public_names()
52
+
53
+
54
+ def test_every_public_name_is_documented():
55
+ missing = _missing()
56
+ assert not missing, ("names missing from packages/embeddedci-openhtf/README.md (document them "
57
+ "or add them to ALLOWLIST with a reason): " + ", ".join(missing))
58
+
59
+
60
+ def test_allowlist_is_still_needed():
61
+ stale = sorted(n for n in ALLOWLIST if n not in public_names())
62
+ assert not stale, "ALLOWLIST names that are no longer public: " + ", ".join(stale)
@@ -21,6 +21,8 @@ from embeddedci_openhtf import ( # noqa: E402
21
21
  adc_read_phase,
22
22
  benchpod_plug,
23
23
  boot_banner_phase,
24
+ current_in_phase,
25
+ current_out_phase,
24
26
  dac_output_phase,
25
27
  flash_phase,
26
28
  power_phase,
@@ -54,6 +56,25 @@ def test_analog_phases_against_the_pod(benchpod_connection):
54
56
  assert record.outcome == Outcome.PASS, failed
55
57
 
56
58
 
59
+ def test_current_loop_phases_against_the_pod(benchpod_connection):
60
+ """The 4-20 mA phases with nothing wired: the output takes a level and returns to its live
61
+ zero (no loop supply is needed for the pod to accept it), and the open input reads 0 mA."""
62
+ from embeddedci.benchpod import BenchPod
63
+
64
+ with BenchPod(benchpod_connection, lease=False) as probe:
65
+ if not probe.capabilities.current_out:
66
+ pytest.skip("this pod's firmware has no current_out command")
67
+ if os.environ.get("BENCHPOD_E2E_J8_WIRED") == "1":
68
+ pytest.skip("BENCHPOD_E2E_J8_WIRED=1: something is connected to J8")
69
+ bench = benchpod_plug(benchpod_connection, la_voltage=LA_VOLTAGE)
70
+ record, failed = _run(
71
+ current_out_phase(bench, current=0.012),
72
+ current_out_phase(bench, current=0.004, name="current_out_zero"),
73
+ current_in_phase(bench, current_range=(-0.0001, 0.0001)),
74
+ )
75
+ assert record.outcome == Outcome.PASS, failed
76
+
77
+
57
78
  def test_flash_and_boot_phases_against_the_dut(benchpod_connection, pytestconfig):
58
79
  firmware = pytestconfig.getoption("benchpod_firmware")
59
80
  if not firmware:
@@ -8,7 +8,7 @@ from embeddedci_openhtf import (
8
8
  close_persistent_benchpods,
9
9
  power_phase,
10
10
  )
11
- from embeddedci_openhtf.plug import _PERSISTENT_POOL
11
+ from embeddedci_openhtf.plug import _PERSISTENT_POOL, _pool_key
12
12
  from _fake import FakeTransport
13
13
 
14
14
 
@@ -47,14 +47,48 @@ def test_persistent_reconnects_after_drop():
47
47
  bench = benchpod_plug(transport=tx, persistent=True)
48
48
  try:
49
49
  _run(power_phase(bench, on=True))
50
- pod1 = _PERSISTENT_POOL[bench]
50
+ key = _pool_key(None, {"transport": tx, "timeout": 30.0})
51
+ pod1 = _PERSISTENT_POOL[key]
51
52
  # simulate the link dying: make the health-check ping fail
52
53
  def boom():
53
54
  raise OSError("link dropped")
54
55
  tx.ping = boom
55
56
  _run(power_phase(bench, on=True))
56
57
  # the dead connection was dropped and a fresh BenchPod opened
57
- pod2 = _PERSISTENT_POOL[bench]
58
+ pod2 = _PERSISTENT_POOL[key]
58
59
  assert pod2 is not pod1
59
60
  finally:
60
61
  close_persistent_benchpods()
62
+
63
+
64
+ def test_plugs_with_the_same_settings_share_one_connection():
65
+ tx = FakeTransport()
66
+ first = benchpod_plug(transport=tx, persistent=True, la_voltage=3.3)
67
+ second = benchpod_plug(transport=tx, persistent=True, la_voltage=3.3)
68
+ try:
69
+ _run(power_phase(first, efuse=1, on=True))
70
+ _run(power_phase(second, efuse=1, on=True))
71
+ assert len(_PERSISTENT_POOL) == 1
72
+ assert len(tx.power_calls) == 2
73
+ finally:
74
+ close_persistent_benchpods()
75
+
76
+
77
+ def test_different_settings_get_their_own_connection():
78
+ tx1, tx2 = FakeTransport(), FakeTransport()
79
+ try:
80
+ _run(power_phase(benchpod_plug(transport=tx1, persistent=True), on=True))
81
+ _run(power_phase(benchpod_plug(transport=tx2, persistent=True), on=True))
82
+ _run(power_phase(benchpod_plug(transport=tx1, persistent=True, timeout=5.0), on=True))
83
+ assert len(_PERSISTENT_POOL) == 3
84
+ finally:
85
+ close_persistent_benchpods()
86
+ assert tx1.closed and tx2.closed
87
+
88
+
89
+ def test_pool_key_reads_settings_by_value():
90
+ wiring = {"signals": {"READY": 5}, "uart": {"baud": 115200}}
91
+ assert _pool_key("10.0.0.5:8080", {"wiring": wiring, "la_voltage": 3.3}) == \
92
+ _pool_key("10.0.0.5:8080", {"la_voltage": 3.3, "wiring": dict(wiring)})
93
+ assert _pool_key("10.0.0.5:8080", {}) != _pool_key("10.0.0.6:8080", {})
94
+ assert _pool_key("x", {"la_voltage": 1.8}) != _pool_key("x", {"la_voltage": 3.3})