From 98290acf1ded2851666c575e5085646bbf953b19 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Mon, 16 Nov 2026 16:46:03 -0600 Subject: [PATCH 1/2] embeddedci 3.0.0: wiring profiles on the pod, nothing wired by default, error codes - Wiring profiles stored on the pod (firmware wiring_list/get/put/delete/default): wiring_profile= (BENCHPOD_WIRING_PROFILE, pytest --benchpod-wiring-profile), load_wiring, stored_wiring, wiring_profiles, set_default_wiring, delete_wiring; save_wiring(profile=None, name=None) stores on the pod over any connection, with a revision check (BP0009) when saving the loaded profile. Older firmware keeps the embeddedci.com profile. - Schema version 2: Wiring() wires nothing, la_mv/efuse/i2c_addr are None when unset; the old defaults are Wiring.preset('embeddedci-reference'); version 1 data still fills them in. - power_on applies the profile first (I/O voltage, then the rail) and records it on the pod; never changes the I/O voltage under a powered board. - FirmwareError.code / .values / .docs_url from the firmware's error codes, rendered with the bundled catalog (error_catalog.json, scripts/sync-error-catalog.sh); errors.explain(). - embeddedci-openhtf 2.4.0 needs embeddedci 3. - README (wiring, error codes, options), changelogs with an upgrade guide, tests. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-openhtf/CHANGELOG.md | 6 + packages/embeddedci-openhtf/pyproject.toml | 4 +- .../embeddedci-openhtf/tests/test_power.py | 16 +- packages/embeddedci/CHANGELOG.md | 33 +++ packages/embeddedci/README.md | 103 +++++-- packages/embeddedci/pyproject.toml | 2 +- .../src/embeddedci/benchpod/client.py | 271 ++++++++++++++++-- .../embeddedci/benchpod/error_catalog.json | 254 ++++++++++++++++ .../src/embeddedci/benchpod/errors.py | 81 +++++- .../src/embeddedci/benchpod/protocol.py | 8 +- .../src/embeddedci/benchpod/pytest_plugin.py | 12 +- .../embeddedci/benchpod/transport/cloud.py | 4 +- .../src/embeddedci/benchpod/transport/tcp.py | 4 +- .../src/embeddedci/benchpod/wiring.py | 121 +++++--- packages/embeddedci/tests/api_surface.json | 17 +- packages/embeddedci/tests/test_client_v2.py | 3 +- packages/embeddedci/tests/test_i2c_master.py | 8 +- packages/embeddedci/tests/test_one_source.py | 27 +- .../embeddedci/tests/test_pin_directions.py | 22 +- packages/embeddedci/tests/test_spi.py | 10 +- .../embeddedci/tests/test_trigger_power.py | 5 +- packages/embeddedci/tests/test_wiring.py | 31 +- .../embeddedci/tests/test_wiring_profiles.py | 207 +++++++++++++ scripts/sync-error-catalog.sh | 13 + 24 files changed, 1115 insertions(+), 147 deletions(-) create mode 100644 packages/embeddedci/src/embeddedci/benchpod/error_catalog.json create mode 100644 packages/embeddedci/tests/test_wiring_profiles.py create mode 100755 scripts/sync-error-catalog.sh diff --git a/packages/embeddedci-openhtf/CHANGELOG.md b/packages/embeddedci-openhtf/CHANGELOG.md index d44a19c..1bfa7bd 100644 --- a/packages/embeddedci-openhtf/CHANGELOG.md +++ b/packages/embeddedci-openhtf/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog — `embeddedci-openhtf` +## 2.4.0 + +- Needs embeddedci 3.0: wiring profiles live on the pod and nothing is wired by default. A plug + without a wiring profile needs `efuse=` for power calls; pass `wiring=` or save the bench's + profile on the pod. + ## 2.3.1 - `signal_generate`, `signal_generate_phase` and `loopback_measure_phase` default to diff --git a/packages/embeddedci-openhtf/pyproject.toml b/packages/embeddedci-openhtf/pyproject.toml index 90dee78..6460d1a 100644 --- a/packages/embeddedci-openhtf/pyproject.toml +++ b/packages/embeddedci-openhtf/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "embeddedci-openhtf" -version = "2.3.1" +version = "2.4.0" description = "OpenHTF plug for driving an EmbeddedCI BenchPod directly over TCP or serial (no cloud)" readme = "README.md" requires-python = ">=3.10" @@ -23,7 +23,7 @@ classifiers = [ "Topic :: Software Development :: Testing", ] dependencies = [ - "embeddedci>=2.12.0,<3", + "embeddedci>=3.0.0,<4", "openhtf>=1.6", ] diff --git a/packages/embeddedci-openhtf/tests/test_power.py b/packages/embeddedci-openhtf/tests/test_power.py index f0a7280..ad65665 100644 --- a/packages/embeddedci-openhtf/tests/test_power.py +++ b/packages/embeddedci-openhtf/tests/test_power.py @@ -37,7 +37,7 @@ def _request(tx, cmd="power_profile"): def test_measure_power_returns_si_units(): tx = FakeTransport() - plug = benchpod_plug(transport=tx)() + plug = benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1})() profile = measure_power(plug, 1.0) assert isinstance(profile, PowerProfile) assert _request(tx) == {"cmd": "power_profile", "efuse": 1, "rate_hz": 500, @@ -51,7 +51,7 @@ def test_measure_power_returns_si_units(): def test_measure_power_passes_its_keywords_through(): tx = FakeTransport() - plug = benchpod_plug(transport=tx)() + plug = benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1})() profile = measure_power(plug, 0.5, efuse=2, rate_hz=500, keep_samples=2) req = _request(tx) assert req["efuse"] == 2 and req["rate_hz"] == 500.0 and req["keep_samples"] == 2 @@ -70,7 +70,7 @@ def test_measure_power_uses_the_wiring_profile_rail(): def test_measure_power_phase_records_current_voltage_and_energy(): tx = FakeTransport() - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0)) + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0)) assert rec.outcome == tr.Outcome.PASS phase = _phase(rec, "measure_power") assert _value(phase, "power_avg_current_a") == pytest.approx(0.052) @@ -85,20 +85,20 @@ def test_measure_power_phase_records_current_voltage_and_energy(): def test_measure_power_phase_limits_pass_and_fail(): tx = FakeTransport() - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0, + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0, avg_current_range=(0, 0.1), peak_current_range=(0, 0.2), energy_range=(0, 1.0))) assert rec.outcome == tr.Outcome.PASS tx = FakeTransport() - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0, + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0, avg_current_range=(0, 0.01))) # a 10 mA budget it blows assert rec.outcome == tr.Outcome.FAIL def test_measure_power_phase_attaches_the_kept_samples(): tx = FakeTransport() - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0, keep_samples=2, + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0, keep_samples=2, efuse=2, rate_hz=500, prefix="sleep")) phase = _phase(rec, "measure_power") assert _value(phase, "sleep_avg_current_a") == pytest.approx(0.052) @@ -109,7 +109,7 @@ def test_measure_power_phase_attaches_the_kept_samples(): def test_measure_power_phase_can_skip_the_attachment(): tx = FakeTransport() - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0, keep_samples=2, + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0, keep_samples=2, attachment=None)) assert "power.json" not in _phase(rec, "measure_power").attachments @@ -117,7 +117,7 @@ def test_measure_power_phase_can_skip_the_attachment(): def test_measure_power_phase_reports_a_fault_and_a_truncated_profile(): tx = FakeTransport() tx.power_stats = dict(tx.power_stats, fault=True, truncated=True) - rec = _run(measure_power_phase(benchpod_plug(transport=tx), duration=1.0)) + rec = _run(measure_power_phase(benchpod_plug(transport=tx, wiring={"version": 2, "efuse": 1}), duration=1.0)) assert rec.outcome == tr.Outcome.PASS # no limits were given; the log carries the warning assert _value(_phase(rec, "measure_power"), "power_peak_current_a") == pytest.approx(0.18) diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 417f1e6..1206269 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog — `embeddedci` +## 3.0.0 + +A major release: wiring profiles live on the pod, nothing is wired by default, and refusals carry +stable error codes. See "Upgrading to 3.0" below. + +- **Wiring profiles stored on the pod** (firmware with the wiring commands): up to 16 named profiles, + one of them the default, the same over LAN, USB and the cloud. `BenchPod(conn, + wiring_profile="k66")` (or `BENCHPOD_WIRING_PROFILE`, pytest `--benchpod-wiring-profile`) loads a + named one, else the pod's default. New: `bp.load_wiring(name)`, `bp.stored_wiring(name)`, + `bp.wiring_profiles()`, `bp.set_default_wiring(name)`, `bp.delete_wiring(name)`. + `bp.save_wiring(profile=None, name=None)` stores on the pod over any connection, signed in or + not; saving the loaded profile refuses (`BP0009`) when someone else saved it meanwhile. A file and + a profile name together is an error. +- **Nothing is wired by default** (schema version 2). `Wiring()` sets no pin, no I/O voltage + (`la_mv` None) and no power rail (`efuse` None); a call that needs one says which to pass. The old + defaults are `Wiring.preset("embeddedci-reference")`; `Wiring.defaults()` returns it. Version 1 + data (or data without `version`) still fills in those values. `Wiring.profile_name` and + `Wiring.profile_rev` say which stored profile a connection uses. +- **`bp.power_on()` applies the wiring profile first**: its I/O voltage (when the pod has none or + another one), then its rail, and records the profile on the pod. `power_on(wiring_profile=...)`. + It never changes the I/O voltage under a powered board. +- **Error codes**: `FirmwareError.code` (`"BP0009"`), `.values` and `.docs_url`, with the message and + the fix from the bundled catalog; `embeddedci.benchpod.errors.explain(code)`. + +### Upgrading to 3.0 + +- A script that relied on the default pins (for example `bp.flash()` with no `swclk`/`swdio` on a + LAN pod with no profile) now raises and names the missing pin. Save the bench's wiring once, + `bp.save_wiring(Wiring.preset(), name="default")` for the reference bench, or pass `wiring=`. +- `power_on()` without `efuse` needs a rail in the profile. +- `Wiring.la_voltage`, `.efuse` and `.i2c_address` can be None. +- Match refusals on `exc.code`, not on the message text. + ## 2.13.21 - GPIO expanders: `bp.expansion("tca9555", addr=0x20, sda=1, scl=2)` attaches an off-the-shelf I2C diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 4c6cff9..f23cb6c 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -310,6 +310,7 @@ macs = bp.mac_addresses() # MacAddresses(eth_mac='02:35:c7:76:b7:9b', wifi_ | `BENCHPOD_API_BASE` | no `api_base` argument / `--benchpod-api-base` | server base URL (default `https://www.embeddedci.com`) | | `BENCHPOD_BUILD_TARGET` | no `--benchpod-build-target` | platform id recorded by the `build_report` fixture | | `BENCHPOD_WIRING` | no `wiring` argument / `--benchpod-wiring` / `benchpod_wiring` fixture | wiring profile file (`.json`/`.toml`), see [Wiring profile](#wiring-profile) | +| `BENCHPOD_WIRING_PROFILE` | no `wiring_profile` argument / `--benchpod-wiring-profile` | the name of a wiring profile stored on the pod to use (default: the pod's default profile), see [Wiring profile](#wiring-profile) | | `BENCHPOD_WIRING_SOURCE` | no `wiring_source` argument | `local` never asks embeddedci.com for the pod's stored wiring profile; `auto` (default) does, see [Wiring profile](#wiring-profile) | | `BENCHPOD_LIFT_DAC_LIMITS` | pytest sessions | `1` clears the pod's DAC output limits for the session and restores the same limits at the end, even when tests fail (only with the output stage switched off) | | `BENCHPOD_TLS` | network connections | `auto` (default), `on` or `off`: TLS to the pod's LAN API on 8443, see [TLS on the LAN](#tls-on-the-lan) | @@ -318,6 +319,24 @@ macs = bp.mac_addresses() # MacAddresses(eth_mac='02:35:c7:76:b7:9b', wifi_ | `BENCHPOD_SENSOR_LIBRARY` | no `version` argument / `--benchpod-sensor-library` | sensor library version: `latest` or a release such as `0.2.0` (default: the version the SDK pins), see [Emulated sensors](#emulated-sensors) | | `BENCHPOD_SENSOR_CACHE` | sensor library downloads | cache folder for downloaded library versions (default `/embeddedci/benchpod-sensors`) | +## Error codes + +When the pod refuses a request, firmware with error codes sends a stable code with it, and the SDK +puts it on the exception: `FirmwareError.code` (`"BP0009"`), `.values` (the values that go with it, +`{"name": "k66", "rev": 2}`) and `.docs_url`. The message says what went wrong and how to fix it +from Python: + +```text +wiring_put: BP0009: The wiring profile k66 changed since it was loaded (it is now at revision 2); +load it again (bp.load_wiring("k66")), redo your change and save, or save under another name +(https://embeddedci.com/docs/errors#BP0009) +``` + +A code never changes meaning and is never reused, so match on `exc.code` in tests and scripts, not +on the text. `embeddedci.benchpod.errors.explain("BP0009")` prints a code's entry offline. +[embeddedci.com/docs/errors](https://embeddedci.com/docs/errors) lists every code. Older firmware +sends no code (`.code == ""`). + ## API conventions and stability 2.0.0 froze the API. The conventions hold everywhere: @@ -441,6 +460,7 @@ The `benchpod` fixture is a `BenchPod` instance, not the module — import const | `--benchpod-connection` | `BENCHPOD_CONNECTION` | — | connection string (also the `benchpod_connection` ini option) | | `--benchpod-la-voltage` | `BENCHPOD_LA_VOLTAGE` | — | override the `benchpod_la_voltage` fixture for one run (1.8 or 3.3); the flag wins over the fixture, the env var only applies when neither is set | | `--benchpod-wiring` | `BENCHPOD_WIRING` | — | wiring profile file (`.json`/`.toml`); the flag wins over the `benchpod_wiring` fixture, the env var only applies when neither is set | +| `--benchpod-wiring-profile` | `BENCHPOD_WIRING_PROFILE` | the pod's default | name of a wiring profile stored on the pod to run with; not with `--benchpod-wiring` | | `--benchpod-efuse` | — | the profile's rail | target-power rail for `benchpod_target` and `pins.efuse` (1 internal, 2 external); `benchpod_target` otherwise follows the wiring profile, `pins.efuse` is 1 | | `--benchpod-firmware` | — | — | firmware image for the `firmware` fixture | | `--benchpod-discover` | — | off | when no connection is configured, find one pod via mDNS (needs `[discovery]`) | @@ -470,7 +490,7 @@ benchpod_connection = 192.168.1.213 | Fixture | Scope | Provides | |---|---|---| | `benchpod_la_voltage` | session | the board's I/O voltage selected on connect — **override it in `conftest.py`** (default `None` → `BENCHPOD_LA_VOLTAGE`) | -| `benchpod_wiring` | session | the bench's wiring profile — **override it in `conftest.py`** (a `Wiring`, dict or file path; default `None` → `BENCHPOD_WIRING`, the pod's profile stored on embeddedci.com, the defaults; see [Wiring profile](#wiring-profile)). An explicit profile also supplies the LA voltage when nothing else sets one | +| `benchpod_wiring` | session | the bench's wiring profile — **override it in `conftest.py`** (a `Wiring`, dict or file path; default `None` → `BENCHPOD_WIRING`, a profile stored on the pod, nothing wired; see [Wiring profile](#wiring-profile)). An explicit profile also supplies the LA voltage when nothing else sets one | | `benchpod` | session | a connected `BenchPod` with the options above applied; LA channels left in GPIO mode are released when the session starts and ends; closed at session end | | `benchpod_connection` | session | the resolved connection string (skips when none) | | `benchpod_target` | function | `benchpod` with the target rail (`--benchpod-efuse`, else the wiring profile's) powered on for the test, off at teardown | @@ -527,44 +547,85 @@ la = bp.capture_la(100_000, trigger=Trigger("READY")) print(wiring.describe()) # a pin table: bias resistor and DUT direction per channel ``` -| Key | Default | Meaning | +| Key | When not set | Meaning | |---|---|---| -| `la_mv` | `3300` | LA I/O-bank voltage in mV (1800 or 3300); `wiring.la_voltage` in volts | -| `efuse` | `1` | target-power rail: 1 internal 5 V, 2 external | -| `uart_rx`, `uart_tx`, `uart_baud` | `5`, `4`, `115200` | `rx` samples the DUT's TX; `tx` drives the DUT's RX | -| `i2c_sda`, `i2c_scl`, `i2c_addr` | `1`, `2`, `"0x76"` | the I2C bus (emulated sensors default to it; put I2C on LA1-LA6, which have pull-ups) | -| `swd_swclk`, `swd_swdio`, `swd_nreset`, `swd_target` | `11`, `12`, `False`, `""` | flashing | +| `la_mv` | not set | LA I/O-bank voltage in mV (1800 or 3300); `wiring.la_voltage` in volts | +| `efuse` | not set (pass `efuse=`) | target-power rail: 1 internal 5 V, 2 external | +| `uart_rx`, `uart_tx`, `uart_baud` | not wired, not wired, `115200` | `rx` samples the DUT's TX; `tx` drives the DUT's RX | +| `i2c_sda`, `i2c_scl`, `i2c_addr` | not wired, not wired, not set | the I2C bus (emulated sensors default to it; put I2C on LA1-LA6, which have pull-ups) | +| `swd_swclk`, `swd_swdio`, `swd_nreset`, `swd_target` | not wired, not wired, `False`, `""` (auto-detect) | flashing | | `spi_sclk`, `spi_mosi`, `spi_miso`, `spi_cs` | not wired | decoder channels | | `signals` | `[]` | named signals: `Signal(name, la, direction="input"/"output"/"open_drain"/"bidir", active_low=False, description="")` | | `dut_dirs` | `{}` | the DUT direction of a role or signal where its default is wrong: `{"uart_rx": "bidir", "READY": "dut_input"}` (role key or signal name to `dut_input`, `dut_output` or `bidir`); see [pin directions](#gpio-on-the-la-pins) | +**Nothing is wired unless the profile says so** (schema version 2, SDK 3.0). A pin the profile does +not set is never driven, and a call that needs it says which one to pass: `bp.flash()` without +`swclk`/`swdio` in the profile raises `ValueError: swd_swclk was not given and the wiring profile has +no swd_swclk`. The EmbeddedCI reference bench (a NUCLEO-F446RE: UART on LA5/LA4, I2C on LA1/LA2, SWD +on LA11/LA12, 3.3 V, internal 5 V), what profiles used to default to, is a preset: +`Wiring.preset("embeddedci-reference")`. A version 1 file or dict (or one without a `version` key) +still means what it did: what it leaves out takes the reference bench's values, and the profile you +get back is version 2 with them written out. Re-save such a file as version 2 with +`benchpod wiring upgrade wiring.json`. + A role set to `None` is not wired. Construction validates the whole profile and raises `ValueError` listing every problem — including two roles or signals on one LA channel; `wiring.warnings()` lists wiring that works but is risky, such as an I2C bus on a channel without a pull-up. -**Where the profile comes from.** The web UI, the CLI, the SDK and the MCP server use one profile -per pod: the one stored on embeddedci.com. `bp.wiring` is resolved once, first match wins: +**Profiles live on the pod.** A pod with current firmware stores up to 16 named profiles (4096 bytes +of JSON each, 16 KB in all), and one of them is its default. Every connection sees the same ones: +LAN, USB and the cloud, from any computer, signed in or not. The web app shows them and keeps their +history. `bp.wiring` is resolved once, first match wins: | # | Source | `bp.wiring.source` | |---|---|---| | 1 | the `wiring=` argument (a `Wiring`, a dict, or a `.json`/`.toml` file); in pytest `--benchpod-wiring`, then the `benchpod_wiring` fixture | `dict`, `file` (a `Wiring` keeps its own) | | 2 | the `BENCHPOD_WIRING` file | `file` | -| 3 | the profile stored on embeddedci.com for this pod, as the web UI's Wiring tab shows it: for `embeddedci:` that device; over the LAN (or a USB console that answers JSON commands), the device the pod reports it is registered as, when an API key (`api_key=` / `BENCHPOD_API_KEY`) or the `benchpod login` session is available and that device is on the same account | `server` | -| 4 | the defaults | `defaults` | +| 3 | a profile stored on the pod: `wiring_profile="k66"` (or `BENCHPOD_WIRING_PROFILE`, pytest `--benchpod-wiring-profile`), else the pod's default profile. A named profile the pod does not have raises | `pod` | +| 4 | firmware that stores no profiles: the profile stored on embeddedci.com for this pod (for `embeddedci:` that device; over the LAN, the device the pod reports it is registered as, with an API key or the `benchpod login` session) | `server` | +| 5 | nothing: `Wiring.undefined()` | `undefined` | -Step 3 never fails the connection. Without credentials, with the pod not registered, the server -unreachable, or the pod on another account, the SDK logs why (logger `embeddedci.benchpod`) and uses -the defaults; over the LAN or USB it gives up after about 3 seconds. The STM32 pod's USB text -console cannot say which device it is registered as, so over USB the defaults apply unless -`wiring=` or `BENCHPOD_WIRING` gives a profile. `wiring_source="local"` (or -`BENCHPOD_WIRING_SOURCE=local`) skips step 3 entirely, for offline benches or a bench that should -ignore the stored profile. +A file (`wiring=` / `BENCHPOD_WIRING`) and a profile name together is an error, not a silent choice. +Step 4 never fails the connection: without credentials, with the pod not registered or the server +unreachable, the SDK logs why (logger `embeddedci.benchpod`) and goes on to step 5; +`wiring_source="local"` (or `BENCHPOD_WIRING_SOURCE=local`) skips it. -`bp.wiring = ...` swaps it for this connection; `bp.save_wiring(profile)` stores it for a cloud device. -A file holds the same JSON object the server stores: +```python +bp = BenchPod(conn) # the pod's default profile +bp = BenchPod(conn, wiring_profile="k66") # a named one + +bp.wiring = bp.wiring.with_changes(uart_baud=9600) # this connection only, nothing saved +bp.save_wiring() # store it, to the profile it was loaded from +bp.save_wiring(name="nrf52840") # store it under that name (created if new) +bp.save_wiring(Wiring.preset(), name="nucleo") # store a full profile (a Wiring, dict or file) +bp.load_wiring("k66") # this connection switches to another stored profile +bp.stored_wiring("k66") # read one without switching +bp.wiring_profiles() # {"default": "k66", "profiles": [{"name", "rev", "bytes"}], ...} +bp.set_default_wiring("k66") # what a connection loads when it names none +bp.delete_wiring("old") # not the default +``` + +`bp.wiring.profile_name` and `bp.wiring.profile_rev` say which stored profile (and revision) this +connection uses; both are empty when the profile came from elsewhere. + +Scripts and tests never save on their own: a test that changes the baud for one run must not change +the bench for everyone. Saving never changes the default; the pod's first profile becomes its +default. Saving the profile this connection loaded checks nobody saved it meanwhile: when someone +did, `save_wiring` raises `FirmwareError` with `code == "BP0009"` instead of overwriting their change +(`load_wiring` to see it). Saving refuses with `BP0016` while the DAC runs or a capture holds the +pod's bus; reading never touches it. Firmware that stores no profiles: `save_wiring()` replaces a +cloud device's single profile on embeddedci.com, and raises over the LAN or USB. + +**Power-on applies the profile.** `bp.power_on()` (or `bp.power_on(wiring_profile="k66")`) sets the +profile's I/O voltage when the pod has none or another one, then switches the profile's rail on and +records on the pod which profile powered the board (`target_status`). It never changes the I/O +voltage under a board that is already powered: that raises, and `bp.set_la_voltage()` does it if you +mean it. + +A file holds the same JSON object the pod stores: ```json -{"uart_rx": 3, "uart_tx": 4, "swd_target": "target/stm32f4x.cfg", +{"version": 2, "la_mv": 3300, "efuse": 1, "uart_rx": 3, "uart_tx": 4, "swd_target": "target/stm32f4x.cfg", "signals": [{"name": "TRIGGER", "la": 9, "direction": "output"}, {"name": "READY", "la": 10}]} ``` diff --git a/packages/embeddedci/pyproject.toml b/packages/embeddedci/pyproject.toml index ca9696c..8f4c145 100644 --- a/packages/embeddedci/pyproject.toml +++ b/packages/embeddedci/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "embeddedci" -version = "2.13.21" +version = "3.0.0" description = "BenchPod SDK and pytest plugin for EmbeddedCI hardware-in-the-loop testing" readme = "README.md" requires-python = ">=3.10" diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 8a5831f..69169c4 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -26,6 +26,7 @@ from __future__ import annotations import base64 +import json import logging import math import os @@ -33,6 +34,7 @@ import time import weakref from contextlib import contextmanager +from dataclasses import replace from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union from . import can as _can @@ -135,12 +137,16 @@ API_BASE_ENV = "BENCHPOD_API_BASE" API_KEY_ENV = "BENCHPOD_API_KEY" WIRING_ENV = "BENCHPOD_WIRING" +#: The name of the pod wiring profile to load (``wiring_profile=``); unset = the pod's default. +WIRING_PROFILE_ENV = "BENCHPOD_WIRING_PROFILE" #: ``local`` keeps the wiring lookup off embeddedci.com (see :attr:`BenchPod.wiring`). WIRING_SOURCE_ENV = "BENCHPOD_WIRING_SOURCE" #: Accepted ``wiring_source`` values: ``auto`` (the default) and ``local``. WIRING_SOURCES = ("auto", "local") #: Budget, in seconds, for finding a LAN/USB pod's stored wiring profile on embeddedci.com. _WIRING_LOOKUP_TIMEOUT = 3.0 +#: Bytes of a wiring profile per wiring_get / wiring_put (the firmware's WIRING_PIECE_MAX). +_WIRING_PIECE = 600 #: Levels of the firmware's parametric generator (it builds each waveform from 8-bit codes). _GENERATOR_MAX_CODE = 255 @@ -233,6 +239,9 @@ def _classified_errors() -> Iterator[None]: specific = classify_firmware_error(exc) if specific is exc: raise + if exc.code: # keep the pod's code on the specific error + from .errors import _attach_code + _attach_code(specific, exc.code, exc.values) raise specific from None @@ -263,6 +272,7 @@ def __init__( lease_ttl: int = DEFAULT_LEASE_TTL, wiring: Union[Wiring, Mapping[str, Any], str, "os.PathLike[str]", None] = None, wiring_source: Optional[str] = None, + wiring_profile: Optional[str] = None, ) -> None: """Open a BenchPod. @@ -292,9 +302,11 @@ def __init__( TCP/serial connections never lease. ``wiring`` is the bench's :class:`~embeddedci.benchpod.wiring.Wiring` profile (a ``Wiring``, a - dict, or a ``.json``/``.toml`` path) — see :attr:`wiring`. ``wiring_source`` (or + dict, or a ``.json``/``.toml`` path) — see :attr:`wiring`. ``wiring_profile`` (or + ``BENCHPOD_WIRING_PROFILE``) names one of the profiles stored on the pod (default: the pod's + default profile); it cannot be combined with ``wiring``. ``wiring_source`` (or ``BENCHPOD_WIRING_SOURCE``) is ``"auto"`` (default) or ``"local"``, which never asks - embeddedci.com for the stored profile. + embeddedci.com for the stored profile (only used for pods whose firmware stores none). """ source = (wiring_source if wiring_source is not None else os.environ.get(WIRING_SOURCE_ENV, "")).strip().lower() or "auto" @@ -302,6 +314,12 @@ def __init__( what = "wiring_source" if wiring_source is not None else WIRING_SOURCE_ENV raise ValueError(f"{what} must be 'auto' or 'local', got {source!r}") self._wiring_source = source + profile_name = (wiring_profile if wiring_profile is not None + else os.environ.get(WIRING_PROFILE_ENV, "")).strip() + if profile_name and (wiring is not None or os.environ.get(WIRING_ENV, "").strip()): + raise ValueError("pass a wiring file or profile (wiring= / BENCHPOD_WIRING) or the name of a " + "profile stored on the pod (wiring_profile= / BENCHPOD_WIRING_PROFILE), not both") + self._wiring_profile = profile_name self._wiring: Optional[Wiring] = Wiring.coerce(wiring) if wiring is not None else None self.timeout = timeout self._lease: Optional[DeviceLease] = None @@ -573,20 +591,26 @@ def wiring(self) -> Wiring: 1. the ``wiring`` argument (or an assigned profile); 2. the ``BENCHPOD_WIRING`` file; - 3. the profile stored on embeddedci.com for this pod (edited in the web UI's Wiring tab): + 3. a profile stored on the pod: ``wiring_profile`` (or ``BENCHPOD_WIRING_PROFILE``), else the + pod's default profile. ``source`` is then ``"pod"`` and :attr:`Wiring.profile_name` its + name. A named profile the pod does not have raises. Firmware that stores no profiles + skips this step; + 4. (firmware that stores no profiles) the profile stored on embeddedci.com for this pod (edited in the web UI's Wiring tab): for a cloud connection, the named device; for a LAN or USB connection, the device the pod reports it is registered as (``cloud_status``), when credentials are available (``api_key``/``BENCHPOD_API_KEY``, or the ``benchpod login`` session) and the device is on that account. ``source`` is then ``"server"``. Skipped with ``wiring_source="local"`` / ``BENCHPOD_WIRING_SOURCE=local``; - 4. the defaults. + 5. nothing: :meth:`Wiring.undefined` (no pin wired, no I/O voltage, no power rail). A call + that needs a pin then says which one to pass. - The lookup in step 3 never raises: without credentials, with the pod not registered, the - server unreachable or the device on another account, it logs why and uses the defaults, + The lookup in step 4 never raises: without credentials, with the pod not registered, the + server unreachable or the device on another account, it logs why and goes on to step 5, and on a LAN/USB connection it gives up after about 3 seconds. Channel arguments fall back to it — ``open_uart()``, ``capture_uart()``, ``flash()``, ``bp.sensors.start()``, the power rail — and :meth:`signal` / GPIO names come from it. - Assign a profile to use another one for this connection (not saved; see :meth:`save_wiring`). + Assign a profile to use another one for this connection (not saved; see :meth:`save_wiring`, + :meth:`load_wiring`). """ if self._wiring is None: self._wiring = self._resolve_wiring() @@ -601,10 +625,17 @@ def _resolve_wiring(self) -> Wiring: env = os.environ.get(WIRING_ENV, "").strip() if env: return Wiring.load(env) + pod = self._pod_wiring(self._wiring_profile or None) + if pod is not None: + return pod + if self._wiring_profile: + raise UnsupportedFeatureError( + f"wiring_profile={self._wiring_profile!r}: this pod's firmware does not store wiring " + "profiles; update it (`benchpod flash-self`) or pass wiring=", feature="wiring_store") if self._wiring_source == "local": - return Wiring.defaults() + return Wiring.undefined() if not self._device_name: # a LAN or USB pod - return self._local_pod_server_wiring() or Wiring.defaults() + return self._local_pod_server_wiring() or Wiring.undefined() api = self._try_server_api() if api is not None: try: @@ -612,8 +643,8 @@ def _resolve_wiring(self) -> Wiring: return Wiring.from_dict(data.get("profile") or {}, source="server", strict=False) except (BenchPodError, ValueError) as exc: _log.warning("could not load the wiring profile of %s from embeddedci.com (%s); " - "using the defaults", self._device_name, exc) - return Wiring.defaults() + "nothing is wired", self._device_name, exc) + return Wiring.undefined() def _wiring_credential(self, deadline: float) -> Optional[Tuple[Optional[str], Optional[Callable[[], str]]]]: """``(api_key, token_provider)`` for the wiring lookup of a LAN/USB pod, or None without @@ -662,7 +693,7 @@ def _local_pod_server_wiring(self) -> Optional[Wiring]: cred = self._wiring_credential(deadline) if cred is None: _log.info("wiring: no embeddedci.com credentials (BENCHPOD_API_KEY or `benchpod " - "login`), so the stored profile is not used; using the defaults") + "login`), so the stored profile is not used; nothing is wired") return None try: device_id = self._pod_cloud_device_id(deadline) @@ -671,10 +702,10 @@ def _local_pod_server_wiring(self) -> Optional[Wiring]: level = logging.INFO if type(self._transport).__name__ == "SerialTransport" \ else logging.WARNING _log.log(level, "wiring: could not ask the pod which embeddedci.com device it is " - "(%s); using the defaults", exc) + "(%s); nothing is wired", exc) return None if not device_id: - _log.info("wiring: the pod is not registered on embeddedci.com; using the defaults") + _log.info("wiring: the pod is not registered on embeddedci.com; nothing is wired") return None from .server_api import ServerApi, ServerApiError @@ -686,22 +717,176 @@ def _local_pod_server_wiring(self) -> Optional[Wiring]: except ServerApiError as exc: if exc.status in (401, 403, 404): _log.warning("wiring: the pod's embeddedci.com device %s is not on this account " - "(HTTP %s); using the defaults", device_id, exc.status) + "(HTTP %s); nothing is wired", device_id, exc.status) return None raise return Wiring.from_dict(data.get("profile") or {}, source="server", strict=False) except Exception as exc: # the lookup is a convenience: never fail the caller over it _log.warning("wiring: could not load the pod's profile from embeddedci.com (%s); " - "using the defaults", exc) + "nothing is wired", exc) + return None + + # -- wiring profiles stored on the pod (firmware wiring_store.h) -------------------------- + + def _pod_cmd(self) -> Optional[Callable[[Dict[str, Any]], Any]]: + return getattr(self._transport, "command", None) + + def _pod_wiring_list(self) -> Optional[Dict[str, Any]]: + """The pod's ``wiring_list``, or None when its firmware stores no profiles.""" + cmd = self._pod_cmd() + if cmd is None: + return None + try: + listing = _dict(cmd({"cmd": "wiring_list"})) + # Firmware that stores profiles always lists them; anything else does not store any. + return listing if isinstance(listing.get("profiles"), list) else None + except FirmwareError: + return None # older firmware refuses it ("unknown cmd"): it stores no profiles + except BenchPodError as exc: + if type(self._transport).__name__ == "SerialTransport": + return None # the USB console runs no JSON commands + raise exc + + def _pod_wiring_get(self, name: str) -> Tuple[Dict[str, Any], int]: + """One profile's JSON from the pod, read in pieces; a save meanwhile starts over.""" + cmd = self._pod_cmd() + assert cmd is not None + for _ in range(3): + buf, rev = b"", None + while True: + piece = _dict(cmd({"cmd": "wiring_get", "name": name, "offset": len(buf)})) + if rev is not None and piece.get("rev") != rev: + break + rev = int(piece.get("rev", 0)) + b64 = str(piece.get("data_b64", "")) + chunk = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)) + buf += chunk + if not chunk or len(buf) >= int(piece.get("total", 0)): + return json.loads(buf.decode("utf-8")), rev + raise BenchPodError(f"wiring profile {name!r} kept changing while it was read; try again") + + def _pod_wiring(self, name: Optional[str]) -> Optional[Wiring]: + """The pod's profile ``name`` (None: its default) as a Wiring, :meth:`Wiring.undefined` when + the pod has no profiles yet, or None when its firmware stores none.""" + listing = self._pod_wiring_list() + if listing is None: + return None + names = [str(p.get("name")) for p in listing.get("profiles") or []] + target = name or listing.get("default") + if not target: + return replace(Wiring.undefined(), source="pod") + if target not in names: + raise FirmwareError( + f"the pod has no wiring profile {target!r} (it has: {', '.join(names) or 'none'})", + cmd="wiring_get") + data, rev = self._pod_wiring_get(str(target)) + prof = Wiring.from_dict(data, source="pod", strict=False) + return replace(prof, source="pod", profile_name=str(target), profile_rev=rev) + + def wiring_profiles(self) -> Dict[str, Any]: + """The wiring profiles stored on the pod: ``{"default": "k66", "profiles": [{"name": "k66", + "rev": 3, "bytes": 812}, ...], "max_profiles": 16, "max_bytes": 4096, "free_bytes": ...}``. + Raises :class:`UnsupportedFeatureError` on firmware that stores none.""" + listing = self._pod_wiring_list() + if listing is None: + raise UnsupportedFeatureError("this pod's firmware does not store wiring profiles; update it " + "(`benchpod flash-self`)", feature="wiring_store") + return listing + + def stored_wiring(self, name: Optional[str] = None) -> Optional[Wiring]: + """The pod's stored profile ``name`` (None: its default) without switching this connection to + it; None when the pod has no such profile or its firmware stores none.""" + try: + return self._pod_wiring(name) + except FirmwareError: return None - def save_wiring(self, wiring: Union[Wiring, Mapping[str, Any], str, None] = None) -> Wiring: - """Store a wiring profile for this cloud device on embeddedci.com (default: :attr:`wiring`) - and use it. The server validates it too; a LAN pod keeps its profile in a file instead.""" + def load_wiring(self, name: Optional[str] = None) -> Wiring: + """Switch this connection to the pod's profile ``name`` (None: the pod's default) and return + it. Nothing on the pod changes; :meth:`set_default_wiring` changes the default.""" + prof = self._pod_wiring(name) + if prof is None: + raise UnsupportedFeatureError("this pod's firmware does not store wiring profiles; update it " + "(`benchpod flash-self`)", feature="wiring_store") + changed = prof != self._wiring + self._wiring = prof + if changed: + self._auto_pin_directions() + return prof + + def save_wiring(self, wiring: Union[Wiring, Mapping[str, Any], str, None] = None, *, + name: Optional[str] = None) -> Wiring: + """Store a wiring profile on the pod and use it on this connection. + + ``wiring``: the profile to store (a :class:`Wiring`, a dict or a ``.json``/``.toml`` path; + default: :attr:`wiring`). ``name``: the pod profile to store it as; default: the profile this + connection loaded (:attr:`Wiring.profile_name`), else the pod's default, else ``"default"``. + Saving to the profile this connection loaded checks that nobody saved it meanwhile and raises + :class:`FirmwareError` ``BP0009`` when someone did, instead of overwriting their change. + Saving never changes which profile is the pod's default (:meth:`set_default_wiring`), + except that the pod's first profile becomes its default. + + Works over every connection (LAN, USB, cloud), signed in or not. Pods whose firmware stores + no profiles: a cloud device's single profile on embeddedci.com is replaced (``name`` must + not be given); a LAN or USB pod raises (update the firmware). + """ profile = self.wiring if wiring is None else Wiring.coerce(wiring) + listing = self._pod_wiring_list() + if listing is None: + return self._save_server_wiring(profile, name) + loaded = self._wiring.profile_name if self._wiring is not None else "" + target = name or loaded or listing.get("default") or "default" + if_rev: Optional[int] = None + if target == loaded and self._wiring is not None: + if_rev = self._wiring.profile_rev + data = json.dumps(profile.to_dict(), separators=(",", ":")).encode("utf-8") + cmd = self._pod_cmd() + assert cmd is not None + done: Dict[str, Any] = {} + with _classified_errors(): + for off in range(0, len(data), _WIRING_PIECE): + req: Dict[str, Any] = {"cmd": "wiring_put", "name": target, "offset": off, "total": len(data), + "data_b64": base64.urlsafe_b64encode(data[off:off + _WIRING_PIECE]) + .decode("ascii").rstrip("=")} + if off == 0 and if_rev is not None: + req["if_revision"] = if_rev + done = _dict(cmd(req)) + saved = replace(profile, source="pod", profile_name=target, profile_rev=int(done.get("rev", 0))) + changed = saved != self._wiring + self._wiring = saved + if changed: + self._auto_pin_directions() + return saved + + def set_default_wiring(self, name: str) -> str: + """Make the pod's profile ``name`` the default: what a connection loads when it names none. + This connection keeps the profile it has (:meth:`load_wiring` switches).""" + cmd = self._pod_cmd() + if cmd is None or self._pod_wiring_list() is None: + raise UnsupportedFeatureError("this pod's firmware does not store wiring profiles; update it " + "(`benchpod flash-self`)", feature="wiring_store") + with _classified_errors(): + return str(_dict(cmd({"cmd": "wiring_default", "name": name})).get("default", name)) + + def delete_wiring(self, name: str) -> None: + """Delete the pod's profile ``name`` (not the default: make another one the default first).""" + cmd = self._pod_cmd() + if cmd is None or self._pod_wiring_list() is None: + raise UnsupportedFeatureError("this pod's firmware does not store wiring profiles; update it " + "(`benchpod flash-self`)", feature="wiring_store") + with _classified_errors(): + cmd({"cmd": "wiring_delete", "name": name}) + + def _save_server_wiring(self, profile: Wiring, name: Optional[str]) -> Wiring: + """Firmware without profile storage: the cloud device's single profile on embeddedci.com.""" + if name: + raise UnsupportedFeatureError(f"save_wiring(name={name!r}): this pod's firmware keeps one wiring " + "profile; update it (`benchpod flash-self`) to store several", + feature="wiring_store") if not self._device_name: - raise BenchPodError("saving a wiring profile needs a cloud device ('embeddedci:'); " - "for a LAN pod keep the profile in a file and pass wiring=") + raise UnsupportedFeatureError("saving a wiring profile on this pod needs newer firmware " + "(`benchpod flash-self`), or a cloud connection " + "('embeddedci:')", feature="wiring_store") api = self._require_server_api() api.put_wiring(api.resolve_device_id(self._device_name), profile.to_dict()) changed = profile != self._wiring @@ -744,6 +929,9 @@ def _wired(self, value: Any, key: str) -> int: return la def _efuse(self, efuse: Optional[Union[Efuse, int]]) -> int: + if efuse is None and self.wiring.efuse is None: + raise ValueError("efuse was not given and the wiring profile sets no power rail: pass efuse=1 " + "(internal 5 V) or efuse=2 (external supply), or set efuse in the profile") return coerce_efuse(self.wiring.efuse if efuse is None else efuse) # -- LA I/O-bank voltage ------------------------------------------------ @@ -779,9 +967,44 @@ def target_power(self, efuse: Optional[Union[Efuse, int]] = None, *, self._transport.target_power(self._efuse(efuse), bool(on), _seconds_to_ms(delay, "delay")) def power_on(self, efuse: Optional[Union[Efuse, int]] = None, - *, delay: Optional[float] = None) -> None: - """Power the target on (omitted ``efuse``: the wiring profile's rail, INTERNAL 5 V by default).""" - self.target_power(efuse, on=True, delay=delay) + *, delay: Optional[float] = None, wiring_profile: Optional[str] = None) -> None: + """Power the target on with its wiring profile applied first. + + In order: ``wiring_profile`` (a profile stored on the pod) becomes this connection's + profile (:meth:`load_wiring`); the profile's I/O voltage is set when the pod has none or + another one; then the rail goes on (omitted ``efuse``: the profile's rail), and the pod + records which profile powered the board (``target_status``). The I/O voltage is never + changed under a board that is already powered: that raises, set it with + :meth:`set_la_voltage` yourself if you mean it. + """ + if wiring_profile: + self.load_wiring(wiring_profile) + w = self.wiring + rail = self._efuse(efuse) + if w.la_voltage is not None: + current = self.get_la_voltage().voltage + if current is None or abs(current - w.la_voltage) > 0.05: + if current is not None and self._rail_on(rail): + raise BenchPodError( + f"the board is powered with I/O at {current:g} V and the wiring profile wants " + f"{w.la_voltage:g} V: power it off first, or call set_la_voltage() if you mean it") + self.set_la_voltage(w.la_voltage) + _log.info("power_on: I/O set to %g V from the wiring profile %s", w.la_voltage, + w.profile_name or "(this connection's)") + cmd = self._pod_cmd() + if w.profile_name and cmd is not None and type(self._transport).__name__ != "SerialTransport": + req: Dict[str, Any] = {"cmd": "target_power", "efuse": rail, "state": 1, + "delay_ms": _seconds_to_ms(delay, "delay"), "profile": w.profile_name} + with _classified_errors(): + cmd(req) + return + self.target_power(rail, on=True, delay=delay) + + def _rail_on(self, rail: int) -> bool: + try: + return bool(self.target_status().efuse(rail).enabled) + except BenchPodError: + return False def power_off(self, efuse: Optional[Union[Efuse, int]] = None, *, delay: Optional[float] = None) -> None: diff --git a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json new file mode 100644 index 0000000..3c32dc9 --- /dev/null +++ b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json @@ -0,0 +1,254 @@ +{ + "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", + "version": 1, + "catalog_sha256": "e3f0e5ef3292ec9d3791bfb0e1de5b44f67b907385745b09286e1c2076a0b90f", + "docs_url": "https://embeddedci.com/docs/errors#{code}", + "codes": { + "BP0001": { + "name": "la_voltage_not_set", + "area": "io", + "since": "next", + "message": "The I/O voltage is not set", + "cause": "The pod starts with its I/O voltage unset and never picks one on its own, so it cannot drive a board at a voltage the board does not take. Anything that uses the LA pins (UART, flashing, captures, GPIO, I2C, SPI, sensor emulation) needs it first.", + "args": {}, + "fix": { + "sdk": "set the board's I/O voltage first: BenchPod(conn, la_voltage=3.3) (1.8 for a 1.8 V board), the benchpod_la_voltage fixture in conftest.py, or bp.set_la_voltage(3.3)", + "cli": "set the board's I/O voltage first: `benchpod la voltage 3.3V` (or 1.8V)", + "mcp": "call set_la_voltage with the board's I/O voltage (1.8 or 3.3) first", + "web": "Set the board's I/O voltage (1.8 V or 3.3 V) in the Pins pane first." + } + }, + "BP0002": { + "name": "unknown_command", + "area": "protocol", + "since": "next", + "message": "The pod does not know the command {cmd}", + "cause": "The firmware on the pod is older than the tool that sent the command, or the command name is wrong. Newer SDK, CLI and MCP versions check the pod's capabilities first and say which firmware a feature needs.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "update the pod's firmware (`benchpod flash-self`, or the firmware update in the web app)", + "cli": "update the pod's firmware with `benchpod flash-self`", + "mcp": "tell the user the pod's firmware is too old for this; they can update it with `benchpod flash-self` or in the web app", + "web": "Update the pod's firmware on its Settings tab." + } + }, + "BP0003": { + "name": "i2c_session_open", + "area": "i2c", + "since": "next", + "message": "An I2C session is already open", + "cause": "The pod runs one I2C master session at a time.", + "args": {}, + "fix": { + "sdk": "close the open session first (its close(), or leave its with block)", + "cli": "end the other I2C command first", + "mcp": "call i2c_close first", + "web": "Close the open I2C session first." + } + }, + "BP0004": { + "name": "spi_session_open", + "area": "spi", + "since": "next", + "message": "An SPI session is already open", + "cause": "The pod runs one SPI master session at a time.", + "args": {}, + "fix": { + "sdk": "close the open session first (its close(), or leave its with block)", + "cli": "end the other SPI command first", + "mcp": "wait for the other SPI call to finish, then try again", + "web": "Close the open SPI session first." + } + }, + "BP0005": { + "name": "bus_engine_busy", + "area": "spi", + "since": "next", + "message": "The engine that runs SWD, SPI and I2C is in use, so {want} cannot start", + "cause": "Flashing (SWD), the SPI master and the I2C master share one engine on the pod. While one of them runs, the other two wait.", + "args": { + "want": "str" + }, + "fix": { + "sdk": "wait for the running flash, SPI or I2C session to finish (close it), then try again", + "cli": "wait for the running flash, SPI or I2C command to finish, then try again", + "mcp": "wait for the running flash, spi or i2c call to finish (i2c_close for an open I2C session), then try again", + "web": "Wait for the running flash, SPI or I2C session to finish." + } + }, + "BP0006": { + "name": "missing_argument", + "area": "protocol", + "since": "next", + "message": "The request is missing {arg}", + "cause": "A required value was not sent. The SDK, CLI and MCP always send it, so this usually means a hand-written protocol request or a tool older than the firmware.", + "args": { + "arg": "str" + }, + "fix": { + "sdk": "pass {arg}; if you did, update the SDK (pip install -U embeddedci)", + "cli": "pass {arg}; if you did, update the CLI", + "mcp": "pass {arg} in the call", + "web": "Reload the page; if it keeps happening, update the pod's firmware." + } + }, + "BP0007": { + "name": "wiring_profile_not_found", + "area": "wiring", + "since": "next", + "message": "The pod has no wiring profile named {name}", + "cause": "Wiring profiles live on the pod. This one was never saved there, was deleted, or was saved on another pod.", + "args": { + "name": "str" + }, + "fix": { + "sdk": "list the pod's profiles with bp.wiring_profiles(), or save this one first with bp.save_wiring(profile, name=\"{name}\")", + "cli": "list the pod's profiles with `benchpod wiring list`, or save this one with `benchpod wiring save --name {name}`", + "mcp": "call wiring to list the pod's profiles, or save_wiring(name=\"{name}\") to create it", + "web": "Pick a profile from the list in the wiring dialog, or create {name} there." + } + }, + "BP0008": { + "name": "wiring_bad_name", + "area": "wiring", + "since": "next", + "message": "{name} is not a valid wiring profile name", + "cause": "Profile names are 1 to 40 characters: lowercase letters, digits and dashes, not starting with a dash.", + "args": { + "name": "str" + }, + "fix": { + "sdk": "use a name like \"nrf52840-dk\" or \"k66\"", + "cli": "use a name like nrf52840-dk or k66", + "mcp": "use a lowercase name with letters, digits and dashes, like \"nrf52840-dk\"", + "web": "Use lowercase letters, digits and dashes, like nrf52840-dk." + } + }, + "BP0009": { + "name": "wiring_revision_conflict", + "area": "wiring", + "since": "next", + "message": "The wiring profile {name} changed since it was loaded (it is now at revision {rev})", + "cause": "Someone saved {name} from another connection (the web app, another script or agent) after this one loaded it. Saving now would overwrite their change, so the pod refuses.", + "args": { + "name": "str", + "rev": "int" + }, + "fix": { + "sdk": "load it again (bp.load_wiring(\"{name}\")), redo your change and save, or save under another name", + "cli": "show the current one with `benchpod wiring show {name}`, then save again, or save under another name", + "mcp": "call load_wiring(\"{name}\") to see the new version, tell the user what changed, then save again or under another name", + "web": "Reload the profile to see the other change, then save again." + } + }, + "BP0010": { + "name": "wiring_store_full", + "area": "wiring", + "since": "next", + "message": "The pod cannot hold another wiring profile (at most {max}, and 16 KB in all)", + "cause": "Wiring profiles live on the pod, in a fixed amount of storage.", + "args": { + "max": "int" + }, + "fix": { + "sdk": "delete a profile you no longer use (bp.delete_wiring(\"name\")) or replace an existing one", + "cli": "delete a profile you no longer use with `benchpod wiring delete `", + "mcp": "ask the user which profile to delete (delete_wiring), or save over an existing one", + "web": "Delete a profile you no longer use in the wiring dialog." + } + }, + "BP0011": { + "name": "wiring_profile_too_large", + "area": "wiring", + "since": "next", + "message": "The wiring profile is {bytes} bytes; the pod takes at most {max}", + "cause": "One wiring profile fits in {max} bytes of JSON. Long signal descriptions or many signals add up.", + "args": { + "bytes": "int", + "max": "int" + }, + "fix": { + "sdk": "shorten the signal descriptions, or split the board into two profiles", + "cli": "shorten the signal descriptions, or split the board into two profiles", + "mcp": "shorten the signal descriptions, or split the wiring into two profiles", + "web": "Shorten the signal descriptions." + } + }, + "BP0012": { + "name": "wiring_not_json_object", + "area": "wiring", + "since": "next", + "message": "The wiring profile is not one JSON object", + "cause": "The pod stores a profile as the JSON object the tools send. This one is cut off or not an object, which points at a damaged upload or a hand-written request.", + "args": {}, + "fix": { + "sdk": "save it again; if it keeps failing, check the profile is valid (Wiring.from_dict)", + "cli": "save it again; check the file is valid JSON", + "mcp": "save it again with a valid profile object", + "web": "Save it again." + } + }, + "BP0013": { + "name": "wiring_delete_default", + "area": "wiring", + "since": "next", + "message": "{name} is the pod's default wiring profile and cannot be deleted", + "cause": "A connection that names no profile uses the default, so the pod always keeps one.", + "args": { + "name": "str" + }, + "fix": { + "sdk": "make another profile the default first (bp.set_default_wiring(\"other\")), then delete {name}", + "cli": "make another profile the default first (`benchpod wiring default `), then delete {name}", + "mcp": "call set_default_wiring with another profile first, then delete {name}", + "web": "Make another profile the default first." + } + }, + "BP0014": { + "name": "wiring_upload_out_of_order", + "area": "wiring", + "since": "next", + "message": "The wiring profile upload skipped ahead (the pod expected offset {expected})", + "cause": "Profiles are sent to the pod in pieces, in order, starting at offset 0. A piece went missing or another upload started in between.", + "args": { + "expected": "int" + }, + "fix": { + "sdk": "save again", + "cli": "save again", + "mcp": "call save_wiring again", + "web": "Save again." + } + }, + "BP0015": { + "name": "wiring_storage_failed", + "area": "wiring", + "since": "next", + "message": "The pod could not read or write its wiring profiles", + "cause": "The flash chip that holds the profiles did not answer or a write did not verify. Profiles saved before are kept: a write never replaces them until it has been read back.", + "args": {}, + "fix": { + "sdk": "try again; if it keeps failing, power-cycle the pod and report it", + "cli": "try again; if it keeps failing, power-cycle the pod and report it", + "mcp": "tell the user the pod's profile storage failed; try once more, then suggest power-cycling the pod", + "web": "Try again. If it keeps failing, power-cycle the pod and contact support." + } + }, + "BP0016": { + "name": "storage_busy", + "area": "wiring", + "since": "next", + "message": "The pod cannot save now: the DAC or a capture is using the bus the storage shares", + "cause": "The flash chip that holds the wiring profiles shares a bus with the DAC replay and the captures. Saving would stop a running waveform, so the pod refuses instead. Reading profiles always works.", + "args": {}, + "fix": { + "sdk": "stop the DAC (bp.dac_stop()) or wait for the capture to finish, then save again", + "cli": "stop the DAC (`benchpod dac stop`) or wait for the capture, then save again", + "mcp": "call dac_stop (after checking with the user) or wait for the capture to finish, then save again", + "web": "Stop the generator or wait for the capture to finish, then save." + } + } + } +} diff --git a/packages/embeddedci/src/embeddedci/benchpod/errors.py b/packages/embeddedci/src/embeddedci/benchpod/errors.py index cbbbf49..66a4f30 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/errors.py +++ b/packages/embeddedci/src/embeddedci/benchpod/errors.py @@ -2,8 +2,10 @@ from __future__ import annotations +import json import re -from typing import Optional +from importlib import resources +from typing import Any, Dict, Mapping, Optional class BenchPodError(Exception): @@ -71,9 +73,18 @@ class FirmwareError(BenchPodError): firmware uses (``la voltage not set``, ``pin conflict: LA4 is in use by gpio``) stay as they are. """ + #: The pod's stable error code (``"BP0009"``), "" from firmware without codes. Match on this, + #: not on the message text. https://embeddedci.com/docs/errors lists every code. + code: str = "" + #: The values sent with the code (``{"name": "k66", "rev": 2}``); ``args`` is Python's own. + values: Dict[str, Any] = {} + #: The code's docs page, "" without a code. + docs_url: str = "" + def __init__(self, message: str, *, cmd: Optional[str] = None) -> None: self.firmware_message = message self.cmd = cmd + self.values = {} text = _sdk_refusal_text(message) if status_too_large(message, cmd): text += (f"; firmware {STATUS_FITS_FIRMWARE} and later send a status that fits: update " @@ -375,6 +386,68 @@ def classify_firmware_error(exc: FirmwareError) -> FirmwareError: return exc -def firmware_error(message: str, *, cmd: Optional[str] = None) -> FirmwareError: - """The :class:`FirmwareError` (its specific subclass when there is one) for a pod refusal.""" - return classify_firmware_error(FirmwareError(message, cmd=cmd)) +# -- stable error codes ------------------------------------------------------------------------ +# +# Firmware with error codes sends {"status":"error","code":"BP0009","args":{...},"message":...}. +# error_catalog.json is benchpod-firmware's errors/errors.json (scripts/sync-error-catalog.sh): the +# message and the SDK's fix for each code. https://embeddedci.com/docs/errors lists them all. + +_CATALOG: Optional[Dict[str, Any]] = None + + +def error_catalog() -> Dict[str, Any]: + """The bundled error catalog: ``{"codes": {"BP0001": {...}}, "docs_url": ...}``.""" + global _CATALOG + if _CATALOG is None: + try: + text = resources.files(__package__).joinpath("error_catalog.json").read_text("utf-8") + _CATALOG = json.loads(text) + except (OSError, ValueError): + _CATALOG = {"codes": {}, "docs_url": "https://embeddedci.com/docs/errors#{code}"} + return _CATALOG + + +def error_docs_url(code: str) -> str: + """The docs page of an error code.""" + return str(error_catalog().get("docs_url", "https://embeddedci.com/docs/errors#{code}")).replace( + "{code}", code) + + +def _fill(template: str, values: Mapping[str, Any]) -> str: + return re.sub(r"\{([a-z0-9_]+)\}", lambda m: str(values.get(m.group(1), "?")), template) + + +def explain(code: str, surface: str = "sdk") -> str: + """A code's entry as text: message, cause and the fix (``surface``: sdk, cli, mcp or web).""" + entry = error_catalog().get("codes", {}).get(code.strip().upper()) + if not entry: + return f"{code}: not in this SDK's catalog; see {error_docs_url(code.strip().upper())}" + return (f"{code.upper()} {entry['name']}: {entry['message']}\n\n{entry['cause']}\n\n" + f"Fix: {entry['fix'].get(surface, '')}\n{error_docs_url(code.upper())}") + + +def _attach_code(exc: FirmwareError, code: str, values: Optional[Mapping[str, Any]]) -> FirmwareError: + """Put the pod's code and values on exc and, when the catalog knows the code, render its + message and the SDK's fix: ``cmd: BP0009: The wiring profile k66 changed ...; load it again + ... (https://embeddedci.com/docs/errors#BP0009)``.""" + exc.code = code + exc.values = dict(values or {}) + exc.docs_url = error_docs_url(code) if code else "" + entry = error_catalog().get("codes", {}).get(code) if code else None + if entry: + text = f"{code}: {_fill(entry['message'], exc.values)}; {_fill(entry['fix']['sdk'], exc.values)} ({exc.docs_url})" + exc.args = (f"{exc.cmd}: {text}" if exc.cmd else text,) + elif code: + exc.args = (f"{exc.args[0] if exc.args else exc.firmware_message} [{code}: {exc.docs_url}]",) + return exc + + +def firmware_error(message: str, *, cmd: Optional[str] = None, code: str = "", + values: Optional[Mapping[str, Any]] = None) -> FirmwareError: + """The :class:`FirmwareError` (its specific subclass when there is one) for a pod refusal. + ``code`` / ``values``: the pod's stable error code and its args, when the firmware sends them.""" + exc = FirmwareError(message, cmd=cmd) + if code == "BP0002": # unknown command: the firmware lacks the feature + exc = UnsupportedFeatureError(message, cmd=cmd, feature=cmd or "") + exc = classify_firmware_error(exc) + return _attach_code(exc, code or "", values) diff --git a/packages/embeddedci/src/embeddedci/benchpod/protocol.py b/packages/embeddedci/src/embeddedci/benchpod/protocol.py index 035b6de..10ce319 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/protocol.py +++ b/packages/embeddedci/src/embeddedci/benchpod/protocol.py @@ -23,6 +23,9 @@ class Reply: data: Any = None message: str = "" more: bool = False + #: The stable error code and its values of an error reply (firmware with error codes). + code: str = "" + args: Any = None def encode_request(req: dict) -> bytes: @@ -46,6 +49,8 @@ def parse_reply(line: bytes) -> Reply: data=obj.get("data"), message=str(obj.get("message", "")), more=bool(obj.get("more", False)), + code=str(obj.get("code") or ""), + args=obj.get("args") if isinstance(obj.get("args"), dict) else None, ) @@ -56,7 +61,8 @@ def raise_for_status(reply: Reply, cmd: Optional[str] = None) -> Reply: Returns the reply unchanged on success so callers can chain. """ if reply.status == "error": - raise firmware_error(reply.message or "unknown firmware error", cmd=cmd) + raise firmware_error(reply.message or "unknown firmware error", cmd=cmd, code=reply.code, + values=reply.args) if reply.status not in ("ok", "chunk"): raise TransportError(f"unexpected reply status {reply.status!r}") return reply diff --git a/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py b/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py index 6a91252..5d40b30 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py +++ b/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py @@ -167,8 +167,14 @@ def pytest_addoption(parser: "pytest.Parser") -> None: "--benchpod-wiring", action="store", default=None, dest="benchpod_wiring", help="Wiring profile file (.json or .toml): which DUT signal is on which LA channel. Normally " "set once by overriding the benchpod_wiring fixture in conftest.py; this flag wins over it. " - "Without either: BENCHPOD_WIRING, then the profile stored on embeddedci.com for the pod " - "(BENCHPOD_WIRING_SOURCE=local skips it), then the defaults.", + "Without either: BENCHPOD_WIRING, then a profile stored on the pod (--benchpod-wiring-profile, " + "else the pod's default), then (older firmware) the profile stored on embeddedci.com " + "(BENCHPOD_WIRING_SOURCE=local skips it), else nothing is wired.", + ) + group.addoption( + "--benchpod-wiring-profile", action="store", default=None, dest="benchpod_wiring_profile", + help="Name of a wiring profile stored on the pod to run with (default: the pod's default " + "profile; also BENCHPOD_WIRING_PROFILE). Cannot be combined with --benchpod-wiring.", ) group.addoption( "--benchpod-discover", @@ -428,10 +434,12 @@ def benchpod(benchpod_connection: str, benchpod_la_voltage: Optional[float], la_voltage = benchpod_la_voltage # None still lets BenchPod read BENCHPOD_LA_VOLTAGE if la_voltage is None and wiring is not None and not os.environ.get("BENCHPOD_LA_VOLTAGE"): la_voltage = wiring.la_voltage + profile_name = pytestconfig.getoption("benchpod_wiring_profile") device = BenchPod( benchpod_connection, la_voltage=la_voltage, wiring=wiring, + **({"wiring_profile": profile_name} if profile_name else {}), **_cloud_kwargs(pytestconfig), ) _release_gpio(device) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py index c2d0464..930a602 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py @@ -433,7 +433,9 @@ def command(self, req: dict) -> Any: # type: ignore[override] continue break if payload.get("status") == "error": - raise firmware_error(payload.get("error") or "device returned an error", cmd=cmd) + raise firmware_error(payload.get("error") or "device returned an error", cmd=cmd, + code=str(payload.get("code") or ""), + values=payload.get("args") if isinstance(payload.get("args"), dict) else None) return payload.get("data") def _command_once(self, url: str, body: bytes, req: dict, cmd: Any, timeout: float) -> dict: diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index 2d80b2b..f8603d4 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -328,7 +328,9 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: if not isinstance(obj, dict): continue if obj.get("status") == "error": - raise firmware_error(obj.get("message") or "capture failed", cmd=cmd) + raise firmware_error(obj.get("message") or "capture failed", cmd=cmd, + code=str(obj.get("code") or ""), + values=obj.get("args") if isinstance(obj.get("args"), dict) else None) yield obj if not bool(obj.get("more", False)): return diff --git a/packages/embeddedci/src/embeddedci/benchpod/wiring.py b/packages/embeddedci/src/embeddedci/benchpod/wiring.py index 701e27a..bb54b85 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/wiring.py +++ b/packages/embeddedci/src/embeddedci/benchpod/wiring.py @@ -9,8 +9,11 @@ ... bp.signal("TRIGGER").pulse(0.005) # the LA channel the profile names TRIGGER -The same schema (version 1) is stored per device on embeddedci.com, where the web UI edits it, and a -cloud connection (``embeddedci:``) loads it from there. See :class:`Wiring`. +Profiles live on the pod (firmware with the wiring commands): up to 16 named profiles, one of them +the default, the same over LAN, USB and the cloud. Schema version 2: what a profile does not set is +undefined (that pin is not wired, no I/O voltage, no power rail). A version 1 object (or one without +a version) still means what it did: what it leaves out takes the reference bench's values +(:meth:`Wiring.preset`). See :class:`Wiring`. """ from __future__ import annotations @@ -23,7 +26,16 @@ from .constants import PULL_OHMS, PULLDOWN_CHANNELS -WIRING_VERSION = 1 +WIRING_VERSION = 2 +#: The schema versions :meth:`Wiring.from_dict` reads: 1 (missing keys = the reference bench) and 2. +WIRING_VERSIONS = (1, 2) +#: The reference bench (the EmbeddedCI NUCLEO-F446RE wiring), and what a version 1 profile fills in. +REFERENCE_BENCH: Mapping[str, Any] = { + "la_mv": 3300, "efuse": 1, "uart_rx": 5, "uart_tx": 4, "i2c_sda": 1, "i2c_scl": 2, + "i2c_addr": "0x76", "swd_swclk": 11, "swd_swdio": 12, +} +#: Presets: complete profiles to start a new one from (:meth:`Wiring.preset`). Copied, never linked. +PRESETS: Mapping[str, Mapping[str, Any]] = {"embeddedci-reference": REFERENCE_BENCH} #: Profile keys that name the LA channel of a DUT signal role. ROLE_KEYS: Tuple[str, ...] = ("uart_rx", "uart_tx", "i2c_sda", "i2c_scl", "swd_swclk", "swd_swdio", @@ -85,25 +97,27 @@ def to_dict(self) -> Dict[str, Any]: @dataclass(frozen=True) class Wiring: - """A bench's wiring profile (schema version 1). Construct it, :meth:`load` a file, or let - :attr:`BenchPod.wiring ` fetch it. + """A bench's wiring profile (schema version 2). Construct it, :meth:`load` a file, or let + :attr:`BenchPod.wiring ` load one from the pod. - Every field has the web UI's default, so ``Wiring()`` is the default bench and a profile only needs - what differs. A role set to ``None`` is not wired. Construction validates the whole profile and + What is not set is undefined: ``Wiring()`` wires nothing, has no I/O voltage (``la_mv`` None) and + no power rail (``efuse`` None); a call that needs one of them says so. Only plain call settings + keep a value (``uart_baud`` 115200, ``swd_nreset`` False, ``swd_target`` auto-detect). Start from + the reference bench with ``Wiring.preset("embeddedci-reference")``. Construction validates the whole profile and raises :class:`ValueError` listing every problem — including two roles or signals on one LA channel. :meth:`warnings` lists wiring that works but is risky (an I2C bus without a pod pull-up). """ - la_mv: int = 3300 - efuse: int = 1 - uart_rx: Optional[int] = 5 - uart_tx: Optional[int] = 4 + la_mv: Optional[int] = None + efuse: Optional[int] = None + uart_rx: Optional[int] = None + uart_tx: Optional[int] = None uart_baud: int = 115200 - i2c_sda: Optional[int] = 1 - i2c_scl: Optional[int] = 2 - i2c_addr: str = "0x76" - swd_swclk: Optional[int] = 11 - swd_swdio: Optional[int] = 12 + i2c_sda: Optional[int] = None + i2c_scl: Optional[int] = None + i2c_addr: Optional[str] = None + swd_swclk: Optional[int] = None + swd_swdio: Optional[int] = None swd_nreset: bool = False swd_target: str = "" spi_sclk: Optional[int] = None @@ -113,8 +127,13 @@ class Wiring: signals: Tuple[Signal, ...] = () #: Profile keys owned by other features (the control loop's ``loop_input_*``), kept as they are. extra: Mapping[str, Any] = field(default_factory=dict) - #: Where this profile came from: ``"defaults"``, ``"file"``, ``"server"`` or ``"dict"``. - source: str = field(default="defaults", compare=False) + #: Where this profile came from: ``"pod"``, ``"file"``, ``"server"``, ``"dict"``, ``"preset"`` or + #: ``"undefined"``. + source: str = field(default="undefined", compare=False) + #: The pod profile this was loaded from (``"k66"``), "" when it did not come from the pod. + profile_name: str = field(default="", compare=False) + #: That profile's revision on the pod when it was loaded (0: not from the pod). + profile_rev: int = field(default=0, compare=False) version: int = WIRING_VERSION #: The DUT direction of a role or signal where its default is wrong: role key or signal name #: -> ``dut_input``, ``dut_output`` or ``bidir`` (see :meth:`pin_dut_dirs`). @@ -131,20 +150,44 @@ def __post_init__(self) -> None: # -- construction --------------------------------------------------------- + @classmethod + def undefined(cls) -> "Wiring": + """A profile with nothing wired, no I/O voltage and no power rail.""" + return cls(source="undefined") + + @classmethod + def preset(cls, name: str = "embeddedci-reference") -> "Wiring": + """A complete profile to start from: ``"embeddedci-reference"`` is the EmbeddedCI reference + bench (a NUCLEO-F446RE: UART on LA5/LA4, I2C on LA1/LA2, SWD on LA11/LA12, 3.3 V, internal + 5 V). Save a copy under your own name: ``bp.save_wiring(Wiring.preset(), name="nucleo")``.""" + try: + values = PRESETS[name] + except KeyError: + raise ValueError(f"no wiring preset {name!r} (presets: {', '.join(sorted(PRESETS))})") from None + return cls(**values, source="preset") + @classmethod def defaults(cls) -> "Wiring": - """The default bench (the web UI's defaults).""" - return cls() + """The reference bench, what a profile was before version 2 left nothing undefined. Kept for + older code: use :meth:`preset` (or :meth:`undefined`).""" + return cls.preset("embeddedci-reference") @classmethod def from_dict(cls, data: Mapping[str, Any], *, source: str = "dict", strict: bool = True) -> "Wiring": - """Build a profile from its JSON object. Absent keys take their defaults; ``null`` pins are not - wired. ``strict=False`` keeps unknown keys in :attr:`extra` instead of rejecting them (for a - profile written by a newer server).""" + """Build a profile from its JSON object. Version 2: absent keys are undefined. Version 1, or no + ``version`` key: absent keys take the reference bench's values (:data:`REFERENCE_BENCH`), as + before version 2; the result is a version 2 profile with them written out. ``null`` pins are + not wired. ``strict=False`` keeps unknown keys in :attr:`extra` instead of rejecting them (for + a profile written by a newer server).""" if not isinstance(data, Mapping): raise ValueError("invalid wiring: a wiring profile must be a JSON object") - scalar = {f.name for f in fields(cls)} - {"signals", "extra", "source", "dut_dirs"} + version = data.get("version", 1) + if not _is_int(version) or version not in WIRING_VERSIONS: + raise ValueError(f"invalid wiring: version must be 1 or 2, got {version!r}") + if version == 1: + data = {**REFERENCE_BENCH, **data, "version": WIRING_VERSION} + scalar = {f.name for f in fields(cls)} - {"signals", "extra", "source", "dut_dirs", "profile_name", "profile_rev"} kwargs: Dict[str, Any] = {} extra: Dict[str, Any] = {} unknown: List[str] = [] @@ -202,10 +245,10 @@ def with_changes(self, **changes: Any) -> "Wiring": return replace(self, **changes) def to_dict(self) -> Dict[str, Any]: - """The profile's JSON object (every key, defaults included).""" + """The profile's JSON object, version 2: every key, ``null`` for what is not set.""" out: Dict[str, Any] = {"version": self.version} for f in fields(self): - if f.name in ("signals", "extra", "source", "version", "dut_dirs"): + if f.name in ("signals", "extra", "source", "version", "dut_dirs", "profile_name", "profile_rev"): continue out[f.name] = getattr(self, f.name) out["signals"] = [s.to_dict() for s in self.signals] @@ -216,14 +259,14 @@ def to_dict(self) -> Dict[str, Any]: # -- lookups ---------------------------------------------------------------- @property - def la_voltage(self) -> float: - """The LA I/O-bank voltage in volts (``la_mv / 1000``).""" - return self.la_mv / 1000.0 + def la_voltage(self) -> Optional[float]: + """The LA I/O-bank voltage in volts (``la_mv / 1000``), None when the profile sets none.""" + return None if self.la_mv is None else self.la_mv / 1000.0 @property - def i2c_address(self) -> int: - """``i2c_addr`` as a 7-bit integer.""" - return int(_i2c_address(self.i2c_addr)) # type: ignore[arg-type] + def i2c_address(self) -> Optional[int]: + """``i2c_addr`` as a 7-bit integer, None when the profile sets none.""" + return None if self.i2c_addr is None else int(_i2c_address(self.i2c_addr)) # type: ignore[arg-type] def assignments(self) -> Iterator[Tuple[str, int]]: """``(role or signal name, LA channel)`` for everything wired.""" @@ -295,7 +338,9 @@ def describe(self) -> str: direction.""" pins = self.pins() dirs = self.pin_dut_dirs() - lines = [f"LA I/O {self.la_voltage:g} V, target power eFuse {self.efuse}"] + io = f"{self.la_voltage:g} V" if self.la_voltage is not None else "not set" + rail = f"eFuse {self.efuse}" if self.efuse is not None else "not set" + lines = [f"LA I/O {io}, target power {rail}"] for la in range(1, 15): pull = PULL_OHMS.get(la) bias = (f"{pull} pull-{'down' if la in PULLDOWN_CHANNELS else 'up'}" if pull else "no pull") @@ -309,10 +354,10 @@ def _errors(self) -> List[str]: errs: List[str] = [] if self.version != WIRING_VERSION: errs.append(f"version must be {WIRING_VERSION}, got {self.version!r}") - if not _is_int(self.la_mv) or self.la_mv not in (1800, 3300): - errs.append(f"la_mv must be 1800 or 3300, got {self.la_mv!r}") - if not _is_int(self.efuse) or self.efuse not in (1, 2): - errs.append(f"efuse must be 1 (internal) or 2 (external), got {self.efuse!r}") + if self.la_mv is not None and (not _is_int(self.la_mv) or self.la_mv not in (1800, 3300)): + errs.append(f"la_mv must be 1800 or 3300 (or None: not set), got {self.la_mv!r}") + if self.efuse is not None and (not _is_int(self.efuse) or self.efuse not in (1, 2)): + errs.append(f"efuse must be 1 (internal) or 2 (external) (or None: not set), got {self.efuse!r}") if not _is_int(self.uart_baud) or not 300 <= self.uart_baud <= 4_000_000: errs.append(f"uart_baud must be 300..4000000, got {self.uart_baud!r}") for key in ROLE_KEYS: @@ -320,7 +365,7 @@ def _errors(self) -> List[str]: if la is not None and not (_is_int(la) and 1 <= la <= 14): errs.append(f"{key} must be an LA channel 1..14 or None, got {la!r}") addr = _i2c_address(self.i2c_addr) - if addr is None or not 0x03 <= addr <= 0x77: + if self.i2c_addr is not None and (addr is None or not 0x03 <= addr <= 0x77): errs.append(f"i2c_addr must be a 7-bit address 0x03..0x77, got {self.i2c_addr!r}") if not isinstance(self.swd_nreset, bool): errs.append(f"swd_nreset must be true or false, got {self.swd_nreset!r}") diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 2ede4a5..56f3cca 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -80,7 +80,7 @@ ] }, "BenchPod": { - "__init__": "(self, connection: 'Optional[str]' = None, *, la_voltage: 'Optional[float]' = None, timeout: 'float' = 30.0, transport: 'Optional[Transport]' = None, api_base: 'Optional[str]' = None, api_key: 'Optional[str]' = None, cloud_token: 'Optional[str]' = None, cloud_audience: 'Optional[str]' = None, cloud_user_token: 'Optional[Callable[[], str]]' = None, lease: 'bool' = True, lease_wait: 'float' = 600.0, lease_ttl: 'int' = 120, wiring: \"Union[Wiring, Mapping[str, Any], str, 'os.PathLike[str]', None]\" = None, wiring_source: 'Optional[str]' = None) -> 'None'", + "__init__": "(self, connection: 'Optional[str]' = None, *, la_voltage: 'Optional[float]' = None, timeout: 'float' = 30.0, transport: 'Optional[Transport]' = None, api_base: 'Optional[str]' = None, api_key: 'Optional[str]' = None, cloud_token: 'Optional[str]' = None, cloud_audience: 'Optional[str]' = None, cloud_user_token: 'Optional[Callable[[], str]]' = None, lease: 'bool' = True, lease_wait: 'float' = 600.0, lease_ttl: 'int' = 120, wiring: \"Union[Wiring, Mapping[str, Any], str, 'os.PathLike[str]', None]\" = None, wiring_source: 'Optional[str]' = None, wiring_profile: 'Optional[str]' = None) -> 'None'", "adc_range": "(self, range: 'Optional[AdcRange]' = None) -> 'AdcRangeState'", "adc_range_test": "(self) -> 'AdcRangeTest'", "adc_read": "(self, source: 'AdcSource' = 'ext', *, range: 'Optional[AdcRange]' = None) -> 'AdcReading'", @@ -121,6 +121,7 @@ "dac_output": "(self, path: 'DacOutputPath', *, volts: 'Optional[float]' = None) -> 'DacOutput'", "dac_stop": "(self) -> 'None'", "decode": "(self, source: 'Union[LaCapture, Sequence[int]]', protocol: 'DecodeProtocol' = 'i2c', *, sample_rate_hz: 'Optional[float]' = None, **channels: 'Any') -> 'list'", + "delete_wiring": "(self, name: 'str') -> 'None'", "disable_pulldown": "(self, *las: 'Union[Pin, int]') -> 'None'", "disable_pullup": "(self, *las: 'Union[Pin, int]') -> 'None'", "enable_pulldown": "(self, *las: 'Union[Pin, int]') -> 'None'", @@ -138,6 +139,7 @@ "la_step": "(self, la: 'Union[Pin, int]', *, steps: 'int', delay: 'float', dir_la: 'Optional[Union[Pin, int]]' = None, direction: 'int' = 0) -> 'Dict[str, Any]'", "lan_tls": "(self) -> \"'LanTls'\"", "leased": "property", + "load_wiring": "(self, name: 'Optional[str]' = None) -> 'Wiring'", "loop_input": "(self, input_code: 'Optional[int]' = None, *, source: 'Optional[LoopSource]' = None, step: 'Optional[int]' = None) -> 'LoopState'", "loop_probe": "(self) -> '_control_loop.IVPoint'", "mac_addresses": "(self, status: 'Optional[Mapping[str, Any]]' = None) -> \"'MacAddresses'\"", @@ -153,7 +155,7 @@ "ping": "(self) -> 'Any'", "power_cycle_and_capture": "(self, *, rx: 'Union[Pin, int, str, None]' = None, tx: 'Union[Pin, int, str, None]' = None, efuse: 'Optional[Union[Efuse, int]]' = None, delay: 'float' = 1.0, duration: 'float' = 4.0, baud: 'Optional[int]' = None, until: 'Optional[_uart.Until]' = None, off_settle: 'float' = 0.3) -> '_uart.UartCapture'", "power_off": "(self, efuse: 'Optional[Union[Efuse, int]]' = None, *, delay: 'Optional[float]' = None) -> 'None'", - "power_on": "(self, efuse: 'Optional[Union[Efuse, int]]' = None, *, delay: 'Optional[float]' = None) -> 'None'", + "power_on": "(self, efuse: 'Optional[Union[Efuse, int]]' = None, *, delay: 'Optional[float]' = None, wiring_profile: 'Optional[str]' = None) -> 'None'", "power_profile": "(self, *, efuse: 'Optional[Union[Efuse, int]]' = None, rate_hz: 'float' = 500.0, keep_samples: 'int' = 4096, max_duration: 'float' = 60.0) -> 'PowerProfileSession'", "power_status": "(self) -> 'PowerStatus'", "pull_state": "(self, la: 'Union[Pin, int]') -> 'PullState'", @@ -166,9 +168,10 @@ "reset_state": "(self) -> 'ResetState'", "reset_target": "(self, *, pulse: 'float' = 0.1) -> 'ResetState'", "save_capture_as_recording": "(self, capture: 'Capture', name: 'str', *, full_scale_v: 'Optional[float]' = None) -> \"'Waveform'\"", - "save_wiring": "(self, wiring: 'Union[Wiring, Mapping[str, Any], str, None]' = None) -> 'Wiring'", + "save_wiring": "(self, wiring: 'Union[Wiring, Mapping[str, Any], str, None]' = None, *, name: 'Optional[str]' = None) -> 'Wiring'", "sensors": "property", "server_api": "property", + "set_default_wiring": "(self, name: 'str') -> 'str'", "set_gpio": "(self, la: 'Union[Pin, int, str, Sequence[Union[Pin, int, str]]]', level: 'Union[int, Sequence[int]]') -> 'None'", "set_la_voltage": "(self, voltage: 'float') -> 'LaVoltage'", "set_lan_tls_cert": "(self, cert_pem: 'Union[str, bytes]', key_pem: 'Union[str, bytes]') -> \"'LanTls'\"", @@ -180,6 +183,7 @@ "spi_flash": "(self, image: \"Union[bytes, str, 'os.PathLike[str]']\", addr: 'int' = 0, *, erase: 'bool' = True, verify: 'bool' = True, hold_reset: 'bool' = False, sck: 'Union[Pin, int, str, None]' = None, mosi: 'Union[Pin, int, str, None]' = None, miso: 'Union[Pin, int, str, None]' = None, cs: 'Union[Pin, int, str, None]' = None, hz: 'int' = 6000000, mode: 'int' = 0, progress: 'Optional[_spi.Progress]' = None) -> '_spi.SpiFlashResult'", "status": "(self) -> 'Dict[str, Any]'", "store_adc_compensation": "(self, hf_dc_gain: 'float', c_top_pf: 'float') -> 'Calibration'", + "stored_wiring": "(self, name: 'Optional[str]' = None) -> 'Optional[Wiring]'", "supports": "(self, feature: 'str') -> 'bool'", "target_power": "(self, efuse: 'Optional[Union[Efuse, int]]' = None, *, on: 'bool', delay: 'Optional[float]' = None) -> 'None'", "target_status": "(self) -> 'TargetStatus'", @@ -188,7 +192,8 @@ "usb_network": "(self, on: 'Optional[bool]' = None) -> 'bool'", "wait_for_level": "(self, la: 'Union[Pin, int, str]', level: 'int', *, timeout: 'float', poll: 'float' = 0.005) -> 'bool'", "waveforms": "property", - "wiring": "property" + "wiring": "property", + "wiring_profiles": "(self) -> 'Dict[str, Any]'" }, "BenchPodError": {}, "BuildReporter": { @@ -1244,6 +1249,8 @@ "signals", "extra", "source", + "profile_name", + "profile_rev", "version", "dut_dirs" ], @@ -1259,8 +1266,10 @@ "load": "(cls, path: 'Union[str, Path]') -> \"'Wiring'\"", "pin_dut_dirs": "(self) -> 'Dict[int, str]'", "pins": "(self) -> 'Dict[int, str]'", + "preset": "(cls, name: 'str' = 'embeddedci-reference') -> \"'Wiring'\"", "signal": "(self, name: 'str') -> 'Signal'", "to_dict": "(self) -> 'Dict[str, Any]'", + "undefined": "(cls) -> \"'Wiring'\"", "warnings": "(self) -> 'List[str]'", "with_changes": "(self, **changes: 'Any') -> \"'Wiring'\"" }, diff --git a/packages/embeddedci/tests/test_client_v2.py b/packages/embeddedci/tests/test_client_v2.py index 691160d..e0ff57d 100644 --- a/packages/embeddedci/tests/test_client_v2.py +++ b/packages/embeddedci/tests/test_client_v2.py @@ -7,7 +7,7 @@ import pytest from embeddedci import benchpod -from embeddedci.benchpod import BenchPod, BenchPodError +from embeddedci.benchpod import Wiring, BenchPod, BenchPodError from embeddedci.benchpod.errors import UnsupportedFeatureError from embeddedci.benchpod.capabilities import Capabilities from embeddedci.benchpod.state import ( @@ -59,6 +59,7 @@ def close(self) -> None: def _bp(replies: Dict[str, Any] | None = None, **kwargs: Any) -> "tuple[BenchPod, FakeTransport]": t = FakeTransport(replies) + kwargs.setdefault("wiring", Wiring.preset()) return BenchPod(transport=t, lease=False, **kwargs), t diff --git a/packages/embeddedci/tests/test_i2c_master.py b/packages/embeddedci/tests/test_i2c_master.py index d86c97a..ad4f990 100644 --- a/packages/embeddedci/tests/test_i2c_master.py +++ b/packages/embeddedci/tests/test_i2c_master.py @@ -166,7 +166,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: def pod(**kw) -> "tuple[BenchPod, BusPod]": fake = BusPod(**kw) - return BenchPod(transport=fake, wiring=Wiring(i2c_sda=1, i2c_scl=2)), fake + return BenchPod(transport=fake, wiring=Wiring.preset().with_changes(i2c_sda=1, i2c_scl=2)), fake # -- I2C master --------------------------------------------------------------------------------- @@ -276,7 +276,7 @@ def test_old_gateware_refused_before_sending(): def test_firmware_gateware_refusal_is_unsupported_feature(): fake = BusPod(gateware=None) fake.gateware = None - bp = BenchPod(transport=fake, wiring=Wiring()) + bp = BenchPod(transport=fake, wiring=Wiring.preset()) fake.gateware = 40 # the pod itself refuses; the SDK saw no gateware in status with pytest.raises(UnsupportedFeatureError): bp.open_i2c() @@ -329,7 +329,7 @@ def test_la_pins_dir_and_warn(): def test_pin_directions_from_wiring(): - w = Wiring(uart_rx=5, uart_tx=4, i2c_sda=1, i2c_scl=2, spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10, swd_swclk=None, swd_swdio=None, + w = Wiring.preset().with_changes(uart_rx=5, uart_tx=4, i2c_sda=1, i2c_scl=2, spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10, swd_swclk=None, swd_swdio=None, signals=(Signal("ALARM", 11, "input"), Signal("TRIG", 12, "output"), Signal("RST", 13, "open_drain"))) bp, fake = pod() @@ -385,7 +385,7 @@ def test_capture_spi_and_gpio_sends(): cap = bp.capture_la(128, send=SpiSend(b"\x9f\x00")) assert fake.commands[-1]["send"] == {"bus": "spi", "tx": b64(b"\x9f\x00")} assert cap.send_result.bus == "spi" and cap.send_result.data == b"\x60\xff" - w = Wiring(signals=(Signal("STROBE", 6, "output"),)) + w = Wiring.preset().with_changes(signals=(Signal("STROBE", 6, "output"),)) bp2 = BenchPod(transport=fake, wiring=w) cap = bp2.capture_la(128, trigger=Trigger("STROBE", "falling"), send=GpioSend("STROBE", 0)) assert fake.commands[-1]["send"] == {"bus": "gpio", "la": 6, "level": 0} diff --git a/packages/embeddedci/tests/test_one_source.py b/packages/embeddedci/tests/test_one_source.py index 2ed6480..3ee36c6 100644 --- a/packages/embeddedci/tests/test_one_source.py +++ b/packages/embeddedci/tests/test_one_source.py @@ -1,7 +1,7 @@ """One wiring profile and one saved connection across the web UI, the CLI, the SDK and MCP. * A LAN/USB BenchPod reads the profile stored on embeddedci.com for the device the pod says it is - registered as, when credentials exist; every failure falls back to the defaults. + registered as, when credentials exist; every failure leaves nothing wired (Wiring.undefined). * ``BenchPod()`` without a connection uses the connection ``benchpod-cli`` saved; the pytest plugin only does so when asked with ``saved``. """ @@ -220,8 +220,9 @@ def test_no_credentials_means_defaults_without_asking_anyone(http, caplog): pod = Pod() with caplog.at_level(logging.INFO, logger="embeddedci.benchpod"): w = BenchPod(transport=pod, lease=False).wiring - assert w == Wiring() and w.source == "defaults" - assert pod.commands == [] and http.requests == [] + assert w == Wiring() and w.source == "undefined" + # Only the pod's own profiles are asked for (this fake pod's firmware stores none). + assert pod.commands == [{"cmd": "wiring_list"}] and http.requests == [] assert "no embeddedci.com credentials" in caplog.text @@ -229,7 +230,7 @@ def test_no_credentials_means_defaults_without_asking_anyone(http, caplog): {"configured": True, "device_id": ""}, {}]) def test_an_unregistered_pod_gets_the_defaults(monkeypatch, http, cloud): monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") - assert BenchPod(transport=Pod(cloud), lease=False).wiring.source == "defaults" + assert BenchPod(transport=Pod(cloud), lease=False).wiring.source == "undefined" assert http.requests == [] @@ -237,7 +238,7 @@ def test_a_pod_that_refuses_cloud_status_gets_the_defaults(monkeypatch, http, ca monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") pod = Pod(FirmwareError("cloud_status: unknown command")) with caplog.at_level(logging.WARNING, logger="embeddedci.benchpod"): - assert BenchPod(transport=pod, lease=False).wiring.source == "defaults" + assert BenchPod(transport=pod, lease=False).wiring.source == "undefined" assert http.requests == [] and "could not ask the pod" in caplog.text assert (pod.timeout, pod.dial_timeout) == (30.0, 10.0) @@ -248,7 +249,7 @@ def test_server_errors_fall_back_to_the_defaults(monkeypatch, http, caplog, stat monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") http.status = status with caplog.at_level(logging.WARNING, logger="embeddedci.benchpod"): - assert BenchPod(transport=Pod(), lease=False).wiring.source == "defaults" + assert BenchPod(transport=Pod(), lease=False).wiring.source == "undefined" assert phrase in caplog.text @@ -257,7 +258,7 @@ def test_server_errors_fall_back_to_the_defaults(monkeypatch, http, caplog, stat def test_an_unreachable_server_falls_back_to_the_defaults(monkeypatch, http, error): monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") http.error = error - assert BenchPod(transport=Pod(), lease=False).wiring.source == "defaults" + assert BenchPod(transport=Pod(), lease=False).wiring.source == "undefined" def test_an_expired_login_falls_back_to_the_defaults(tmp_path, http): @@ -265,14 +266,14 @@ def test_an_expired_login_falls_back_to_the_defaults(tmp_path, http): (_cli_dir(tmp_path) / "token.json").write_text(json.dumps({ "access_token": "a", "refresh_token": "r", "access_expires_at": past.isoformat(), "refresh_expires_at": past.isoformat()})) - assert BenchPod(transport=Pod(), lease=False).wiring.source == "defaults" + assert BenchPod(transport=Pod(), lease=False).wiring.source == "undefined" assert http.requests == [] def test_a_malformed_stored_profile_falls_back_to_the_defaults(monkeypatch, http): monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") http.body = {"profile": {"uart_rx": 99}} - assert BenchPod(transport=Pod(), lease=False).wiring.source == "defaults" + assert BenchPod(transport=Pod(), lease=False).wiring.source == "undefined" def test_explicit_wiring_and_the_wiring_file_still_win(monkeypatch, http, tmp_path): @@ -290,10 +291,10 @@ def test_explicit_wiring_and_the_wiring_file_still_win(monkeypatch, http, tmp_pa def test_wiring_source_local_skips_the_lookup(monkeypatch, http): monkeypatch.setenv("BENCHPOD_API_KEY", "eci_test") pod = Pod() - assert BenchPod(transport=pod, lease=False, wiring_source="local").wiring.source == "defaults" + assert BenchPod(transport=pod, lease=False, wiring_source="local").wiring.source == "undefined" monkeypatch.setenv("BENCHPOD_WIRING_SOURCE", "LOCAL") - assert BenchPod(transport=pod, lease=False).wiring.source == "defaults" - assert pod.commands == [] and http.requests == [] + assert BenchPod(transport=pod, lease=False).wiring.source == "undefined" + assert all(c == {"cmd": "wiring_list"} for c in pod.commands) and http.requests == [] # The argument wins over the variable. assert BenchPod(transport=pod, lease=False, wiring_source="auto").wiring.source == "server" @@ -302,7 +303,7 @@ def test_wiring_source_local_also_skips_a_cloud_devices_profile(monkeypatch): bp = BenchPod(transport=Pod(), lease=False, wiring_source="local") bp._device_name = "bench-1" monkeypatch.setattr(bp, "_try_server_api", lambda: pytest.fail("asked the server")) - assert bp.wiring.source == "defaults" + assert bp.wiring.source == "undefined" def test_a_bad_wiring_source_is_rejected(monkeypatch): diff --git a/packages/embeddedci/tests/test_pin_directions.py b/packages/embeddedci/tests/test_pin_directions.py index f9cf25f..4519e35 100644 --- a/packages/embeddedci/tests/test_pin_directions.py +++ b/packages/embeddedci/tests/test_pin_directions.py @@ -29,12 +29,12 @@ def _sent(fake): # -- the profile ---------------------------------------------------------------------------------- def test_defaults_cover_every_wired_role(): - assert Wiring().pin_dut_dirs() == {5: "dut_output", 4: "dut_input", 1: "bidir", 2: "bidir", + assert Wiring.preset().pin_dut_dirs() == {5: "dut_output", 4: "dut_input", 1: "bidir", 2: "bidir", 11: "dut_input", 12: "bidir"} def test_dut_dirs_override_roles_and_signals_case_insensitively(): - w = Wiring(signals=(Signal("READY", 9), Signal("TRIG", 10, "output")), + w = Wiring.preset().with_changes(signals=(Signal("READY", 9), Signal("TRIG", 10, "output")), dut_dirs={"uart_rx": "bidir", "ready": "dut_input"}) assert w.dut_dir("uart_rx") == "bidir" and w.dut_dir("READY") == "dut_input" assert w.dut_dir("TRIG") == "dut_input" and w.dut_dir("uart_tx") == "dut_input" @@ -48,7 +48,7 @@ def test_dut_dirs_override_roles_and_signals_case_insensitively(): ]) def test_dut_dirs_are_validated(dirs, msg): with pytest.raises(ValueError, match=msg): - Wiring(dut_dirs=dirs) + Wiring.preset().with_changes(dut_dirs=dirs) def test_dut_dirs_round_trip_and_old_profiles_stay_valid(): @@ -56,11 +56,11 @@ def test_dut_dirs_round_trip_and_old_profiles_stay_valid(): assert w.to_dict()["dut_dirs"] == {"READY": "bidir"} assert Wiring.from_dict(w.to_dict()) == w assert Wiring.from_dict({"uart_rx": 5}).dut_dirs == {} - assert Wiring().to_dict()["dut_dirs"] == {} + assert Wiring.preset().to_dict()["dut_dirs"] == {} def test_describe_shows_the_direction(): - text = Wiring().describe() + text = Wiring.preset().describe() assert "uart_rx" in text and "dut_output" in text.splitlines()[5] @@ -68,7 +68,7 @@ def test_describe_shows_the_direction(): def test_connect_sends_the_wiring_directions(): fake = BusPod() - bp = BenchPod(transport=fake, wiring=Wiring(signals=(Signal("READY", 9),))) + bp = BenchPod(transport=fake, wiring=Wiring.preset().with_changes(signals=(Signal("READY", 9),))) assert bp.pin_directions_status == "sent" assert _sent(fake) == [ {"cmd": "la_dir", "la": [3, 6, 7, 8, 10, 13, 14], "dir": "unknown"}, @@ -86,7 +86,7 @@ def test_connect_sends_the_wiring_directions(): @pytest.mark.parametrize("version", ["3.10.3", "3.9.6", ""]) def test_older_firmware_is_skipped_quietly(version): fake = OldPod(version) - bp = BenchPod(transport=fake, wiring=Wiring()) + bp = BenchPod(transport=fake, wiring=Wiring.preset()) assert _sent(fake) == [] assert bp.pin_directions_status.startswith("not sent: this pod's firmware") assert "la_dir (3.10.4+)" in bp.pin_directions_status @@ -94,18 +94,18 @@ def test_older_firmware_is_skipped_quietly(version): def test_a_new_profile_is_sent_and_moves_marks(): fake = BusPod() - bp = BenchPod(transport=fake, wiring=Wiring()) + bp = BenchPod(transport=fake, wiring=Wiring.preset()) fake.commands.clear() - bp.wiring = Wiring(uart_rx=9, uart_tx=10) + bp.wiring = Wiring.preset().with_changes(uart_rx=9, uart_tx=10) assert bp.pin_directions_status == "sent" assert fake.dirs[5] == "unknown" and fake.dirs[9] == "dut_output" and fake.dirs[10] == "dut_input" def test_a_driven_pin_does_not_fail_the_connect_or_the_assignment(): fake = BusPod() - bp = BenchPod(transport=fake, wiring=Wiring(uart_rx=None)) + bp = BenchPod(transport=fake, wiring=Wiring.preset().with_changes(uart_rx=None)) bp.gpio(9, "output") # LA9 unwired: a push-pull GPIO is fine - bp.wiring = Wiring(uart_rx=9) # now the profile says LA9 is the DUT's TX + bp.wiring = Wiring.preset().with_changes(uart_rx=9) # now the profile says LA9 is the DUT's TX assert "direction conflict: LA9" in bp.pin_directions_status # The rest still went out, DUT outputs last. assert fake.dirs[4] == "dut_input" and fake.dirs[1] == "bidir" diff --git a/packages/embeddedci/tests/test_spi.py b/packages/embeddedci/tests/test_spi.py index b256393..faaf4b8 100644 --- a/packages/embeddedci/tests/test_spi.py +++ b/packages/embeddedci/tests/test_spi.py @@ -100,7 +100,7 @@ def command(self, req: dict) -> Any: @pytest.fixture def pod(): fake = SpiPod() - bp = BenchPod(transport=fake, wiring=Wiring(uart_rx=3, uart_tx=4, spi_sclk=13, spi_mosi=14, spi_miso=6, spi_cs=5)) + bp = BenchPod(transport=fake, wiring=Wiring.preset().with_changes(uart_rx=3, uart_tx=4, spi_sclk=13, spi_mosi=14, spi_miso=6, spi_cs=5)) return bp, fake @@ -114,10 +114,10 @@ def test_open_spi_takes_pins_from_wiring_and_rounds_hz(pod): def test_open_spi_needs_the_capability_and_a_valid_mode(): - bp = BenchPod(transport=SpiPod(caps=["la"]), wiring=Wiring(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) + bp = BenchPod(transport=SpiPod(caps=["la"]), wiring=Wiring.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) with pytest.raises(BenchPodError): bp.open_spi() - bp = BenchPod(transport=SpiPod(), wiring=Wiring(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) + bp = BenchPod(transport=SpiPod(), wiring=Wiring.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) with pytest.raises(ValueError): bp.open_spi(mode=4) @@ -125,7 +125,7 @@ def test_open_spi_needs_the_capability_and_a_valid_mode(): def test_spi_modes_1_and_2_need_gateware_55(): from embeddedci.benchpod import UnsupportedFeatureError - wiring = Wiring(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10) + wiring = Wiring.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10) old = SpiPod(gateware=54) with pytest.raises(UnsupportedFeatureError, match="gateware v55"): BenchPod(transport=old, wiring=wiring).open_spi(mode=1) @@ -208,7 +208,7 @@ def test_spi_flash_holds_reset_and_releases_it_on_failure(pod): def test_spi_flash_refuses_an_empty_bus_before_erasing(): fake = SpiPod(present=False) - bp = BenchPod(transport=fake, wiring=Wiring(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) + bp = BenchPod(transport=fake, wiring=Wiring.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) with pytest.raises(FirmwareError, match="no SPI flash answers"): bp.spi_flash(b"\x01\x02") assert not [c for c in fake.commands if c.get("op") in ("erase", "write")] diff --git a/packages/embeddedci/tests/test_trigger_power.py b/packages/embeddedci/tests/test_trigger_power.py index 2458081..2a5e8c0 100644 --- a/packages/embeddedci/tests/test_trigger_power.py +++ b/packages/embeddedci/tests/test_trigger_power.py @@ -55,6 +55,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: def _bp(pod: Optional[StreamPod] = None, **kwargs: Any): pod = pod or StreamPod() + kwargs.setdefault("wiring", Wiring.preset()) return BenchPod(transport=pod, lease=False, **kwargs), pod @@ -79,7 +80,7 @@ def test_triggered_la_capture_request_and_result(): def test_trigger_names_come_from_the_wiring_profile(): - bp, pod = _bp(wiring=Wiring(signals=[Signal("READY", 10)])) + bp, pod = _bp(wiring=Wiring.preset().with_changes(signals=[Signal("READY", 10)])) bp.capture_la(8, trigger=Trigger("ready", "rising")) assert pod.requests[-1]["trigger"] == {"la": 10, "edge": "rising"} @@ -118,7 +119,7 @@ def test_triggers_need_firmware_that_has_them(): def test_measure_power_request_and_units(): - bp, pod = _bp(wiring=Wiring(efuse=2)) + bp, pod = _bp(wiring=Wiring.preset().with_changes(efuse=2)) pod.chunks["power_profile"] = [ {"status": "ok", "t_us": [0, 500000], "current_ua": [50000, 54000], "bus_mv": [5010, 5000], "more": True}, diff --git a/packages/embeddedci/tests/test_wiring.py b/packages/embeddedci/tests/test_wiring.py index 595080d..5d28631 100644 --- a/packages/embeddedci/tests/test_wiring.py +++ b/packages/embeddedci/tests/test_wiring.py @@ -10,13 +10,34 @@ import pytest from embeddedci.benchpod import BenchPod, Signal, Wiring +from embeddedci.benchpod.wiring import ROLE_KEYS -def test_defaults_are_the_web_ui_defaults(): +def test_nothing_is_wired_by_default(): w = Wiring() + assert all(getattr(w, k) is None for k in ROLE_KEYS) + assert (w.la_mv, w.la_voltage, w.efuse, w.i2c_addr, w.i2c_address) == (None, None, None, None, None) + assert w.uart_baud == 115200 and w.version == 2 and w.source == "undefined" and w.pins() == {} + assert Wiring.undefined() == w + + +def test_the_reference_preset_is_the_old_default_bench(): + w = Wiring.preset("embeddedci-reference") assert (w.uart_rx, w.uart_tx, w.uart_baud, w.i2c_sda, w.i2c_scl) == (5, 4, 115200, 1, 2) assert (w.swd_swclk, w.swd_swdio, w.efuse, w.la_voltage, w.i2c_address) == (11, 12, 1, 3.3, 0x76) - assert w.source == "defaults" and w.warnings() == [] + assert w.source == "preset" and w.warnings() == [] and Wiring.defaults() == w + with pytest.raises(ValueError, match="no wiring preset"): + Wiring.preset("nope") + + +def test_version_1_fills_the_reference_bench_and_version_2_does_not(): + assert Wiring.from_dict({"uart_rx": 7}).swd_swclk == 11 # no version: version 1 + assert Wiring.from_dict({"version": 1, "uart_rx": 7}).la_mv == 3300 + v2 = Wiring.from_dict({"version": 2, "uart_rx": 7}) + assert v2.uart_rx == 7 and v2.swd_swclk is None and v2.la_mv is None + assert Wiring.from_dict({"version": 1, "uart_rx": 7}).to_dict()["version"] == 2 + with pytest.raises(ValueError, match="version must be 1 or 2"): + Wiring.from_dict({"version": 3}) def test_lookups_by_role_and_signal(): @@ -43,12 +64,13 @@ def test_every_problem_is_reported_at_once(): def test_one_channel_one_user(): with pytest.raises(ValueError, match="LA4 is used by both uart_tx and i2c_sda"): - Wiring(i2c_sda=4) + Wiring(uart_tx=4, i2c_sda=4) with pytest.raises(ValueError, match="LA9 is used by both A and B"): Wiring(signals=[Signal("A", 9), Signal("B", 9)]) with pytest.raises(ValueError, match="already used"): Wiring(signals=[Signal("A", 9), Signal("a", 10)]) Wiring(uart_tx=None, i2c_sda=4) # not wired frees the channel + Wiring(i2c_sda=4) # nothing else is wired by default def test_warnings_for_risky_wiring(): @@ -192,7 +214,8 @@ def device_parameters(self, name): def test_save_wiring_needs_a_cloud_device(monkeypatch): monkeypatch.delenv("BENCHPOD_WIRING", raising=False) - with pytest.raises(Exception, match="cloud device"): + # A LAN pod whose firmware stores no profiles cannot save one. + with pytest.raises(Exception, match="newer firmware"): BenchPod(transport=WiredFake(), lease=False).save_wiring() diff --git a/packages/embeddedci/tests/test_wiring_profiles.py b/packages/embeddedci/tests/test_wiring_profiles.py new file mode 100644 index 0000000..68eb227 --- /dev/null +++ b/packages/embeddedci/tests/test_wiring_profiles.py @@ -0,0 +1,207 @@ +"""Wiring profiles stored on the pod (firmware wiring_store.h): loading, saving in pieces, revision +conflicts, the default, power-on with a profile, and the error codes on refusals.""" + +from __future__ import annotations + +import base64 +import json +from typing import Any, Dict, List, Optional + +import pytest + +from embeddedci.benchpod import BenchPod, Wiring +from embeddedci.benchpod.errors import FirmwareError, UnsupportedFeatureError, firmware_error + + +class ProfilePod: + """A fake pod transport that stores wiring profiles like the firmware does.""" + + def __init__(self, profiles: Optional[Dict[str, dict]] = None, default: str = "") -> None: + self.profiles: Dict[str, bytes] = {n: json.dumps(p).encode() for n, p in (profiles or {}).items()} + self.revs: Dict[str, int] = {n: 1 for n in self.profiles} + self.default = default or next(iter(self.profiles), "") + self.commands: List[dict] = [] + self.la_mv: Optional[int] = None + self.rails = {1: False, 2: False} + self._up = b"" + self._up_name = "" + self._if_rev: Optional[int] = None + + def status(self) -> Dict[str, Any]: + return {"board": "stm32h563", "adc_bits": 16, "caps": []} + + def ping(self) -> Any: + return "pong" + + def close(self) -> None: + pass + + def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: + self.rails[efuse] = on + + def _fail(self, code: str, msg: str, cmd: str, **values: Any) -> None: + raise firmware_error(msg, cmd=cmd, code=code, values=values) + + def command(self, req: dict) -> Any: + self.commands.append(req) + verb, name = req["cmd"], req.get("name", "") + if verb == "wiring_list": + return {"default": self.default or None, + "profiles": [{"name": n, "rev": self.revs[n], "bytes": len(b)} for n, b in self.profiles.items()], + "max_profiles": 16, "max_bytes": 4096, "free_bytes": 10000} + if verb == "wiring_get": + if name not in self.profiles: + self._fail("BP0007", "no such profile", verb, name=name) + data, off = self.profiles[name], req.get("offset", 0) + piece = data[off:off + 600] + return {"name": name, "rev": self.revs[name], "total": len(data), "offset": off, + "data_b64": base64.urlsafe_b64encode(piece).decode().rstrip("=")} + if verb == "wiring_put": + b64 = req["data_b64"] + piece = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)) + if req["offset"] == 0: + self._up, self._up_name, self._if_rev = b"", name, req.get("if_revision") + self._up += piece + if len(self._up) < req["total"]: + return {"name": name, "received": len(self._up), "total": req["total"]} + if self._if_rev is not None and self._if_rev != self.revs.get(name, 0): + self._fail("BP0009", "profile changed since it was loaded", verb, name=name, + rev=self.revs.get(name, 0)) + self.profiles[name] = self._up + self.revs[name] = self.revs.get(name, 0) + 1 + self.default = self.default or name + return {"name": name, "rev": self.revs[name], "default": self.default == name} + if verb == "wiring_default": + if name not in self.profiles: + self._fail("BP0007", "no such profile", verb, name=name) + self.default = name + return {"default": name} + if verb == "wiring_delete": + if name == self.default: + self._fail("BP0013", "cannot delete the default profile", verb, name=name) + del self.profiles[name] + return {"name": name, "deleted": True} + if verb == "la_voltage": + if "mv" in req: + self.la_mv = req["mv"] + return {"mv": self.la_mv or 0, "st": 1} + if verb == "target_status": + return {f"efuse{n}": {"enabled": int(self.rails[n]), "fault": 0, "valid": 1} for n in (1, 2)} + if verb == "target_power": + self.rails[req["efuse"]] = bool(req["state"]) + return {"efuse": req["efuse"], "enabled": req["state"], "delay_ms": 0} + return {} + + def sent(self, verb: str) -> List[dict]: + return [c for c in self.commands if c["cmd"] == verb] + + +K66 = {"version": 2, "la_mv": 1800, "efuse": 2, "uart_rx": 3, "uart_tx": 2} +NRF = {"version": 2, "la_mv": 3300, "efuse": 1, "swd_swclk": 11, "swd_swdio": 12} + + +@pytest.fixture(autouse=True) +def _no_env(monkeypatch): + for var in ("BENCHPOD_WIRING", "BENCHPOD_WIRING_PROFILE", "BENCHPOD_WIRING_SOURCE"): + monkeypatch.delenv(var, raising=False) + + +def test_the_pods_default_profile_is_loaded(): + pod = ProfilePod({"k66": K66, "nrf": NRF}, default="nrf") + w = BenchPod(transport=pod, lease=False).wiring + assert (w.source, w.profile_name, w.profile_rev, w.swd_swclk, w.uart_rx) == ("pod", "nrf", 1, 11, None) + + +def test_a_named_profile_is_loaded_and_a_missing_one_raises(): + pod = ProfilePod({"k66": K66, "nrf": NRF}, default="nrf") + assert BenchPod(transport=pod, lease=False, wiring_profile="k66").wiring.uart_rx == 3 + with pytest.raises(FirmwareError, match="no wiring profile 'nope'"): + _ = BenchPod(transport=pod, lease=False, wiring_profile="nope").wiring + + +def test_a_pod_without_profiles_wires_nothing(): + w = BenchPod(transport=ProfilePod(), lease=False).wiring + assert w == Wiring() and w.source == "pod" + + +def test_a_file_and_a_profile_name_together_is_an_error(monkeypatch): + with pytest.raises(ValueError, match="not both"): + BenchPod(transport=ProfilePod(), lease=False, wiring={"version": 2}, wiring_profile="k66") + monkeypatch.setenv("BENCHPOD_WIRING", "wiring.json") + with pytest.raises(ValueError, match="not both"): + BenchPod(transport=ProfilePod(), lease=False, wiring_profile="k66") + + +def test_a_big_profile_goes_both_ways_in_pieces(): + sigs = [{"name": f"S{i}", "la": i + 1, "description": "d" * 80} for i in range(14)] + pod = ProfilePod({"default": {"version": 2}}) + bp = BenchPod(transport=pod, lease=False) + saved = bp.save_wiring({"version": 2, "signals": sigs}, name="big") + assert len(pod.sent("wiring_put")) > 1 and saved.profile_name == "big" and saved.profile_rev == 1 + bp2 = BenchPod(transport=pod, lease=False, wiring_profile="big") + assert len(bp2.wiring.signals) == 14 and len(pod.sent("wiring_get")) > 1 + + +def test_saving_the_loaded_profile_checks_its_revision(): + pod = ProfilePod({"k66": K66}) + bp = BenchPod(transport=pod, lease=False) + assert bp.wiring.profile_rev == 1 # loaded now, at rev 1 + other = BenchPod(transport=pod, lease=False) + other.save_wiring(other.wiring.with_changes(uart_baud=9600)) # someone else saves k66 + with pytest.raises(FirmwareError) as exc: + bp.save_wiring(bp.wiring.with_changes(uart_baud=19200)) + err = exc.value + assert err.code == "BP0009" and err.values == {"name": "k66", "rev": 2} + assert "load it again" in str(err) and err.docs_url.endswith("#BP0009") + bp.load_wiring("k66") + assert bp.save_wiring(bp.wiring.with_changes(uart_baud=19200)).profile_rev == 3 + + +def test_saving_under_a_name_does_not_change_the_default(): + pod = ProfilePod({"k66": K66}) + bp = BenchPod(transport=pod, lease=False) + bp.save_wiring(NRF, name="nrf") + assert pod.default == "k66" and bp.wiring.profile_name == "nrf" + assert bp.set_default_wiring("nrf") == "nrf" and pod.default == "nrf" + assert bp.wiring_profiles()["default"] == "nrf" + + +def test_deleting_the_default_is_refused_with_its_code(): + pod = ProfilePod({"k66": K66, "nrf": NRF}, default="k66") + bp = BenchPod(transport=pod, lease=False) + with pytest.raises(FirmwareError) as exc: + bp.delete_wiring("k66") + assert exc.value.code == "BP0013" + bp.delete_wiring("nrf") + assert "nrf" not in pod.profiles + + +def test_power_on_applies_the_profile_first(): + pod = ProfilePod({"k66": K66, "nrf": NRF}, default="nrf") + bp = BenchPod(transport=pod, lease=False) + bp.power_on(wiring_profile="k66") + assert pod.la_mv == 1800 and pod.rails[2] is True + tp = pod.sent("target_power")[-1] + assert tp["profile"] == "k66" and tp["efuse"] == 2 + # A powered board never gets its I/O voltage changed by the next power_on. + with pytest.raises(Exception, match="power it off first"): + bp.power_on(efuse=2, wiring_profile="nrf") + + +def test_power_on_with_nothing_wired_needs_a_rail(): + with pytest.raises(ValueError, match="sets no power rail"): + BenchPod(transport=ProfilePod(), lease=False).power_on() + + +def test_firmware_without_profile_storage(): + class OldPod(ProfilePod): + def command(self, req: dict) -> Any: + if req["cmd"].startswith("wiring_"): + raise firmware_error("unknown cmd", cmd=req["cmd"], code="BP0002", values={"cmd": req["cmd"]}) + return super().command(req) + bp = BenchPod(transport=OldPod(), lease=False, wiring_source="local") + assert bp.wiring == Wiring() + with pytest.raises(UnsupportedFeatureError): + bp.wiring_profiles() + with pytest.raises(UnsupportedFeatureError, match="newer firmware"): + bp.save_wiring() diff --git a/scripts/sync-error-catalog.sh b/scripts/sync-error-catalog.sh new file mode 100755 index 0000000..1aeee14 --- /dev/null +++ b/scripts/sync-error-catalog.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Copy the BenchPod error catalog (errors/errors.json, generated in benchpod-firmware from +# errors/catalog.toml) into the SDK, which renders a refusal's message and fix from it. +# +# scripts/sync-error-catalog.sh [path/to/benchpod-firmware] # default: ../benchpod-firmware +set -euo pipefail +here="$(cd "$(dirname "$0")/.." && pwd)" +fw="${1:-$here/../benchpod-firmware}" +src="$fw/errors/errors.json" +dst="$here/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json" +[ -f "$src" ] || { echo "sync-error-catalog: no $src (pass the benchpod-firmware checkout)" >&2; exit 1; } +cp "$src" "$dst" +python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print("sync-error-catalog:", len(d["codes"]), "codes, catalog", d["catalog_sha256"][:12])' "$dst" From ca13c9e3fc46e0a0944c1fe25064fd9795687ed9 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Mon, 16 Nov 2026 16:46:03 -0600 Subject: [PATCH 2/2] embeddedci-mcp 3.0.0: stored wiring profiles, explicit save with hints, opt-in autosave - wiring lists the pod's profiles and unsaved_changes with a hint; new tools save_wiring, load_wiring, set_default_wiring, delete_wiring; connect(wiring_profile=), power_on(wiring_profile=). - set_wiring changes this connection only (version 2); --wiring-autosave / BENCHPOD_WIRING_AUTOSAVE also stores it, never a change of the I/O voltage, power rail or SWD target. - power_on applies the profile first and names it in the result. - Coded refusals show the code, the agent's fix and the docs link. - Agent instructions: ask before saving, never guess a missing pin. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 12 ++ packages/embeddedci-mcp/README.md | 13 +- packages/embeddedci-mcp/pyproject.toml | 4 +- packages/embeddedci-mcp/server.json | 4 +- .../src/embeddedci_mcp/__main__.py | 6 + .../src/embeddedci_mcp/guide.py | 2 +- .../src/embeddedci_mcp/models.py | 32 ++- .../src/embeddedci_mcp/server.py | 199 ++++++++++++++++-- .../src/embeddedci_mcp/session.py | 10 +- .../src/embeddedci_mcp/summaries.py | 3 +- packages/embeddedci-mcp/tests/conftest.py | 10 +- .../tests/test_saved_connection_and_wiring.py | 2 +- packages/embeddedci-mcp/tests/test_tools.py | 5 +- .../embeddedci-mcp/tests/test_wiring_tools.py | 6 +- .../embeddedci-mcp/tests/tools_surface.json | 146 ++++++++++++- 15 files changed, 402 insertions(+), 52 deletions(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index 3a3f96f..beb57d0 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog — `embeddedci-mcp` +## 3.0.0 + +- Needs embeddedci 3.0. Wiring profiles live on the pod: `wiring` lists them and reports + `unsaved_changes` with a hint; new tools `save_wiring`, `load_wiring`, `set_default_wiring`, + `delete_wiring`; `connect(wiring_profile=)` and `power_on(wiring_profile=)`. `set_wiring` changes + this connection only (version 2: what it leaves out is undefined); `--wiring-autosave` + (`BENCHPOD_WIRING_AUTOSAVE`) also stores it, never a change of the I/O voltage, rail or SWD target. +- `power_on` applies the profile first (I/O voltage, then the rail) and names the profile in its + result. +- Refusals with a stable error code show the code, the fix for an agent and the docs link. + + ## 2.13.21 - Needs embeddedci 2.13.21. New `expansion` tool: attach an I2C/SPI GPIO expander board diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index fff8d85..ae709b7 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -134,6 +134,7 @@ chat never blocks CI on that pod. | --- | --- | --- | --- | | `--connection` | `BENCHPOD_CONNECTION` | the CLI's saved connection, else mDNS | host[:port], serial device, `usb`, `usb:`, `discover`, `saved`, or `embeddedci:`; unset = `benchpod set-connection`'s saved one, else find the one pod on the LAN | | `--la-voltage` | `BENCHPOD_LA_VOLTAGE` | — | LA I/O voltage (1.8 or 3.3) applied on connect | +| `--wiring-autosave` | `BENCHPOD_WIRING_AUTOSAVE` | off | `set_wiring` also stores the profile on the pod (not a change of the I/O voltage, power rail or SWD target: those need `save_wiring`) | | — | `BENCHPOD_API_KEY` | — | cloud pods and the waveform library (without it, cloud tools use the `benchpod login` session) | | — | `BENCHPOD_API_BASE` | `https://www.embeddedci.com` | another embeddedci server | | — | `BENCHPOD_WIRING` | — | wiring profile file (`.json`/`.toml`) that wins over the stored profile | @@ -177,7 +178,7 @@ description, ranges and enums, so an agent sees more than this table. | Tool | Purpose | Parameters | | --- | --- | --- | -| `connect` | Open a connection (closing any previous one) and report status, capabilities and where the wiring profile came from. Without a `connection` or a configured default (`--connection`, `BENCHPOD_CONNECTION`, the CLI's saved connection), finds the one pod on the LAN over mDNS. | `connection`, `la_voltage`, `lease_wait=30` | +| `connect` | Open a connection (closing any previous one) and report status, capabilities and where the wiring profile came from. Without a `connection` or a configured default (`--connection`, `BENCHPOD_CONNECTION`, the CLI's saved connection), finds the one pod on the LAN over mDNS. `wiring_profile` names a profile stored on the pod (default: the pod's default profile). | `connection`, `la_voltage`, `lease_wait=30`, `wiring_profile` | | `disconnect` | Close UART/CAN sessions and the connection, releasing a cloud lease. | none | | `status` | Firmware, capabilities, LA voltage, open sessions and warnings (works when not connected); `eth_mac` and `wifi_mac`, the MACs a network admin registers before the pod gets an address (from the pod with firmware after 3.10.7, else from embeddedci.com's record; `wifi_mac` null until the pod scanned for Wi-Fi or joined). | none | | `set_la_voltage` | Select the LA I/O voltage to match the DUT (1.8 V needs a rev3 pod). | **`voltage`** | @@ -192,14 +193,18 @@ description, ranges and enums, so an agent sees more than this table. | Tool | Purpose | Parameters | | --- | --- | --- | -| `wiring` | Which DUT signal is on which LA channel, plus the power rail, UART baud and SWD target. | none | -| `set_wiring` | Replace the wiring profile for this connection, or store it on embeddedci.com. Also sends the profile's pin directions to the pod (`la_dir`, firmware 3.10.4+; `directions` in the result says whether it worked). | **`profile`**, `save=false` | +| `wiring` | Which DUT signal is on which LA channel, plus the I/O voltage, power rail, UART baud and SWD target; the profiles stored on the pod and `unsaved_changes` (what this connection changed that is not stored). What a profile does not set is undefined. | none | +| `set_wiring` | Replace the wiring profile for this connection only (version 2: what it leaves out is undefined); `save=true`, or the server's `--wiring-autosave`, also stores it on the pod. Autosave never stores a change of the I/O voltage, rail or SWD target. Also sends the profile's pin directions to the pod (`la_dir`, firmware 3.10.4+). | **`profile`**, `save=false` | +| `save_wiring` | Store this connection's profile (or `profile`) on the pod, under `name` or the profile it was loaded from. Saving the loaded profile refuses with `BP0009` when someone else saved it meanwhile. Never changes the pod's default. | `name`, `profile` | +| `load_wiring` | Switch this connection to a profile stored on the pod (omit `name`: the pod's default). Nothing on the pod changes. | `name` | +| `set_default_wiring` | Make a stored profile the pod's default: what every connection uses when it names none. | **`name`** | +| `delete_wiring` | Delete a stored profile (not the default: `BP0013`). | **`name`** | ### Power | Tool | Purpose | Parameters | | --- | --- | --- | -| `power_on` | Switch the target's power rail on (optionally scheduled pod-side). | `efuse`, `delay` | +| `power_on` | Power the board on with its wiring profile applied first: the profile's I/O voltage (when the pod has none or another one), then the rail; the pod records the profile. Never changes the I/O voltage under a powered board. `wiring_profile` powers on with a stored profile. | `efuse`, `delay`, `wiring_profile` | | `power_off` | Switch the target's power rail off. | `efuse`, `delay` | | `power_status` | Both target-power rails, internal 5 V (efuse 1) and external (efuse 2): on/off, tripped, bus voltage and current, and the pod's own draw. | none | | `reset_target` | Drive the DUT's reset line from the pod's reset pin. | `action=pulse`, `pulse=0.1` | diff --git a/packages/embeddedci-mcp/pyproject.toml b/packages/embeddedci-mcp/pyproject.toml index bd6235a..2e5cdbd 100644 --- a/packages/embeddedci-mcp/pyproject.toml +++ b/packages/embeddedci-mcp/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "embeddedci-mcp" -version = "2.13.21" +version = "3.0.0" description = "MCP server that lets AI agents drive an EmbeddedCI BenchPod hardware-in-the-loop bench" readme = "README.md" requires-python = ">=3.10" @@ -26,7 +26,7 @@ classifiers = [ dependencies = [ # cloud: the embeddedci: destination; discovery: connect("discover") over mDNS; # analysis: dominant frequency in capture summaries; yaml: sensor definitions an agent writes. - "embeddedci[cloud,discovery,analysis,yaml]>=2.13.21,<3", + "embeddedci[cloud,discovery,analysis,yaml]>=3.0.0,<4", "mcp>=1.12,<2", "anyio>=4", "pydantic>=2.7", diff --git a/packages/embeddedci-mcp/server.json b/packages/embeddedci-mcp/server.json index 3193650..acb890f 100644 --- a/packages/embeddedci-mcp/server.json +++ b/packages/embeddedci-mcp/server.json @@ -3,7 +3,7 @@ "name": "io.github.embeddedci-com/embeddedci-mcp", "title": "EmbeddedCI BenchPod", "description": "Drive a BenchPod hardware-in-the-loop bench: power, flash, UART, I2C, CAN, analog and logic.", - "version": "2.13.21", + "version": "3.0.0", "websiteUrl": "https://www.embeddedci.com/docs/benchpod-mcp", "repository": { "url": "https://github.com/embeddedci-com/embeddedci-python", @@ -15,7 +15,7 @@ "registryType": "pypi", "registryBaseUrl": "https://pypi.org", "identifier": "embeddedci-mcp", - "version": "2.13.21", + "version": "3.0.0", "runtimeHint": "uvx", "transport": { "type": "stdio" diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/__main__.py b/packages/embeddedci-mcp/src/embeddedci_mcp/__main__.py index 88f2b2d..a888065 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/__main__.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/__main__.py @@ -41,6 +41,11 @@ def build_parser() -> argparse.ArgumentParser: "'usb', 'usb:', or 'embeddedci:'. Falls back to BENCHPOD_CONNECTION.") parser.add_argument("--la-voltage", type=float, choices=[1.8, 3.3], default=None, help="LA I/O voltage applied on connect. Falls back to BENCHPOD_LA_VOLTAGE.") + parser.add_argument("--wiring-autosave", action="store_true", + default=os.environ.get("BENCHPOD_WIRING_AUTOSAVE", "").strip().lower() in ("1", "true", "yes", "on"), + help="set_wiring also stores the profile on the pod, except a change of the I/O voltage, " + "the power rail or the SWD target. Falls back to BENCHPOD_WIRING_AUTOSAVE. Default: off " + "(the agent calls save_wiring).") parser.add_argument("--lease-wait", type=float, default=30.0, help="Cloud: seconds connect waits for a busy shared device (default 30).") parser.add_argument("--idle-timeout", type=float, default=600.0, @@ -71,6 +76,7 @@ def main(argv: Optional[Sequence[str]] = None) -> None: SESSION.default_connection = args.connection SESSION.default_la_voltage = args.la_voltage + SESSION.wiring_autosave = bool(args.wiring_autosave) SESSION.lease_wait = args.lease_wait SESSION.idle_timeout = max(0.0, args.idle_timeout) SESSION.timeout = args.timeout diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index 77e6c4d..cf1f27c 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -14,7 +14,7 @@ Cloud pods: cloud_list_devices lists the pods registered on embeddedci.com (name, online) without connecting to any; connect to one with its `connection` ('embeddedci:'). Tools named cloud_* talk to embeddedci.com, not to a pod. Cloud access (cloud_* and connect to 'embeddedci:') authenticates with BENCHPOD_API_KEY, else the user's `benchpod login` session; if neither exists, ask the user to run `benchpod login`. -Wiring: the pod has 14 generic LA channels (LA1-LA14) and nothing is fixed. Call `wiring` first: it is the bench's profile (the one stored on embeddedci.com and shown in the web UI's Wiring tab when the pod is registered and the user is signed in; `source` says where it came from): which DUT signal is on which channel, the target-power rail, the UART baud, the SWD target. Every channel, baud, rail or SWD argument you omit comes from it, and channel arguments also accept its names ("READY", "uart_rx"). Confirm it with the user if it looks wrong; `set_wiring` replaces it (save=true stores it on embeddedci.com). Target power is internal 5 V (efuse 1) or external (efuse 2). The DUT's reset line goes to the pod's own reset pin: flash(nreset=true), reset_target. +Wiring: the pod has 14 generic LA channels (LA1-LA14) and nothing is fixed. Call `wiring` first: it is the bench's profile, normally one of the named profiles stored on the pod itself (the same ones the web app shows; `profile_name`, the pod's default unless connect(wiring_profile=...) named another): which DUT signal is on which channel, the I/O voltage, the target-power rail, the UART baud, the SWD target. Every channel, baud, rail or SWD argument you omit comes from it, and channel arguments also accept its names ("READY", "uart_rx"). What the profile does not set is undefined: when a tool says a pin is missing, ask the user which LA channel it is on, never guess. Confirm the wiring with the user if it looks wrong. `set_wiring` changes it for this connection only: nothing is stored until save_wiring (or the server's --wiring-autosave). Once the wiring works on the board, ask the user whether to save it, and under which name when it is a different board (save_wiring(name='nrf52840')). `unsaved_changes` in the result lists what is not stored; it is lost on disconnect. load_wiring switches to another stored profile, set_default_wiring changes the pod's default (ask first). power_on applies the profile first (its I/O voltage, then the rail) and records it on the pod. Refusals carry a stable code (BP0009 ...) with the fix; follow it. Target power is internal 5 V (efuse 1) or external (efuse 2). The DUT's reset line goes to the pod's own reset pin: flash(nreset=true), reset_target. GPIO: each LA channel has one owner at a time. gpio_mode claims channels (input/output/open_drain), gpio_write drives them, gpio_read reads any channel's live level, gpio_wait polls for one, gpio_pulse emits FPGA-timed pulses, gpio_release frees them. Release a GPIO channel before uart_open, flash or sensor_start uses it, otherwise the pod refuses with "pin conflict: LA4 is in use by gpio; release it with gpio_release(la=[4])": the error names the tool that frees the channel (gpio_release, uart_close, sensor_stop); la_pins shows every channel's owner. Captures observe all 14 channels whatever owns them. diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py index db003d7..75236fc 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py @@ -166,14 +166,28 @@ class WiringResult(BaseModel): """The bench's effective wiring profile: which DUT signal is on which LA channel.""" source: str = Field(description=( - "Where the profile came from: server (stored on embeddedci.com for this pod, over the cloud " - "or, signed in, over the LAN/USB), file (BENCHPOD_WIRING), dict (set_wiring) or defaults.")) - version: int = 1 - la_voltage: float = Field(description="LA I/O-bank voltage the profile asks for, in volts.") - efuse: int = Field(description=( - "Target-power rail the tools default to: internal 5 V (efuse 1) or external (efuse 2).")) + "Where the profile came from: pod (a profile stored on the pod), file (BENCHPOD_WIRING), dict " + "(set_wiring, not saved), server (older firmware: the profile on embeddedci.com) or undefined " + "(nothing is wired).")) + version: int = 2 + profile_name: str = Field("", description=( + "The pod profile this connection uses ('' when it came from elsewhere).")) + profile_rev: int = Field(0, description="That profile's revision on the pod when it was loaded.") + default_profile: Optional[str] = Field(None, description="The pod's default profile.") + profiles: List[Dict[str, Any]] = Field(default_factory=list, description=( + "The profiles stored on the pod: [{name, rev, bytes}]. Empty on firmware that stores none.")) + unsaved_changes: List[str] = Field(default_factory=list, description=( + "Keys of this connection's profile that differ from the copy stored on the pod: lost on " + "disconnect unless saved (save_wiring).")) + hint: Optional[str] = Field(None, description="What to do next about saving, when anything.") + autosave: bool = Field(False, description="The server saves set_wiring's profile on the pod (--wiring-autosave).") + la_voltage: Optional[float] = Field(description=( + "LA I/O-bank voltage the profile asks for, in volts; null when it sets none.")) + efuse: Optional[int] = Field(description=( + "Target-power rail the tools default to: internal 5 V (efuse 1) or external (efuse 2); null " + "when the profile sets none (pass efuse).")) uart_baud: int - i2c_address: int = Field(description="The profile's I2C address (i2c_addr) as a 7-bit integer.") + i2c_address: Optional[int] = Field(description="The profile's I2C address (i2c_addr) as a 7-bit integer; null when unset.") swd_nreset: bool swd_target: str pins: List[WiringPin] = Field(description="LA1-LA14 with what is wired to each and its bias resistor.") @@ -181,7 +195,7 @@ class WiringResult(BaseModel): warnings: List[str] = Field(default_factory=list, description="Wiring that works but is risky (e.g. an I2C bus with no pull-up).") profile: Dict[str, Any] = Field(default_factory=dict, description="The profile as its JSON object.") - saved: bool = Field(False, description="set_wiring stored this profile on embeddedci.com.") + saved: bool = Field(False, description="This call stored the profile (on the pod, or on embeddedci.com for older firmware).") directions: Optional[str] = Field(None, description=( "'sent' when the pod has the profile's pin directions (la_dir: sent on connect and by " "set_wiring), else 'not sent: ' (older firmware, or a DUT output pin driven right now).")) @@ -276,6 +290,8 @@ class GpioReleaseResult(BaseModel): # -- power ----------------------------------------------------------------------- class PowerResult(BaseModel): + profile: Optional[str] = Field(None, description="The wiring profile the board was powered on with.") + la_voltage: Optional[float] = Field(None, description="The I/O voltage the profile set before power-on.") efuse: int = Field(description="The rail used: internal 5 V (efuse 1) or external (efuse 2).") on: bool delay: Optional[float] = None diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index 4dedd90..c395815 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -19,6 +19,7 @@ import json import os import re +from dataclasses import replace import time from typing import Annotated, Any, Callable, Dict, List, Literal, Optional, Tuple, TypeVar, Union @@ -215,7 +216,24 @@ def _error_text(exc: BenchPodError) -> str: return f"{cmd}: {text}" if cmd else text +def _coded_text(exc: BenchPodError) -> Optional[str]: + """A refusal with a stable error code, rendered with the catalog's fix for an agent.""" + from embeddedci.benchpod.errors import error_catalog + code = getattr(exc, "code", "") + entry = error_catalog().get("codes", {}).get(code) if code else None + if not entry: + return None + values = getattr(exc, "values", {}) or {} + fill = lambda t: re.sub(r"\{([a-z0-9_]+)\}", lambda m: str(values.get(m.group(1), "?")), t) # noqa: E731 + cmd = getattr(exc, "cmd", None) + text = f"{code}: {fill(entry['message'])}; {fill(entry['fix']['mcp'])} (docs: {exc.docs_url})" + return f"{cmd}: {text}" if cmd else text + + def _tool_error(exc: BenchPodError) -> ToolError: + coded = _coded_text(exc) + if coded: + return ToolError(f"{type(exc).__name__}: {coded}") msg = f"{type(exc).__name__}: {_error_text(exc)}" hint = _refusal_hint(exc) return ToolError(f"{msg}. {hint}" if hint else msg) @@ -430,6 +448,9 @@ async def connect( "Select the LA I/O-bank voltage right after connecting (the DUT's I/O voltage)."))] = None, lease_wait: Annotated[float, Field(ge=0, le=3600, description=( "Cloud only: seconds to wait when another run holds the shared device."))] = 30.0, + wiring_profile: Annotated[Optional[str], Field(description=( + "A wiring profile stored on the pod to use (the `wiring` tool lists them); omit for the " + "pod's default profile."))] = None, ctx: Context = None, # type: ignore[assignment] ) -> m.StatusResult: """Open a BenchPod connection (closing any previous one and its sessions) and report status. @@ -438,7 +459,8 @@ async def connect( or after the server's idle timeout (the next tool call then reconnects). """ def op() -> m.StatusResult: - SESSION.connect(connection, la_voltage=la_voltage, lease_wait=lease_wait) + SESSION.connect(connection, la_voltage=la_voltage, lease_wait=lease_wait, + wiring_profile=wiring_profile) try: return _status() except BaseException: @@ -474,20 +496,56 @@ async def set_la_voltage(voltage: Literal[1.8, 3.3]) -> m.LaVoltageResult: # -- wiring profile ------------------------------------------------------------------- +#: Changes that are never saved on their own (autosave): what can hurt a board, or a new board. +_NEVER_AUTOSAVE = ("la_mv", "efuse", "swd_target") + + +def _pod_wiring_state(pod: Any, result: m.WiringResult) -> m.WiringResult: + """The pod's stored profiles, what this connection has not saved, and the hint about it.""" + result.autosave = SESSION.wiring_autosave + try: + listing = pod.wiring_profiles() + except BenchPodError: + return result # firmware that stores no profiles + result.default_profile = listing.get("default") + result.profiles = list(listing.get("profiles") or []) + w = pod.wiring + names = {str(p.get("name")) for p in result.profiles} + stored = pod.stored_wiring(w.profile_name) if w.profile_name in names else None + cur, ref = w.to_dict(), (stored.to_dict() if stored is not None else {}) + result.unsaved_changes = sorted(k for k in set(cur) | set(ref) + if k != "version" and cur.get(k) != ref.get(k)) + if result.unsaved_changes: + target = w.profile_name or result.default_profile or "default" + result.hint = (f"not saved: the web app, CI and other connections still use profile {target!r}. " + "Once the user confirms this wiring is right on the board, ask whether to save it: " + "save_wiring() for this profile, save_wiring(name=...) for another board.") + roles = [k for k in result.unsaved_changes if k in ("uart_rx", "uart_tx", "i2c_sda", "i2c_scl", + "swd_swclk", "swd_swdio", "spi_sclk", "spi_mosi", + "spi_miso", "spi_cs", "signals")] + if any(k in _NEVER_AUTOSAVE for k in result.unsaved_changes) or len(roles) >= 4: + result.hint += (" This looks like a different board (I/O voltage, power rail, SWD target or " + "most pins changed): prefer save_wiring(name='') over overwriting " + f"{target!r}.") + return result + + @mcp.tool(annotations=_ann("Wiring profile", read_only=True)) async def wiring() -> m.WiringResult: """Which DUT signal is on which LA channel — call this first, before any channel argument. - Returns the bench's effective profile: a 14-row pin table (what is wired to each channel and - its bias resistor), the named signals, the target-power rail, the UART baud and the SWD target, - plus warnings about risky wiring. Every tool whose channel, baud, rail or SWD arguments are - omitted takes them from this profile, and channel arguments accept these names. + Returns the profile this connection uses (normally a profile stored on the pod: profile_name, + the pod's default unless connect named another): a 14-row pin table, the named signals, the + power rail, the UART baud and the SWD target, warnings about risky wiring, the pod's stored + profiles and unsaved_changes (what set_wiring changed that is not stored yet). Every tool whose + channel, baud, rail or SWD arguments are omitted takes them from this profile; what the profile + does not set is undefined, and a tool that needs it says so: ask the user, never guess a pin. """ def op() -> m.WiringResult: pod = SESSION.require() result = wiring_summary(pod.wiring) result.directions = pod.pin_directions_status - return result + return _pod_wiring_state(pod, result) return await _call(op) @@ -495,39 +553,130 @@ def op() -> m.WiringResult: @mcp.tool(annotations=_ann("Set the wiring profile", idempotent=True, cloud=True)) async def set_wiring( profile: Annotated[Dict[str, Any], Field(description=( - "The profile as a JSON object (schema version 1): la_mv, efuse, uart_rx/uart_tx/uart_baud, " + "The profile as a JSON object (schema version 2): la_mv, efuse, uart_rx/uart_tx/uart_baud, " "i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals " - "[{name, la, direction, active_low, description}]. Absent keys take their default; a pin " - "set to null is not wired."))], + "[{name, la, direction, active_low, description}]. What it leaves out is undefined (not " + "wired); a pin set to null is not wired. {\"version\": 1} objects fill in the reference bench."))], save: Annotated[bool, Field(description=( - "Also store the profile for this device on embeddedci.com (cloud devices only), so other " - "runs and the web UI see it. false = use it for this connection only."))] = False, + "Also store it on the pod (as save_wiring does). Default false: this connection only, unless " + "the server runs with --wiring-autosave."))] = False, ) -> m.WiringResult: - """Replace the wiring profile this connection uses (and optionally store it on embeddedci.com). + """Replace the wiring profile this connection uses. It is NOT stored on the pod unless save is + true (or the server autosaves): the result's unsaved_changes and hint say what is not stored. The profile is validated first: two roles or signals on one LA channel, an out-of-range pin or - an unknown key are rejected with a message naming every problem. + an unknown key are rejected with a message naming every problem. Autosave never stores a change + of the I/O voltage, the power rail or the SWD target: call save_wiring for those. """ def op() -> m.WiringResult: pod = SESSION.require() - pod.wiring = Wiring.from_dict(profile) - if save: + before = pod.wiring + data = dict(profile) + data.setdefault("version", 2) + pod.wiring = replace(Wiring.from_dict(data), profile_name=before.profile_name, + profile_rev=before.profile_rev, source="dict") + risky = any(before.to_dict().get(k) != pod.wiring.to_dict().get(k) for k in _NEVER_AUTOSAVE) + do_save = save or (SESSION.wiring_autosave and not risky) + if do_save: pod.save_wiring() - result = wiring_summary(pod.wiring, saved=save) + result = wiring_summary(pod.wiring, saved=do_save) # Assigning the profile sent its pin directions (la_dir) on firmware that has it. result.directions = pod.pin_directions_status + result = _pod_wiring_state(pod, result) + if SESSION.wiring_autosave and risky and not save: + result.hint = ("not autosaved: the I/O voltage, power rail or SWD target changed. " + + (result.hint or "Call save_wiring once the user confirms it.")) return result return await _call(op) +@mcp.tool(annotations=_ann("Save the wiring profile on the pod", idempotent=True, cloud=True)) +async def save_wiring( + name: Annotated[Optional[str], Field(description=( + "The pod profile to store it as (1-40 characters: a-z, 0-9, -). Default: the profile this " + "connection loaded, else the pod's default. Use a new name for a different board."))] = None, + profile: Annotated[Optional[Dict[str, Any]], Field(description=( + "A full profile to store instead of this connection's (schema version 2)."))] = None, +) -> m.WiringResult: + """Store a wiring profile on the pod, where the web app, CI and every other connection see it. + + Ask the user first: saving changes what everyone uses. Saving the profile this connection + loaded fails with BP0009 when someone else saved it meanwhile (load_wiring shows their version). + Saving never changes the pod's default profile (set_default_wiring does). + """ + def op() -> m.WiringResult: + pod = SESSION.require() + data = None + if profile is not None: + data = dict(profile) + data.setdefault("version", 2) + pod.save_wiring(data, name=name) + result = wiring_summary(pod.wiring, saved=True) + result.directions = pod.pin_directions_status + return _pod_wiring_state(pod, result) + + return await _call(op) + + +@mcp.tool(annotations=_ann("Load a stored wiring profile", idempotent=True)) +async def load_wiring( + name: Annotated[Optional[str], Field(description="The pod profile to use; omit for the pod's default.")] = None, +) -> m.WiringResult: + """Switch this connection to one of the pod's stored profiles (nothing on the pod changes). + Use it when the user says the bench is wired for another board, or after a BP0009 conflict.""" + def op() -> m.WiringResult: + pod = SESSION.require() + pod.load_wiring(name) + result = wiring_summary(pod.wiring) + result.directions = pod.pin_directions_status + return _pod_wiring_state(pod, result) + + return await _call(op) + + +@mcp.tool(annotations=_ann("Set the default wiring profile", idempotent=True, cloud=True)) +async def set_default_wiring( + name: Annotated[str, Field(description="The pod profile every connection uses when it names none.")], +) -> m.WiringResult: + """Make a stored profile the pod's default (ask the user: it changes what everyone gets).""" + def op() -> m.WiringResult: + pod = SESSION.require() + pod.set_default_wiring(name) + result = wiring_summary(pod.wiring) + return _pod_wiring_state(pod, result) + + return await _call(op) + + +@mcp.tool(annotations=_ann("Delete a stored wiring profile", destructive=True, cloud=True)) +async def delete_wiring( + name: Annotated[str, Field(description="The pod profile to delete (not the default).")], +) -> m.WiringResult: + """Delete one of the pod's stored profiles. Ask the user first. The default cannot be deleted + (BP0013): make another one the default first.""" + def op() -> m.WiringResult: + pod = SESSION.require() + pod.delete_wiring(name) + result = wiring_summary(pod.wiring) + return _pod_wiring_state(pod, result) + + return await _call(op) + + # -- power ---------------------------------------------------------------------------- -def _switch_power(efuse: Optional[int], on: bool, delay: Optional[float]) -> m.PowerResult: +def _switch_power(efuse: Optional[int], on: bool, delay: Optional[float], + wiring_profile: Optional[str] = None) -> m.PowerResult: pod = SESSION.require() - rail = pod.wiring.efuse if efuse is None else efuse - pod.target_power(rail, on=on, delay=delay) - return m.PowerResult(efuse=rail, on=on, delay=delay) + if on: + pod.power_on(efuse, delay=delay, wiring_profile=wiring_profile) + else: + pod.target_power(efuse, on=False, delay=delay) + w = pod.wiring + rail = w.efuse if efuse is None else efuse + return m.PowerResult(efuse=rail, on=on, delay=delay, profile=w.profile_name or None, + la_voltage=w.la_voltage if on else None) @mcp.tool(annotations=_ann("Power target on", destructive=True, idempotent=True)) @@ -535,9 +684,15 @@ async def power_on( efuse: WiredEfuse = None, delay: Annotated[Optional[float], Field(description=( "Seconds: schedule the power-on pod-side and return at once (e.g. to power on during a capture)."))] = None, + wiring_profile: Annotated[Optional[str], Field(description=( + "A stored wiring profile to power the board with (it becomes this connection's profile); " + "omit to use the current one."))] = None, ) -> m.PowerResult: - """Switch the target's power rail on. The result says which rail was used.""" - return await _call(lambda: _switch_power(efuse, True, delay)) + """Power the board on with its wiring profile applied first: the profile's I/O voltage is set + (when the pod has none or another one), then the rail goes on, and the pod records the profile. + The result names the rail, the profile and the I/O voltage. Never changes the I/O voltage under + a board that is already powered.""" + return await _call(lambda: _switch_power(efuse, True, delay, wiring_profile)) @mcp.tool(annotations=_ann("Power target off", destructive=True, idempotent=True)) diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/session.py b/packages/embeddedci-mcp/src/embeddedci_mcp/session.py index 7adaf7b..59347c2 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/session.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/session.py @@ -134,6 +134,10 @@ def __init__(self) -> None: #: LA voltage applied on connect when the tool call does not pass one (``--la-voltage``); #: falls back to ``BENCHPOD_LA_VOLTAGE`` inside the SDK. self.default_la_voltage: Optional[float] = None + #: The pod wiring profile `connect` loads (None: the pod's default). + self.wiring_profile: Optional[str] = None + #: --wiring-autosave / BENCHPOD_WIRING_AUTOSAVE: set_wiring also stores the profile on the pod. + self.wiring_autosave: bool = False self.timeout: float = 30.0 self.lease_wait: float = 30.0 #: Seconds without a tool call before a leased (cloud) connection is released; 0 = never. @@ -200,14 +204,16 @@ def reconnectable(self) -> bool: return self._pod is None and self._idle_closed and self._reconnect is not None def _open(self, connection: str, la_voltage: Optional[float], lease_wait: float) -> BenchPod: + kwargs = {"wiring_profile": self.wiring_profile} if self.wiring_profile else {} return BenchPod(connection, la_voltage=la_voltage, timeout=self.timeout, lease_wait=lease_wait, - cloud_user_token=cloud_user_token(connection)) + cloud_user_token=cloud_user_token(connection), **kwargs) def connect(self, connection: Optional[str] = None, *, la_voltage: Optional[float] = None, - lease_wait: Optional[float] = None) -> BenchPod: + lease_wait: Optional[float] = None, wiring_profile: Optional[str] = None) -> BenchPod: """Open (or re-open) the device, closing any prior connection and sessions first.""" with self.lock: self.disconnect() + self.wiring_profile = wiring_profile or None conn = (connection or self.default_connection or os.environ.get(ENV_VAR) or saved_connection()) if not conn: diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py index b30972a..9bb22d9 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py @@ -122,7 +122,8 @@ def wiring_summary(wiring: Wiring, *, saved: bool = False) -> m.WiringResult: pins = wiring.pins() dirs = wiring.pin_dut_dirs() return m.WiringResult( - source=wiring.source, version=wiring.version, la_voltage=wiring.la_voltage, + source=wiring.source, version=wiring.version, profile_name=wiring.profile_name, + profile_rev=wiring.profile_rev, la_voltage=wiring.la_voltage, efuse=wiring.efuse, uart_baud=wiring.uart_baud, i2c_address=wiring.i2c_address, swd_nreset=wiring.swd_nreset, swd_target=wiring.swd_target, pins=[m.WiringPin(la=la, wired_to=pins.get(la), pull=_bias(la), dut_dir=dirs.get(la)) diff --git a/packages/embeddedci-mcp/tests/conftest.py b/packages/embeddedci-mcp/tests/conftest.py index f3a557b..85bbc06 100644 --- a/packages/embeddedci-mcp/tests/conftest.py +++ b/packages/embeddedci-mcp/tests/conftest.py @@ -12,7 +12,7 @@ import anyio import pytest -from embeddedci.benchpod import BenchPod +from embeddedci.benchpod import Wiring, BenchPod from embeddedci.benchpod.constants import PULL_OHMS, PULLDOWN_CHANNELS from embeddedci.benchpod.errors import FirmwareError from embeddedci.benchpod.transport.base import Transport @@ -642,7 +642,13 @@ def fake_open(monkeypatch, fake_transport): def factory(connection, **kwargs): seen["connection"] = connection seen.update(kwargs) - return BenchPod(transport=fake_transport, lease=False, la_voltage=kwargs.get("la_voltage")) + # The fake bench is wired like the reference bench (version 2 profiles leave nothing wired + # by default); a test that names a stored profile gets the pod's lookup instead. + if kwargs.get("wiring_profile"): + return BenchPod(transport=fake_transport, lease=False, la_voltage=kwargs.get("la_voltage"), + wiring_profile=kwargs["wiring_profile"]) + return BenchPod(transport=fake_transport, lease=False, la_voltage=kwargs.get("la_voltage"), + wiring=Wiring.preset()) monkeypatch.setattr(session_mod, "BenchPod", factory) return seen diff --git a/packages/embeddedci-mcp/tests/test_saved_connection_and_wiring.py b/packages/embeddedci-mcp/tests/test_saved_connection_and_wiring.py index 8fa5aad..c25565b 100644 --- a/packages/embeddedci-mcp/tests/test_saved_connection_and_wiring.py +++ b/packages/embeddedci-mcp/tests/test_saved_connection_and_wiring.py @@ -133,4 +133,4 @@ def factory(connection, **kwargs): def test_status_reports_the_defaults_when_nothing_is_stored(connected): - assert call("status")["wiring_source"] == "defaults" + assert call("status")["wiring_source"] == "preset" # the test bench is wired like the reference diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index cd7762f..4ac6edc 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -18,7 +18,7 @@ EXPECTED_TOOLS = { "connect", "disconnect", "status", "set_la_voltage", - "wiring", "set_wiring", + "wiring", "set_wiring", "save_wiring", "load_wiring", "set_default_wiring", "delete_wiring", "power_on", "power_off", "power_status", "reset_target", "measure_power", "power_profile_start", "power_profile_stop", "la_pins", "gpio_mode", "gpio_write", "gpio_read", "gpio_wait", "gpio_pulse", "gpio_release", @@ -300,7 +300,8 @@ def test_disconnect(connected): # -- power + flash --------------------------------------------------------------------- def test_power_tools(connected): - assert call("power_on", efuse=1, delay=0.5) == {"efuse": 1, "on": True, "delay": 0.5} + assert call("power_on", efuse=1, delay=0.5) == {"efuse": 1, "on": True, "delay": 0.5, + "profile": None, "la_voltage": 3.3} assert ("target_power", 1, True, 500) in connected.calls status = call("power_status") assert status["internal"]["enabled"] is True and status["internal"]["bus_voltage"] == 5.01 diff --git a/packages/embeddedci-mcp/tests/test_wiring_tools.py b/packages/embeddedci-mcp/tests/test_wiring_tools.py index 8be9acf..c76d395 100644 --- a/packages/embeddedci-mcp/tests/test_wiring_tools.py +++ b/packages/embeddedci-mcp/tests/test_wiring_tools.py @@ -49,7 +49,7 @@ def test_wiring_reports_risky_wiring_as_warnings(connected): def test_wiring_defaults_when_the_bench_has_no_profile(connected): result = call("wiring") - assert result["source"] == "defaults" and result["efuse"] == 1 + assert result["source"] == "preset" and result["efuse"] == 1 # the test bench: the reference preset assert {p["la"]: p["wired_to"] for p in result["pins"]}[5] == "uart_rx" @@ -68,11 +68,11 @@ def test_set_wiring_rejects_an_invalid_profile(connected): call("set_wiring", profile={"uart_rx": 4, "uart_tx": 4}) # both roles on LA4 with pytest.raises(ToolError, match="unknown key"): call("set_wiring", profile={"uart_rxx": 4}) - assert SESSION.require().wiring.source == "defaults" # nothing changed + assert SESSION.require().wiring.source == "preset" # nothing changed def test_set_wiring_save_needs_a_cloud_device(connected): - with pytest.raises(ToolError, match="cloud device"): + with pytest.raises(ToolError, match="newer firmware"): call("set_wiring", profile=BENCH, save=True) diff --git a/packages/embeddedci-mcp/tests/tools_surface.json b/packages/embeddedci-mcp/tests/tools_surface.json index 6125b0c..cc06164 100644 --- a/packages/embeddedci-mcp/tests/tools_surface.json +++ b/packages/embeddedci-mcp/tests/tools_surface.json @@ -1237,6 +1237,19 @@ "minimum": 0, "title": "Lease Wait", "type": "number" + }, + "wiring_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A wiring profile stored on the pod to use (the `wiring` tool lists them); omit for the pod's default profile.", + "title": "Wiring Profile" } }, "title": "connectArguments", @@ -1702,6 +1715,29 @@ "type": "object" } }, + "delete_wiring": { + "annotations": { + "destructiveHint": true, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Delete a stored wiring profile" + }, + "input": { + "properties": { + "name": { + "description": "The pod profile to delete (not the default).", + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "delete_wiringArguments", + "type": "object" + } + }, "disconnect": { "annotations": { "destructiveHint": false, @@ -3086,6 +3122,34 @@ "type": "object" } }, + "load_wiring": { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false, + "title": "Load a stored wiring profile" + }, + "input": { + "properties": { + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The pod profile to use; omit for the pod's default.", + "title": "Name" + } + }, + "title": "load_wiringArguments", + "type": "object" + } + }, "loop_input": { "annotations": { "destructiveHint": true, @@ -3430,6 +3494,19 @@ "default": null, "description": "Target-power rail: internal 5 V (efuse 1) or external (efuse 2). Omit for the wiring profile's rail.", "title": "Efuse" + }, + "wiring_profile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A stored wiring profile to power the board with (it becomes this connection's profile); omit to use the current one.", + "title": "Wiring Profile" } }, "title": "power_onArguments", @@ -3917,6 +3994,48 @@ "type": "object" } }, + "save_wiring": { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Save the wiring profile on the pod" + }, + "input": { + "properties": { + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The pod profile to store it as (1-40 characters: a-z, 0-9, -). Default: the profile this connection loaded, else the pod's default. Use a new name for a different board.", + "title": "Name" + }, + "profile": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A full profile to store instead of this connection's (schema version 2).", + "title": "Profile" + } + }, + "title": "save_wiringArguments", + "type": "object" + } + }, "sensor_capture": { "annotations": { "destructiveHint": false, @@ -4556,6 +4675,29 @@ "type": "object" } }, + "set_default_wiring": { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": true, + "readOnlyHint": false, + "title": "Set the default wiring profile" + }, + "input": { + "properties": { + "name": { + "description": "The pod profile every connection uses when it names none.", + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "set_default_wiringArguments", + "type": "object" + } + }, "set_la_voltage": { "annotations": { "destructiveHint": false, @@ -4629,13 +4771,13 @@ "properties": { "profile": { "additionalProperties": true, - "description": "The profile as a JSON object (schema version 1): la_mv, efuse, uart_rx/uart_tx/uart_baud, i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals [{name, la, direction, active_low, description}]. Absent keys take their default; a pin set to null is not wired.", + "description": "The profile as a JSON object (schema version 2): la_mv, efuse, uart_rx/uart_tx/uart_baud, i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals [{name, la, direction, active_low, description}]. What it leaves out is undefined (not wired); a pin set to null is not wired. {\"version\": 1} objects fill in the reference bench.", "title": "Profile", "type": "object" }, "save": { "default": false, - "description": "Also store the profile for this device on embeddedci.com (cloud devices only), so other runs and the web UI see it. false = use it for this connection only.", + "description": "Also store it on the pod (as save_wiring does). Default false: this connection only, unless the server runs with --wiring-autosave.", "title": "Save", "type": "boolean" }