From d9dd9480dfbc3176a0f90d3cc7fe6074539e14be Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 22:08:18 -0600 Subject: [PATCH 01/10] Client API 2: drive firmware 4.0 only, features from the table CLIENT_API is 2. A pod below client API 2 (firmware 3.x) raises the new FirmwareTooOldError on connect, with the firmware update to run (the USB console decides by firmware version). Every legacy path for firmware without the features table is gone: the caps list, status caps:false, version fallbacks (la_dir, bus master, diag), the pullup form of pulls, the 8-bit generate, the la_pins subset fallback and the console's la-voltage/power/dap/uart text commands. Firmware 4.0 split la into la_pull and la_step, sends captures as base64 by default and takes generate in volts with freq_hz/sample_rate_hz; the SDK follows. Features table synced to revision 11. Test fakes written for 3.x statuses are read as 4.0 by tests/conftest.py; tests of removed paths are gone. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 12 + .../src/embeddedci_mcp/guide.py | 9 +- .../src/embeddedci_mcp/models.py | 3 - .../src/embeddedci_mcp/server.py | 24 +- packages/embeddedci-mcp/tests/conftest.py | 53 ++-- .../tests/test_bus_master_tools.py | 8 - .../embeddedci-mcp/tests/test_gpio_tools.py | 16 +- .../embeddedci-mcp/tests/test_refusals.py | 47 ++-- packages/embeddedci-mcp/tests/test_tools.py | 51 ++-- .../tests/test_trigger_power_tools.py | 15 +- packages/embeddedci-openhtf/tests/_fake.py | 15 +- .../embeddedci-openhtf/tests/test_analog.py | 35 ++- packages/embeddedci/CHANGELOG.md | 31 +++ packages/embeddedci/README.md | 109 ++++---- .../src/embeddedci/benchpod/__init__.py | 2 + .../src/embeddedci/benchpod/capabilities.py | 146 ++--------- .../src/embeddedci/benchpod/capture.py | 30 +-- .../src/embeddedci/benchpod/client.py | 240 +++++++----------- .../src/embeddedci/benchpod/errors.py | 16 ++ .../src/embeddedci/benchpod/feature_map.json | 78 +++++- .../src/embeddedci/benchpod/feature_map.py | 28 +- .../src/embeddedci/benchpod/runs/recorder.py | 5 +- .../embeddedci/benchpod/sensors/emulation.py | 17 +- .../src/embeddedci/benchpod/state.py | 26 +- .../embeddedci/benchpod/transport/__init__.py | 2 +- .../src/embeddedci/benchpod/transport/base.py | 7 - .../embeddedci/benchpod/transport/serial.py | 215 ++-------------- .../src/embeddedci/benchpod/transport/tcp.py | 9 +- .../src/embeddedci/benchpod/wiring.py | 3 - packages/embeddedci/tests/api_surface.json | 5 +- packages/embeddedci/tests/conftest.py | 75 ++++++ packages/embeddedci/tests/runs_fake.py | 8 +- packages/embeddedci/tests/test_can.py | 15 +- .../embeddedci/tests/test_capabilities.py | 43 ++-- .../tests/test_capabilities_scope.py | 23 +- packages/embeddedci/tests/test_capture.py | 32 ++- packages/embeddedci/tests/test_client_api.py | 97 +++++-- packages/embeddedci/tests/test_client_v2.py | 68 ++--- packages/embeddedci/tests/test_cloud.py | 2 +- .../embeddedci/tests/test_control_loop.py | 32 ++- .../tests/test_current_out_waveforms.py | 28 +- .../embeddedci/tests/test_dac_path_default.py | 7 +- .../embeddedci/tests/test_dac_path_ranges.py | 6 +- .../embeddedci/tests/test_digital_v3r4.py | 7 +- packages/embeddedci/tests/test_esp_flash.py | 2 +- packages/embeddedci/tests/test_expansion.py | 27 +- packages/embeddedci/tests/test_feature_map.py | 78 ++---- packages/embeddedci/tests/test_generate16.py | 39 +-- packages/embeddedci/tests/test_gpio.py | 14 +- .../embeddedci/tests/test_image_switching.py | 2 +- .../embeddedci/tests/test_motor_emulator.py | 14 +- .../embeddedci/tests/test_pin_directions.py | 20 -- packages/embeddedci/tests/test_pod_lease.py | 35 +-- .../embeddedci/tests/test_pull_direction.py | 65 +---- packages/embeddedci/tests/test_replay.py | 2 +- packages/embeddedci/tests/test_runs.py | 8 +- packages/embeddedci/tests/test_sensors.py | 27 +- .../tests/test_serial_text_console.py | 41 +-- packages/embeddedci/tests/test_spi.py | 6 +- packages/embeddedci/tests/test_status_diag.py | 12 +- .../embeddedci/tests/test_trigger_power.py | 9 +- packages/embeddedci/tests/test_uart_frame.py | 10 +- .../tests/test_unsupported_feature.py | 33 ++- packages/embeddedci/tests/test_usb_net.py | 16 +- .../embeddedci/tests/test_wiring_profiles.py | 62 ++--- 65 files changed, 956 insertions(+), 1266 deletions(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index e15cf46..493d819 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -1,7 +1,19 @@ # Changelog — `embeddedci-mcp` +## 4.0.0 + +Pairs with BenchPod firmware 4.0.0 and embeddedci 4.0. Breaking changes: + +- **Firmware 4.0 or later only.** `connect` to a pod with firmware 3.x fails with + `FirmwareTooOldError`, which tells the agent to have the user update the pod's firmware + (`benchpod flash-self` or the web app). The instructions say so too. +- `generate` returns no `bits` (the pod always plays 16 bits). +- A serial device path (the USB console) supports `status` only. + ## 3.0.6 +Never released: its changes ship in 4.0.0. + - Every command carries `"client": "mcp "` and the client API level (with embeddedci after 3.0.5). - **Client too old:** a pod whose firmware is newer than this server handles (it announces a diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index eb04efa..7caedde 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -8,7 +8,7 @@ Drive an EmbeddedCI BenchPod: a hardware-in-the-loop tester wired to a real target board (the DUT). Start every session with: -1. connect — a host[:port] or 'embeddedci:'. Omit it to use the server default (--connection, else BENCHPOD_CONNECTION, else the connection saved with `benchpod set-connection`); with none configured, connect finds the one pod on the LAN over mDNS, and if it finds none or several its error lists them and what to pass instead (a host, 'usb', or a cloud pod from cloud_list_devices). With firmware 3.9.0 and later, 'usb' reaches the full API over the pod's USB network adapter (unless Wi-Fi is configured on the pod, which turns USB networking off; status then reports kind 'usb_net' when it worked). With several pods plugged into one computer, 'usb' errors and lists them by name; pick one with 'usb:' (for example 'usb:benchpod-baea06'). A serial device path, or 'usb' that fell back to the console (kind 'serial'), only supports status, LA voltage and power on an STM32 pod; everything else needs the network, the USB network or cloud. +1. connect — a host[:port] or 'embeddedci:'. Omit it to use the server default (--connection, else BENCHPOD_CONNECTION, else the connection saved with `benchpod set-connection`); with none configured, connect finds the one pod on the LAN over mDNS, and if it finds none or several its error lists them and what to pass instead (a host, 'usb', or a cloud pod from cloud_list_devices). 'usb' reaches the full API over the pod's USB network adapter (unless Wi-Fi is configured on the pod, which turns USB networking off; status then reports kind 'usb_net' when it worked). With several pods plugged into one computer, 'usb' errors and lists them by name; pick one with 'usb:' (for example 'usb:benchpod-baea06'). A serial device path, or 'usb' that fell back to the console (kind 'serial'), only supports status; everything else needs the network, the USB network or cloud. This server needs pod firmware 4.0.0 or later: FirmwareTooOldError on connect means the pod runs firmware 3.x; tell the user to update it (benchpod flash-self, or the firmware update in the web app). 2. The I/O voltage (1.8 or 3.3, the DUT's; 5.0 on a digital v3r4 pod, see set_la_voltage) comes from the wiring profile's la_mv: connect sets it, so status normally reports one. When status warns that none is selected, the profile sets none: ask the user for the board's I/O voltage and set it in the profile (set_wiring with la_mv, then save_wiring), or call set_la_voltage for this session. The pod refuses flash, UART, LA capture, pull resistors and sensor emulation until it is set. 3. status shows firmware, capabilities, the LA voltage and open sessions. @@ -23,11 +23,11 @@ Typical flows: - Flash and boot: flash(file) then power_cycle_and_capture(until_regex) — with a wiring profile that is all; otherwise pass swclk, swdio, target, nreset and rx, tx. - SPI flash (a 25-series chip on four LA pins, wiring spi_sclk/spi_mosi/spi_miso/spi_cs): spi_flash_info to see it answers, then spi_flash_program(file, addr); hold_reset=true keeps the DUT off the bus. spi_transfer talks to any other SPI device. -- I2C master (gateware v55+): set_pull([sda, scl], pull="up"), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions (firmware 3.10.4+), so this is on by default. +- I2C master (gateware v55+): set_pull([sda, scl], pull="up"), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions, so this is on by default. - Interactive console: uart_open, power_on, uart_read(until_regex), uart_write, uart_close. - Emulate sensors (I2C, SPI, UART, analog; firmware with the 'sensors' capability): the pod plays a sensor from a definition. sensor_library lists ready ones (bme280, bmp280, sht4x, mpu6050, gps_nmea, ...) and sensor_show gives one's YAML and params. For I2C, set_pull([sda, scl], pull="up") on LA1-LA6 (LA7/LA8 pull down only) first. sensor_start(definition=, pins={sda, scl} | {tx} | ...), then sensor_set(instance, values) changes readings, sensor_stimulus_load + sensor_stimulus_start play values over time, sensor_fault injects a fault, sensor_status shows bus activity, sensor_capture waits for the DUT's next transaction on an I2C sensor's bus and decodes it, sensor_stop ends it. A part the library lacks: read sensor_format, write a definition from the datasheet, check it with sensor_validate, then sensor_start it. A GPS module is gps_nmea on pins={tx: }. - Analog: dac_output (DC), generate (sine/square/sawtooth) and replay drive the DAC and route its path; adc_read gives one calibrated value, capture_adc a waveform summary; dac_stop ends any DAC output. -- 4-20 mA input: adc_read(source='current_in') reads terminal J8 and returns current in amps (0.004 to 0.020 for a live loop) next to the voltage across the sense resistor (249 ohm; from analog module v3r5 100 ohm behind a 30 mA limiter, read in the low range by default, so a reading stuck near 28.5 to 31.5 mA is the limiter). calibration shows whether the pod has calibrated its ADC offset there. If not, analog readings can be off by up to about 50 mV: ask the user to disconnect J8, then calibrate (once per pod, stored on the pod; on firmware 3.9.3+ it corrects every ADC source). +- 4-20 mA input: adc_read(source='current_in') reads terminal J8 and returns current in amps (0.004 to 0.020 for a live loop) next to the voltage across the sense resistor (249 ohm; from analog module v3r5 100 ohm behind a 30 mA limiter, read in the low range by default, so a reading stuck near 28.5 to 31.5 mA is the limiter). calibration shows whether the pod has calibrated its ADC offset there. If not, analog readings can be off by up to about 50 mV: ask the user to disconnect J8, then calibrate (once per pod, stored on the pod; it corrects every ADC source). - 4-20 mA output: current_out(current) holds a loop current on terminal J9, in amps (0.012 is 12 mA), and returns the current actually held and the range. It needs an external floating loop supply on J9 and cannot go below about 4 mA or above about 20 mA. It shares the DAC with the voltage outputs and switches them off; dac_stop does not return the loop to 4 mA, current_out(0.004) does. The loop must float: nothing in it may touch pod ground, also not through a target that shares a ground with the pod (SWD, UART). Ask the user how J9 is wired first, and never suggest wiring J9 straight into J8. generate, replay and replay_waveform take dac_path='current_out' to play a waveform as a current (levels in amps); capture_adc(source='current_in') summarises the loop current in amps. - Gateware images: the FPGA runs either the 'loop' image (control_loop) or the 'deep_replay' image (replays longer than 2048 samples). control_loop, replay and replay_waveform switch automatically (~3 s; switched_image in the result says so). A switch resets the FPGA and stops any DAC output, UART session or sensor emulation, so start those after it. fpga_image switches explicitly. I2C/SPI/UART sensors run on a third, emulation image that sensor_start loads by itself (control_loop and deep replays are unavailable while it runs). - Logic: capture_la, then decode_la (i2c/uart/spi) re-decodes that capture without re-capturing, and la_timing measures edge times, pulse widths, frequency and the delay between two channels (e.g. trigger pin to result pin). @@ -64,8 +64,7 @@ Target power internal 5 V (efuse 1) efuse=1 (external: efuse=2) Pull resistors: set_pull(las, pull="up"|"down"|"off"); the pod picks the value. Today's boards -(pull_status shows each channel's supported directions; they pull to the LA voltage, 1.8 V or 3.3 V; -firmware 3.10.12 and older refuses them at 1.8 V): +(pull_status shows each channel's supported directions; they pull to the LA voltage, 1.8 V or 3.3 V): LA1, LA2 4.7k up LA3, LA4 2.2k up LA5, LA6 10k up LA7, LA8 10k down only LA9-LA14 none diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py index cd991a3..1b944e8 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py @@ -82,7 +82,6 @@ class CapabilitiesInfo(BaseModel): sensors: bool = Field(False, description=( "Sensor emulation from definitions (sensor_start and the other sensor_* tools). Without it " "the firmware is too old for sensor emulation.")) - sensors_format: int = Field(0, description="The sensor definition format the pod reads (0 = not reported).") flash_kb: int = Field(0, description="Internal flash of the pod's MCU in KiB (0 = not reported).") ota_sig: bool = Field(False, description="Firmware updates are signed and the pod checks them.") sig_policy: str = Field("", description="Signature policy: audit (report only) or required.") @@ -773,8 +772,6 @@ class GenerateResult(BaseModel): freq_hz: float dac_path: str cotrig: bool - bits: int = Field(default=8, description=( - "16 when the pod played the calibrated 16-bit waveform (firmware 3.9.1+), 8 for 8-bit levels.")) class StopResult(BaseModel): diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index 842392b..53f8892 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -285,7 +285,21 @@ def _coded_text(exc: BenchPodError) -> Optional[str]: return f"{cmd}: {text}" if cmd else text +def _firmware_too_old_text(exc: BenchPodError) -> Optional[str]: + """The SDK's FirmwareTooOldError: the pod runs firmware 3.x, which this server does not drive.""" + if not isinstance(exc, _errors.FirmwareTooOldError): + return None + fw = getattr(exc, "firmware_version", "") or "3.x" + return (f"the pod runs firmware {fw} (client API {getattr(exc, 'api', 1)}); this BenchPod MCP " + f"server (embeddedci-mcp {_mcp_version()}) needs firmware 4.0.0 or later. Tell the user " + "to update the pod's firmware with the BenchPod CLI (benchpod flash-self) or the " + "firmware update in the web app, then reconnect; retrying will not help") + + def _tool_error(exc: BenchPodError) -> ToolError: + fw_old = _firmware_too_old_text(exc) + if fw_old: + return ToolError(f"{type(exc).__name__}: {fw_old}") too_old = _client_too_old_text(exc) if too_old: return ToolError(f"{type(exc).__name__}: {too_old}") @@ -2560,20 +2574,18 @@ async def generate( ) -> m.GenerateResult: """Drive a sine, square or sawtooth on a DAC output. - On firmware 3.9.1+ the pod takes the volts, calibrates them for dac_path and plays the waveform - at the DAC's full 16 bits (bits=16 in the result); both peaks must then be on the path. Older firmware builds it from 8-bit levels (bits=8): 256 steps over the path. + The pod takes the volts, calibrates them for dac_path and plays the waveform at the DAC's full + 16 bits; both peaks must be on the path. dac_path current_out plays it as a current on the 4-20 mA output (J9), with amplitude and offset - in amps and steps of about 0.25 uA (63 uA on older firmware). See current_out for the wiring it needs. The DAC voltage + in amps and steps of about 0.25 uA. See current_out for the wiring it needs. The DAC voltage outputs are switched off for it. dac_stop then leaves the loop where the waveform stopped: call current_out(0.004) to go back to 4 mA. """ handle = await _call(lambda: SESSION.require().generate( waveform, freq_hz=freq_hz, amplitude=amplitude, offset=offset, **_dac_path_arg(dac_path, route), duration=duration, sample_rate_hz=sample_rate_hz, on_capture=on_capture, route=route)) - bits = 16 if (handle.data or {}).get("bits") == 16 else 8 - return m.GenerateResult(waveform=waveform, freq_hz=freq_hz, dac_path=handle.dac_path, cotrig=handle.cotrig, - bits=bits) + return m.GenerateResult(waveform=waveform, freq_hz=freq_hz, dac_path=handle.dac_path, cotrig=handle.cotrig) @mcp.tool(annotations=_ann("Stop the DAC", idempotent=True)) diff --git a/packages/embeddedci-mcp/tests/conftest.py b/packages/embeddedci-mcp/tests/conftest.py index cfb7b98..a8053bb 100644 --- a/packages/embeddedci-mcp/tests/conftest.py +++ b/packages/embeddedci-mcp/tests/conftest.py @@ -13,7 +13,7 @@ import pytest from embeddedci.benchpod import Wiring, BenchPod -from embeddedci.benchpod.constants import PULL_OHMS, PULLDOWN_CHANNELS +from embeddedci.benchpod.constants import PULL_TABLE from embeddedci.benchpod.errors import FirmwareError from embeddedci.benchpod.transport.base import Transport @@ -117,11 +117,21 @@ def __init__(self) -> None: # -- Transport ABC -- def status(self) -> Any: - caps = list(self.caps) - if self.image is not None: - caps.append("dac_control_loop" if self.image == 0 else "dac_deep_replay") - return {"version": getattr(self, "version", "2.0.0"), "board": "stm32h563", "adc_bits": 16, "adc_fullscale_mv": 4096, - "caps": caps, "gateware": 55} + """A firmware 4.0 status: the features table decides from ``gateware``, ``fpga_image`` + and the facts. :attr:`caps` names the gateware-gated features the test wants (the + gateware follows them) and the facts (``nrst_pin``).""" + caps = set(self.caps) + gw = 55 + for name, need in (("uart_frame", 56), ("uart_hd", 57), ("uart_de", 58)): + if name in caps: + gw = need + if "gpio_read" not in caps: + gw = 34 + image = {0: "loop", 1: "deep"}.get(self.image, "unknown") if self.image is not None else "unknown" + return {"version": getattr(self, "version", "4.0.0"), "board": "stm32h563", "adc_bits": 16, + "adc_fullscale_mv": 4096, "api": 2, "min_client_api": 2, "features_rev": 10, + "gateware": getattr(self, "gateware", None) or gw, "fpga_image": image, + "nrst_pin": "nrst_pin" in caps, "hw": [], "analog": getattr(self, "analog", True)} def ping(self) -> Any: return "pong" @@ -282,18 +292,25 @@ def _cmd_sensor_regs(self, req): return {"instance": req["instance"], "start": req["start"], "len": n, "data_b64": base64.b64encode(bytes(range(n))).decode()} - def _cmd_la(self, req): - if "steps" in req: - return {"la": req["la"], "steps": req["steps"], "delay_us": req["delay_us"], - "status": "started"} + def _cmd_la_step(self, req): + return {"la": req["la"], "steps": req["steps"], "delay_us": req["delay_us"], + "status": "started"} + + def _cmd_la_pull(self, req): if "la" not in req: - return {"la_pullup_mask": 3, "pullups_available": 1} + return {"la_pullup_mask": 3, "pullups_available": True} la = req["la"] - if "pullup" in req: - self.pull_on[la] = req["pullup"] == "on" - return {"la": la, "pullup": int(self.pull_on.get(la, False)), - "ohms": PULL_OHMS.get(la, ""), "pull": "down" if la in PULLDOWN_CHANNELS else "up", - "pullups_available": 1} + hw = PULL_TABLE.get(la) + want = req.get("pull") + if want in ("up", "down") and (not hw or want not in hw.dirs): + from embeddedci.benchpod.errors import firmware_error + raise firmware_error("", cmd="la_pull", code="BP0024" if hw else "BP0023", + values={"la": la, "want": want, "have": hw.default if hw else ""}) + if want is not None: + self.pull_on[la] = want != "off" + on = self.pull_on.get(la, False) + return {"la": la, "state": (hw.default if on else "off") if hw else "off", + "dirs": list(hw.dirs) if hw else [], "pullups_available": True} # -- LA pin ownership + GPIO (the firmware's la_pins / gpio contract) -- def _conflict(self, la: int) -> str: @@ -304,8 +321,8 @@ def _conflict(self, la: int) -> str: def _pin(self, la: int) -> Dict[str, Any]: pull = None - if la in PULL_OHMS: - pull = {"dir": "down" if la in PULLDOWN_CHANNELS else "up", "ohms": PULL_OHMS[la], + if la in PULL_TABLE: + pull = {"dir": PULL_TABLE[la].default, "ohms": PULL_TABLE[la].ohms, "on": self.pull_on[la]} e = {"la": la, "function": self.function[la], "gpio": self.mode[la], "level": self.level[la], "pull": pull} diff --git a/packages/embeddedci-mcp/tests/test_bus_master_tools.py b/packages/embeddedci-mcp/tests/test_bus_master_tools.py index e24a32c..2386a56 100644 --- a/packages/embeddedci-mcp/tests/test_bus_master_tools.py +++ b/packages/embeddedci-mcp/tests/test_bus_master_tools.py @@ -74,14 +74,6 @@ def test_set_wiring_sends_the_directions(connected): assert pins[3]["dut_dir"] is None -def test_older_firmware_skips_the_directions(connected): - r = call("set_wiring", profile={"uart_rx": 7, "uart_tx": 8}) - assert r["directions"] == "not sent: this pod's firmware (2.0.0) has no la_dir (3.10.4+)" - assert 7 not in connected.dirs - # Older firmware is not a problem to warn about. - assert not any("pin directions" in w for w in call("status")["warnings"]) - - def test_spi_modes_1_and_2(connected): connected.caps.append("spi_master") from embeddedci_mcp.session import SESSION diff --git a/packages/embeddedci-mcp/tests/test_gpio_tools.py b/packages/embeddedci-mcp/tests/test_gpio_tools.py index 9fc721e..4634b28 100644 --- a/packages/embeddedci-mcp/tests/test_gpio_tools.py +++ b/packages/embeddedci-mcp/tests/test_gpio_tools.py @@ -21,7 +21,7 @@ def test_la_pins_reports_every_channel_with_levels(connected): assert [p["la"] for p in result["pins"]] == list(range(1, 15)) assert _pin(result, 1) == {"la": 1, "function": "none", "gpio": None, "level": None, "pull": "up", "pull_dirs": ["up"], "pull_ohms": "4.7k", "pull_on": False, "in_use": False, - "dir": None, "warnings": None} + "dir": "bidir", "warnings": None} assert _pin(result, 7)["pull"] == "down" and _pin(result, 12)["pull"] is None assert _pin(result, 14)["pull"] is None assert {lv["la"]: lv["level"] for lv in result["levels"]}[11] == 1 @@ -41,12 +41,6 @@ def test_la_pins_shows_who_owns_a_channel(connected): assert _pin(result, 4)["function"] == "uart_tx" -def test_la_pins_needs_the_firmware_capability(connected): - without_caps(connected, "la_pins") - with pytest.raises(ToolError, match="la_pins"): - call("la_pins") - - # -- configuring and driving ------------------------------------------------------------- def test_gpio_mode_claims_channels_in_one_command(connected): @@ -105,7 +99,7 @@ def test_gpio_wait_times_out_without_failing(connected): def test_gpio_pulse_runs_a_step_train(connected): assert call("gpio_pulse", la=3, width=0.001, count=5) == {"la": 3, "count": 5, "width": 0.001} - assert connected.requests[-1] == {"cmd": "la", "la": 3, "steps": 5, "delay_us": 1000} + assert connected.requests[-1] == {"cmd": "la_step", "la": 3, "steps": 5, "delay_us": 1000} # -- ownership conflicts reach the agent ------------------------------------------------------ @@ -133,9 +127,3 @@ def test_pull_conflict_reaches_the_agent(connected): call("gpio_mode", la=[7], mode="open_drain") -def test_gpio_needs_the_firmware_capability(connected): - without_caps(connected, "la_pins") - with pytest.raises(ToolError, match="la_pins"): - call("gpio_mode", la=[3]) - with pytest.raises(ToolError, match="la_pins"): - call("gpio_release") diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index ca17b53..43c4b8e 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -27,23 +27,23 @@ def command(req): def test_leased_names_the_holder_and_the_time_left(connected): - _refuse(connected, "la", "busy: a cloud job holds this pod (octo/ci run 9, 12 s left)") + _refuse(connected, "la_step", "busy: a cloud job holds this pod (octo/ci run 9, 12 s left)") with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) msg = str(info.value) - assert "PodLeasedError: la: busy: a cloud job holds this pod (octo/ci run 9, 12 s left)" in msg + assert "PodLeasedError: la_step: busy: a cloud job holds this pod (octo/ci run 9, 12 s left)" in msg assert msg.endswith("Wait for that job to finish and retry; reads such as status still work " "meanwhile.") def test_locked_says_to_use_the_cloud_or_usb(connected): - _refuse(connected, "la", "locked: la needs the cloud or the USB console") + _refuse(connected, "la_step", "locked: la needs the cloud or the USB console") with pytest.raises(ToolError, match=r"PodLockedError: .*connect with 'embeddedci:'"): call("gpio_pulse", la=3, width=0.001, count=5) def test_forbidden_says_who_may(connected): - _refuse(connected, "la", "forbidden: la needs an organization owner or admin") + _refuse(connected, "la_step", "forbidden: la needs an organization owner or admin") with pytest.raises(ToolError, match=r"PermissionDeniedError: .*benchpod:admin scope"): call("gpio_pulse", la=3, width=0.001, count=5) @@ -54,18 +54,18 @@ def test_forbidden_says_who_may(connected): @needs_unsupported def test_unknown_command_says_the_firmware_lacks_it(connected): - _refuse(connected, "la", "unknown cmd") + _refuse(connected, "la_step", "unknown cmd") with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) msg = str(info.value) - assert "UnsupportedFeatureError: la: unknown cmd" in msg + assert "UnsupportedFeatureError: la_step: unknown cmd" in msg assert "firmware or gateware lacks the feature" in msg and "retrying will not help" in msg @needs_unsupported def test_digital_board_says_it_has_no_analog(connected): # The hint goes by the refusal's text, whichever command drew it. - _refuse(connected, "la", "this BenchPod has no analog front end (digital board): no DAC, ADC or " + _refuse(connected, "la_step", "this BenchPod has no analog front end (digital board): no DAC, ADC or " "analog outputs. Restart the pod after fitting an analog add-on") with pytest.raises(ToolError, match=r"UnsupportedFeatureError: .*digital-only board"): call("gpio_pulse", la=3, width=0.001, count=5) @@ -78,17 +78,17 @@ def command(req): connected.command = command with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) - assert str(info.value).endswith("FirmwareError: la: unknown target") + assert str(info.value).endswith("FirmwareError: la_step: unknown target") # -- the firmware's protocol-level fixes, named as tools --------------------------------------- # Texts: benchpod-firmware stm32h563/src/command_handler.c (require_la_voltage) and la_pins.c. def test_la_voltage_not_set_names_set_la_voltage(connected): - _refuse(connected, "la", "la voltage not set; set it with la_voltage (mv 1800 or 3300) first") + _refuse(connected, "la_step", "la voltage not set; set it with la_voltage (mv 1800 or 3300) first") with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) - assert str(info.value).endswith("FirmwareError: la: la voltage not set; the wiring profile sets no " + assert str(info.value).endswith("FirmwareError: la_step: la voltage not set; the wiring profile sets no " "I/O voltage: ask the user for the board's (1.8 or 3.3, 5.0 on a digital v3r4 pod), set it in " "the profile (set_wiring with la_mv 1800 or 3300, then save_wiring) " "or call set_la_voltage") @@ -108,20 +108,20 @@ def test_la_voltage_not_set_names_set_la_voltage(connected): ("can_rx", 'stop it with {"cmd":"can_stop"}', 'stop it with {"cmd":"can_stop"}'), # unknown: as is ]) def test_pin_conflict_names_the_tool(connected, function, hint, fix): - _refuse(connected, "la", f"pin conflict: LA3 is in use by {function}; {hint}") + _refuse(connected, "la_step", f"pin conflict: LA3 is in use by {function}; {hint}") with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) assert str(info.value).endswith( - f"PinConflictError: la: pin conflict: LA3 is in use by {function}; {fix}") + f"PinConflictError: la_step: pin conflict: LA3 is in use by {function}; {fix}") def test_pull_conflict_names_set_pull(connected): - _refuse(connected, "la", "pull conflict: LA7 has its 10k pull-down engaged, which gpio open_drain " + _refuse(connected, "la_step", "pull conflict: LA7 has its 10k pull-down engaged, which gpio open_drain " "can't work with (a released line would read low); disable it with " '{"cmd":"la","la":7,"pullup":"off"} or use another channel') with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) - assert "PullConflictError: la: pull conflict: LA7" in str(info.value) + assert "PullConflictError: la_step: pull conflict: LA7" in str(info.value) assert str(info.value).endswith('disable it with set_pull(las=[7], pull="off") or use another channel') @@ -190,16 +190,27 @@ def test_requests_name_this_server(): @needs_client_api def test_a_pod_above_this_servers_level_fails_the_connect(fake_open, fake_transport): real = fake_transport.status - fake_transport.status = lambda: {**real(), "version": "3.11.0", "api": 2, "min_client_api": 1} + fake_transport.status = lambda: {**real(), "version": "5.0.0", "api": 3, "min_client_api": 2} with pytest.raises(ToolError) as info: call("connect", connection="192.168.1.50", la_voltage=3.3) msg = str(info.value) assert "ClientTooOldError: this BenchPod MCP server (embeddedci-mcp " in msg - assert "the pod's firmware 3.11.0 speaks client API 2, this server handles 1" in msg + assert "the pod's firmware 5.0.0 speaks client API 3, this server handles 2" in msg assert "uvx embeddedci-mcp@latest" in msg and "pip install -U embeddedci-mcp" in msg assert "benchpod plugin" in msg and "pip install -U embeddedci " not in msg +def test_firmware_3_fails_the_connect_with_the_update(fake_open, fake_transport): + real = fake_transport.status + fake_transport.status = lambda: {k: v for k, v in {**real(), "version": "3.10.13"}.items() + if k not in ("api", "min_client_api")} + with pytest.raises(ToolError) as info: + call("connect", connection="192.168.1.50", la_voltage=3.3) + msg = str(info.value) + assert "FirmwareTooOldError: the pod runs firmware 3.10.13 (client API 1)" in msg + assert "needs firmware 4.0.0 or later" in msg and "benchpod flash-self" in msg + + @needs_client_api def test_bp0030_on_a_tool_says_to_update_this_server(connected): def command(req): @@ -210,7 +221,7 @@ def command(req): with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) msg = str(info.value) - assert "ClientTooOldError: la: this BenchPod MCP server" in msg + assert "ClientTooOldError: la_step: this BenchPod MCP server" in msg assert "needs client API 2 or newer, this server sent 1" in msg assert "uvx embeddedci-mcp@latest" in msg @@ -223,5 +234,5 @@ def command(req): with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) msg = str(info.value) - assert "la: BP0001: la voltage not set; the wiring profile sets no I/O voltage" in msg + assert "la_step: BP0001: la voltage not set; the wiring profile sets no I/O voltage" in msg assert "call set_la_voltage" in msg diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index 6dffebd..47ddd85 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -14,7 +14,7 @@ from embeddedci_mcp.server import mcp from embeddedci_mcp.session import SESSION -from conftest import call, without_caps +from conftest import call EXPECTED_TOOLS = { "connect", "disconnect", "status", "set_la_voltage", @@ -293,7 +293,7 @@ def test_schema_rejects_bad_arguments(connected): def test_sdk_value_errors_become_tool_errors(connected): with pytest.raises(ToolError, match="invalid argument"): - call("generate", waveform="sine", freq_hz=10, amplitude=0.0001, dac_path="3v3") + call("generate", waveform="sine", freq_hz=10, amplitude=0.00001, dac_path="3v3") def test_disconnect(connected): @@ -434,7 +434,7 @@ def test_uart_session_read_write(connected): def test_uart_frame_format(connected): # 8N1 by default; parity / stop bits need the pod's uart_frame capability assert call("uart_open", rx=5, tx=4)["parity"] == "none" - with pytest.raises(ToolError, match="firmware 3.10.8"): + with pytest.raises(ToolError, match="gateware v56"): call("uart_open", rx=5, tx=4, parity="even") connected.caps.append("uart_frame") SESSION.require().refresh_capabilities() @@ -577,12 +577,6 @@ def test_sensor_stimulus_tools(connected): call("sensor_stimulus_load", stimulus=INLINE) -def test_sensor_tools_refuse_old_firmware(connected): - without_caps(connected, "sensors") - with pytest.raises(ToolError, match="too old for sensor emulation; update the firmware"): - call("sensor_start", definition="bmp280", pins={"sda": 2, "scl": 1}) - - def test_pulls(connected): res = call("set_pull", las=[7], enabled=True) # the older form still works assert res["channels"][0]["direction"] == "down" and res["channels"][0]["state"] == "down" @@ -664,14 +658,13 @@ def test_waveforms_on_the_current_output_are_in_amps(connected): out = call("generate", waveform="sine", freq_hz=2, amplitude=0.006, offset=0.012, dac_path="current_out") assert out["dac_path"] == "current_out" gen = connected.requests[-1] - assert gen["cmd"] == "generate" and (gen["amplitude"], gen["offset"]) == (96, 127) - # The voltage outputs are switched off first; no voltage path is routed. - assert {"cmd": "analog_path", "path": "current_out"} in connected.requests + assert gen["cmd"] == "generate" and (gen["amplitude_ua"], gen["offset_ua"]) == (6000, 12000) + # The pod switches the voltage outputs off itself; no voltage path is routed. assert not any(r.get("cmd") == "dac_out" for r in connected.requests) played = call("replay", volts=[0.004, 0.012, 0.020], dac_path="current_out", sample_rate_hz=1000) assert played["dac_path"] == "current_out" and played["samples"] == 3 - with pytest.raises(Exception, match="at most"): + with pytest.raises(Exception, match="must stay within"): call("generate", waveform="sine", freq_hz=2, amplitude=12, dac_path="current_out") # mA by mistake @@ -691,9 +684,10 @@ def test_correlated_capture_of_the_current_input_is_in_amps(connected): assert call("capture_correlated", adc_samples=64, la_samples=64)["adc"]["unit"] == "V" -def test_current_out_needs_newer_firmware(connected): - without_caps(connected, "current_out") - with pytest.raises(Exception, match="current_out"): +def test_current_out_needs_the_analog_board(connected): + connected.analog = False + SESSION.require().refresh_capabilities() + with pytest.raises(Exception, match="analog front end"): call("current_out", current=0.012) @@ -734,12 +728,6 @@ def test_dmm_calibration_tools(connected): assert cleared["dac"]["5v"] is None and cleared["adc_gain_ppm"]["cal1"] == 1850 -def test_dmm_calibration_needs_newer_firmware(connected): - without_caps(connected, "cal_dmm") - with pytest.raises(Exception, match="cal_dmm"): - call("calibrate_adc_gain", source="cal1") - - def test_calibrate_refusal_is_a_tool_error(connected): connected.error = "calibrate: current_in reads 996 mV, it must be within +/-50 mV of zero. Something is driving J8. Disconnect it and try again" with pytest.raises(Exception, match="996 mV"): @@ -747,9 +735,10 @@ def test_calibrate_refusal_is_a_tool_error(connected): assert call("calibration")["calibrated"] is False -def test_calibrate_needs_newer_firmware(connected): - without_caps(connected, "calibrate") - with pytest.raises(Exception, match="calibrate"): +def test_calibrate_needs_the_analog_board(connected): + connected.analog = False + SESSION.require().refresh_capabilities() + with pytest.raises(Exception, match="analog front end"): call("calibration") @@ -789,18 +778,20 @@ def test_capture_correlated(connected): def test_generate_and_stop(connected): result = call("generate", waveform="sine", freq_hz=1000, amplitude=1.0, on_capture=True) # No dac_path: the 3.3 V output, the lowest voltage one. - assert result == {"waveform": "sine", "freq_hz": 1000.0, "dac_path": "3v3", "cotrig": True, "bits": 8} - assert connected.requests[-2] == {"cmd": "dac_out", "path": "3v3"} - assert connected.requests[-1]["amplitude"] == 77 + assert result == {"waveform": "sine", "freq_hz": 1000.0, "dac_path": "3v3", "cotrig": True} + assert connected.requests[-1] == {"cmd": "generate", "waveform": "sine", "freq_hz": 1000, + "path": "3v3", "amplitude_v": 1.0, "offset_v": 1.65, + "on_capture": True} assert call("dac_stop") == {"stopped": True} # route=false keeps a loopback set up with analog_path: no dac_out before the generator, and # the volts scale for the routed DAC (cal1 is the 5 V one). call("analog_path", path="cal1") res = call("generate", waveform="square", freq_hz=100, amplitude=1.0, route=False) assert [r["cmd"] for r in connected.requests[-2:]] == ["analog_path", "generate"] - assert res["dac_path"] == "5v" and connected.requests[-1]["amplitude"] == 51 + assert res["dac_path"] == "5v" and connected.requests[-1]["route"] is False + assert connected.requests[-1]["offset_v"] == 2.5 res = call("generate", waveform="sine", freq_hz=100, amplitude=1.0, dac_path="12v") - assert res["dac_path"] == "12v" and connected.requests[-2] == {"cmd": "dac_out", "path": "12v"} + assert res["dac_path"] == "12v" and connected.requests[-1]["path"] == "12v" def test_replay_sources(connected): diff --git a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py index 55f7d73..009f6ef 100644 --- a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py +++ b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py @@ -7,7 +7,7 @@ from embeddedci_mcp.session import SESSION -from conftest import call, without_caps +from conftest import call # -- triggers ----------------------------------------------------------------------------- @@ -47,8 +47,9 @@ def test_a_trigger_that_never_fires_is_a_tool_error(connected): call("capture_la", samples=100, sample_rate_hz=1e6, trigger_la=9) -def test_triggers_need_the_firmware_capability(connected): - without_caps(connected, "capture_trigger") +def test_triggers_need_the_gateware(connected): + connected.gateware = 34 # capture triggers: gateware v35 + SESSION.require().refresh_capabilities() with pytest.raises(ToolError, match="capture_trigger"): call("capture_la", samples=100, trigger_la=9) @@ -123,14 +124,6 @@ def test_disconnect_forgets_the_running_profile(connected): assert SESSION.power_profile is None -def test_power_profiles_need_the_firmware_capability(connected): - without_caps(connected, "power_profile") - with pytest.raises(ToolError, match="power_profile"): - call("measure_power", duration=1.0) - with pytest.raises(ToolError, match="power_profile"): - call("power_profile_start") - - def test_the_schema_bounds_the_power_arguments(connected): with pytest.raises(ToolError): call("measure_power", duration=1.0, rate_hz=5000) diff --git a/packages/embeddedci-openhtf/tests/_fake.py b/packages/embeddedci-openhtf/tests/_fake.py index ec62d63..fde3381 100644 --- a/packages/embeddedci-openhtf/tests/_fake.py +++ b/packages/embeddedci-openhtf/tests/_fake.py @@ -92,11 +92,12 @@ def __init__(self, banner: bytes = b"reset\r\nAPP_OK build 1\r\n", "bus_mv": [5010, 5000]} def status(self): - status = {"status": "ok", "fake": True, "caps": list(self.caps)} - if self.image is not None: - status["caps"] += ["dac", "dac_replay", - "dac_control_loop" if self.image == 0 else "dac_deep_replay"] - return status + """A firmware 4.0 status. ``image`` None is a pod without the DAC images (and so, here, + without the analog front end).""" + return {"status": "ok", "fake": True, "version": "4.0.0", "api": 2, "min_client_api": 2, + "features_rev": 10, "gateware": 59, + "fpga_image": {0: "loop", 1: "deep"}.get(self.image, "unknown"), + "analog": self.image is not None or "current_out" in self.caps, "hw": []} def ping(self): return {"status": "ok", "data": "pong"} @@ -112,8 +113,10 @@ def uart_proxy_start(self, rx: int, tx: int, baud: int) -> RawLink: # JSON commands. Returns the reply *data* (what the real transport.command yields). def command(self, req: dict): - self.commands.append(req) cmd = req.get("cmd") + if cmd in ("wiring_list", "la_dir"): # the connect's own: no stored profile + return {} + self.commands.append(req) if cmd == "la_voltage": return {"mv": req.get("mv", 0)} if cmd == "analog_path": diff --git a/packages/embeddedci-openhtf/tests/test_analog.py b/packages/embeddedci-openhtf/tests/test_analog.py index e0c9dc7..d11ec5d 100644 --- a/packages/embeddedci-openhtf/tests/test_analog.py +++ b/packages/embeddedci-openhtf/tests/test_analog.py @@ -65,24 +65,20 @@ def test_signal_generate_phase_converts_volts_through_generate(): freq_hz=1000, amplitude=1.0, duration=0.5)) assert rec.outcome == tr.Outcome.PASS i = _cmds(tx).index("generate") - # generate routes the DAC path first (3v3 when none is given), then sends 8-bit generator - # codes: 1.0 V / (3.3 V / 255) = 77, offset defaults to mid-range 1.65 V -> 127. - assert tx.commands[i - 1] == {"cmd": "dac_out", "path": "3v3"} - assert tx.commands[i] == {"cmd": "generate", "waveform": "sine", "freq": 1000.0, - "amplitude": 77, "offset": 127, "duration_ms": 500} + # generate sends volts on the path (3v3 when none is given; the pod routes it); the offset + # defaults to mid-range 1.65 V. + assert tx.commands[i] == {"cmd": "generate", "waveform": "sine", "freq_hz": 1000, "path": "3v3", + "amplitude_v": 1.0, "offset_v": 1.65, "duration_ms": 500} def test_signal_generate_helper_path_offset_and_rate(): tx = FakeTransport() plug = benchpod_plug(transport=tx)() - handle = signal_generate(plug, waveform="square", freq_hz=50, amplitude=1.1, offset=0.66, + handle = signal_generate(plug, waveform="square", freq_hz=50, amplitude=0.6, offset=0.66, dac_path="3v3", sample_rate_hz=250_000) assert isinstance(handle, DacHandle) and handle.dac_path == "3v3" - assert tx.commands[-2:] == [ - {"cmd": "dac_out", "path": "3v3"}, - {"cmd": "generate", "waveform": "square", "freq": 50.0, "amplitude": 85, "offset": 51, - "sample_rate_mhz": 0.25}, - ] + assert tx.commands[-1] == {"cmd": "generate", "waveform": "square", "freq_hz": 50, "path": "3v3", + "amplitude_v": 0.6, "offset_v": 0.66, "sample_rate_hz": 250000} handle.stop() assert tx.commands[-1] == {"cmd": "dac_stop"} @@ -109,7 +105,7 @@ def test_adc_capture_phase_records_volts(): mean_range=(1.5, 1.8), pp_range=(3.2, 3.4))) assert rec.outcome == tr.Outcome.PASS assert tx.commands[-2:] == [{"cmd": "analog_path", "path": "adc_ext"}, - {"cmd": "capture", "samples": 8}] + {"cmd": "capture", "samples": 8, "enc": "dec"}] p = _phase(rec, "adc_capture") assert _value(p, "adc_mean_v") == pytest.approx(sum(TRI_V) / 8) assert _value(p, "adc_pp_v") == pytest.approx(3.3) @@ -127,7 +123,7 @@ def test_adc_capture_phase_source_none_leaves_routing_and_passes_rate(): sample_rate_hz=100_000, prefix="rail", attachment=None)) assert rec.outcome == tr.Outcome.PASS assert "analog_path" not in _cmds(tx) - assert tx.commands[-1] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.1} + assert tx.commands[-1] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.1, "enc": "dec"} p = _phase(rec, "adc_capture") assert _value(p, "rail_pp_v") == pytest.approx(3.3) assert "adc.json" not in p.attachments @@ -168,12 +164,11 @@ def test_loopback_measure_phase_generates_captures_then_stops(): pp_range=(3.0, 3.5), mean_range=(1.5, 1.8))) assert rec.outcome == tr.Outcome.PASS # DAC first (its path re-applies and would open a loopback relay), then route the ADC. - assert _cmds(tx) == ["dac_out", "generate", "analog_path", "capture", "dac_stop"] - assert tx.commands[0] == {"cmd": "dac_out", "path": "3v3"} - assert tx.commands[1] == {"cmd": "generate", "waveform": "sine", "freq": 100.0, - "amplitude": 77, "offset": 127} - assert tx.commands[2] == {"cmd": "analog_path", "path": "adc_ext"} - assert tx.commands[3] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.05} + assert _cmds(tx) == ["generate", "analog_path", "capture", "dac_stop"] + assert tx.commands[0] == {"cmd": "generate", "waveform": "sine", "freq_hz": 100, "path": "3v3", + "amplitude_v": 1.0, "offset_v": 1.65} + assert tx.commands[1] == {"cmd": "analog_path", "path": "adc_ext"} + assert tx.commands[2] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.05, "enc": "dec"} p = _phase(rec, "loopback_measure") assert _value(p, "adc_pp_v") == pytest.approx(3.3) assert _value(p, "adc_mean_v") == pytest.approx(sum(TRI_V) / 8) @@ -184,7 +179,7 @@ def test_loopback_measure_phase_internal_loopback_source(): rec = _run(loopback_measure_phase(benchpod_plug(transport=tx), freq_hz=100, amplitude=1.0, dac_path="12v", samples=8, source="cal2", settle=0)) assert rec.outcome == tr.Outcome.PASS - assert tx.commands[0] == {"cmd": "dac_out", "path": "12v"} + assert tx.commands[0]["cmd"] == "generate" and tx.commands[0]["path"] == "12v" assert {"cmd": "analog_path", "path": "cal2"} in tx.commands diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index dfbb9c0..131bf84 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -1,7 +1,38 @@ # Changelog — `embeddedci` +## 4.0.0 + +Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: + +- **Firmware 4.0 or later only.** `CLIENT_API` is 2 and every request says so. Connecting to a + pod with firmware 3.x (client API 1, or no `api` in its status) raises the new + `FirmwareTooOldError` (an `UnsupportedFeatureError`, `feature="client_api"`), which says to + update the pod with `benchpod flash-self` or the web app, or to stay on embeddedci 3.x. Over the + USB console, which announces no level, the firmware version decides. A pod whose + `min_client_api` is above 2 raises `ClientTooOldError`. +- **Features come from the table only.** The `caps` list and every version fallback are gone: + `Capabilities` reads `features_rev`, the gateware, the image and the facts from `status` (and + the cloud `cap.features_rev`, `cap.gateware`, `cap.fpga_image`), never `status` with + `"caps":false`. `Capabilities.sensors_format` and the `signal` alias for the scope are gone; + `Transport.status_without_caps()` is gone. `diag()` sends `diag` only. +- **USB console:** firmware 4.0's console answers `status`, `ping` and `identity` only, so the + serial transport no longer sends `la-voltage`, `power`, `dap-start` or `uart-proxy`; they raise + a `TransportError` that points at `usb` (the USB network adapter) or a network address. The + parsed `usb` status line reports `net` as a boolean, as the JSON status does. +- **`generate` sends volts only**: `path` with `amplitude_v`/`offset_v`, or `amplitude_ua`/ + `offset_ua` on `current_out`, `freq_hz` and `sample_rate_hz` in hertz; the pod routes the path. + The 8-bit form is gone. The MCP `generate` result has no `bits`. +- **Captures take base64 by default:** the SDK no longer asks for `"enc":"b64"`; a transport + without chunked streaming asks for `"enc":"dec"`. +- Pull resistors use `la_pull` and step trains `la_step` (firmware 4.0 split the `la` command). + `PullState` reads the 4.0 reply (`state`, `dirs`, `pullups_available` as a boolean); the + resistor value comes from the board table, `la_pins` reports it on every board. +- Features table revision 11. + ## 3.0.6 +Never released: its changes ship in 4.0.0. + - **Error codes decide the exception class.** Every code in the error catalog (`BP0001` to `BP0030`) maps to one class, and the code's values fill its fields; the text decides only for a refusal without a code (older firmware) or with a code newer than this SDK. New `WiringError` diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 23acbd1..6b605ca 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -31,6 +31,11 @@ with BenchPod("192.168.1.213", la_voltage=3.3) as bp: # or "usb", or "emb No pin numbers: the SWD channels, the UART pair, the baud and the power rail come from the bench's [wiring profile](#wiring-profile). Pass them explicitly when you want to override it. +**Pod firmware 4.0 or later.** embeddedci 4.x drives pods with firmware 4.0.0 and later (client +API 2). Connecting to a pod with firmware 3.x raises `FirmwareTooOldError`, which says to update +the pod with the BenchPod CLI (`benchpod flash-self`) or the firmware update in the web app; to +keep firmware 3.x, stay on embeddedci 3.x (`pip install 'embeddedci<4'`). + **Contents:** [Install](#install) · [Quick start](#quick-start) · [API conventions](#api-conventions-and-stability) · [pytest plugin](#pytest-plugin) · [Test runs](#test-run-recording) · [Power and reset](#power-reset-and-power-monitoring) · [Flashing](#flashing) · [UART](#uart) · @@ -248,13 +253,11 @@ Wi-Fi or the cloud the pod refuses the change (`PodLockedError`). Turning it bac console: `benchpod usb-network on`. Status reports it as `usb.setting` and, when the adapter is off, `usb.off_reason` (`"setting"` or `"wifi"`). -**Compatibility.** The SDK decides per pod, from what the pod reports (the `usb` line of its -console `status`), never from its own version: - -| | Pod firmware before 3.9.0 | Pod firmware 3.9.0 and later | -|---|---|---| -| **This SDK (2.12.0+)** | As before: `usb` is the console (status, ping, LA voltage, target power); the rest needs the network or the cloud. Console auto-detect still finds `0483:5740` and `2E8A`. | `usb` is the full API over the USB network adapter when it is up. When USB networking is off (Wi-Fi configured) or down, it is the full API over the pod's Ethernet or Wi-Fi address from its console status, when this computer reaches it (logged as a warning; the pod's external LAN policy applies there; `transport.usb_lan_fallback` says why); else the console. | -| **An older SDK (2.11.x)** | Unchanged. | `usb` is the console: its auto-detect probes every USB serial port, so it finds a 3.9.0 pod (same USB id `0483:5740`; tested). Status and ping work; LA voltage and target power, which 3.9.0 moved to the JSON API, fail with the pod's "moved to the network API ... update" line. A network address or `embeddedci:` works fully. | +**When the USB network is off.** `usb` is the full API over the USB network adapter when it is +up. When USB networking is off (Wi-Fi configured) or down, it is the full API over the pod's +Ethernet or Wi-Fi address from its console status, when this computer reaches it (logged as a +warning; the pod's external LAN policy applies there; `transport.usb_lan_fallback` says why); +else the console, which answers `status` and `ping` only. **Several pods on USB.** Auto-detect reads each pod's name (its identity short id, `baea06` for `benchpod-baea06`) from the console's `identity` command. Connection `usb:` opens the pod @@ -267,15 +270,15 @@ on an open console. **Otherwise use the network (or the cloud) for testing.** The STM32 pod's USB console is a text shell for setup and diagnostics with no JSON mode, so over the console the SDK can only read -`status()`, `ping()`, select the LA voltage and switch target power (without `delay`). Everything -else (flashing, UART, analog, captures, sensor emulation, CAN) raises a `TransportError` right -away that points at the network connection. (On firmware 3.9.0 and later the LA voltage and target -power moved to the network too; see the compatibility table above.) +`status()` and `ping()`. Everything else (the LA voltage, target power, flashing, UART, analog, +captures, sensor emulation, CAN) raises a `TransportError` right away that points at the network +connection or `usb` (the USB network adapter). Over the console the firmware version decides the +client API check: firmware 3.x raises `FirmwareTooOldError` there too. -| | TCP | USB network (`usb`, firmware 3.9.0+) | USB console (STM32 pod) | Cloud | +| | TCP | USB network (`usb`) | USB console (STM32 pod) | Cloud | |---|---|---|---|---| -| `status`, `ping`, LA voltage, target power on/off | yes | yes | yes | yes | -| Scheduled power changes (`delay=`), flashing, UART, analog, captures, sensor emulation, CAN, control loop | yes | yes | no | yes | +| `status`, `ping` | yes | yes | yes | yes | +| LA voltage, target power, flashing, UART, analog, captures, sensor emulation, CAN, control loop | yes | yes | no | yes | | `replay()` / client-side `replay_waveform()` (streams the waveform to the pod) | yes | yes | no | yes | | Device lease | the pod's lease (feature `lease`) | the pod's lease (feature `lease`) | no | the server's lease | @@ -428,28 +431,34 @@ properties `can_gpio`, `can_trigger`, `can_spi`, `can_profile_power`, `can_calib `UnsupportedFeatureError` (see [Errors](#errors)), before anything is sent when the capabilities already say so. -Where those come from: firmware after 3.10.10 no longer lists its features. The SDK asks for its -`status` without the list (`"caps":false`) and gets `capabilities.features_rev`, the revision of -the features table the firmware is built from, plus the running image (`capabilities.fpga_image`) -and a few hardware facts. The SDK ships that table (`embeddedci.benchpod.feature_map`, a copy of -benchpod-firmware's `features/features.json`), so this needs no network: `capabilities.features` -is every feature the table gives the pod, and `bp.supports()` also takes table names without a -flag of their own (`"la_dir"`, `"i2c_master"`, `"diag"`, `"wiring_store"`, ...). Older firmware -sends its list as before and gets the same answers. A pod with a higher `features_rev` than the -SDK knows logs a warning once: update the SDK (`pip install -U embeddedci`) to use those features. +Where those come from: the pod's `status` (and its cloud capabilities frame) carries +`capabilities.features_rev`, the revision of the features table its firmware is built from, plus +the running image (`capabilities.fpga_image`), the gateware and a few hardware facts. The SDK +ships that table (`embeddedci.benchpod.feature_map`, a copy of benchpod-firmware's +`features/features.json`), so this needs no network: `capabilities.features` is every feature the +table gives the pod, and `bp.supports()` also takes table names without a flag of their own +(`"la_dir"`, `"i2c_master"`, `"diag"`, `"wiring_store"`, ...). A pod with a higher `features_rev` +than the SDK knows logs a warning once: update the SDK (`pip install -U embeddedci`) to use those +features. **Client API level.** A new feature is additive, so an older SDK just misses it. The other kind of change, one an older SDK would misread (a reply that changes shape, a field that changes meaning, a refusal text replaced), raises the firmware's client API level. The SDK is built for -`embeddedci.benchpod.feature_map.CLIENT_API` (1) and sends it with every JSON command as -`"client_api"`, with `"client": "sdk "` (the MCP server sends `"mcp "`); older -firmware ignores both. Firmware after 3.10.13 announces its level (`capabilities.api`, with -`capabilities.min_client_api`; `capabilities.client_api_level` counts a pod that does not say as -1). When the pod's level is above the SDK's, connecting raises `ClientTooOldError`, which says -the pod's firmware version and both levels; the pod raises the same error (`BP0030`) for a client -below its `min_client_api`. Either way the fix is `pip install -U embeddedci`. `status`, `diag`, -`ping` and `lease_release` are never refused, so a too-old client can still see what the pod -runs. +`embeddedci.benchpod.feature_map.CLIENT_API` (2) and sends it with every JSON command as +`"client_api"`, with `"client": "sdk "` (the MCP server sends `"mcp "`). The pod +announces its level (`capabilities.api`, with `capabilities.min_client_api`; +`capabilities.client_api_level` counts a pod that does not say as 1). + +- A pod below `feature_map.MIN_POD_API` (2, firmware 3.x) raises `FirmwareTooOldError` on connect: + update the pod (`benchpod flash-self`, or the firmware update in the web app), or use + embeddedci 3.x with it. +- A pod above the SDK's level, or one whose `min_client_api` is above it, raises + `ClientTooOldError`, which says the pod's firmware version and both levels; the pod raises the + same error (`BP0030`) for a client below its `min_client_api`. The fix is + `pip install -U embeddedci`. + +`status`, `diag`, `ping` and `lease_release` are never refused, so a mismatched client can still +see what the pod runs. ```python @@ -1351,11 +1360,10 @@ bp.apply_pin_directions() # send them again (raises on a con print(bp.la_dir()) # every pin's LaPinState, dir included ``` -**The wiring profile's directions are on by default.** On a pod with firmware 3.10.4 or later (`bp.capabilities.la_dir`) -the SDK sends them with `la_dir` when it connects and whenever `bp.wiring` changes, and marks the pins -the profile doesn't name `unknown`. On older firmware it skips this quietly. -`bp.pin_directions_status` says how it went: `"sent"`, or `"not sent: "` (older firmware, or -a pin the profile calls a DUT output that is driven right now; the other directions still go out). +**The wiring profile's directions are on by default.** The SDK sends them with `la_dir` when it +connects and whenever `bp.wiring` changes, and marks the pins the profile doesn't name `unknown`. +`bp.pin_directions_status` says how it went: `"sent"`, or `"not sent: "` (for example a pin +the profile calls a DUT output that is driven right now; the other directions still go out). The connection never fails over it. The pod forgets the directions on a reboot; the next connect sends them again. @@ -1418,8 +1426,7 @@ arguments it returns the `ExpansionStatus`, and `expansion(None)` detaches. on the DUT's I2C bus. - `pullups`: `"pod"` switches on the pod's pull-ups (LA1-LA6 only; they pull to the LA voltage) and `"external"` relies on the breakout's. By default `"pod"` when both pins are on LA1-LA6 and - the pod has pull-ups at this LA voltage, else `"external"`. At 1.8 V that needs firmware newer - than 3.10.12; with older firmware the breakout needs its own pull-ups to 1.8 V. + the pod has pull-ups at this LA voltage (1.8 V and 3.3 V), else `"external"`. - `hz` defaults to 400 kHz for I2C chips (100 kHz for the PCF8574) and 1 MHz for SPI chips. - SPI chips take `spi=(sck, mosi, miso, cs)` (or a dict with those keys) instead of `sda`/`scl`; omitted, the wiring profile's `spi_sclk`, `spi_mosi`, `spi_miso` and `spi_cs`. The pod's SPI @@ -1505,9 +1512,8 @@ compiles and plays it. So firmware that probes a sensor can be tested with it pr reporting chosen values, following a curve over time, or failing in a chosen way. Up to 4 I2C sensors (on one bus or several), 1 SPI sensor, 1 UART sensor and 2 analog sensors (one per analog output) run at once; each is an **instance** with a name you pick (1 to 16 characters of `a-z`, -`0-9` and `_`; the definition's `name` by default, so a longer definition name needs `instance=`). Needs pod firmware with the `sensors` capability (`Capabilities.sensors`, -`Capabilities.sensors_format`); older firmware raises `UnsupportedFeatureError`: "this pod's -firmware is too old for sensor emulation; update the firmware". +`0-9` and `_`; the definition's `name` by default, so a longer definition name needs `instance=`). Every +pod with firmware 4.0 has it (`Capabilities.sensors`). ```python from embeddedci.benchpod import PIN1, PIN2, i2c @@ -1861,8 +1867,7 @@ print(max(loop.currents)) # a capture of J8 carries the loop cu bp.replay(loop, dac_path="current_out") # play the captured loop back on J9 ``` -- `generate` steps are about 0.25 µA on firmware 3.9.1+ (`capabilities.generate16`, 16-bit) and - 63 µA on older firmware (8-bit levels). `replay` is 16-bit. +- `generate` steps are about 0.25 µA (16-bit). `replay` is 16-bit too. - Stopping the returned handle returns the loop to 4 mA. A bare `dac_stop()` does not. - A capture or recording of a voltage has no current to reproduce: on `current_out` it needs `mapping="fit"`, which stretches its shape over the output's range. The same holds for a @@ -2061,11 +2066,10 @@ from embeddedci.benchpod import Fault bp.generate("square", freq_hz=10, amplitude=1.65, offset=1.65, dac_path="3v3", duration=5.0) ``` -On firmware 3.9.1+ (`capabilities.generate16`) the pod takes the volts, applies its own per-path -calibration and plays the waveform at the DAC's full 16 bits (about 50 µV a step on `3v3`); both -peaks must be on the path (0 to 3.3 V works: the pod clamps a peak just past an end it cannot quite -reach). Older firmware builds it from 8-bit levels: 256 steps -over the path (about 13 mV on `3v3`). +The pod takes the volts (`amplitude_v`, `offset_v` on the wire, or microamps on `current_out`), +applies its own per-path calibration, routes the path (unless `route=False`) and plays the waveform +at the DAC's full 16 bits (about 50 µV a step on `3v3`); both peaks must be on the path (0 to 3.3 V +works: the pod clamps a peak just past an end it cannot quite reach). ```python golden = bp.capture_adc(16_384, sample_rate_hz=100_000, source="ext") @@ -2518,6 +2522,7 @@ Match a pod refusal on its code or class, not its text: see [Error codes](#error | `UnsupportedFeatureError` (a `FirmwareError`) | the pod lacks the feature: its capabilities say so (raised before anything is sent), it answers `unknown cmd` (`BP0002`), its gateware is too old (`BP0017`; `feature` names it), or the digital-only board has no analog front end | `feature`, `firmware_version`, `firmware_message`, `cmd` | | `WiringError` (a `FirmwareError`) | a wiring-profile operation was refused (`BP0007` to `BP0015`): no such profile, a bad name, a revision conflict, the store is full, too large, not a JSON object, the default cannot be deleted, an upload out of order, the storage failed | `name`, `code`, `values` | | `ClientTooOldError` (a `FirmwareError`) | this SDK is too old for the pod's firmware: the pod announces a client API level above `CLIENT_API` (raised on connect), or refuses the SDK's level (`BP0030`). Update the SDK: `pip install -U embeddedci` | `client_api`, `api`, `min_client_api`, `firmware_version` | +| `FirmwareTooOldError` (an `UnsupportedFeatureError`) | the pod runs firmware 3.x (client API below 2), which this SDK does not drive (raised on connect). Update the pod: `benchpod flash-self`, or the firmware update in the web app; or use embeddedci 3.x with it | `api`, `firmware_version`, `feature` (`"client_api"`) | | `UartTimeout` | `UartSession.expect` timed out | `text` | | `UartLinkError` (a `UartTimeout` and `ConnectionClosedError`) | the UART link died with an error while `UartSession` waited | `text`, `cause` | | `PinConflictError` | an LA channel is already used by another function (a `FirmwareError`) | `la`, `function` | @@ -2554,7 +2559,7 @@ lease_wait=600.0, lease_ttl=120, wiring=None, lease_purpose=None)`. A context ma | Area | Methods and properties | |---|---| -| Connection and device | `ping()`, `status()`, `diag()` (heap, per-task stacks, network-stack and console counters: the `diag` command on firmware 3.10.9+, else the full `status`), `mac_addresses(status=None)` (the Ethernet and Wi-Fi MACs, see [MAC addresses](#mac-addresses-managed-networks)), `capabilities`, `refresh_capabilities()` (drop the cached capabilities and read them again), `close()`, `leased` (true while this client holds a lease, see [Device leases](#device-leases)), `local_lease()` (the pod's own lease: `LocalLease`), `wiring`, `save_wiring(wiring=None, name=None)` (store a wiring profile on the pod; firmware before 3.10.8: on embeddedci.com), `signal(name)`, `fpga_image(image)`, `usb_cc()`, `usb_network(on=None)` (the USB network setting; `False` turns the adapter off over the USB link), `lan_tls()`, `set_lan_tls_https_only(on)`, `regenerate_lan_tls()`, `set_lan_tls_cert(cert_pem, key_pem)` (the LAN API over TLS, see [TLS on the LAN](#tls-on-the-lan)) | +| Connection and device | `ping()`, `status()`, `diag()` (heap, per-task stacks, network-stack and console counters: the `diag` command), `mac_addresses(status=None)` (the Ethernet and Wi-Fi MACs, see [MAC addresses](#mac-addresses-managed-networks)), `capabilities`, `refresh_capabilities()` (drop the cached capabilities and read them again), `close()`, `leased` (true while this client holds a lease, see [Device leases](#device-leases)), `local_lease()` (the pod's own lease: `LocalLease`), `wiring`, `save_wiring(wiring=None, name=None)` (store a wiring profile on the pod; firmware before 3.10.8: on embeddedci.com), `signal(name)`, `fpga_image(image)`, `usb_cc()`, `usb_network(on=None)` (the USB network setting; `False` turns the adapter off over the USB link), `lan_tls()`, `set_lan_tls_https_only(on)`, `regenerate_lan_tls()`, `set_lan_tls_cert(cert_pem, key_pem)` (the LAN API over TLS, see [TLS on the LAN](#tls-on-the-lan)) | | LA voltage | `set_la_voltage(volts)`, `get_la_voltage()` | | Power and reset | `power_on(efuse=None, *, delay=None)`, `power_off(efuse=None, *, delay=None)`, `target_power(efuse=None, *, on, delay=None)`, `target_status()`, `power_status()`, `measure_power(duration, *, efuse=None, rate_hz=500.0, keep_samples=0)`, `power_profile(*, efuse=None, rate_hz=500.0, keep_samples=4096, max_duration=60.0)`, `reset_target(*, pulse=0.1)`, `set_reset(asserted)`, `reset_state()` | | Flashing | `flash(...)`, `spi_flash(image, addr=0, *, erase=True, verify=True, hold_reset=False, sck=, mosi=, miso=, cs=)`, `open_spi(...)`, `open_motor_emulator(...)` | @@ -2667,8 +2672,8 @@ reported keeps its default (`False`, `0` or `""`), so a feature check is just |---|---| | Identity | `board`, `firmware_version`, `board_rev` (`"v2"`, `"v3"`, `"v3r2"`, `"v3r4"` (digital v3r4), `"unknown"`, or `""`), `la_vccio_mv` (the LA I/O voltage the pod reports, 5000 in 5 V mode) | | ADC | `adc_bits`, `adc_fullscale_mv`, `adc_channels`, `adc_offset_counts`, `adc_affine` (the front-end fit, of the range in use), `adc_low_range` (analog module v3r4+: the low range), `adc_range` (`"normal"`, `"low"`, or `""` before firmware 3.9.5), `adc_range_fullscale` (volts, ±), `adc_max_count`, `counts_to_volts(count)` | -| DAC and replay | `dac`, `dac_dc`, `dac_replay`, `dac_deep_replay`, `dac_control_loop`, `dac_loop_sources` (gateware v29+), `dac_loop_input_map` (v30+), `dac_cotrig` (v27+), `generate16` (firmware 3.9.1+: `generate` in calibrated 16-bit volts), `dac_bits`, `dac_replay_bits`, `dac_replay_max_samples`, `dac_fullscale_mv`, `dac_channels`, `dac_limits` (output limits on the DAC paths) | -| Features | `scope`, `analyzer`, `serial`, `tunnel`, `command`, `ota`, `la_pins`, `gpio_read` (direct pin reads, v35+), `capture_trigger` (v35+), `power_profile`, `capture_b64` (faster ADC read-back, used automatically), `nrst_pin` (the dedicated reset pin, rev3), `usb_cc` (rev3), `vref_out` (digital v3r4: pin 21 switched and measured, 5 V I/O, pulls with a strength on every channel), `spi_master` (v45+), `spi_stream`, `uart_frame` (UART parity and stop bits, gateware v56+), `uart_hd` (one-wire UART and boot-mode entry, gateware v57+), `calibrate`, `cal_dmm` (firmware 3.9.4+: `calibrate_dac`, `calibrate_adc_gain`), `current_out`, `can`, `pod_current` (`PowerStatus.pod`), `sensors` (sensor emulation from definitions, with `sensors_format` the format the pod reads), `analog` (`False` on the digital-only board, `None` when not announced) | +| DAC and replay | `dac`, `dac_dc`, `dac_replay`, `dac_deep_replay`, `dac_control_loop`, `dac_loop_sources` (gateware v29+), `dac_loop_input_map` (v30+), `dac_cotrig` (v27+), `generate16` (`generate` in calibrated 16-bit volts: every analog pod), `dac_bits`, `dac_replay_bits`, `dac_replay_max_samples`, `dac_fullscale_mv`, `dac_channels`, `dac_limits` (output limits on the DAC paths) | +| Features | `scope`, `analyzer`, `serial`, `tunnel`, `command`, `ota`, `la_pins`, `gpio_read` (direct pin reads, v35+), `capture_trigger` (v35+), `power_profile`, `capture_b64` (faster ADC read-back, used automatically), `nrst_pin` (the dedicated reset pin, rev3), `usb_cc` (rev3), `vref_out` (digital v3r4: pin 21 switched and measured, 5 V I/O, pulls with a strength on every channel), `spi_master` (v45+), `spi_stream`, `uart_frame` (UART parity and stop bits, gateware v56+), `uart_hd` (one-wire UART and boot-mode entry, gateware v57+), `calibrate`, `cal_dmm` (firmware 3.9.4+: `calibrate_dac`, `calibrate_adc_gain`), `current_out`, `can`, `pod_current` (`PowerStatus.pod`), `sensors` (sensor emulation from definitions), `analog` (`False` on the digital-only board, `None` when not announced) | | Firmware updates and policies | `flash_kb` (MCU flash in KiB, 0 when not reported), `blob_slots`, `ota_sig`, `sig_policy` (`"audit"`, `"required"`, ...), `sig_keys`, `sig_policy_cmd`, `lan_policy` (`"open"`, `"locked"`, `"off"`), `lan_policy_cmd`, `tunnel_max_tier`, `lease_state` (the pod refuses LAN writes while a cloud job holds it), `cloud_ca`, `cloud_proxy`, `ws_auth_v2` (server only) | | Boot health | `safe_mode`, `safe_reason`, `last_crash`, `reset_cause`, `boot_warning()` (a one-line warning after safe mode or a crash, else `None`) | | Source | `raw` (the map it was parsed from) | diff --git a/packages/embeddedci/src/embeddedci/benchpod/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/__init__.py index 6a37884..a595aac 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/__init__.py @@ -98,6 +98,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin BenchPodError, CanTimeout, ClientTooOldError, + FirmwareTooOldError, CloudAuthError, ConnectionClosedError, ConnectionConfigError, @@ -361,6 +362,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin "PodLeaseLostError", "WiringError", "ClientTooOldError", + "FirmwareTooOldError", "PermissionDeniedError", "UartTimeout", "UartLinkError", diff --git a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py index c821228..8f36a20 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py +++ b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py @@ -21,9 +21,8 @@ from __future__ import annotations -import re from dataclasses import dataclass, field -from typing import Any, Dict, FrozenSet, Mapping, Optional, Tuple +from typing import Any, Dict, FrozenSet, Mapping, Optional from . import feature_map as _feature_map @@ -84,23 +83,8 @@ def _as_bool(m: Mapping[str, Any], *keys: str) -> Optional[bool]: return None -#: Boolean capabilities the firmware's ``status`` reports as top-level ``true`` fields (and the -#: server as ``cap.``), command_handler.c handle_status / cloud_client.c. #: The first gateware with the I2C master, SPI modes 1 and 2 and send-and-capture. BUS_MASTER_GATEWARE = 55 -#: The first firmware with UART parity and stop bits (gateware v56, capability ``uart_frame``). -UART_FRAME_FIRMWARE = "3.10.8" -#: The first firmware with ``la_dir`` (pin directions). -LA_DIR_FIRMWARE = (3, 10, 4) - - -def _version_tuple(version: str) -> Optional[Tuple[int, int, int]]: - """``"3.10.4"`` / ``"v3.10.4-dev"`` as ``(3, 10, 4)``; None when it is not a version.""" - m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)", (version or "").strip()) - return (int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else None - -_STATUS_FLAGS = ("ota_sig", "sig_policy_cmd", "lan_policy_cmd", "tunnel_max_tier", "lease_state", - "cloud_ca", "cloud_proxy", "blob_slots", "can_fd") def _crash_text(v: Any) -> str: @@ -254,8 +238,6 @@ class Capabilities: dac_limits: bool = False #: User-defined sensor emulation from a definition (:attr:`BenchPod.sensors`). sensors: bool = False - #: The sensor definition format the pod reads (``1``); 0 when not reported. - sensors_format: int = 0 #: The emulation gateware image (I2C, SPI and UART sensors) is installed or running; analog #: sensors work without it. sensors_digital: bool = False @@ -339,79 +321,19 @@ def from_status(cls, status: Mapping[str, Any]) -> "Capabilities": c.adc_channels = v if (v := _as_int(status, "la_vccio_mv")) is not None: c.la_vccio_mv = v - # Top-level fields of newer firmware (not in caps[]). - for attr in _STATUS_FLAGS: - if status.get(attr) is True: - setattr(c, attr, True) if (v := _as_bool(status, "analog")) is not None: c.analog = v if (v := _as_int(status, "flash_kb")) is not None and v > 0: c.flash_kb = v if (v := _as_int(status, "gateware")) is not None and v > 0: c.gateware = v - if (v := _as_int(status, "sensors_format")) is not None and v > 0: - c.sensors_format = v if status.get("sensors_digital") is True: c.sensors_digital = True if (v := _as_int(status, "sig_keys")) is not None and v > 0: c.sig_keys = v c.sig_policy = str(status.get("sig_policy", "") or "") c.lan_policy = str(status.get("lan_policy", "") or "") - caps = status.get("caps") - if isinstance(caps, (list, tuple)): - names = {str(x).lower() for x in caps} - # "signal" stood for the scope on firmware that predates the analog flag. Current - # firmware lists it on every board, the digital-only one included, and names "scope" - # itself, so it only counts when the status has no analog flag. - legacy = _as_bool(status, "analog") is None - c.scope = c.scope or "scope" in names or (legacy and "signal" in names) - c.analyzer = c.analyzer or ("la" in names or "analyzer" in names) - c.serial = c.serial or ("uart" in names or "serial" in names) - # The DAC/gateware features. Firmware advertises these in status.caps[] built from - # signal_engine_caps() — the same source as the cloud `capabilities` announce — so a - # DIRECT (LAN/serial) client now sees the same feature set a cloud client does. - # Older firmware simply omits them and every flag stays False, as before. - for name, attr in ( - ("dac", "dac"), - ("dac_dc", "dac_dc"), - ("dac_replay", "dac_replay"), - ("dac_deep_replay", "dac_deep_replay"), - ("dac_control_loop", "dac_control_loop"), - ("dac_cotrig", "dac_cotrig"), - ("generate16", "generate16"), - ("dac_loop_sources", "dac_loop_sources"), - ("dac_loop_input_map", "dac_loop_input_map"), - ("ota", "ota"), - ("tunnel", "tunnel"), - ("command", "command"), - ("la_pins", "la_pins"), - ("gpio_read", "gpio_read"), - ("capture_trigger", "capture_trigger"), - ("power_profile", "power_profile"), - ("capture_b64", "capture_b64"), - ("nrst_pin", "nrst_pin"), - ("usb_cc", "usb_cc"), - ("spi_master", "spi_master"), - ("spi_stream", "spi_stream"), - ("uart_frame", "uart_frame"), - ("uart_hd", "uart_hd"), - ("uart_de", "uart_de"), - ("calibrate", "calibrate"), - ("cal_dmm", "cal_dmm"), - ("current_out", "current_out"), - ("can", "can"), - ("pod_current", "pod_current"), - ("adc_low_range", "adc_low_range"), - ("dac_limits", "dac_limits"), - ("sensors", "sensors"), - ("sensor_la_trigger", "sensor_la_trigger"), - *((f, f) for f in _STATUS_FLAGS), - ): - if name in names and hasattr(c, attr): - setattr(c, attr, True) - if "analog" in names: - c.analog = True - # Firmware after 3.10.10, asked with "caps":false: no list, the features table instead. + # Firmware 4.0 (client API 2): the features table decides every feature flag. if (rev := _as_int(status, "features_rev")) is not None and rev > 0: c.features_rev = rev c.fpga_image = str(status.get("fpga_image", "") or "") @@ -442,14 +364,11 @@ def _apply_features(self, facts: Mapping[str, Any]) -> None: setattr(self, fact, True) def has(self, feature: str) -> bool: - """Whether the pod has ``feature``: a table name (``"la_dir"``, ``"i2c_master"``, ...) - when the pod announced :attr:`features_rev`, else the flag of that name (older firmware).""" - if self.features_rev and feature in _feature_map.feature_map().get("features", {}): + """Whether the pod has ``feature``: a name in the features table (``"la_dir"``, + ``"i2c_master"``, ...), else the flag of that name (``"serial"``, ``"analyzer"``).""" + entry = _feature_map.feature_map().get("features", {}).get(feature) + if entry is not None and entry.get("status") != "retired": return feature in self.features - if feature == "la_dir": - return self.la_dir - if feature in ("i2c_master", "spi_modes_1_2"): - return self.bus_master return bool(getattr(self, _TABLE_ALIASES.get(feature, feature), False)) def _apply_range(self, src: Mapping[str, Any], prefix: str = "") -> None: @@ -488,42 +407,13 @@ def from_parameters(cls, params: Mapping[str, Any]) -> "Capabilities": c.dac_fullscale_mv = v if (v := _as_int(params, "cap.dac_channels")) is not None and v > 0: c.dac_channels = v - c.generate16 = _as_int(params, "cap.generate_bits") == 16 - for attr, key in ( - ("dac", "cap.dac"), ("dac_dc", "cap.dac_dc"), ("dac_replay", "cap.dac_replay"), - ("dac_deep_replay", "cap.dac_deep_replay"), - ("dac_control_loop", "cap.dac_control_loop"), - ("dac_loop_sources", "cap.dac_loop_sources"), - ("dac_loop_input_map", "cap.dac_loop_input_map"), ("dac_cotrig", "cap.dac_cotrig"), - ("scope", "cap.scope"), - ("analyzer", "cap.analyzer"), ("serial", "cap.serial"), ("tunnel", "cap.tunnel"), - ("command", "cap.command"), ("ota", "cap.ota"), - ("la_pins", "cap.la_pins"), ("gpio_read", "cap.gpio_read"), - ("capture_trigger", "cap.capture_trigger"), ("power_profile", "cap.power_profile"), - ("capture_b64", "cap.capture_b64"), - ("nrst_pin", "cap.nrst_pin"), ("usb_cc", "cap.usb_cc"), - ("spi_master", "cap.spi_master"), ("spi_stream", "cap.spi_stream"), - ("uart_frame", "cap.uart_frame"), - ("calibrate", "cap.calibrate"), ("cal_dmm", "cap.cal_dmm"), ("current_out", "cap.current_out"), - ("can", "cap.can"), ("pod_current", "cap.pod_current"), - ("adc_low_range", "cap.adc_low_range"), - ("sensors", "cap.sensors"), - ("sensors_digital", "cap.sensors_digital"), - ("dac_limits", "cap.dac_limits"), - ("ws_auth_v2", "cap.ws_auth_v2"), - *((f, f"cap.{f}") for f in _STATUS_FLAGS), - ): - b = _as_bool(params, key) - if b is not None: - setattr(c, attr, b) + c.ws_auth_v2 = _as_bool(params, "cap.ws_auth_v2") is True # Tri-state: "" (not announced) stays None. c.analog = _as_bool(params, "cap.analog") if (v := _as_int(params, "cap.flash_kb")) is not None and v > 0: c.flash_kb = v if (v := _as_int(params, "cap.gateware")) is not None and v > 0: c.gateware = v - if (v := _as_int(params, "cap.sensors_format")) is not None and v > 0: - c.sensors_format = v if (v := _as_int(params, "cap.api")) is not None and v > 0: c.api = v if (v := _as_int(params, "cap.min_client_api")) is not None and v > 0: @@ -532,6 +422,14 @@ def from_parameters(cls, params: Mapping[str, Any]) -> "Capabilities": c.sig_keys = v c.sig_policy = str(params.get("cap.sig_policy", "") or "") c.lan_policy = str(params.get("cap.lan_policy", "") or "") + # The features from the table, as for status (the server writes the frame's + # features_rev, gateware and facts as cap.*). + if (rev := _as_int(params, "cap.features_rev")) is not None and rev > 0: + c.features_rev = rev + c.fpga_image = str(params.get("cap.fpga_image", "") or "") + facts = _feature_map.facts_from_frame(params, prefix="cap.") + c.features = _feature_map.resolve(rev, c.gateware, facts) + c._apply_features(facts) c.safe_mode = _as_bool(params, "cap.safe_mode") is True c.safe_reason = str(params.get("cap.safe_reason", "") or "") if c.safe_mode else "" c.last_crash = _crash_text(params.get("cap.last_crash")) @@ -587,19 +485,13 @@ def boot_warning(self) -> Optional[str]: @property def la_dir(self) -> bool: - """The pod takes pin directions (``la_dir``, firmware 3.10.4+). False when the firmware - version is unknown.""" - if self.features_rev: - return "la_dir" in self.features - v = _version_tuple(self.firmware_version) - return v is not None and v >= LA_DIR_FIRMWARE + """The pod takes pin directions (feature ``la_dir``).""" + return "la_dir" in self.features @property def bus_master(self) -> bool: """The I2C master, SPI modes 1 and 2 and send-and-capture (gateware v55+).""" - if self.features_rev: - return "i2c_master" in self.features - return self.gateware >= BUS_MASTER_GATEWARE + return "i2c_master" in self.features @property def adc_max_count(self) -> int: @@ -627,7 +519,7 @@ def counts_to_volts(self, count: float) -> float: @property def client_api_level(self) -> int: """The pod's client API level: :attr:`api`, or 1 for firmware that does not announce one - (3.10.13 and older).""" + (3.10.13 and older, which this SDK does not drive).""" return self.api or 1 def merge(self, other: "Capabilities") -> "Capabilities": diff --git a/packages/embeddedci/src/embeddedci/benchpod/capture.py b/packages/embeddedci/src/embeddedci/benchpod/capture.py index 370cc22..119fdb2 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/capture.py +++ b/packages/embeddedci/src/embeddedci/benchpod/capture.py @@ -17,7 +17,7 @@ import math import sys from array import array -from typing import Any, List, Optional +from typing import Any, List, Optional, Union from .capabilities import ADC_WRAP_SPAN, ADC_WRAP_THRESHOLD, Capabilities from .errors import BenchPodError @@ -63,6 +63,17 @@ def rate_mhz(rate_hz: Optional[float]) -> Optional[float]: return float(rate_hz) / 1e6 +def rate_hz(rate_hz: Optional[float]) -> Optional[Union[int, float]]: + """A sample rate in hertz for the firmware's ``sample_rate_hz`` (``None`` stays ``None`` = + device default); an int when it is whole.""" + if rate_hz is None: + return None + if rate_hz <= 0: + raise ValueError(f"sample rate must be > 0 Hz, got {rate_hz!r}") + f = float(rate_hz) + return int(f) if f.is_integer() else f + + def _us(seconds: Optional[float], name: str) -> int: if seconds is None: return 0 @@ -89,17 +100,8 @@ def _stream_or_samples(transport: Any, req: dict): fn = getattr(transport, "samples", None) if fn is None: raise BenchPodError("this transport does not support captures") - yield {"status": "ok", "data": fn(req), "more": False} - - -def _want_b64(transport: Any, caps: Capabilities, req: dict) -> None: - """Ask for base64 ADC chunks when the pod offers them and the transport yields whole chunks. - - A pod without ``capture_b64`` never sees the key, and the ``samples`` fallback flattens only - ``data``, so it is left out there too. - """ - if caps.capture_b64 and getattr(transport, "stream_chunks", None) is not None: - req["enc"] = "b64" + # samples() flattens only the decimal "data" lists: ask for those, not the default base64. + yield {"status": "ok", "data": fn({**req, "enc": "dec"}), "more": False} def _dense(chunk: dict) -> List[int]: @@ -151,7 +153,6 @@ def capture_adc(transport: Any, caps: Capabilities, *, samples: int = 4096, mhz = rate_mhz(sample_rate_hz) if mhz is not None: req["sample_rate_mhz"] = mhz - _want_b64(transport, caps, req) counts: List[int] = [] rate = 0.0 for chunk in _stream_or_samples(transport, req): @@ -328,9 +329,6 @@ def capture_correlated(transport: Any, caps: Capabilities, *, adc_samples: int = if stop_us > 0: req["stop_dac_after_us"] = stop_us _apply_trigger(req, trigger, trigger_timeout) - if adc_samples: - _want_b64(transport, caps, req) - adc_counts: List[int] = [] la_edges: List[List[int]] = [] la_upto = 0 diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index ba65066..6476fd8 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -51,7 +51,7 @@ from . import motor_emulator as _motor_emulator from . import spi as _spi from . import uart as _uart -from .capabilities import (ADC_WRAP_SPAN, ADC_WRAP_THRESHOLD, BUS_MASTER_GATEWARE, UART_FRAME_FIRMWARE, +from .capabilities import (ADC_WRAP_SPAN, ADC_WRAP_THRESHOLD, BUS_MASTER_GATEWARE, AffineCal, Capabilities) from .constants import ( ADC_SOURCE_PATHS, @@ -101,9 +101,9 @@ coerce_pin, ) from .connection import resolve_connection -from .errors import (BenchPodError, ClientTooOldError, FirmwareError, PullDirectionError, - UnsupportedFeatureError, classify_firmware_error, firmware_error, - status_too_large) +from .errors import (BenchPodError, ClientTooOldError, FirmwareError, FirmwareTooOldError, + PullDirectionError, UnsupportedFeatureError, classify_firmware_error, + firmware_error) from .flash import FlashResult from .gpio import LA_DIRS, ExtPin, GpioPin, LaPinState from .lease import DEFAULT_LEASE_TTL, DEFAULT_LEASE_WAIT, DeviceLease @@ -157,8 +157,6 @@ #: 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 #: The 4-20 mA output (J9) as a waveform output path. Levels on it are amps. _CURRENT_OUT = "current_out" # The DAC output each named analog path drives (cal1/cal2 loop the 5 V / 12 V DAC back to the ADC). @@ -210,6 +208,16 @@ def _mac_text(v: Any) -> Optional[str]: return v.strip().lower() if isinstance(v, str) and v.strip() else None +def _major_version(version: str) -> Optional[int]: + """The major number of a firmware version (``"4.0.0"`` -> 4), None when it is not one.""" + m = re.match(r"^v?(\d+)\.", (version or "").strip()) + return int(m.group(1)) if m else None + +def _num(v: float) -> Union[int, float]: + """A number for the wire: an int when it is whole (``1000.0`` -> ``1000``).""" + f = float(v) + return int(f) if f.is_integer() else f + def _sdk_version() -> str: try: from importlib.metadata import version @@ -556,28 +564,16 @@ def status(self) -> Dict[str, Any]: return _dict(self._transport.status()) def _caps_status(self) -> Dict[str, Any]: - """``status`` for the capabilities: without the ``caps`` list where the firmware has the - features table (:mod:`~embeddedci.benchpod.feature_map`).""" - read = getattr(self._transport, "status_without_caps", None) - return _dict(read() if callable(read) else self._transport.status()) + """``status`` for the capabilities (:mod:`~embeddedci.benchpod.feature_map`).""" + return _dict(self._transport.status()) def diag(self) -> Dict[str, Any]: """The pod's health counters: ``heap_free``, ``heap_min``, ``stack_min``, per-task ``stacks``, the network stack's ``lwip_mem_*`` and ``pbuf_pool_*`` high-water marks, - ``malloc_failures``, the console's ``rx_dropped``/``tx_dropped`` and ``board_rev_mv``. - - Firmware 3.10.9+ answers the ``diag`` command; older firmware has them in its full - :meth:`status`, which this reads instead (over the cloud that status is the short form, - so only the heap and ``stack_min`` are there). + ``malloc_failures``, the console's ``rx_dropped``/``tx_dropped`` and ``board_rev_mv`` + (the ``diag`` command). """ - try: - return _dict(self.command({"cmd": "diag"})) - except UnsupportedFeatureError: - st = self.status() - keys = ("heap_free", "heap_min", "stack_min", "stacks", "lwip_mem_max", "lwip_mem_size", - "pbuf_pool_max", "pbuf_pool_size", "malloc_failures", "rx_dropped", "tx_dropped", - "board_rev_mv") - return {k: st[k] for k in keys if k in st} + return _dict(self.command({"cmd": "diag"})) def mac_addresses(self, status: Optional[Mapping[str, Any]] = None) -> "MacAddresses": """The pod's Ethernet and Wi-Fi MACs, for a network that hands out addresses only to @@ -624,10 +620,10 @@ def capabilities(self) -> Capabilities: try: status = self._caps_status() except FirmwareError as exc: - # Firmware 3.10.4's status can be too large for the cloud channel. Reading it again - # will not help: use the server's capabilities alone, and keep them. + # A status too large for the cloud channel (BP0054): reading it again will not + # help, so use the server's capabilities alone, and keep them. _log.warning("could not read the pod's status for its capabilities: %s", exc) - status, status_ok = {}, status_too_large(exc.firmware_message, exc.cmd) + status, status_ok = {}, exc.code == "BP0054" except BenchPodError as exc: _log.warning("could not read the pod's status for its capabilities: %s", exc) status, status_ok = {}, False @@ -648,26 +644,52 @@ def capabilities(self) -> Capabilities: except BenchPodError: pass if not status_ok: - self._check_client_api(caps) + if caps.api or caps.firmware_version: + self._check_client_api(caps) return caps self._caps = caps self._check_client_api(self._caps) return self._caps def _check_client_api(self, caps: Capabilities) -> None: - """Raise :class:`ClientTooOldError` when the pod speaks a client API level above - :data:`~embeddedci.benchpod.feature_map.CLIENT_API`: its firmware changed a reply or a - message in a way this SDK would misread. A pod without ``api`` counts as 1.""" - if caps.client_api_level <= _feature_map.CLIENT_API: - return + """Refuse a pod this SDK does not drive. + + :class:`FirmwareTooOldError` for firmware 3.x: its client API level is below + :data:`~embeddedci.benchpod.feature_map.MIN_POD_API` (a pod that announces none counts as + 1; over the USB console, which announces none, its firmware version decides). + :class:`ClientTooOldError` when the pod speaks a level above + :data:`~embeddedci.benchpod.feature_map.CLIENT_API`, or takes none this low + (``min_client_api``): its firmware changed a reply or a message in a way this SDK would + misread.""" fw = caps.firmware_version or "unknown" + level = caps.client_api_level + if not caps.api and self._console_only(): + major = _major_version(caps.firmware_version) + level = _feature_map.MIN_POD_API if major is None or major >= 4 else 1 + if level < _feature_map.MIN_POD_API: + raise FirmwareTooOldError( + f"the pod runs firmware {fw} (client API {level}); this SDK (embeddedci " + f"{_sdk_version()}) needs firmware {_feature_map.MIN_FIRMWARE} or later (client API " + f"{_feature_map.MIN_POD_API}). Update the pod with the BenchPod CLI (`benchpod " + f"flash-self`) or the firmware update in the web app, or keep this firmware and use " + f"embeddedci 3.x (pip install 'embeddedci<4')", + api=level, firmware_version=caps.firmware_version) + if level <= _feature_map.CLIENT_API and caps.min_client_api <= _feature_map.CLIENT_API: + return raise ClientTooOldError( f"this SDK is too old for the pod's firmware {fw}: the pod speaks client API " - f"{caps.client_api_level}, this SDK (embeddedci {_sdk_version()}) handles client API " - f"{_feature_map.CLIENT_API}; update the SDK (pip install -U embeddedci)", - client_api=_feature_map.CLIENT_API, api=caps.client_api_level, + f"{level} (and takes {caps.min_client_api} or newer), this SDK (embeddedci " + f"{_sdk_version()}) handles client API {_feature_map.CLIENT_API}; update the SDK (pip " + f"install -U embeddedci)", + client_api=_feature_map.CLIENT_API, api=level, min_client_api=caps.min_client_api, firmware_version=caps.firmware_version) + def _console_only(self) -> bool: + """The USB text console (no JSON API), which announces no client API level.""" + from .transport.serial import SerialTransport + + return isinstance(self._transport, SerialTransport) + def _direct_network(self) -> bool: """A LAN or USB network connection: one that should get the pod's full status.""" from .transport.tcp import TcpTransport @@ -687,9 +709,8 @@ def _full_status(self, status: Dict[str, Any]) -> Dict[str, Any]: return again _log.warning( "the pod sent its short status over the network: its full status did not fit the connection. " - "The ADC calibration and the feature flags it leaves out come from embeddedci.com when " - "this computer is signed in, else from the board's defaults, so ADC readings can be " - "off. Firmware 3.10.9 keeps the full status small: update the pod (benchpod flash-self).") + "The ADC calibration it leaves out comes from embeddedci.com when this computer is " + "signed in, else from the board's defaults, so ADC readings can be off.") return again def refresh_capabilities(self) -> Capabilities: @@ -929,10 +950,9 @@ def _pod_wiring_list(self) -> Optional[Dict[str, Any]]: 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 + return None # a pod that refuses the listing: no stored profile to use except BenchPodError as exc: if type(self._transport).__name__ == "SerialTransport": return None # the USB console runs no JSON commands @@ -1644,14 +1664,6 @@ def _pulls_at(self, volts: Optional[float]) -> bool: except BenchPodError: return False - def _pull_dir_api(self) -> bool: - """The pod takes ``pull: up|down|off`` (feature ``la_pull_dir``); older firmware only - ``pullup: on|off``, on today's boards.""" - try: - return self.supports("la_pull_dir") - except BenchPodError: - return False - @staticmethod def _pull_want(la: int, pull: Union[str, bool, None]) -> str: """``pull`` as "up" / "down" / "off". True (deprecated) is the channel's own direction.""" @@ -1670,10 +1682,10 @@ def _pull_want(la: int, pull: Union[str, bool, None]) -> str: def _pull_refusal(la: int, want: str, supported: Tuple[str, ...]) -> PullDirectionError: """The pod's own refusal (BP0023 / BP0024), for what the SDK refuses before asking.""" if not supported: - return firmware_error(f"LA{la} has no pull resistor on this board", cmd="la", + return firmware_error(f"LA{la} has no pull resistor on this board", cmd="la_pull", code="BP0023", values={"la": la}) # type: ignore[return-value] have = supported[0] - return firmware_error(f"LA{la} supports pull-{have} only on this board", cmd="la", + return firmware_error(f"LA{la} supports pull-{have} only on this board", cmd="la_pull", code="BP0024", values={"la": la, "want": want, "have": have}) # type: ignore[return-value] def set_pull(self, la: Union[Pin, int], pull: Union[PullDirection, bool, None, object] = _NO_PULL, *, @@ -1696,32 +1708,19 @@ def set_pull(self, la: Union[Pin, int], pull: Union[PullDirection, bool, None, o pull = bool(enabled) la_i = coerce_pin(la, "la") want = self._pull_want(la_i, pull) # type: ignore[arg-type] - if self._pull_dir_api(): - with _classified_errors(): - reply = self.command({"cmd": "la", "la": la_i, "pull": want}) - return PullState.from_reply(reply, la_i) - # Older firmware: only pullup on/off, which engages the channel's one direction. Check the - # direction here, so "up" never engages LA7's pull-down. - hw = PULL_TABLE.get(la_i) - if want != "off" and (not hw or want not in hw.dirs): - raise self._pull_refusal(la_i, want, hw.dirs if hw else ()) - if not hw: - return PullState.none(la_i) with _classified_errors(): - reply = self.command({"cmd": "la", "la": la_i, "pullup": "off" if want == "off" else "on"}) + reply = self.command({"cmd": "la_pull", "la": la_i, "pull": want}) return PullState.from_reply(reply, la_i) def pull_state(self, la: Union[Pin, int]) -> PullState: """Read LA ``la``'s pull resistor: engaged, direction, value, supported directions.""" la_i = coerce_pin(la, "la") - if la_i not in PULL_TABLE and not self._pull_dir_api(): - return PullState.none(la_i) # older firmware refuses the query on LA9-LA14 with _classified_errors(): - return PullState.from_reply(self.command({"cmd": "la", "la": la_i}), la_i) + return PullState.from_reply(self.command({"cmd": "la_pull", "la": la_i}), la_i) def enabled_pulls(self) -> List[int]: """The LA channels whose pull resistor is currently engaged (either direction).""" - mask = int(_dict(self.command({"cmd": "la"})).get("la_pullup_mask", 0) or 0) + mask = int(_dict(self.command({"cmd": "la_pull"})).get("la_pullup_mask", 0) or 0) return [la for la in range(1, 15) if mask >> (la - 1) & 1] def enable_pullup(self, *las: Union[Pin, int]) -> None: @@ -1749,11 +1748,7 @@ def _release_pull(self, la: Union[Pin, int], kind: str) -> None: """Switch the pull off, refusing a channel that can't pull ``kind`` at all (so a typo like disable_pullup(7) is not silently a no-op).""" la_i = coerce_pin(la, "la") - if self._pull_dir_api(): - supported = self.pull_state(la_i).supported - else: - hw = PULL_TABLE.get(la_i) - supported = hw.dirs if hw else () + supported = self.pull_state(la_i).supported if kind not in supported: raise self._pull_refusal(la_i, kind, supported) self.set_pull(la_i, "off") @@ -2289,8 +2284,8 @@ def _uart_link(self, rx: Any, tx: Any, baud: Optional[int], parity: Optional[str if not self.supports("uart_frame"): fw = self.capabilities.firmware_version or "unknown" raise UnsupportedFeatureError( - f"UART parity and stop bits need firmware {UART_FRAME_FIRMWARE}+ (gateware v56; " - f"this pod runs firmware {fw}): update the pod's firmware", + f"UART parity and stop bits need gateware v56 (feature uart_frame; this pod " + f"runs firmware {fw}): update the pod's firmware", feature="uart_frame", firmware_version=self.capabilities.firmware_version) if entry is not None and not isinstance(entry, _uart.UartEntry): raise ValueError(f"entry must be a UartEntry, got {type(entry).__name__}") @@ -2850,22 +2845,17 @@ def decode(self, source: Union[LaCapture, Sequence[int]], protocol: DecodeProtoc # -- output paths: volts, or amps on the 4-20 mA output ------------------------ - def _output_range(self, dac_path: str, *, generator: bool = False) -> tuple: + def _output_range(self, dac_path: str) -> tuple: """``(min, max)`` an output path spans, in its own unit: volts, or AMPS on ``current_out``. - The 4-20 mA output's range is the pod's own (``current_out_range``), read once. The - 8-bit generator (``generator=True``) tops out a little under it: a level is the high - byte of the 16-bit DAC code, so level 255 is code 65280. + The 4-20 mA output's range is the pod's own (``current_out_range``), read once. """ if dac_path != _CURRENT_OUT: return _dsp.dac_path_range_v(dac_path) if self._current_out_span is None: rng = self.current_out_range() self._current_out_span = (rng.min_current, rng.max_current) - lo, hi = self._current_out_span - if generator: - hi = lo + (hi - lo) * 65280.0 / 65535.0 - return lo, hi + return self._current_out_span def _route_output(self, dac_path: str) -> None: """Route an output before a waveform plays on it. The 4-20 mA output only switches the DAC @@ -2907,15 +2897,14 @@ def generate(self, waveform: Waveshape = "sine", *, freq_hz: float, amplitude: f """Generate a parametric waveform (``sine``/``square``/``sawtooth``) on a DAC output path. ``amplitude`` is the peak in volts and ``offset`` the center in volts (default: the middle - of ``dac_path``'s range — 0 V on the bipolar ±12 V ``12v`` path). On firmware 3.9.1+ - (:attr:`Capabilities.generate16`) the pod takes the volts, converts them with its per-path - calibration and plays the waveform at the DAC's full 16 bits; both peaks must then be on - the path (a peak within 5% of an end the pod cannot quite reach is clamped to it). Older firmware builds it from 8-bit levels, so volts are - quantised to ``full_scale / 255`` using the same volts→code mapping as :meth:`replay`. + of ``dac_path``'s range — 0 V on the bipolar ±12 V ``12v`` path). The pod takes the volts, + converts them with its per-path calibration and plays the waveform at the DAC's full 16 + bits; both peaks must be on the path (a peak within 5% of an end the pod cannot quite + reach is clamped to it). ``dac_path="current_out"`` plays it as a current on the 4-20 mA output (J9): ``amplitude`` and ``offset`` are then AMPS (``amplitude=0.006, offset=0.012`` swings 6 to - 18 mA, in steps of about 0.25 µA at 16 bits, 63 µA at 8 bits). The DAC voltage outputs are switched off, and stopping + 18 mA, in steps of about 0.25 µA). The DAC voltage outputs are switched off, and stopping the handle returns the loop to 4 mA. See :meth:`current_out` for the wiring. ``duration`` (seconds) stops it by itself; omitted, it runs until :meth:`dac_stop` or the returned handle's ``stop()``. ``on_capture=True`` defers the start to the next capture's @@ -2936,48 +2925,6 @@ def generate(self, waveform: Waveshape = "sine", *, freq_hz: float, amplitude: f check_choice(dac_path, DAC_PATHS, "dac_path") if freq_hz <= 0: raise ValueError(f"freq_hz must be > 0, got {freq_hz!r}") - if self.capabilities.generate16: - return self._generate16(waveform, freq_hz=freq_hz, amplitude=amplitude, offset=offset, - dac_path=dac_path, duration=duration, - sample_rate_hz=sample_rate_hz, on_capture=on_capture, route=route) - vmin, vmax = self._output_range(dac_path, generator=True) - unit = "A" if dac_path == _CURRENT_OUT else "V" - span = vmax - vmin - step = span / _GENERATOR_MAX_CODE - amp_code = int(round(float(amplitude) / step)) - if amplitude <= 0 or amp_code < 1: - raise ValueError(f"amplitude must be at least {step:.4g} {unit} on the {dac_path} path, " - f"got {amplitude!r}") - if amp_code > _GENERATOR_MAX_CODE: - raise ValueError(f"amplitude must be at most {span:.4g} {unit} on the {dac_path} path, got {amplitude!r}") - off_v = (vmin + vmax) / 2.0 if offset is None else float(offset) - off_code = int(round((off_v - vmin) / step)) - if not 0 <= off_code <= _GENERATOR_MAX_CODE: - raise ValueError(f"offset must be within {vmin:.4g}..{vmax:.4g} {unit} on the {dac_path} path, " - f"got {offset!r}") - req: Dict[str, Any] = {"cmd": "generate", "waveform": waveform, "freq": float(freq_hz), - "amplitude": amp_code, "offset": off_code} - if duration is not None: - ms = _seconds_to_ms(duration, "duration") - if ms <= 0: - raise ValueError("duration must be at least 1 ms; omit it to run until stopped") - req["duration_ms"] = ms - mhz = _capture.rate_mhz(sample_rate_hz) - if mhz is not None: - req["sample_rate_mhz"] = mhz - if on_capture: - req["on_capture"] = True - if route: - self._route_output(dac_path) - d = _dict(self.command(req)) - return DacHandle(stop=self._stop_for(dac_path), dac_path=dac_path, - cotrig=bool(d.get("cotrig", False)), data=d) - - def _generate16(self, waveform: str, *, freq_hz: float, amplitude: float, offset: Optional[float], - dac_path: str, duration: Optional[float], sample_rate_hz: Optional[float], - on_capture: bool, route: bool) -> DacHandle: - """:meth:`generate` on firmware 3.9.1+: the calibrated 16-bit form. The pod routes the - output itself (unless ``route=False``) and refuses peaks it cannot reach.""" vmin, vmax = self._output_range(dac_path) current = dac_path == _CURRENT_OUT unit = "A" if current else "V" @@ -2992,7 +2939,7 @@ def _generate16(self, waveform: str, *, freq_hz: float, amplitude: float, offset if off - amp < vmin - slack or off + amp > vmax + slack: raise ValueError(f"the peaks {off - amp:.4g} to {off + amp:.4g} {unit} must stay within " f"{vmin:.4g}..{vmax:.4g} {unit} on the {dac_path} path") - req: Dict[str, Any] = {"cmd": "generate", "waveform": waveform, "freq": float(freq_hz)} + req: Dict[str, Any] = {"cmd": "generate", "waveform": waveform, "freq_hz": _num(freq_hz)} if current: req["amplitude_ua"] = round(amp * 1e6) req["offset_ua"] = round(off * 1e6) @@ -3003,9 +2950,9 @@ def _generate16(self, waveform: str, *, freq_hz: float, amplitude: float, offset if ms <= 0: raise ValueError("duration must be at least 1 ms; omit it to run until stopped") req["duration_ms"] = ms - mhz = _capture.rate_mhz(sample_rate_hz) - if mhz is not None: - req["sample_rate_mhz"] = mhz + rate = _capture.rate_hz(sample_rate_hz) + if rate is not None: + req["sample_rate_hz"] = rate if on_capture: req["on_capture"] = True if not route: @@ -3535,10 +3482,9 @@ def la_pins(self, la: Union[Pin, int, str, Sequence[Union[Pin, int, str]], None] """Every LA channel's function (``none``, ``gpio``, ``uart_rx``, …), GPIO mode and level, and bias resistor. A channel that is in use refuses other functions. - ``la``: only these channels (a channel, a wiring name, or a list), in pin order. Firmware - after 3.10.12 sends only those; older firmware sends all 14 and the SDK keeps the ones asked - for. A full listing too large for one cloud reply (a long sensor instance name on every - pin) is read in two parts by itself.""" + ``la``: only these channels (a channel, a wiring name, or a list), in pin order. A full + listing too large for one cloud reply (a long sensor instance name on every pin) is read + in two parts by itself.""" self._require_capability("la_pins", "LA pin modes and GPIO") if la == "all": la = None @@ -3552,8 +3498,6 @@ def la_pins(self, la: Union[Pin, int, str, Sequence[Union[Pin, int, str]], None] if "reply too large" not in str(getattr(e, "firmware_message", "") or e): raise first = self._la_pins_query(list(range(1, 8))) - if len(first) > 7: # firmware without the subset: it listed everything again - raise return first + [p for p in self._la_pins_query(list(range(8, 15))) if p.la >= 8] def _la_pins_query(self, las: Optional[List[int]]) -> List[LaPinState]: @@ -3640,8 +3584,9 @@ def apply_pin_directions(self, wiring: Optional[Wiring] = None) -> List[LaPinSta def _auto_pin_directions(self) -> None: """Send the wiring's pin directions on connect and on a new profile, when the firmware - has ``la_dir``. Raises only :class:`ClientTooOldError` (the pod's client API level is above - this SDK's); anything else goes to :attr:`pin_directions_status`.""" + has ``la_dir``. Raises only :class:`ClientTooOldError` and :class:`FirmwareTooOldError` (the + pod's client API level is not this SDK's); anything else goes to + :attr:`pin_directions_status`.""" if getattr(self, "_transport", None) is None: return try: @@ -3658,14 +3603,16 @@ def _auto_pin_directions(self) -> None: self._check_client_api(caps) if not caps.la_dir: fw = caps.firmware_version or "unknown" - self.pin_directions_status = (f"not sent: this pod's firmware ({fw}) has no " - "la_dir (3.10.4+)") + self.pin_directions_status = f"not sent: this pod's firmware ({fw}) has no la_dir" return self.apply_pin_directions() self.pin_directions_status = "sent" except ClientTooOldError: self.pin_directions_status = "not sent: this SDK is too old for the pod's firmware" raise + except FirmwareTooOldError: + self.pin_directions_status = "not sent: the pod's firmware is too old for this SDK" + raise except Exception as exc: # a convenience on connect: report it, never fail the caller self.pin_directions_status = f"not sent: {exc}" _log.warning("pin directions from the wiring were not sent to the pod: %s", exc) @@ -3946,9 +3893,8 @@ def expansion( check_choice(pull, _i2c_master.PULLUPS, "pullups") if pull == "pod" and not pod_ok: raise _expansion.ExpansionError( - "pullups='pod' needs both pins on LA1-LA6 (only they have pod pull-ups) and, at " - "1.8 V, firmware with pull-ups at 1.8 V (newer than 3.10.12); use pullups='external' " - "with pull-ups on the breakout") + "pullups='pod' needs both pins on LA1-LA6 (only they have pod pull-ups) and an " + "LA voltage of 1.8 V or 3.3 V; use pullups='external' with pull-ups on the breakout") else: if sda is not None or scl is not None or pullups is not None: raise ValueError(f"the {info.name} is an SPI chip: sda, scl and pullups do not " @@ -4214,7 +4160,7 @@ def la_step(self, la: Union[Pin, int], *, steps: int, delay: float, f"(half the step period), got {delay!r}") if direction not in (0, 1): raise ValueError(f"direction must be 0 or 1, got {direction!r}") - req: Dict[str, Any] = {"cmd": "la", "la": self._resolve_la(la, why=_EXT_PULSES)[0], + req: Dict[str, Any] = {"cmd": "la_step", "la": self._resolve_la(la, why=_EXT_PULSES)[0], "steps": int(steps), "delay_us": delay_us} if dir_la is not None: diff --git a/packages/embeddedci/src/embeddedci/benchpod/errors.py b/packages/embeddedci/src/embeddedci/benchpod/errors.py index e60bbd5..30d74da 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/errors.py +++ b/packages/embeddedci/src/embeddedci/benchpod/errors.py @@ -313,6 +313,22 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, client_api: int = self.firmware_version = firmware_version +class FirmwareTooOldError(UnsupportedFeatureError): + """The pod runs firmware this SDK does not drive: firmware 3.x, which speaks client API 1. + This SDK (4.x) needs firmware 4.0.0 or later (client API 2). + + Raised on connect. :attr:`api` is the pod's client API level (1 for firmware that does not + announce one), :attr:`firmware_version` its firmware. Update the pod with the BenchPod CLI + (``benchpod flash-self``) or the firmware update in the web app; or keep firmware 3.x and + use embeddedci 3.x (``pip install 'embeddedci<4'``). An :class:`UnsupportedFeatureError` + (feature ``"client_api"``).""" + + def __init__(self, message: str, *, cmd: Optional[str] = None, api: int = 0, + firmware_version: str = "") -> None: + super().__init__(message, cmd=cmd, feature="client_api", firmware_version=firmware_version) + self.api = api + + class PermissionDeniedError(FirmwareError, TransportError): """The caller is not allowed to do this: the pod's ``forbidden: needs an organization owner or admin`` on a cloud tunnel, or an HTTP 403 from the server (the API key lacks a diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json index bbc5dbd..1b5ea18 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json +++ b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json @@ -1,10 +1,10 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 8, - "api": 1, - "min_client_api": 0, - "table_sha256": "02f6411c240dcbc0cedda72648ba8713eb498a9a878ecca7f9fc817a3da586b2", + "revision": 11, + "api": 2, + "min_client_api": 2, + "table_sha256": "ea8870a74cd198ed990eeec337ab4792870bb26185f2c5449c7a23bd8dc94b05", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -223,7 +223,7 @@ "board": "any", "legacy_caps": "capture_b64", "legacy_frame": "capture_b64", - "docs": "API.md#base64-samples-encb64" + "docs": "API.md#base64-samples-the-default" }, "blob_slots": { "rev": 1, @@ -237,7 +237,7 @@ "board": "any", "legacy_caps": "can", "legacy_frame": "can", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "ota_sig": { "rev": 1, @@ -347,7 +347,7 @@ "board": "any", "legacy_caps": "can_fd", "legacy_frame": "can_fd", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "la_dir": { "rev": 1, @@ -661,13 +661,13 @@ "rev": 3, "firmware": "3.10.12", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "la_pull_1v8": { "rev": 4, "firmware": "3.10.13", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "log_level": { "rev": 4, @@ -704,6 +704,66 @@ "firmware": "next", "board": "any", "docs": "API.md#client-compatibility" + }, + "lan_tls_default": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#lan_tls--the-lan-api-over-tls" + }, + "sig_always_required": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#sig_policy--which-firmware-and-blob-updates-the-pod-accepts" + }, + "generate_volts_only": { + "rev": 10, + "firmware": "next", + "board": "analog", + "docs": "API.md#generate--dac-waveform-output" + }, + "json_names_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#commands" + }, + "can_start_stop": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#can_start--bring-can-up" + }, + "la_step_pull_split": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#la_pull--la-pin-pull-resistors" + }, + "json_booleans_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#target_power--enabledisable-a-target-power-efuse" + }, + "console_recovery_json": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "usb-serial-interface.md#removed-in-firmware-400" + }, + "usb_host": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#usb_host--usb-host-mode" + }, + "dac_pinout_guard": { + "rev": 11, + "firmware": "next", + "board": "any", + "docs": "API.md#dac-pinout-on-the-flat-cable" } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.py b/packages/embeddedci/src/embeddedci/benchpod/feature_map.py index 64dc0d7..8da5ed1 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/feature_map.py +++ b/packages/embeddedci/src/embeddedci/benchpod/feature_map.py @@ -4,11 +4,11 @@ ``features/features.toml``; ``scripts/sync-feature-map.sh`` copies it here). It ships with the SDK, so deciding what a pod can do needs no network connection. -A pod with firmware after 3.10.10 answers ``{"cmd":"status","caps":false}`` with -``features_rev`` (the table revision it is built from), ``fpga_image`` and the ``hw`` facts -instead of the ``caps`` list. :func:`resolve` turns those into the set of features the pod has: -every entry with ``rev <= features_rev`` whose gateware, board and ``requires`` facts match. -Older firmware sends the ``caps`` list as before (:meth:`Capabilities.from_status` reads it). +A pod's ``status`` (and its cloud capabilities frame) carries ``features_rev`` (the table +revision its firmware is built from), ``fpga_image`` and the ``hw`` facts. :func:`resolve` turns +those into the set of features the pod has: every entry with ``rev <= features_rev`` whose +gateware, board and ``requires`` facts match. Firmware 4.0 (client API 2) is the first this SDK +drives; it always sends them. """ from __future__ import annotations @@ -21,13 +21,20 @@ #: The client API level this SDK is built for: the highest pod ``api`` it handles. The pod -#: announces its level as ``api`` (``status`` with ``"caps":false``, the cloud capabilities frame; -#: a pod that does not counts as 1), every request carries this one as ``client_api``, and a pod -#: whose ``api`` is higher has changed a reply or a message in a way this SDK would misread +#: announces its level as ``api`` (``status``, the cloud capabilities frame; a pod that does not +#: counts as 1), every request carries this one as ``client_api``, and a pod whose ``api`` is +#: higher has changed a reply or a message in a way this SDK would misread #: (:class:`~embeddedci.benchpod.errors.ClientTooOldError`). Raised by hand, together with the #: code that handles the new level, when a synced table raises its ``api``: a test checks that it #: equals the bundled table's. -CLIENT_API = 1 +CLIENT_API = 2 + +#: The lowest pod ``api`` this SDK drives: firmware 4.0.0. A pod below it (firmware 3.x) is +#: refused on connect with :class:`~embeddedci.benchpod.errors.FirmwareTooOldError`. +MIN_POD_API = 2 + +#: The first firmware with :data:`MIN_POD_API`. +MIN_FIRMWARE = "4.0.0" @lru_cache(maxsize=1) @@ -70,8 +77,6 @@ def facts_from_status(status: Mapping[str, Any]) -> Dict[str, Any]: out[name] = v if name == "fpga_image" else v is True elif "hw" in f: out[name] = f["hw"] in hw_names - if "analog" not in out: - out["analog"] = True # firmware before the analog flag: every pod was an analog board return out @@ -85,7 +90,6 @@ def facts_from_frame(params: Mapping[str, Any], prefix: str = "") -> Dict[str, A continue v = params[key] out[name] = str(v) if name == "fpga_image" else str(v).strip().lower() in ("true", "1") - out.setdefault("analog", True) return out diff --git a/packages/embeddedci/src/embeddedci/benchpod/runs/recorder.py b/packages/embeddedci/src/embeddedci/benchpod/runs/recorder.py index 0871eb3..4ab7343 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/runs/recorder.py +++ b/packages/embeddedci/src/embeddedci/benchpod/runs/recorder.py @@ -2,7 +2,7 @@ :class:`Recorder` wraps one transport *instance*: it binds wrappers as instance attributes for ``command``, ``command_sequence``, ``samples``, ``stream_chunks``, ``status``, -``status_without_caps``, ``target_power``, ``dap_start`` and ``uart_proxy_start``, so the +``target_power``, ``dap_start`` and ``uart_proxy_start``, so the transport's class (and ``isinstance``) is unchanged and no transport class needs to know about it. A call made from inside another recorded call (``status`` sending ``command``) is recorded once, as the outer call. @@ -27,7 +27,6 @@ "samples": "samples", "stream_chunks": "stream", "status": "status", - "status_without_caps": "status", "target_power": "power", "dap_start": "raw", "uart_proxy_start": "raw", @@ -190,8 +189,6 @@ def _request(name: str, args: tuple, kwargs: dict) -> Any: return list(args[0] if args else kwargs.get("reqs") or []) if name == "status": return {"cmd": "status"} - if name == "status_without_caps": - return {"cmd": "status", "caps": False} if name == "target_power": keys = ("efuse", "on", "delay_ms") req = dict(zip(keys, args)) diff --git a/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py index 67479e8..5502487 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py +++ b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py @@ -532,9 +532,7 @@ def capture(self, instance: str, samples: int = MAX_LA_BYTES, and starts the capture on its START, with 1/8 of the samples from before it, so a DUT that reads its sensor now and then is caught. No bus traffic in time raises :class:`~embeddedci.benchpod.errors.TriggerTimeout`. ``wait_for_traffic=False`` captures - at once. Firmware without the ``sensor_la_trigger`` capability (3.10.3 and earlier) - always captures at once: call it right after the DUT starts talking, or lower the rate - for a longer window. SPI and UART instances are refused by the pod: capture their pins + at once. SPI and UART instances are refused by the pod: capture their pins with :meth:`~embeddedci.benchpod.BenchPod.la_capture`.""" self._require() n = int(samples) @@ -547,13 +545,12 @@ def capture(self, instance: str, samples: int = MAX_LA_BYTES, if wait_for_traffic and not 1 <= timeout_ms <= MAX_CAPTURE_TIMEOUT_MS: raise ValueError(f"timeout_s is 0.001..{MAX_CAPTURE_TIMEOUT_MS // 1000} s, got {timeout_s!r}") req: Dict[str, Any] = {"cmd": "sensor_la", "instance": _instance_name(instance), - "samples": n, "sample_rate_mhz": rate / 1e6} - if self._pod.supports("sensor_la_trigger"): - if wait_for_traffic: - req["trigger"] = "start" - req["timeout_ms"] = timeout_ms - else: - req["trigger"] = "none" + "samples": n, "sample_rate_hz": int(rate) if rate.is_integer() else rate} + if wait_for_traffic: + req["trigger"] = "start" + req["timeout_ms"] = timeout_ms + else: + req["trigger"] = "none" return self._samples(req) def running_digital(self) -> List[str]: diff --git a/packages/embeddedci/src/embeddedci/benchpod/state.py b/packages/embeddedci/src/embeddedci/benchpod/state.py index 92d9f15..abe80bb 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/state.py +++ b/packages/embeddedci/src/embeddedci/benchpod/state.py @@ -263,26 +263,26 @@ def none(cls, la: int, raw: Optional[Dict[str, Any]] = None) -> "PullState": @classmethod def from_reply(cls, reply: Any, la: int) -> "PullState": - """From the pod's ``la`` reply. Firmware before ``la_pull_dir`` sends no ``state`` or - ``dirs``; the board table (:data:`~embeddedci.benchpod.constants.PULL_TABLE`) fills them.""" + """From the pod's ``la_pull`` reply (``state``, ``dirs``, ``pullups_available``). The + reply has no resistor value: on boards with one resistor per channel it comes from the + board table (:data:`~embeddedci.benchpod.constants.PULL_TABLE`), ``la_pins`` reports it + on every board.""" from .constants import PULL_TABLE d = _d(reply) la = int(d.get("la", la)) hw = PULL_TABLE.get(la) dirs = d.get("dirs") - supported = (tuple(str(x) for x in dirs) if isinstance(dirs, list) - else (hw.dirs if hw else ())) - pull = d.get("pull") - direction: Optional[str] = (str(pull) if pull in ("up", "down") - else (hw.default if hw and pull is None else None)) + supported = tuple(str(x) for x in dirs) if isinstance(dirs, list) else () state = d.get("state") - enabled = (state in ("up", "down")) if isinstance(state, str) else bool(d.get("pullup", 0)) - if isinstance(state, str) and state in ("up", "down"): - direction = state - return cls(la=la, enabled=enabled, direction=direction, - ohms=str(d.get("ohms", hw.ohms if hw else "") or ""), - available=bool(d.get("pullups_available", 1)), supported=supported, + enabled = state in ("up", "down") + direction: Optional[str] = (str(state) if enabled + else (supported[0] if len(supported) == 1 else None)) + ohms = d.get("ohms") + if not isinstance(ohms, str): + ohms = hw.ohms if hw and supported == hw.dirs else "" + return cls(la=la, enabled=enabled, direction=direction, ohms=ohms, + available=d.get("pullups_available") is not False, supported=supported, strength=str(d["strength"]) if isinstance(d.get("strength"), str) else None, held=str(d["held"]) if isinstance(d.get("held"), str) else None, raw=d) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py index 3ec6a6a..0c2887e 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py @@ -84,7 +84,7 @@ def usb_net_address(status: Any) -> Optional[str]: console's text status parsed by :func:`~.serial.parse_text_status`), or None when USB networking is off, its link is down, or the firmware has no USB network (before 3.9.0).""" usb = status.get("usb") if isinstance(status, dict) else None - if not isinstance(usb, dict) or usb.get("net") != "on" or usb.get("link") is not True: + if not isinstance(usb, dict) or usb.get("net") is not True or usb.get("link") is not True: return None try: ip = ipaddress.IPv4Address(str(usb.get("ip", ""))) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/base.py b/packages/embeddedci/src/embeddedci/benchpod/transport/base.py index 2bf92a2..8cc0c2b 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/base.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/base.py @@ -61,13 +61,6 @@ class Transport(ABC): def status(self) -> Any: """Return the pod's status report (a dict).""" - def status_without_caps(self) -> Any: - """The status report a client with the features table asks for: ``"caps":false``, so - firmware after 3.10.10 sends ``features_rev`` instead of the ``caps`` list (older firmware - ignores the argument and sends the list). A transport that cannot send it returns - :meth:`status`.""" - return self.status() - @abstractmethod def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: """Enable (``on=True``) or disable a target-power eFuse (1 or 2). diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py index 990a9f6..1399474 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py @@ -21,8 +21,6 @@ BenchPodError, ConnectionClosedError, ConnectionConfigError, - FirmwareError, - UnsupportedFeatureError, TransportError, TransportTimeout, ) @@ -39,7 +37,6 @@ # and 0x1209 is every pid.codes device), so they only ORDER the ports to probe. # Identification is by probing for BENCHPOD_MARKER, never by vendor id alone. POD_VIDS = (0x2E8A, 0x0483, 0x1209) -RP_VID = 0x2E8A # deprecated alias, kept for callers that imported it # The substring the firmware's ``status`` prints to identify itself # ("device : benchpod"). @@ -50,21 +47,14 @@ PROBE_TIMEOUT = 2.0 BAUD = 115200 PROMPT = "> " -DAP_READY = "dap ready" # console prints "dap ready" then carries framed CMSIS-DAP -DAP_LEAVE = b"\x00\x00" # zero-length frame — leaves the console DAP passthrough -UART_READY = "uart ready" # console prints "uart ready (press Ctrl-] to exit)" -CTRL_RBRACKET = b"\x1d" # Ctrl-] — leaves the console UART proxy # The prompt followed only by complete firmware log lines ("[sig] ...\r\n"): see _read_until_prompt. _PROMPT_THEN_LOG = re.compile(r"(?:^|\n)>[ \t]*(?P(?:\[[A-Za-z0-9_.:-]+\][^\r\n]*\r?\n)+)\Z") _CLEAR_LINE = b"\x08" * 128 # backspaces to clear any partial input line _RAW_READ_TIMEOUT = 0.1 # poll interval while bridging raw CMSIS-DAP bytes -UNKNOWN_COMMAND = "unknown command" -#: Firmware 3.9.0 answers a console command it moved to the JSON API with this marker instead. -MOVED_TO_NETWORK = "moved to the network API" - -#: JSON commands the text console answers through its text equivalents (it has no JSON mode) -#: (the STM32 pod's console is a text shell: status, ping, la-voltage, power, diagnostics). -TEXT_CONSOLE_COMMANDS = ("status", "ping", "la_voltage") +#: JSON commands the text console answers through its text equivalents (it has no JSON mode): +#: firmware 4.0's console keeps status, ping and identity; everything else is on the JSON API +#: (the LAN, the USB network adapter or the cloud). +TEXT_CONSOLE_COMMANDS = ("status", "ping") @contextmanager @@ -129,12 +119,12 @@ def parse_text_status(raw: str) -> Dict[str, Any]: def parse_usb_status_line(value: str) -> Optional[Dict[str, Any]]: """Parse the value of the console status's ``usb`` line into the JSON status's ``usb`` dict - (``{"net": "on"|"off", "link": bool, "ip": ..., "host_ip": ...}``), or None when the line - does not describe the USB network adapter (older firmware).""" + (``{"net": bool, "link": bool, "ip": ..., "host_ip": ...}``), or None when the line does not + describe the USB network adapter.""" m = re.search(r"\bnet (on|off)\b", value) if not m: return None - usb: Dict[str, Any] = {"net": m.group(1)} + usb: Dict[str, Any] = {"net": m.group(1) == "on"} link = re.search(r"\blink (up|down)\b", value) usb["link"] = bool(link and link.group(1) == "up") if ip := re.search(r"\bpod " + _IPV4, value): @@ -332,68 +322,6 @@ def autodetect_port(name: str = "") -> str: ) -class _SerialRawLink: - """Adapts the open serial port to :class:`RawLink` for a raw console mode. - - ``read`` blocks (polling on a short timeout) until data arrives or the link - is closed, so a quiet stretch of the stream is not mistaken for EOF. - ``close`` sends a mode-specific quit byte (``Q`` for SWD, Ctrl-] ``0x1d`` for - UART proxy) to leave the mode; it does not close the underlying port (the - transport owns that). - """ - - def __init__(self, port, quit_byte: bytes = b"Q") -> None: - self._port = port - self._closed = False - self._quit = quit_byte - self._port.timeout = _RAW_READ_TIMEOUT - #: The error that ended the link, if it did not end cleanly (see RawLink). - self.error: Optional[BaseException] = None - - def read(self, n: int) -> bytes: - # Return as soon as ANY byte is available — do NOT wait for the full `n`. - # pyserial's read(n) only returns early once `n` bytes arrive, so reading - # `n` here would stall the full per-read timeout on every remote_bitbang - # sample (the pod replies a byte or two at a time), throttling a flash to - # a crawl. Block for the first byte, then drain whatever else is buffered. - while not self._closed: - try: - first = self._port.read(1) - if not first: - continue # read timeout with no data → poll again (or until closed) - waiting = getattr(self._port, "in_waiting", 0) or 0 - if waiting and n > 1: - first += self._port.read(min(n - 1, waiting)) - except OSError as exc: # unplugged: the stream has ended, say why - if not self._closed: - self.error = ConnectionClosedError(f"the USB serial link failed ({exc})") - self._closed = True - return b"" - return first - return b"" - - def write(self, data: bytes) -> int: - # Do NOT flush() here. flush() is tcdrain — it blocks until the OS has - # physically transmitted every byte, which on a USB-serial adapter can - # stall for tens of ms (or longer on a driver hiccup) on every write. - # In the SWD bridge that blocks the oc->pod pump thread, backs up - # OpenOCD, and can freeze a whole flash. The kernel transmits the queued - # bytes asynchronously regardless (serial has no Nagle), so the pod still - # receives them promptly and replies — we just don't wait on the drain. - self._port.write(data) - return len(data) - - def close(self) -> None: - if self._closed: - return - self._closed = True - try: - self._port.write(self._quit) - self._port.flush() - except Exception: - pass - - class SerialTransport(Transport): """Talks to the pod over the USB serial console.""" @@ -461,10 +389,9 @@ def _send_command(self, line: str) -> str: @staticmethod def _unsupported(what: str) -> str: return (f"{what!r} is not available over this pod's USB console, which only answers " - "text commands (status, ping, LA voltage, target power); connect over the network " - "(host[:port]) or the cloud (embeddedci:) for it. On firmware 3.9.0 and " - "later, connection 'usb' reaches the full API over the pod's USB network adapter " - "(off while Wi-Fi is configured on the pod)") + "status and ping; connect over the network (host[:port]) or the cloud " + "(embeddedci:) for it. Connection 'usb' reaches the full API over the " + "pod's USB network adapter (off while Wi-Fi is configured on the pod)") def command(self, req: dict) -> Any: """Answer a JSON command through its text-console equivalent: the commands in @@ -518,130 +445,26 @@ def _text_ping(self, req: dict) -> str: raise TransportError(f"the pod did not answer ping: {out.strip()!r}") return "pong" - def _moved_to_json(self, what: str) -> TransportError: - """Firmware 3.9.0 moved the instrument commands off the console to the JSON API.""" + def _needs_network(self, what: str) -> TransportError: + """The USB console of firmware 4.0 answers status, ping and identity only.""" return TransportError( - f"this pod's firmware (3.9.0 or later) has no {what} on its USB console " - f"{self.device or ''}: it is a network command. Connect with 'usb', which uses the " - "pod's USB network adapter (Wi-Fi configured on the pod turns it off; `benchpod " - "clear-wifi` turns it back on) or else the pod's network address (refused while its " - "external LAN policy is off), or pass that address".replace(" ", " ")) - - def _text_la_voltage(self, req: dict) -> Dict[str, Any]: - line = "la-voltage" + (f" {int(req['mv'])}" if req.get("mv") is not None else "") - out = self._send_command(line) - if MOVED_TO_NETWORK in out: - raise self._moved_to_json("la-voltage") - if "needs a v3 pod" in out or "usage:" in out: - msg = next((ln.strip() for ln in out.replace("\r", "\n").split("\n") - if "needs a v3 pod" in ln or "usage:" in ln), out.strip()) - raise FirmwareError(msg, cmd="la_voltage") - m = re.search(r"LA VCCIO = (?:(\d+) mV|UNSET) \(st=(-?\d+)\)", out) - if not m: - raise TransportError(f"unexpected la-voltage reply: {out.strip()!r}") - return {"mv": int(m.group(1) or 0), "st": int(m.group(2))} + f"{what} is not on this pod's USB console {self.device or ''}: it is a network " + "command. Connect with 'usb', which uses the pod's USB network adapter (Wi-Fi " + "configured on the pod turns it off; `benchpod clear-wifi` turns it back on), or pass " + "the pod's network address".replace(" ", " ")) def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: - if delay_ms: - raise TransportError("the pod's USB console cannot schedule a delayed power change; " - "use delay=None, or a network/cloud connection") - out = self._send_command(f"power {int(efuse)} {'on' if on else 'off'}") - if MOVED_TO_NETWORK in out: - raise self._moved_to_json("power") - if UNKNOWN_COMMAND in out or "bad eFuse" in out or "ERROR:" in out: - raise TransportError(f"firmware rejected power {efuse}: {out.strip()!r}") - - def _console_raw_handshake( - self, cmd: str, ready: str, quit_byte: bytes - ) -> RawLink: - """Send a console command, read until the ``ready`` sentinel, then hand - back the raw byte link (its ``close()`` sends ``quit_byte`` to exit). - - On any failure we still send ``quit_byte``: by the time the sentinel is - due the firmware may already have armed and switched to the raw mode, so - without it the pod stays wedged until its inactivity watchdog and the - next handshake fails too. - """ - with _port_errors(cmd.split()[0]): - return self._console_raw_handshake_inner(cmd, ready, quit_byte) - - def _console_raw_handshake_inner(self, cmd: str, ready: str, quit_byte: bytes) -> RawLink: - # Recover from a previous raw session that didn't cleanly exit (e.g. a - # stalled flash whose Q got dropped on a flaky link): send the quit byte - # so the pod leaves raw mode, then this command is parsed by the console - # rather than swallowed as protocol bytes. Harmless when already in text - # mode (an unknown char, cleared below). - try: - self._port.write(quit_byte) - self._port.flush() - time.sleep(0.1) - self._port.reset_input_buffer() - except Exception: - pass - self._write_line(cmd) - deadline = time.monotonic() + self.timeout - verb = cmd.split()[0] - acc = bytearray() - - def _recover_and_raise(msg: str): - try: - self._port.write(quit_byte) - self._port.flush() - time.sleep(0.1) - self._port.reset_input_buffer() - except Exception: - pass - raise TransportError(msg) - - # Match the ``ready`` sentinel as a substring of the accumulated output - # rather than line-by-line: the firmware can emit a long, newline-less - # run (backspace echo from the clear-line prefix) before the sentinel, - # and the command echo never contains the sentinel, so this is robust. - while time.monotonic() < deadline: - chunk = self._port.read(256) - if chunk: - acc.extend(chunk) - text = acc.decode("utf-8", errors="replace") - if ready in text: - return _SerialRawLink(self._port, quit_byte=quit_byte) - if UNKNOWN_COMMAND in text: - _recover_and_raise( - f"this pod's USB console has no '{verb}' command — flashing and the UART " - "proxy need a network (host[:port]) or cloud (embeddedci:) connection" - ) - if "ERROR:" in text or "usage:" in text: - _recover_and_raise( - f"{verb} rejected by firmware; pod output:\n{text.strip()}" - ) - _recover_and_raise( - f"{verb}: pod never reported {ready!r}; pod output:\n{acc.decode('utf-8', 'replace').strip()}" - ) + raise self._needs_network("target power") def dap_start(self, swclk: int, swdio: int, packet_size: Optional[int] = None, packet_count: Optional[int] = None, wait_ms: Optional[int] = None) -> RawLink: - # The USB console's dap-start keeps the default 256 x 1 packets. - cmd = f"dap-start {swclk} {swdio}" - return self._console_raw_handshake(cmd, DAP_READY, quit_byte=DAP_LEAVE) + raise self._needs_network("SWD (flashing)") def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", stop_bits: int = 1, half_duplex: bool = False, entry: Any = None, de: Optional[int] = None, de_active_low: bool = False) -> RawLink: - if de is not None: - raise UnsupportedFeatureError( - "UART de needs the network, the USB network or the cloud: the USB console's " - "uart-proxy has no DE", feature="uart_de") - if half_duplex or entry is not None: - raise UnsupportedFeatureError( - "UART half_duplex and entry need the network, the USB network or the cloud: the " - "USB console's uart-proxy has neither", feature="uart_hd") - if parity != "none" or stop_bits != 1: - raise UnsupportedFeatureError( - "UART parity and stop bits need the network, the USB network or the cloud: the " - "USB console's uart-proxy is 8N1 only", feature="uart_frame") - return self._console_raw_handshake( - f"uart-proxy {rx} {tx} {baud}", UART_READY, quit_byte=CTRL_RBRACKET - ) + raise self._needs_network("the UART proxy") def close(self) -> None: try: diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index 6ef9ea0..7e02751 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -307,7 +307,11 @@ def command(self, req: dict) -> Any: pass def samples(self, req: dict) -> List[int]: - """Send a command whose reply is a chunked sample array.""" + """Send a command whose reply is a chunked sample array, flattened from its decimal + ``data`` lists (asks for ``"enc":"dec"`` unless ``req`` names an encoding; captures come + as base64 otherwise, which :meth:`stream_chunks` yields).""" + req = {**req} + req.setdefault("enc", "dec") timeout = request_timeout(req, self.timeout) sock = self._dial(timeout, kind="capture") buf = bytearray() @@ -434,9 +438,6 @@ def stage_psram(self, data: bytes) -> int: def status(self) -> Any: return self.command({"cmd": "status"}) - def status_without_caps(self) -> Any: - return self.command({"cmd": "status", "caps": False}) - def ping(self) -> Any: return self.command({"cmd": "ping"}) diff --git a/packages/embeddedci/src/embeddedci/benchpod/wiring.py b/packages/embeddedci/src/embeddedci/benchpod/wiring.py index 57eaff0..5e413b1 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/wiring.py +++ b/packages/embeddedci/src/embeddedci/benchpod/wiring.py @@ -380,9 +380,6 @@ def warnings(self) -> List[str]: if _is_int(self.uart_rx) and self._pull_may_be(self.uart_rx, "down"): out.append(f"uart_rx is on LA{self.uart_rx}, which has a pull-down; the UART idles high, " "so keep the pull disabled") - if self.la_mv == 1800 and self.pulls: - out.append("pulls: at 1.8 V the pull resistors need firmware newer than 3.10.12; older " - "firmware leaves them off") return out def pull_directions(self) -> Dict[int, str]: diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 651cc16..d015937 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -342,7 +342,6 @@ "analog", "dac_limits", "sensors", - "sensors_format", "sensors_digital", "sensor_la_trigger", "flash_kb", @@ -582,6 +581,9 @@ "FirmwareError": { "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None) -> 'None'" }, + "FirmwareTooOldError": { + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, api: 'int' = 0, firmware_version: 'str' = '') -> 'None'" + }, "FlashError": {}, "FlashResult": { "__fields__": [ @@ -1398,6 +1400,7 @@ "Fault", "FaultType", "FirmwareError", + "FirmwareTooOldError", "FlashError", "FlashResult", "FpgaImage", diff --git a/packages/embeddedci/tests/conftest.py b/packages/embeddedci/tests/conftest.py index 20be5d5..c602db2 100644 --- a/packages/embeddedci/tests/conftest.py +++ b/packages/embeddedci/tests/conftest.py @@ -22,6 +22,9 @@ def pytest_configure(config): "markers", "bench_needs(*names): the e2e test uses these optional bench resources (free " "LA channels and the like, e2e/e2e_bench.py NEEDS); it skips when the bench sets them to " "'none'") + config.addinivalue_line( + "markers", "firmware_3: the test's fake pod is firmware 3.x on purpose (no api in its " + "status): conftest does not read it as firmware 4.0") @pytest.fixture(scope="session") @@ -43,3 +46,75 @@ def _isolated_benchpod_cli_config(request, tmp_path_factory, monkeypatch): or os.sep + "examples" + os.sep in path: return monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path_factory.mktemp("xdg"))) + + +def as_firmware_4(status): + """A fake pod's ``status`` written for firmware 3.x (a ``caps`` list, no ``api``) as firmware + 4.0 sends it: ``api`` 2, ``features_rev``, ``gateware`` and the facts the list implied. A + status that sets ``api`` comes back unchanged (the tests of the api check).""" + if not isinstance(status, dict) or "api" in status: + return status + st = dict(status) + listed = "caps" in st + caps = {str(c).lower() for c in st.pop("caps", None) or []} + st.update(api=2, min_client_api=2) + st.setdefault("features_rev", 10) + st.setdefault("gateware", 59) + if not listed: + image = "loop" + elif "dac_deep_replay" in caps: + image = "deep" + elif "dac_control_loop" in caps: + image = "loop" + else: # a list without either image's feature: the emulation image, or a single image + image = "emu" if st.get("sensors_digital") is True else "unknown" + st.setdefault("fpga_image", image) + if "sensors_digital" in caps: + st.setdefault("sensors_digital", True) + if "nrst_pin" in caps: + st.setdefault("nrst_pin", True) + hw = list(st.get("hw") or []) + for fact, name in (("pod_current", "pod_current"), ("usb_cc", "usb_cc"), + ("adc_low_range", "adc_low_range"), ("wifi_scan", "wifi")): + if fact in caps and name not in hw: + hw.append(name) + st["hw"] = hw + return st + + +@pytest.fixture(autouse=True) +def _fake_pods_run_firmware_4(request, monkeypatch): + """Unit tests' fake pods were written for firmware 3.x statuses: the SDK reads them as + firmware 4.0 (:func:`as_firmware_4`). Hardware tests (e2e, examples) talk to real pods.""" + path = str(request.node.fspath) + if os.sep + "e2e" + os.sep in path or os.sep + "examples" + os.sep in path: + return + if request.node.get_closest_marker("firmware_3"): + return # the test's fake is a firmware 3.x pod on purpose + from embeddedci.benchpod.client import BenchPod + + real = BenchPod._caps_status + monkeypatch.setattr(BenchPod, "_caps_status", lambda self: as_firmware_4(real(self))) + # Fakes for firmware before la_dir (3.10.4) expect a connect that sends nothing: keep it so + # for them (test_pin_directions.py covers the directions sent on connect). + real_auto = BenchPod._auto_pin_directions + + def auto(self): + t = getattr(self, "_transport", None) + try: + st = real(self) if t is not None and type(t).__name__ != "SerialTransport" else {} + except Exception: + st = {} + if isinstance(st, dict) and "api" not in st and _before_la_dir(st.get("version")): + self.pin_directions_status = "not sent: a fake pod written for firmware before la_dir" + return + real_auto(self) + + monkeypatch.setattr(BenchPod, "_auto_pin_directions", auto) + + +def _before_la_dir(version): + import re + + m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)", str(version or "")) + return m is None or tuple(int(x) for x in m.groups()) < (3, 10, 4) diff --git a/packages/embeddedci/tests/runs_fake.py b/packages/embeddedci/tests/runs_fake.py index b47563a..0b8c1c7 100644 --- a/packages/embeddedci/tests/runs_fake.py +++ b/packages/embeddedci/tests/runs_fake.py @@ -6,8 +6,9 @@ from embeddedci.benchpod.transport.base import Transport -STATUS = {"version": "3.10.11", "board": "stm32h563", "board_rev": "v3", "analog": True, - "gateware": 58, "features_rev": 0, "caps": ["calibrate", "la_pins"]} +STATUS = {"version": "4.0.0", "board": "stm32h563", "board_rev": "v3", "analog": True, + "gateware": 58, "features_rev": 10, "api": 2, "min_client_api": 2, "fpga_image": "deep", + "hw": []} CALIBRATION = {"source": "current_in", "calibrated": True, "offset": 0.0012} @@ -65,9 +66,6 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: def status(self) -> Any: return self.command({"cmd": "status"}) - def status_without_caps(self) -> Any: - return self.command({"cmd": "status", "caps": False}) - def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: self.requests.append({"cmd": "target_power", "efuse": efuse, "on": on}) diff --git a/packages/embeddedci/tests/test_can.py b/packages/embeddedci/tests/test_can.py index 7480c18..ade7658 100644 --- a/packages/embeddedci/tests/test_can.py +++ b/packages/embeddedci/tests/test_can.py @@ -329,9 +329,9 @@ def test_assert_periodic_flags_too_few(bp, pod): def test_can_capability_flag_from_status_and_cloud_parameters(): from embeddedci.benchpod.capabilities import Capabilities - assert Capabilities.from_status({"caps": ["la", "can"]}).can - assert not Capabilities.from_status({"caps": ["la"]}).can # older firmware: not announced - assert Capabilities.from_parameters({"cap.can": "true"}).can + fw4 = Capabilities.from_status({"features_rev": 10, "gateware": 59}) + assert fw4.can and fw4.can_fd + assert Capabilities.from_parameters({"cap.features_rev": "10"}).can assert not Capabilities.from_parameters({}).can @@ -354,15 +354,6 @@ def test_can_config_data_bitrate_below_bitrate_rejected(bp): bp.can_config(bitrate=1_000_000, data_bitrate=500_000) -def test_can_fd_needs_capability(bp, pod): - from embeddedci.benchpod.errors import UnsupportedFeatureError - pod.caps = ["can"] - with pytest.raises(UnsupportedFeatureError): - bp.can_config(data_bitrate=2_000_000) - with pytest.raises(UnsupportedFeatureError): - bp.can_write(0x1, bytes(12)) - - def test_can_write_rejects_more_than_64(bp): with pytest.raises(ValueError): bp.can_write(0x1, bytes(65)) diff --git a/packages/embeddedci/tests/test_capabilities.py b/packages/embeddedci/tests/test_capabilities.py index d926931..c1351a4 100644 --- a/packages/embeddedci/tests/test_capabilities.py +++ b/packages/embeddedci/tests/test_capabilities.py @@ -34,9 +34,8 @@ def test_from_parameters_full_set(): params = { "cap.board": "stm32h563", "cap.adc_bits": "16", "cap.adc_fullscale_mv": "4096", "cap.adc_cal_a": "65.7889", "cap.adc_cal_b": "-0.001003762", "cap.adc_cal_unwrap": "true", - "cap.dac_replay": "true", "cap.dac_deep_replay": "true", + "cap.features_rev": "10", "cap.gateware": "59", "cap.fpga_image": "deep", "cap.dac_replay_bits": "16", "cap.dac_replay_max_samples": "2097152", - "cap.scope": "true", "cap.analyzer": "true", } caps = Capabilities.from_parameters(params) assert caps.dac_replay and caps.dac_deep_replay @@ -58,7 +57,8 @@ def test_from_parameters_integer_uv_nv_cal(): def test_merge_prefers_server_params(): status = Capabilities.from_status({"board": "stm32h563", "adc_bits": 16}) server = Capabilities.from_parameters({"cap.dac_replay_max_samples": "2097152", - "cap.dac_replay_bits": "16", "cap.dac_deep_replay": "true"}) + "cap.dac_replay_bits": "16", "cap.features_rev": "10", + "cap.gateware": "59", "cap.fpga_image": "deep"}) merged = status.merge(server) assert merged.dac_replay_max_samples == 2097152 assert merged.dac_deep_replay is True @@ -67,10 +67,10 @@ def test_merge_prefers_server_params(): def test_rev3_board_features_from_status(): v3 = Capabilities.from_status({"board": "stm32h563", "board_rev": "v3", "nrst_pin": True, - "caps": ["la", "nrst_pin", "usb_cc"]}) + "features_rev": 10, "hw": ["usb_cc"]}) assert v3.board_rev == "v3" and v3.nrst_pin and v3.usb_cc v2 = Capabilities.from_status({"board": "stm32h563", "board_rev": "v2", "nrst_pin": False, - "caps": ["la"]}) + "features_rev": 10, "hw": []}) assert v2.board_rev == "v2" and not v2.nrst_pin and not v2.usb_cc @@ -103,45 +103,42 @@ def test_boot_health_from_parameters(): "the pod is in safe mode. Some features are off") -# -- the policy / update / hardening flags (firmware 3.6 status, server cap.*) ------------------ +# -- the policy / update / hardening flags (firmware 4.0 status, server cap.*) ------------------ -_STATUS_3_6 = { - "version": "3.6.0", "board": "stm32h563", "flash_kb": 2048, - "ota_sig": True, "sig_policy": "audit", "sig_keys": 2, "sig_policy_cmd": True, - "lan_policy": "locked", "lan_policy_cmd": True, "tunnel_max_tier": True, "lease_state": True, - "cloud_ca": True, "cloud_proxy": True, +_STATUS_4_0 = { + "version": "4.0.0", "board": "stm32h563", "flash_kb": 2048, "api": 2, "min_client_api": 2, + "features_rev": 10, "gateware": 59, "fpga_image": "loop", "hw": [], + "sig_policy": "required", "sig_keys": 2, "lan_policy": "locked", "lease": {"held": False, "holder": "", "left_s": 0}, "analog": True, - "caps": ["signal", "la", "analog", "scope", "dac_limits", "calibrate", "current_out"], } def test_status_policy_and_update_flags(): - c = Capabilities.from_status(_STATUS_3_6) - assert c.flash_kb == 2048 and c.ota_sig and c.sig_policy == "audit" and c.sig_keys == 2 + c = Capabilities.from_status(_STATUS_4_0) + assert c.flash_kb == 2048 and c.ota_sig and c.sig_policy == "required" and c.sig_keys == 2 assert c.sig_policy_cmd and c.lan_policy == "locked" and c.lan_policy_cmd assert c.tunnel_max_tier and c.lease_state and c.cloud_ca and c.cloud_proxy - assert c.analog is True and c.dac_limits + assert c.analog is True and c.dac_limits and c.api == 2 and c.min_client_api == 2 def test_status_of_a_digital_only_board(): - c = Capabilities.from_status({"analog": False, "caps": ["la"]}) + c = Capabilities.from_status({**_STATUS_4_0, "analog": False}) assert c.analog is False and not c.dac_limits -def test_older_firmware_leaves_the_new_flags_unknown(): +def test_a_status_without_the_table_has_no_features(): + """Firmware 3.x without features_rev: nothing is decided from it (the SDK refuses the pod).""" c = Capabilities.from_status({"version": "3.1.1", "caps": ["la", "scope"]}) assert c.analog is None and not c.ota_sig and c.sig_policy == "" and c.flash_kb == 0 - assert not c.lease_state and not c.tunnel_max_tier + assert not c.lease_state and not c.tunnel_max_tier and not c.scope def test_server_parameters_policy_and_update_flags(): c = Capabilities.from_parameters({ - "cap.analog": "true", "cap.dac_limits": "true", "cap.flash_kb": "1024", - "cap.blob_slots": "true", "cap.ota_sig": "true", "cap.sig_policy": "required", - "cap.sig_policy_cmd": "true", "cap.lan_policy": "open", "cap.lan_policy_cmd": "true", - "cap.tunnel_max_tier": "true", "cap.ws_auth_v2": "true", "cap.lease_state": "true", - "cap.cloud_ca": "true", "cap.cloud_proxy": "true", "cap.pod_current": "true", + "cap.analog": "true", "cap.flash_kb": "1024", "cap.features_rev": "10", + "cap.gateware": "59", "cap.fpga_image": "loop", "cap.sig_policy": "required", + "cap.lan_policy": "open", "cap.ws_auth_v2": "true", "cap.pod_current": "true", }) assert c.analog is True and c.dac_limits and c.flash_kb == 1024 and c.blob_slots assert c.ota_sig and c.sig_policy == "required" and c.sig_policy_cmd diff --git a/packages/embeddedci/tests/test_capabilities_scope.py b/packages/embeddedci/tests/test_capabilities_scope.py index cfa43e6..197f2a2 100644 --- a/packages/embeddedci/tests/test_capabilities_scope.py +++ b/packages/embeddedci/tests/test_capabilities_scope.py @@ -1,21 +1,22 @@ -"""Capabilities.scope from a pod's status: the digital-only board has no scope.""" +"""Capabilities.scope from a firmware 4.0 status: the features table decides, so the digital-only +board has no scope and the analog one has it.""" from embeddedci.benchpod.capabilities import Capabilities +_FW4 = {"board": "stm32h563", "adc_bits": 16, "version": "4.0.0", "api": 2, "min_client_api": 2, + "features_rev": 10, "gateware": 59, "fpga_image": "loop"} + def test_digital_board_has_no_scope(): - # Firmware 3.6+ lists "signal" on every board and names "scope" itself on the analog one. - status = {"board": "stm32h563", "adc_bits": 16, "analog": False, - "caps": ["signal", "gpio", "power", "la", "analyzer", "command"]} - assert Capabilities.from_status(status).scope is False + c = Capabilities.from_status({**_FW4, "analog": False}) + assert c.scope is False and c.dac is False and c.analyzer is True def test_analog_board_has_the_scope(): - status = {"board": "stm32h563", "adc_bits": 16, "analog": True, - "caps": ["signal", "la", "analog", "scope", "dac"]} - assert Capabilities.from_status(status).scope is True + assert Capabilities.from_status({**_FW4, "analog": True}).scope is True -def test_firmware_without_the_analog_flag_keeps_signal_as_scope(): - status = {"board": "stm32h563", "adc_bits": 16, "caps": ["signal", "la"]} - assert Capabilities.from_status(status).scope is True +def test_a_caps_list_is_ignored(): + """Firmware 4.0 sends no caps list; one in a status decides nothing.""" + c = Capabilities.from_status({"board": "stm32h563", "caps": ["signal", "la", "scope", "dac"]}) + assert not c.scope and not c.dac and not c.analyzer diff --git a/packages/embeddedci/tests/test_capture.py b/packages/embeddedci/tests/test_capture.py index 189ad1e..348eec2 100644 --- a/packages/embeddedci/tests/test_capture.py +++ b/packages/embeddedci/tests/test_capture.py @@ -68,20 +68,30 @@ def _b64(words): return base64.urlsafe_b64encode(struct.pack(f"<{len(words)}H", *words)).rstrip(b"=").decode() -B64_CAPS = Capabilities.from_status({"adc_bits": 8, "adc_fullscale_mv": 2550, - "caps": ["signal", "capture_b64"]}) +B64_CAPS = NAIVE -def test_capture_b64_is_requested_only_when_the_pod_offers_it(): - assert B64_CAPS.capture_b64 and not NAIVE.capture_b64 +def test_captures_take_the_default_base64(): + """Firmware 4.0 sends base64 by default: a streamed capture names no encoding.""" t = FakeCaptureTransport({}) cap_mod.capture_adc(t, NAIVE, samples=4) - assert "enc" not in t.sent[0] # an older pod never sees the key - cap_mod.capture_adc(t, B64_CAPS, samples=4) - assert t.sent[1]["enc"] == "b64" - # An LA-only capture has no dense ADC region to encode. - cap_mod.capture_correlated(t, B64_CAPS, adc_samples=0, la_samples=8) - assert "enc" not in t.sent[2] + assert "enc" not in t.sent[0] + cap_mod.capture_correlated(t, NAIVE, adc_samples=4, la_samples=8) + assert "enc" not in t.sent[1] + + +def test_a_transport_without_chunks_asks_for_decimal(): + class _Flat: + def __init__(self): + self.sent = [] + + def samples(self, req): + self.sent.append(req) + return [1, 2, 3] + + t = _Flat() + assert cap_mod.capture_adc(t, NAIVE, samples=3).counts == [1, 2, 3] + assert t.sent == [{"cmd": "capture", "samples": 3, "enc": "dec"}] def test_capture_adc_decodes_b64_chunks(): @@ -104,7 +114,7 @@ def test_capture_correlated_decodes_b64_adc_alongside_rle_la(): {"status": "chunk", "la": True, "la_edges": [[0, 5], [2, 6]], "la_upto": 4, "more": False}, ]}) cc = cap_mod.capture_correlated(t, B64_CAPS, adc_samples=3, la_samples=4) - assert t.sent[0]["enc"] == "b64" + assert "enc" not in t.sent[0] assert cc.adc.counts == [10, 20, 30] assert cc.la.words == [5, 5, 6, 6] diff --git a/packages/embeddedci/tests/test_client_api.py b/packages/embeddedci/tests/test_client_api.py index 546ace9..7df5a6b 100644 --- a/packages/embeddedci/tests/test_client_api.py +++ b/packages/embeddedci/tests/test_client_api.py @@ -10,7 +10,7 @@ import pytest -from embeddedci.benchpod import BenchPod, ClientTooOldError, protocol +from embeddedci.benchpod import BenchPod, ClientTooOldError, FirmwareTooOldError, protocol from embeddedci.benchpod.errors import firmware_error from embeddedci.benchpod import feature_map as _feature_map from embeddedci.benchpod.feature_map import CLIENT_API, table_api @@ -25,7 +25,7 @@ def test_client_api_is_the_bundled_tables(): """A features-table sync that raises ``api`` fails here: raise CLIENT_API by hand, with the code that handles the new level.""" bundled = json.loads(Path(_feature_map.__file__).with_name("feature_map.json").read_text("utf-8")) - assert CLIENT_API == bundled["api"] == table_api() == 1 + assert CLIENT_API == bundled["api"] == table_api() == 2 assert bundled["min_client_api"] <= bundled["api"] @@ -101,10 +101,11 @@ def test_the_usb_console_text_protocol_gets_nothing(): # -- the pod's level on connect ----------------------------------------------------------------- class _Pod: - """A pod whose caps-less status announces ``api`` (or nothing, like firmware 3.10.13).""" + """A pod whose status announces ``api`` (or nothing, like firmware 3.10.13).""" - def __init__(self, status_extra: Dict[str, Any]) -> None: + def __init__(self, status_extra: Dict[str, Any], version: str = "4.0.0") -> None: self.extra = status_extra + self.version = version self.requests: List[dict] = [] self.timeout = 30.0 self.refuse_with: Dict[str, Any] = {} @@ -112,17 +113,13 @@ def __init__(self, status_extra: Dict[str, Any]) -> None: def status(self) -> Dict[str, Any]: return self.command({"cmd": "status"}) - def status_without_caps(self) -> Dict[str, Any]: - return self.command({"cmd": "status", "caps": False}) - def command(self, req: dict) -> Any: self.requests.append(req) if req["cmd"] == "status": - return {"version": "3.11.0", "board": "stm32h563", "features_rev": 8, "gateware": 59, - **self.extra} + return {"version": self.version, "board": "stm32h563", "features_rev": 10, + "gateware": 59, **self.extra} if self.refuse_with: - raise firmware_error("update the BenchPod SDK, MCP or CLI", cmd=req["cmd"], - code="BP0030", values=self.refuse_with) + raise firmware_error("", cmd=req["cmd"], code="BP0030", values=self.refuse_with) return {} def ping(self) -> Any: @@ -132,47 +129,91 @@ def close(self) -> None: pass -@pytest.mark.parametrize("extra", [{}, {"api": 1, "min_client_api": 0}, {"api": 1, "min_client_api": 1}]) -def test_a_pod_at_this_level_or_without_one_connects(extra): - bp = BenchPod(transport=_Pod(extra), lease=False, api_key="", api_base="") - assert bp.capabilities.client_api_level == 1 - assert bp.capabilities.api == extra.get("api", 0) +def test_a_pod_at_this_level_connects(): + bp = BenchPod(transport=_Pod({"api": 2, "min_client_api": 2}), lease=False, api_key="", api_base="") + assert bp.capabilities.client_api_level == 2 and bp.capabilities.api == 2 + + +@pytest.mark.firmware_3 +@pytest.mark.parametrize("extra,version", [ + ({}, "3.10.13"), # no api: client API 1 + ({"api": 1, "min_client_api": 0}, "3.11.0"), # development builds after 3.10.13 +]) +def test_firmware_3_is_refused_on_connect(extra, version): + pod = _Pod(extra, version) + with pytest.raises(FirmwareTooOldError) as e: + BenchPod(transport=pod, lease=False, api_key="", api_base="") + err = e.value + assert err.api == 1 and err.firmware_version == version and err.feature == "client_api" + msg = str(err) + assert version in msg and "4.0.0" in msg and "benchpod flash-self" in msg + assert "embeddedci<4" in msg + # Nothing but the status reads reached the pod. + assert {r["cmd"] for r in pod.requests} == {"status"} def test_a_pod_above_this_level_refuses_the_connect(): - pod = _Pod({"api": 2, "min_client_api": 1}) + pod = _Pod({"api": 3, "min_client_api": 2}) with pytest.raises(ClientTooOldError) as e: BenchPod(transport=pod, lease=False, api_key="", api_base="") err = e.value - assert err.api == 2 and err.client_api == CLIENT_API and err.min_client_api == 1 - assert err.firmware_version == "3.11.0" + assert err.api == 3 and err.client_api == CLIENT_API and err.min_client_api == 2 + assert err.firmware_version == "4.0.0" msg = str(err) - assert "3.11.0" in msg and "client API 2" in msg and f"client API {CLIENT_API}" in msg + assert "4.0.0" in msg and "client API 3" in msg and f"client API {CLIENT_API}" in msg assert "pip install -U embeddedci" in msg +def test_a_pod_that_takes_no_client_this_old_refuses_the_connect(): + with pytest.raises(ClientTooOldError): + BenchPod(transport=_Pod({"api": 3, "min_client_api": 3}), lease=False, api_key="", api_base="") + + +@pytest.mark.firmware_3 def test_capabilities_after_an_update_check_again(): - pod = _Pod({"api": 1}) + pod = _Pod({"api": 2}) bp = BenchPod(transport=pod, lease=False, api_key="", api_base="") - pod.extra = {"api": 2} # the pod was updated meanwhile + pod.extra = {"api": 3} # the pod was updated meanwhile with pytest.raises(ClientTooOldError): bp.refresh_capabilities() + pod.extra, pod.version = {}, "3.10.13" # rolled back to firmware 3.x + with pytest.raises(FirmwareTooOldError): + bp.refresh_capabilities() def test_bp0030_raises_client_too_old(): - pod = _Pod({"api": 1, "min_client_api": 2}) + pod = _Pod({"api": 2, "min_client_api": 2}) bp = BenchPod(transport=pod, lease=False, api_key="", api_base="") - pod.refuse_with = {"client_api": 1, "min_client_api": 2, "api": 2} + pod.refuse_with = {"client_api": 1, "min_client_api": 3, "api": 3} with pytest.raises(ClientTooOldError) as e: bp.command({"cmd": "gpio", "la": 4, "mode": "off"}) - assert e.value.code == "BP0030" and e.value.min_client_api == 2 and e.value.client_api == 1 + assert e.value.code == "BP0030" and e.value.min_client_api == 3 and e.value.client_api == 1 assert "pip install -U embeddedci" in str(e.value) +@pytest.mark.firmware_3 +def test_the_console_decides_by_version(): + """The USB console announces no api: its firmware version decides.""" + from embeddedci.benchpod.transport.serial import SerialTransport + + class _Console(SerialTransport): + def __init__(self, version: str) -> None: + self.version, self.timeout, self.device = version, 1.0, "/dev/x" + + def command(self, req: dict) -> Any: + return {"version": self.version, "board": "stm32h563"} if req["cmd"] == "status" else "pong" + + def close(self) -> None: + pass + + assert BenchPod(transport=_Console("4.0.0"), lease=False, api_key="", api_base="").capabilities + with pytest.raises(FirmwareTooOldError): + BenchPod(transport=_Console("3.10.13"), lease=False, api_key="", api_base="").capabilities + + def test_the_cloud_frame_carries_it_too(): from embeddedci.benchpod.capabilities import Capabilities - c = Capabilities.from_parameters({"cap.api": "2", "cap.min_client_api": "1"}) - assert c.api == 2 and c.min_client_api == 1 and c.client_api_level == 2 + c = Capabilities.from_parameters({"cap.api": "2", "cap.min_client_api": "2"}) + assert c.api == 2 and c.min_client_api == 2 and c.client_api_level == 2 assert Capabilities.from_parameters({}).client_api_level == 1 - diff --git a/packages/embeddedci/tests/test_client_v2.py b/packages/embeddedci/tests/test_client_v2.py index 6580f16..a197328 100644 --- a/packages/embeddedci/tests/test_client_v2.py +++ b/packages/embeddedci/tests/test_client_v2.py @@ -29,14 +29,16 @@ class FakeTransport: """Records every command and power call; replies are looked up by ``cmd``.""" - def __init__(self, replies: Dict[str, Any] | None = None) -> None: + def __init__(self, replies: Dict[str, Any] | None = None, analog: bool = True) -> None: self.commands: List[dict] = [] self.power: List[tuple] = [] self.replies = replies or {} self.closed = False + self.analog = analog def status(self) -> Any: - return {"board": "stm32h563", "adc_bits": 16, "adc_fullscale_mv": 4096} + return {"board": "stm32h563", "adc_bits": 16, "adc_fullscale_mv": 4096, + **({} if self.analog else {"analog": False})} def ping(self) -> Any: return "pong" @@ -173,10 +175,10 @@ def test_power_status_pod_draw(): def test_pod_current_capability(): - assert Capabilities.from_status({"caps": ["la", "pod_current"]}).pod_current - assert not Capabilities.from_status({"caps": ["la"]}).pod_current - assert Capabilities.from_parameters({"cap.pod_current": "true"}).pod_current - assert not Capabilities.from_parameters({"cap.pod_current": "false"}).pod_current + assert Capabilities.from_status({"features_rev": 10, "hw": ["pod_current"]}).pod_current + assert not Capabilities.from_status({"features_rev": 10, "hw": []}).pod_current + assert Capabilities.from_parameters({"cap.features_rev": "10", "cap.pod_current": "true"}).pod_current + assert not Capabilities.from_parameters({"cap.features_rev": "10", "cap.pod_current": "false"}).pod_current def test_reset_line(): @@ -201,29 +203,8 @@ def test_usb_cc(): # -- bias resistors ------------------------------------------------------------ -def test_pullups_and_pulldowns_are_not_interchangeable(): - bp, t = _bp({"la": lambda req: {"la": req.get("la"), "pullup": 1, "ohms": "10k", - "pull": "down" if req.get("la") in (7, 8) else "up", - "pullups_available": 1}}) - # firmware without la_pull_dir: the SDK checks the direction itself, like the pod would - with pytest.raises(ValueError, match="LA7 supports pull-down only"): - bp.enable_pullup(7) - with pytest.raises(ValueError, match="LA2 supports pull-up only"): - bp.enable_pulldown(2) - with pytest.raises(ValueError, match="LA9 has no pull resistor"): - bp.enable_pullup(9) - assert t.commands == [] - bp.enable_pullup(1, 2) - bp.enable_pulldown(8) - assert t.commands == [{"cmd": "la", "la": 1, "pullup": "on"}, - {"cmd": "la", "la": 2, "pullup": "on"}, - {"cmd": "la", "la": 8, "pullup": "on"}] - state = bp.pull_state(8) - assert isinstance(state, PullState) and state.direction == "down" and state.enabled - - def test_enabled_pulls_decodes_the_mask(): - bp, _ = _bp({"la": {"la_pullup_mask": 0b10000101, "pullups_available": 1}}) + bp, _ = _bp({"la_pull": {"la_pullup_mask": 0b10000101, "pullups_available": True}}) assert bp.enabled_pulls() == [1, 3, 8] @@ -323,10 +304,11 @@ def test_current_out_refuses_what_is_not_amps(): assert t.commands == [] -def test_current_out_needs_the_capability(): - bp, t = _bp() # older firmware: no `current_out` +def test_current_out_needs_the_analog_board(): + t = FakeTransport(analog=False) # the digital-only board: no 4-20 mA output + bp = BenchPod(transport=t, lease=False, wiring=Wiring.preset()) for call in (lambda: bp.current_out(0.012), bp.current_out_range): - with pytest.raises(BenchPodError, match="current_out"): + with pytest.raises(BenchPodError, match="analog front end"): call() assert t.commands == [] assert BenchPod(transport=CurrentPod(), lease=False).capabilities.current_out @@ -368,10 +350,11 @@ def test_calibrate_runs_reads_and_clears(): bp.calibrate("ext") # type: ignore[arg-type] -def test_calibrate_needs_the_capability(): - bp, t = _bp() # firmware 3.3.0 and older: no `calibrate` +def test_calibrate_needs_the_analog_board(): + t = FakeTransport(analog=False) + bp = BenchPod(transport=t, lease=False, wiring=Wiring.preset()) for call in (bp.calibrate, bp.calibration, bp.clear_calibration): - with pytest.raises(BenchPodError, match="calibrate"): + with pytest.raises(BenchPodError, match="analog front end"): call() assert t.commands == [] assert BenchPod(transport=CalPod(), lease=False).capabilities.calibrate @@ -425,15 +408,10 @@ def test_calibrate_adc_gain_and_partial_clear(): bp.clear_calibration("everything") # type: ignore[arg-type] -def test_dmm_calibration_needs_cal_dmm(): - t = CalPod({"calibrate": lambda req: _CAL}) # 3.4.0 to 3.9.2: offset only +def test_a_reply_without_dmm_parts(): + t = CalPod({"calibrate": lambda req: _CAL}) bp = BenchPod(transport=t, lease=False) - for call in (lambda: bp.calibrate_dac("5v", [(1, 1.0), (40000, 3.0)]), lambda: bp.calibrate_adc_gain("cal1"), - lambda: bp.clear_calibration("adc")): - with pytest.raises(BenchPodError, match="cal_dmm"): - call() - assert t.commands == [] - old = bp.calibration() # an old reply has no DMM parts + old = bp.calibration() # a pod never calibrated with a DMM assert old.dac == {} and old.adc_gain_ppm == {} and not old.dmm and old.measured is None assert old.zero_count is None @@ -442,7 +420,7 @@ def test_capture_adc_routes_the_source_first(): bp, t = _bp({"analog_path": {"path": "cal1"}}) cap = bp.capture_adc(2, source="cal1", sample_rate_hz=100_000) assert t.commands[0] == {"cmd": "analog_path", "path": "cal1"} - assert t.commands[1] == {"cmd": "capture", "samples": 2, "sample_rate_mhz": 0.1} + assert t.commands[1] == {"cmd": "capture", "samples": 2, "sample_rate_mhz": 0.1, "enc": "dec"} assert cap.source == "cal1" and len(cap) == 2 @@ -464,7 +442,7 @@ def test_power_cycle_capture_window_must_cover_the_power_on(): def test_la_step_delay_is_seconds(): bp, t = _bp() bp.la_step(3, steps=200, delay=0.0005, dir_la=4, direction=1) - assert t.commands[-1] == {"cmd": "la", "la": 3, "steps": 200, "delay_us": 500, + assert t.commands[-1] == {"cmd": "la_step", "la": 3, "steps": 200, "delay_us": 500, "dir_la": 4, "direction": 1} with pytest.raises(ValueError): bp.la_step(3, steps=10, delay=0) @@ -493,8 +471,6 @@ def test_can_read_returns_frames(): res = bp.can_read(max_frames=4) assert t.commands[-1] == {"cmd": "can_read", "max": 4} assert res.overflow == 2 and res.frames[0].id == 0x123 and res.frames[0].data == b"\x01\x02" - with pytest.raises(UnsupportedFeatureError): # >8 bytes needs CAN FD (can_fd capability) - bp.can_write(0x10, list(range(9))) with pytest.raises(ValueError): bp.can_write(0x10, list(range(65))) with pytest.raises(ValueError): diff --git a/packages/embeddedci/tests/test_cloud.py b/packages/embeddedci/tests/test_cloud.py index 128db9b..c3c493b 100644 --- a/packages/embeddedci/tests/test_cloud.py +++ b/packages/embeddedci/tests/test_cloud.py @@ -549,7 +549,7 @@ def test_cloud_command_retries_other_instance(monkeypatch): @pytest.mark.parametrize("req", [ {"cmd": "can_write", "id": 1, "data": "00"}, {"cmd": "nrst", "pulse_ms": 10}, - {"cmd": "la", "la": 1, "steps": 5, "delay_us": 100}, + {"cmd": "la_step", "la": 1, "steps": 5, "delay_us": 100}, {"cmd": "spi_xfer", "tx": "9f"}, {"cmd": "generate", "waveform": "sine"}, {"cmd": "target_power", "efuse": 1, "state": 1, "delay_ms": 500}, diff --git a/packages/embeddedci/tests/test_control_loop.py b/packages/embeddedci/tests/test_control_loop.py index f0639e9..cec601b 100644 --- a/packages/embeddedci/tests/test_control_loop.py +++ b/packages/embeddedci/tests/test_control_loop.py @@ -178,15 +178,15 @@ def test_generate_on_capture_sets_flag(): assert "on_capture" not in t.commands[-1] -def test_generate_maps_volts_to_generator_codes_and_routes_the_path(): +def test_generate_sends_volts_and_the_pod_routes_the_path(): bp, t = _bp() h = bp.generate("square", freq_hz=50, amplitude=1.0, dac_path="5v", duration=0.25, sample_rate_hz=100_000) - route, gen = t.commands[-2], t.commands[-1] - assert route == {"cmd": "dac_out", "path": "5v"} - # 5 V over 255 levels: 1.0 V peak -> 51, default offset = mid-range 2.5 V -> 128. - assert gen == {"cmd": "generate", "waveform": "square", "freq": 50.0, "amplitude": 51, - "offset": 128, "duration_ms": 250, "sample_rate_mhz": 0.1} + gen = t.commands[-1] + # The default offset is mid-range: 2.5 V on the 5 V path. + assert gen == {"cmd": "generate", "waveform": "square", "freq_hz": 50, "path": "5v", + "amplitude_v": 1.0, "offset_v": 2.5, "duration_ms": 250, + "sample_rate_hz": 100000} h.stop() assert t.commands[-1] == {"cmd": "dac_stop"} @@ -194,8 +194,8 @@ def test_generate_maps_volts_to_generator_codes_and_routes_the_path(): def test_generate_rejects_values_outside_the_path(): bp, t = _bp() with pytest.raises(ValueError, match="amplitude"): - bp.generate("sine", freq_hz=10, amplitude=0.001, dac_path="3v3") - with pytest.raises(ValueError, match="offset"): + bp.generate("sine", freq_hz=10, amplitude=0.00001, dac_path="3v3") + with pytest.raises(ValueError, match="must stay within"): bp.generate("sine", freq_hz=10, amplitude=1.0, offset=6.0, dac_path="5v") with pytest.raises(ValueError, match="waveform"): bp.generate("triangle", freq_hz=10, amplitude=1.0) # type: ignore[arg-type] @@ -244,8 +244,12 @@ def test_capture_stop_dac_absent_when_unset(): # -- capabilities flags ------------------------------------------------------ def test_capabilities_parse_new_flags(): - c = Capabilities.from_parameters({"cap.dac_control_loop": "true", "cap.dac_cotrig": "true"}) + c = Capabilities.from_parameters({"cap.features_rev": "10", "cap.gateware": "59", + "cap.fpga_image": "loop"}) assert c.dac_control_loop is True and c.dac_cotrig is True + deep = Capabilities.from_parameters({"cap.features_rev": "10", "cap.gateware": "59", + "cap.fpga_image": "deep"}) + assert deep.dac_control_loop is False and deep.dac_deep_replay is True c2 = Capabilities.from_parameters({}) assert c2.dac_control_loop is False and c2.dac_cotrig is False @@ -387,8 +391,10 @@ def test_constant_and_linear_curves(): def test_capabilities_parse_loop_sources(): - c = Capabilities.from_parameters({"cap.dac_control_loop": "true", - "cap.dac_loop_sources": "true"}) + c = Capabilities.from_parameters({"cap.features_rev": "10", "cap.gateware": "29", + "cap.fpga_image": "loop"}) assert c.dac_loop_sources is True - # Absent on a pre-v29 pod -> False, so a caller offers/uses the ADC source only. - assert Capabilities.from_parameters({"cap.dac_control_loop": "true"}).dac_loop_sources is False + # Absent on pre-v29 gateware -> False, so a caller offers/uses the ADC source only. + old = Capabilities.from_parameters({"cap.features_rev": "10", "cap.gateware": "28", + "cap.fpga_image": "loop"}) + assert old.dac_control_loop is True and old.dac_loop_sources is False diff --git a/packages/embeddedci/tests/test_current_out_waveforms.py b/packages/embeddedci/tests/test_current_out_waveforms.py index b2e0341..be93429 100644 --- a/packages/embeddedci/tests/test_current_out_waveforms.py +++ b/packages/embeddedci/tests/test_current_out_waveforms.py @@ -26,11 +26,13 @@ class _Pod: def __init__(self) -> None: self.commands: List[dict] = [] + self.digital = False self.data = b"" self.counts = [64543, 62560, 60577] # 4, 12 and 20 mA with the _CAL fit def status(self) -> Any: - return {"board": "stm32h563", "adc_bits": 16, "version": "3.5.0", "caps": self.caps} + return {"board": "stm32h563", "adc_bits": 16, "version": "3.5.0", "caps": self.caps, + **({"analog": False} if self.digital else {})} def command(self, req: dict) -> Any: self.commands.append(req) @@ -70,12 +72,12 @@ def _cmds(t: _Pod) -> List[str]: def test_generate_takes_amps_and_switches_the_voltage_outputs_off(): bp, t = _bp() handle = bp.generate("sine", freq_hz=2, amplitude=0.006, offset=0.012, dac_path="current_out") - # The range comes from the pod, then the route (voltage outputs off), then the generator. - assert _cmds(t) == ["current_out", "analog_path", "generate"] + # The range comes from the pod, then the generator in microamps (the pod switches the + # voltage outputs off itself). + assert _cmds(t) == ["current_out", "generate"] assert t.commands[0] == {"cmd": "current_out"} - assert t.commands[1] == {"cmd": "analog_path", "path": "current_out"} - # 8-bit levels on 4.016..20.016 mA (level 255 is the high byte of the top code). - assert (t.commands[2]["amplitude"], t.commands[2]["offset"]) == (96, 127) + assert t.commands[1] == {"cmd": "generate", "waveform": "sine", "freq_hz": 2, + "amplitude_ua": 6000, "offset_ua": 12000} assert handle.dac_path == "current_out" # Stop returns the loop to its live zero: dac_stop alone would leave it where it stopped. @@ -87,10 +89,10 @@ def test_generate_takes_amps_and_switches_the_voltage_outputs_off(): def test_generate_defaults_to_mid_range_and_refuses_what_does_not_fit(): bp, t = _bp() bp.generate("square", freq_hz=1, amplitude=0.004, dac_path="current_out") - assert t.commands[-1]["offset"] in (127, 128) # the middle of the range - with pytest.raises(ValueError, match="0.004016..0.02002 A"): + assert t.commands[-1]["offset_ua"] == 12047 # the middle of the range + with pytest.raises(ValueError, match="0.004016..0.02008 A"): bp.generate("sine", freq_hz=1, amplitude=0.004, offset=0.002, dac_path="current_out") - with pytest.raises(ValueError, match="at most 0.016 A"): + with pytest.raises(ValueError, match="must stay within"): bp.generate("sine", freq_hz=1, amplitude=12, dac_path="current_out") # mA by mistake @@ -153,12 +155,12 @@ def test_a_captured_loop_replays_as_the_same_current(): assert list(memoryview(t.data).cast("H")) == [0, 65535] -def test_the_current_path_needs_the_capability(): +def test_the_current_path_needs_the_analog_board(): bp, t = _bp() - t.caps = ["dac", "dac_replay"] # older firmware - with pytest.raises(BenchPodError, match="current_out"): + t.digital = True + with pytest.raises(BenchPodError, match="analog front end"): bp.generate("sine", freq_hz=1, amplitude=0.004, dac_path="current_out") - with pytest.raises(BenchPodError, match="current_out"): + with pytest.raises(BenchPodError, match="analog front end"): bp.replay([0.012], dac_path="current_out") assert t.commands == [] diff --git a/packages/embeddedci/tests/test_dac_path_default.py b/packages/embeddedci/tests/test_dac_path_default.py index 9252f56..9a2792e 100644 --- a/packages/embeddedci/tests/test_dac_path_default.py +++ b/packages/embeddedci/tests/test_dac_path_default.py @@ -47,9 +47,8 @@ def test_generate_without_a_path_routes_3v3(pod): bp, t = pod h = bp.generate("sine", freq_hz=100, amplitude=1.0) assert h.dac_path == "3v3" - assert t.commands[-2] == {"cmd": "dac_out", "path": "3v3"} - # 1 V over 3.3 V / 255 levels; offset at mid-range 1.65 V. - assert t.commands[-1]["amplitude"] == 77 and t.commands[-1]["offset"] == 127 + # The pod routes the path itself; the offset is mid-range, 1.65 V. + assert t.commands[-1]["path"] == "3v3" and t.commands[-1]["offset_v"] == 1.65 def test_replay_without_a_path_routes_3v3(pod): @@ -62,7 +61,7 @@ def test_replay_without_a_path_routes_3v3(pod): def test_an_explicit_path_is_kept(pod): bp, t = pod assert bp.generate("sine", freq_hz=100, amplitude=1.0, dac_path="5v").dac_path == "5v" - assert t.commands[-2] == {"cmd": "dac_out", "path": "5v"} + assert t.commands[-1]["path"] == "5v" @pytest.mark.parametrize(("setup", "expected"), [ diff --git a/packages/embeddedci/tests/test_dac_path_ranges.py b/packages/embeddedci/tests/test_dac_path_ranges.py index 5b6bf72..8026e31 100644 --- a/packages/embeddedci/tests/test_dac_path_ranges.py +++ b/packages/embeddedci/tests/test_dac_path_ranges.py @@ -60,10 +60,10 @@ def test_generate_on_12v_defaults_to_0_volts(monkeypatch): bp = BenchPod(transport=t, lease=False) bp.generate("square", freq_hz=10, amplitude=1.0, dac_path="12v") gen = t.commands[-1] - # 24 V over 255 levels: 1 V peak -> 11 levels, default offset 0 V -> mid-scale 128. - assert gen["amplitude"] == 11 and gen["offset"] == 128 + # The default offset is 0 V, the middle of the bipolar path. + assert gen["amplitude_v"] == 1.0 and gen["offset_v"] == 0.0 bp.generate("square", freq_hz=10, amplitude=1.0, offset=-6.0, dac_path="12v") - assert t.commands[-1]["offset"] == round(6.0 / (24 / 255)) + assert t.commands[-1]["offset_v"] == -6.0 with pytest.raises(ValueError, match="-12..12"): bp.generate("sine", freq_hz=10, amplitude=1.0, offset=13.0, dac_path="12v") diff --git a/packages/embeddedci/tests/test_digital_v3r4.py b/packages/embeddedci/tests/test_digital_v3r4.py index 0afa3e4..9a9aafa 100644 --- a/packages/embeddedci/tests/test_digital_v3r4.py +++ b/packages/embeddedci/tests/test_digital_v3r4.py @@ -58,7 +58,7 @@ def command(self, req: dict) -> Any: if self.v3r4: out["vref_out"] = self._vref() return out - if req["cmd"] == "la": + if req["cmd"] == "la_pull": la = req["la"] want = req.get("pull") # None: a query if want is None: @@ -69,9 +69,8 @@ def command(self, req: dict) -> Any: self.pulls.pop(la, None) d, s = self.pulls.get(la, ("off", "none")) ohms = {"2.2k": "2.2k", "10k": "10k", "none": "10k"}[s] - out = {"la": la, "pullup": int(d != "off"), "ohms": ohms, "pull": d if d != "off" else "up", - "state": d, "dirs": ["up", "down"], "strength": s, - "strengths": ["10k", "2.2k", "both"], "pullups_available": 1} + out = {"la": la, "ohms": ohms, "state": d, "dirs": ["up", "down"], "strength": s, + "strengths": ["10k", "2.2k", "both"], "pullups_available": True} if self.held and d != "off": out.update(pullup=0, state="off", held=self.held) return out diff --git a/packages/embeddedci/tests/test_esp_flash.py b/packages/embeddedci/tests/test_esp_flash.py index b6dde0c..7fdcabe 100644 --- a/packages/embeddedci/tests/test_esp_flash.py +++ b/packages/embeddedci/tests/test_esp_flash.py @@ -64,7 +64,7 @@ def close(self) -> None: pass def status(self) -> Any: - return {} + return {"fpga_image": "deep"} # ESP32 flashing runs on the deep replay image def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: pass diff --git a/packages/embeddedci/tests/test_expansion.py b/packages/embeddedci/tests/test_expansion.py index 3a95cf7..2d2528d 100644 --- a/packages/embeddedci/tests/test_expansion.py +++ b/packages/embeddedci/tests/test_expansion.py @@ -121,11 +121,8 @@ def __init__(self, chips: Dict[int, Any], *, mv: int = 3300, features_rev: int = self.gpio: Dict[int, dict] = {} def status(self) -> Dict[str, Any]: - if self.features_rev: # 4: la_pull_1v8, pulls at a 1.8 V bank - return {"board": "stm32h563", "version": "3.10.13", "gateware": 58, "fpga_image": "deep", - "features_rev": self.features_rev, "hw": ["nrst_pin"]} - return {"board": "stm32h563", "version": "3.10.4", "gateware": 55, - "caps": ["la", "la_pins", "gpio_read", "capture_trigger", "spi_master"]} + return {"board": "stm32h563", "version": "4.0.0", "gateware": 58, "fpga_image": "deep", + "features_rev": self.features_rev or 10, "hw": ["nrst_pin"]} def ping(self) -> Any: return "pong" @@ -142,14 +139,12 @@ def command(self, req: dict) -> Any: cmd = req["cmd"] if cmd == "la_voltage": return {"mv": self.mv} - if cmd == "la" and "pullup" in req: - (self.pullups.add if req["pullup"] == "on" else self.pullups.discard)(req["la"]) - return {"la": req["la"], "pullup": req["pullup"]} - if cmd == "la" and "pull" in req: - on = req["pull"] != "off" - (self.pullups.add if on else self.pullups.discard)(req["la"]) - return {"la": req["la"], "pullup": int(on), "ohms": "4.7k", "pull": "up", - "state": "up" if on else "off", "dirs": ["up"], "pullups_available": 1} + if cmd == "la_pull" and "la" in req: + if "pull" in req: + (self.pullups.add if req["pull"] != "off" else self.pullups.discard)(req["la"]) + on = req["la"] in self.pullups + return {"la": req["la"], "state": "up" if on else "off", "dirs": ["up"], + "pullups_available": True} if cmd == "i2c_start": if self.session: raise FirmwareError("i2c busy: send i2c_stop first", cmd=cmd) @@ -246,11 +241,7 @@ def test_voltage_checks(): fake = ExpPod({0x20: Tca9555()}, mv=0) with pytest.raises(ExpansionError, match="set the LA voltage first"): BenchPod(transport=fake).expansion("tca9555") - with pytest.raises(ExpansionError, match="at 1.8 V, firmware with pull-ups at 1.8 V"): - attach(mv=1800, pullups="pod") # older firmware: none at 1.8 V - bp, fake, st = attach(mv=1800) # so the breakout's pull-ups - assert st.pullups == "external" and fake.pullups == set() - bp, fake, st = attach(mv=1800, features_rev=4) # la_pull_1v8: the pod's, at 1.8 V + bp, fake, st = attach(mv=1800) # the pod's pull-ups at 1.8 V too assert st.pullups == "pod" and fake.pullups == {1, 2} diff --git a/packages/embeddedci/tests/test_feature_map.py b/packages/embeddedci/tests/test_feature_map.py index ea4dbfa..1e907df 100644 --- a/packages/embeddedci/tests/test_feature_map.py +++ b/packages/embeddedci/tests/test_feature_map.py @@ -1,5 +1,5 @@ """The features table (feature_map.json, benchpod-firmware's features/features.json): what a pod -that sends features_rev can do, and that it matches what the caps list said before.""" +that sends features_rev can do.""" from __future__ import annotations @@ -14,41 +14,21 @@ from embeddedci.benchpod.capabilities import Capabilities from embeddedci.benchpod.client import BenchPod -# A 3.10.10 analog pod on the loop image and gateware 56, as its plain status lists it -# (cloud_caps_emit_list). -LEGACY_LIST = [ - "signal", "gpio", "power", "swd", "uart", "la", "analyzer", "command", "tunnel", "ota", - "la_pins", "power_profile", "capture_b64", "can", "can_fd", "sensors", "sensor_la_trigger", - "usb_net", "usb_net_setting", "lan_tls", "wifi_scan", "pod_current", "adc_low_range", "analog", - "scope", "dac_limits", "calibrate", "cal_dmm", "current_out", "dac", "dac_dc", "dac_replay", - "dac_control_loop", "dac_cotrig", "generate16", "dac_loop_sources", "dac_loop_input_map", - "gpio_read", "capture_trigger", "spi_master", "spi_stream", "uart_frame", "nrst_pin", "usb_cc", -] -TOP = {"version": "3.10.10", "board": "stm32h563", "analog": True, "nrst_pin": True, - "gateware": 56, "sensors_digital": True, "ota_sig": True, "sig_policy_cmd": True, - "lan_policy_cmd": True, "tunnel_max_tier": True, "lease_state": True, "cloud_ca": True, - "cloud_proxy": True} -NEW_FACTS = {"features_rev": 1, "fpga_image": "loop", +# A firmware 4.0 analog pod on the loop image and gateware 56. +TOP = {"version": "4.0.0", "board": "stm32h563", "analog": True, "nrst_pin": True, + "gateware": 56, "sensors_digital": True, "api": 2, "min_client_api": 2} +NEW_FACTS = {"features_rev": 10, "fpga_image": "loop", "hw": ["wifi", "usb_cc", "pod_current", "adc_low_range"]} -# Flags the old list never carried (frame only, or not at all) that the table now gives. -TABLE_ONLY = {"blob_slots", "ws_auth_v2"} - -def _flags(c: Capabilities) -> Dict[str, bool]: - return {k: v for k, v in vars(c).items() if isinstance(v, bool)} - - -def test_table_matches_the_old_list(): - old = Capabilities.from_status({**TOP, "caps": LEGACY_LIST}) - new = Capabilities.from_status({**TOP, **NEW_FACTS}) - assert old.features_rev == 0 and new.features_rev == 1 - lost = sorted(k for k, v in _flags(old).items() if v and not getattr(new, k)) - gained = sorted(k for k, v in _flags(new).items() if v and not getattr(old, k)) - assert lost == [], f"the table lost {lost}" - assert set(gained) <= TABLE_ONLY, f"the table gave more than expected: {gained}" - assert new.fpga_image == "loop" - assert {"la_dir", "i2c_master", "diag", "wiring_store", "error_codes"} <= new.features +def test_the_table_gives_the_flags(): + c = Capabilities.from_status({**TOP, **NEW_FACTS}) + assert c.features_rev == 10 and c.fpga_image == "loop" + assert c.scope and c.dac and c.dac_control_loop and c.serial and c.analyzer and c.ota + assert c.capture_b64 and c.gpio_read and c.spi_master and c.uart_frame and c.can_fd + assert c.usb_cc and c.pod_current and c.adc_low_range and c.nrst_pin and c.sensors_digital + assert {"la_dir", "i2c_master", "diag", "wiring_store", "error_codes", "json_names_4", + "generate_volts_only", "can_start_stop", "la_step_pull_split"} <= c.features def test_image_and_gateware_decide(): @@ -81,11 +61,12 @@ def test_rev_above_the_pod(monkeypatch): def test_has_names_without_a_flag(): - new = Capabilities.from_status({**TOP, **NEW_FACTS, "version": "3.10.10"}) + new = Capabilities.from_status({**TOP, **NEW_FACTS}) assert new.has("la_dir") and new.has("diag") and new.has("can_fd") and not new.has("nope") - old = Capabilities.from_status({**TOP, "version": "3.10.3", "gateware": 54, "caps": ["la"]}) - assert not old.has("la_dir") and not old.has("i2c_master") - assert Capabilities.from_status({**TOP, "version": "3.10.4", "caps": []}).has("la_dir") + assert new.has("serial") and new.has("uart") + # A status without the table (firmware 3.x, which the SDK refuses) gives nothing. + old = Capabilities.from_status({"version": "3.10.4", "gateware": 54, "caps": ["la"]}) + assert not old.has("la_dir") and not old.has("i2c_master") and not old.has("la") def test_first_firmware(): @@ -94,26 +75,18 @@ def test_first_firmware(): class _Pod: - """A LAN pod: answers status with or without the caps list.""" + """A LAN pod with firmware 4.0.""" - def __init__(self, new_firmware: bool) -> None: - self.new = new_firmware + def __init__(self) -> None: self.requests: List[dict] = [] self.timeout = 30.0 def status(self) -> Dict[str, Any]: return self.command({"cmd": "status"}) - def status_without_caps(self) -> Dict[str, Any]: - return self.command({"cmd": "status", "caps": False}) - def command(self, req: dict) -> Any: self.requests.append(req) - if req["cmd"] != "status": - return {} - if self.new and req.get("caps") is False: - return {**TOP, **NEW_FACTS} - return {**TOP, "caps": LEGACY_LIST} # old firmware ignores "caps" + return {**TOP, **NEW_FACTS} if req["cmd"] == "status" else {} def ping(self) -> Any: return "pong" @@ -122,13 +95,12 @@ def close(self) -> None: pass -@pytest.mark.parametrize("new_firmware", [True, False]) -def test_client_asks_without_the_list(new_firmware): - pod = _Pod(new_firmware) +def test_client_reads_the_table(): + pod = _Pod() bp = BenchPod(transport=pod, lease=False, api_key="", api_base="") assert bp.supports("uart_frame") and bp.supports("spi_master") - assert {"cmd": "status", "caps": False} in pod.requests - assert bp.capabilities.features_rev == (1 if new_firmware else 0) + assert {"cmd": "status"} in pod.requests and not [r for r in pod.requests if "caps" in r] + assert bp.capabilities.features_rev == 10 assert bp.supports("la_dir") diff --git a/packages/embeddedci/tests/test_generate16.py b/packages/embeddedci/tests/test_generate16.py index 591a40e..83cbe43 100644 --- a/packages/embeddedci/tests/test_generate16.py +++ b/packages/embeddedci/tests/test_generate16.py @@ -1,7 +1,9 @@ -"""generate() on firmware 3.9.1+ (Capabilities.generate16): the calibrated 16-bit form. +"""generate(): the calibrated 16-bit form, the only one firmware 4.0 takes. The pod gets volts (or microamps on the 4-20 mA output) and converts them with its own per-path -calibration, so the SDK sends the values, not 8-bit levels, and lets the pod route the output. +calibration, so the SDK sends the values (``amplitude_v``/``offset_v`` with ``path``, or +``amplitude_ua``/``offset_ua``), ``freq_hz`` and ``sample_rate_hz`` in hertz, and lets the pod +route the output. """ from __future__ import annotations @@ -25,7 +27,7 @@ def command(self, req): if req.get("cmd") == "current_out": return {"min_ua": 4055, "max_ua": 20094} if req.get("cmd") == "generate": - return {"bits": 16} if "generate16" in self.caps else None + return {"cotrig": True} if req.get("on_capture") else None return {} def close(self): @@ -42,16 +44,27 @@ def test_volts_are_sent_and_the_pod_routes(monkeypatch): bp, t = _pod(monkeypatch, ["analog", "dac", "generate16"]) assert bp.capabilities.generate16 h = bp.generate("sine", freq_hz=1000, amplitude=0.004, offset=1.65, dac_path="3v3") - assert t.commands == [{"cmd": "generate", "waveform": "sine", "freq": 1000.0, "path": "3v3", + assert t.commands == [{"cmd": "generate", "waveform": "sine", "freq_hz": 1000, "path": "3v3", "amplitude_v": 0.004, "offset_v": 1.65}] - assert h.data == {"bits": 16} + assert h.data == {} and not h.cotrig + + +def test_sample_rate_goes_in_hertz(monkeypatch): + bp, t = _pod(monkeypatch, ["generate16"]) + bp.generate("sine", freq_hz=100000, amplitude=1, offset=1.65, dac_path="3v3", + sample_rate_hz=1e6) + assert t.commands[-1] == {"cmd": "generate", "waveform": "sine", "freq_hz": 100000, + "path": "3v3", "amplitude_v": 1.0, "offset_v": 1.65, + "sample_rate_hz": 1000000} + bp.generate("sine", freq_hz=12.5, amplitude=1, offset=1.65, dac_path="3v3") + assert t.commands[-1]["freq_hz"] == 12.5 def test_route_false_and_on_capture(monkeypatch): bp, t = _pod(monkeypatch, ["generate16"]) bp.generate("sawtooth", freq_hz=100, amplitude=0.05, offset=2.5, dac_path="5v", route=False, on_capture=True, duration=0.5) - assert t.commands[-1] == {"cmd": "generate", "waveform": "sawtooth", "freq": 100.0, "path": "5v", + assert t.commands[-1] == {"cmd": "generate", "waveform": "sawtooth", "freq_hz": 100, "path": "5v", "amplitude_v": 0.05, "offset_v": 2.5, "duration_ms": 500, "on_capture": True, "route": False} @@ -72,15 +85,7 @@ def test_peaks_past_the_path_are_refused_not_clipped(monkeypatch): assert not [c for c in t.commands if c["cmd"] == "generate"] -def test_older_firmware_keeps_the_8bit_levels(monkeypatch): - bp, t = _pod(monkeypatch, ["analog", "dac"]) - assert not bp.capabilities.generate16 - bp.generate("sine", freq_hz=10, amplitude=1.0, offset=2.5, dac_path="5v") - gen = t.commands[-1] - assert gen["amplitude"] == 51 and gen["offset"] == 128 and "amplitude_v" not in gen - - -def test_cloud_parameters(): - assert Capabilities.from_parameters({"cap.generate_bits": "16"}).generate16 - assert not Capabilities.from_parameters({"cap.generate_bits": "8"}).generate16 +def test_every_analog_pod_has_it(): + assert Capabilities.from_parameters({"cap.features_rev": "10"}).generate16 + assert not Capabilities.from_parameters({"cap.features_rev": "10", "cap.analog": "false"}).generate16 assert not Capabilities.from_parameters({}).generate16 diff --git a/packages/embeddedci/tests/test_gpio.py b/packages/embeddedci/tests/test_gpio.py index 8b261c4..2d97fa8 100644 --- a/packages/embeddedci/tests/test_gpio.py +++ b/packages/embeddedci/tests/test_gpio.py @@ -36,7 +36,8 @@ def __init__(self, *, caps: Optional[List[str]] = None) -> None: # -- transport surface -- def status(self) -> Dict[str, Any]: - return {"board": "stm32h563", "adc_bits": 16, "version": "0.4.0", "caps": self.caps} + return {"board": "stm32h563", "adc_bits": 16, "version": "0.4.0", "caps": self.caps, + "gateware": 59 if "gpio_read" in self.caps else 34} def ping(self) -> Any: return "pong" @@ -58,7 +59,7 @@ def command(self, req: dict) -> Any: return {"pins": [self._entry(la) for la in range(1, 15)], "levels": self._levels()} if cmd == "gpio": return self._gpio(req) - if cmd == "la": + if cmd == "la_step": return {"la": req["la"], "steps": req.get("steps"), "status": "started"} return {} @@ -205,7 +206,7 @@ def test_signals_by_name_with_active_low(): pod.inputs = 1 << 9 assert ready.read() == 1 and bp.wait_for_level("READY", 1, timeout=0) reset.pulse(0.002, count=3) - assert pod.commands[-1] == {"cmd": "la", "la": 9, "steps": 3, "delay_us": 2000} + assert pod.commands[-1] == {"cmd": "la_step", "la": 9, "steps": 3, "delay_us": 2000} def test_wait_for_level_times_out(): @@ -223,13 +224,6 @@ def test_pin_levels_fall_back_to_a_capture_without_gpio_read(): assert levels[9] == 1 and levels[1] == 0 and not any(c["cmd"] == "gpio" for c in pod.commands) -def test_gpio_needs_firmware_that_has_it(): - bp, pod = _bp(PinPod(caps=["la"])) - with pytest.raises(BenchPodError, match="la_pins.*firmware 0.4.0"): - bp.gpio(9) - assert pod.commands == [] - - def test_error_classification(): plain = FirmwareError("la voltage not set", cmd="gpio") assert classify_firmware_error(plain) is plain diff --git a/packages/embeddedci/tests/test_image_switching.py b/packages/embeddedci/tests/test_image_switching.py index 544c206..5822591 100644 --- a/packages/embeddedci/tests/test_image_switching.py +++ b/packages/embeddedci/tests/test_image_switching.py @@ -281,7 +281,7 @@ def test_runs_on_the_loop_image(benchpod): assert benchpod.capabilities.dac_control_loop -@pytest.mark.benchpod_capability("dac_cotrig") +@pytest.mark.benchpod_capability("adc_low_range") def test_a_missing_feature_still_skips(benchpod): pass """) diff --git a/packages/embeddedci/tests/test_motor_emulator.py b/packages/embeddedci/tests/test_motor_emulator.py index 6379286..ca479ef 100644 --- a/packages/embeddedci/tests/test_motor_emulator.py +++ b/packages/embeddedci/tests/test_motor_emulator.py @@ -71,8 +71,10 @@ class EmuPod: PROGRAMN, DONE = 9, 10 - def __init__(self, *, boards: Optional[Dict[int, Board]] = None, caps: Optional[List[str]] = None) -> None: + def __init__(self, *, boards: Optional[Dict[int, Board]] = None, caps: Optional[List[str]] = None, + gateware: int = 59) -> None: self.caps = ["la", "la_pins", "gpio_read", "spi_master", "spi_stream"] if caps is None else caps + self.gateware = gateware self.boards = {0: Board()} if boards is None else boards self.commands: List[dict] = [] self.armed: Optional[dict] = None @@ -87,7 +89,8 @@ def __init__(self, *, boards: Optional[Dict[int, Board]] = None, caps: Optional[ # -- transport surface def status(self) -> Dict[str, Any]: - return {"board": "stm32h563", "adc_bits": 16, "version": "3.4.0", "caps": self.caps} + return {"board": "stm32h563", "adc_bits": 16, "version": "3.4.0", "caps": self.caps, + "gateware": self.gateware} def ping(self) -> Any: return "pong" @@ -403,7 +406,7 @@ def test_open_motor_emulator_checks(pod): bp, fake = pod with pytest.raises(ValueError): bp.open_motor_emulator(hz=8_000_000) - bp2 = BenchPod(transport=EmuPod(caps=["la", "la_pins"]), wiring=WIRING) + bp2 = BenchPod(transport=EmuPod(caps=["la", "la_pins"], gateware=44), wiring=WIRING) with pytest.raises(BenchPodError): bp2.open_motor_emulator() @@ -432,8 +435,9 @@ def command(req): def test_capability(): - assert Capabilities.from_status({"caps": ["spi_master", "spi_stream"]}).spi_stream - assert Capabilities.from_parameters({"cap.spi_stream": "true"}).spi_stream + assert Capabilities.from_status({"features_rev": 10, "gateware": 45}).spi_stream + assert not Capabilities.from_status({"features_rev": 10, "gateware": 44}).spi_stream + assert Capabilities.from_parameters({"cap.features_rev": "10", "cap.gateware": "59"}).spi_stream def test_configure_from_a_file_and_input_checks(pod, tmp_path): diff --git a/packages/embeddedci/tests/test_pin_directions.py b/packages/embeddedci/tests/test_pin_directions.py index 4519e35..034c152 100644 --- a/packages/embeddedci/tests/test_pin_directions.py +++ b/packages/embeddedci/tests/test_pin_directions.py @@ -11,17 +11,6 @@ from test_i2c_master import BusPod -class OldPod(BusPod): - def __init__(self, version: str) -> None: - super().__init__() - self.version = version - - def status(self): - st = super().status() - st["version"] = self.version - return st - - def _sent(fake): return [c for c in fake.commands if c["cmd"] == "la_dir"] @@ -83,15 +72,6 @@ def test_connect_sends_the_wiring_directions(): bp.signal("READY").configure("output") -@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.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 - - def test_a_new_profile_is_sent_and_moves_marks(): fake = BusPod() bp = BenchPod(transport=fake, wiring=Wiring.preset()) diff --git a/packages/embeddedci/tests/test_pod_lease.py b/packages/embeddedci/tests/test_pod_lease.py index 575a108..c5bc3c1 100644 --- a/packages/embeddedci/tests/test_pod_lease.py +++ b/packages/embeddedci/tests/test_pod_lease.py @@ -26,7 +26,7 @@ class LeasePod: """A JSON/TCP pod with one RAM lease. Every connection reads lines until the client closes.""" - def __init__(self, features_rev: int = 5, knows_lease: bool = True) -> None: + def __init__(self, features_rev: int = 10, knows_lease: bool = True) -> None: self.features_rev = features_rev self.knows_lease = knows_lease self.lease: Optional[Dict[str, Any]] = None # id, holder, purpose, deadline @@ -131,9 +131,10 @@ def _handle(self, n: int, req: Dict[str, Any]) -> Dict[str, Any]: "message": f"lease lost: stopped by {by}"} live = self._live() if cmd == "status": - data: Dict[str, Any] = {"version": "3.10.13", "board": "stm32h563", "gateware": 58, - "features_rev": self.features_rev} - if req.get("caps") is False and self.knows_lease: + data: Dict[str, Any] = {"version": "4.0.0", "board": "stm32h563", "gateware": 58, + "features_rev": self.features_rev, "api": 2, + "min_client_api": 2} + if self.knows_lease: data["local_lease"] = ({"held": True, "holder": self.lease["holder"], "purpose": self.lease["purpose"], "left_s": self._view(n)["left_s"], @@ -337,32 +338,6 @@ def test_a_stopped_runner_lease_fails_the_join(pod, monkeypatch): _open(pod) -def test_no_lease_feature_takes_none(): - p = LeasePod(features_rev=4) - try: - bp = _open(p) - bp.command({"cmd": "gpio"}) - assert not bp.leased and "lease_acquire" not in p.cmds() - assert not any("lease" in r for r in p.log) # no extra key for older firmware - bp.close() - assert "lease_release" not in p.cmds() - finally: - p.close() - - -def test_no_lease_feature_warns_when_a_runner_lease_was_expected(monkeypatch, caplog): - monkeypatch.setenv("BENCHPOD_LEASE", "L-runner") - p = LeasePod(features_rev=4) - try: - with caplog.at_level(logging.WARNING, logger="embeddedci.benchpod"): - bp = _open(p) - assert any("BENCHPOD_LEASE" in r.message for r in caplog.records) - assert "lease_acquire" not in p.cmds() - bp.close() - finally: - p.close() - - def test_pod_that_does_not_know_the_command_takes_none(): p = LeasePod(knows_lease=False) try: diff --git a/packages/embeddedci/tests/test_pull_direction.py b/packages/embeddedci/tests/test_pull_direction.py index 5fa2453..2f548fa 100644 --- a/packages/embeddedci/tests/test_pull_direction.py +++ b/packages/embeddedci/tests/test_pull_direction.py @@ -37,40 +37,27 @@ def close(self) -> None: def command(self, req: dict) -> Any: if req.get("cmd") == "status": return self.status() - assert req["cmd"] == "la", req + assert req["cmd"] == "la_pull", req self.sent.append(req) if "la" not in req: mask = sum(1 << (la - 1) for la, on in self.on.items() if on) - return {"la_pullup_mask": mask, "pullups_available": 1} + return {"la_pullup_mask": mask, "pullups_available": True} la = req["la"] hw = PULL_TABLE.get(la) - if self.features_rev < 3: - if "pull" in req: - raise AssertionError("old firmware got pull") - if not hw: - raise firmware_error("no pull-up on this la", cmd="la") - if "pullup" in req: - self.on[la] = req["pullup"] == "on" - return {"la": la, "pullup": int(self.on.get(la, False)), "ohms": hw.ohms, "pull": hw.default, - "pullups_available": 1} want = req.get("pull") - if want is None and "pullup" in req: - want = (hw.default if hw else "none") if req["pullup"] == "on" else "off" - if want in ("up", "down", "none") and not hw: - raise firmware_error(f"LA{la} has no pull resistor on this board", cmd="la", code="BP0023", - values={"la": la}) + if want in ("up", "down") and not hw: + raise firmware_error("", cmd="la_pull", code="BP0023", values={"la": la}) if want in ("up", "down") and want not in hw.dirs: - raise firmware_error(f"LA{la} supports pull-{hw.default} only on this board", cmd="la", - code="BP0024", values={"la": la, "want": want, "have": hw.default}) + raise firmware_error("", cmd="la_pull", code="BP0024", + values={"la": la, "want": want, "have": hw.default}) if want is not None and hw: self.on[la] = want != "off" on = self.on.get(la, False) - return {"la": la, "pullup": int(on), "ohms": hw.ohms if hw else "", - "pull": hw.default if hw else "none", "state": (hw.default if on else "off") if hw else "off", - "dirs": list(hw.dirs) if hw else [], "pullups_available": 1} + return {"la": la, "state": (hw.default if on else "off") if hw else "off", + "dirs": list(hw.dirs) if hw else [], "pullups_available": True} -def _bp(features_rev: int = 3) -> "tuple[BenchPod, Pod]": +def _bp(features_rev: int = 10) -> "tuple[BenchPod, Pod]": pod = Pod(features_rev) return BenchPod(transport=pod, lease=False, wiring={"version": 2}), pod @@ -79,15 +66,15 @@ def test_new_firmware_gets_the_direction(): bp, pod = _bp(3) assert bp.supports("la_pull_dir") st = bp.set_pull(1, "up") - assert pod.sent[-1] == {"cmd": "la", "la": 1, "pull": "up"} + assert pod.sent[-1] == {"cmd": "la_pull", "la": 1, "pull": "up"} assert isinstance(st, PullState) assert st.enabled and st.state == "up" and st.direction == "up" and st.supported == ("up",) assert st.ohms == "4.7k" st = bp.set_pull(7, "down") - assert pod.sent[-1] == {"cmd": "la", "la": 7, "pull": "down"} and st.state == "down" + assert pod.sent[-1] == {"cmd": "la_pull", "la": 7, "pull": "down"} and st.state == "down" for off in ("off", None, False): st = bp.set_pull(7, off) - assert pod.sent[-1] == {"cmd": "la", "la": 7, "pull": "off"} and st.state == "off" + assert pod.sent[-1] == {"cmd": "la_pull", "la": 7, "pull": "off"} and st.state == "off" assert not st.enabled and st.direction == "down" assert bp.enabled_pulls() == [1] @@ -111,7 +98,7 @@ def test_new_firmware_refusals_carry_the_code(): def test_true_false_and_enabled_still_work(): bp, pod = _bp(3) assert bp.set_pull(8, True).state == "down" # True = the channel's own direction - assert pod.sent[-1] == {"cmd": "la", "la": 8, "pull": "down"} + assert pod.sent[-1] == {"cmd": "la_pull", "la": 8, "pull": "down"} assert bp.set_pull(2, enabled=True).state == "up" assert bp.set_pull(2, enabled=False).state == "off" with pytest.raises(TypeError, match="needs pull"): @@ -130,35 +117,11 @@ def test_shortcuts(): with pytest.raises(PullDirectionError, match="LA3 supports pull-up only"): bp.disable_pulldown(3) bp.disable_pulldown(8) - assert pod.sent[-1] == {"cmd": "la", "la": 8, "pull": "off"} + assert pod.sent[-1] == {"cmd": "la_pull", "la": 8, "pull": "off"} with pytest.raises(PullDirectionError, match="LA7 supports pull-down only"): bp.enable_pullup(7) -def test_old_firmware_falls_back_to_pullup(): - bp, pod = _bp(2) - assert not bp.supports("la_pull_dir") - st = bp.set_pull(3, "up") - assert pod.sent[-1] == {"cmd": "la", "la": 3, "pullup": "on"} - assert st.state == "up" and st.supported == ("up",) and st.ohms == "2.2k" - st = bp.set_pull(3, "off") - assert pod.sent[-1] == {"cmd": "la", "la": 3, "pullup": "off"} and st.state == "off" - bp.set_pull(7, "down") - assert pod.sent[-1] == {"cmd": "la", "la": 7, "pullup": "on"} - n = len(pod.sent) - # the SDK refuses what the old firmware would do wrong (pullup:on on LA7 pulls DOWN) - with pytest.raises(PullDirectionError) as e: - bp.set_pull(7, "up") - assert e.value.code == "BP0024" and e.value.have == "down" - with pytest.raises(PullDirectionError) as e: - bp.set_pull(10, "up") - assert e.value.code == "BP0023" - # LA9-LA14: answered here, old firmware refuses the query - assert bp.set_pull(10, "off").supported == () - assert bp.pull_state(10).state == "off" - assert len(pod.sent) == n - - def test_wiring_pulls_map_and_list(): w = Wiring.from_dict({"version": 2, "pulls": {"1": "up", "2": "UP", "7": "down"}}) assert w.pulls == {1: "up", 2: "up", 7: "down"} diff --git a/packages/embeddedci/tests/test_replay.py b/packages/embeddedci/tests/test_replay.py index 2e6ca9a..8b07b10 100644 --- a/packages/embeddedci/tests/test_replay.py +++ b/packages/embeddedci/tests/test_replay.py @@ -20,7 +20,7 @@ def __init__(self) -> None: self.uploads: List[dict] = [] def status(self): - return {"board": "stm32h563", "adc_bits": 16, "adc_fullscale_mv": 4096} + return {"board": "stm32h563", "adc_bits": 16, "adc_fullscale_mv": 4096, "fpga_image": "deep"} def command(self, req: dict) -> Any: self.commands.append(req) diff --git a/packages/embeddedci/tests/test_runs.py b/packages/embeddedci/tests/test_runs.py index 7b16bc6..461e418 100644 --- a/packages/embeddedci/tests/test_runs.py +++ b/packages/embeddedci/tests/test_runs.py @@ -366,8 +366,8 @@ def test_benchpod_attaches_to_the_active_run(tmp_path): assert active_run() is None assert "can_write" in calls block = run.pod() - assert block == {"name": "benchpod-abc123", "board": "analog-v3", "firmware": "3.10.11", - "gateware": 58, "features_rev": 0, + assert block == {"name": "benchpod-abc123", "board": "analog-v3", "firmware": "4.0.0", + "gateware": 58, "features_rev": 10, "calibration_sha256": sha256_of_json(CALIBRATION), "connection": "lan"} # the calibration read is provenance, not part of the test's calls assert "calibrate" not in calls @@ -487,7 +487,7 @@ def test_plugin_writes_a_run_folder(pytester): inputs = record["inputs"] assert set(inputs) == {"dut_firmware", "tests", "pod", "wiring", "tools", "github"} assert inputs["dut_firmware"]["file"] == "app.elf" and inputs["dut_firmware"]["size"] == 8 - assert inputs["pod"]["firmware"] == "3.10.11" and inputs["pod"]["connection"] == "lan" + assert inputs["pod"]["firmware"] == "4.0.0" and inputs["pod"]["connection"] == "lan" assert set(inputs["tools"]) == {"cli", "sdk", "python", "pytest", "os"} assert set(inputs["github"]) == {"run_id", "run_attempt", "run_url", "workflow", "actor"} assert set(record["health"]) == {"valid", "reasons", "lost_samples", "rate_misses", "busy_retries", @@ -571,7 +571,7 @@ def test_pass(pod, measure): assert set(part["health"]) == {"lost_samples", "rate_misses", "busy_retries", "reconnects", "measurements_dropped", "trace_truncated", "reasons"} assert set(part["tools"]) == {"sdk", "python", "pytest"} - assert part["pod"]["firmware"] == "3.10.11" + assert part["pod"]["firmware"] == "4.0.0" case = part["cases"][0] assert case["step"] == "hil" and case["measurements"][0]["name"] == "v" line = _lines(out / case["trace"])[0] diff --git a/packages/embeddedci/tests/test_sensors.py b/packages/embeddedci/tests/test_sensors.py index 7f780ff..3fc2935 100644 --- a/packages/embeddedci/tests/test_sensors.py +++ b/packages/embeddedci/tests/test_sensors.py @@ -219,19 +219,6 @@ def make_pod(**kw) -> "tuple[BenchPod, FakePod]": return bp, fake -def test_old_firmware_gets_a_clear_error_before_anything_is_sent(): - bp, fake = make_pod(caps=("dac",)) - for call in (lambda: bp.sensors.start("bme280"), lambda: bp.sensors.status(), - lambda: bp.sensors.validate("bme280"), lambda: bp.sensors.stop()): - with pytest.raises(UnsupportedFeatureError) as info: - call() - assert str(info.value) == ("this pod's firmware is too old for sensor emulation; " - "update the firmware") - assert info.value.feature == "sensors" - # Only the pin directions the SDK sends from the wiring on connect. - assert [c for c in fake.commands if c["cmd"] != "la_dir"] == [] - - def test_start_defines_in_chunks_then_starts_with_wired_pins(): bp, fake = make_pod() s = bp.sensors.start("bme280", instance="env", pins={"drdy": "DRDY"}, address=0x77, @@ -296,9 +283,9 @@ def test_handle_drives_set_fault_regs_capture_and_stop(): with pytest.raises(ValueError, match="length is 1..9"): s.regs(0xF7, 10) assert len(s.capture(64)) == 64 - assert fake.commands[-1]["sample_rate_mhz"] == 0.5, "500 kHz by default: the pod's own default is too fast" + assert fake.commands[-1]["sample_rate_hz"] == 500000, "500 kHz by default: the pod's own default is too fast" s.capture(16, sample_rate_hz=2_000_000) - assert fake.commands[-1]["sample_rate_mhz"] == 2.0 + assert fake.commands[-1]["sample_rate_hz"] == 2000000 with pytest.raises(ValueError, match="1..4096"): s.capture(4097) with pytest.raises(ValueError, match="at least one value"): @@ -333,7 +320,7 @@ def test_capture_waits_for_the_dut_on_firmware_with_sensor_la_trigger(): s = bp.sensors.start(MINIMAL, pins={"sda": 2, "scl": 1}) s.capture(64) req = fake.commands[-1] - assert req["trigger"] == "start" and req["timeout_ms"] == 2000 and req["sample_rate_mhz"] == 0.5 + assert req["trigger"] == "start" and req["timeout_ms"] == 2000 and req["sample_rate_hz"] == 500000 s.i2c_transactions(16, timeout_s=0.25) assert fake.commands[-1]["timeout_ms"] == 250 bp.sensors.capture("probe", 16, wait_for_traffic=False) @@ -348,14 +335,6 @@ def test_capture_waits_for_the_dut_on_firmware_with_sensor_la_trigger(): assert isinstance(err, TriggerTimeout) and (err.la, err.edge) == (2, "falling") -def test_capture_on_firmware_without_the_trigger_sends_the_old_request(): - bp, fake = make_pod() - s = bp.sensors.start(MINIMAL, pins={"sda": 2, "scl": 1}) - for wait in (True, False): - s.capture(16, wait_for_traffic=wait) - assert set(fake.commands[-1]) == {"cmd", "instance", "samples", "sample_rate_mhz"} - - def test_capture_of_a_uart_or_spi_sensor_points_at_la_capture(): bp, _ = make_pod() s = bp.sensors.start({"format": 1, "kind": "uart", "name": "gps", "uart": {"baud": 9600}}, diff --git a/packages/embeddedci/tests/test_serial_text_console.py b/packages/embeddedci/tests/test_serial_text_console.py index 6625990..e2c77c1 100644 --- a/packages/embeddedci/tests/test_serial_text_console.py +++ b/packages/embeddedci/tests/test_serial_text_console.py @@ -1,5 +1,6 @@ """The STM32 pod's USB console is a text shell with no JSON mode: the serial transport answers -status / ping / LA voltage / power through text commands and fails fast on everything else.""" +status and ping through text commands (firmware 4.0 keeps only those, and identity, on the +console) and fails fast on everything else.""" from __future__ import annotations @@ -8,14 +9,14 @@ import pytest from embeddedci.benchpod.client import BenchPod -from embeddedci.benchpod.errors import FirmwareError, TransportError +from embeddedci.benchpod.errors import TransportError from embeddedci.benchpod.transport.serial import SerialTransport, parse_text_status STATUS = ( " device : benchpod\r\n" " mac : 02:00:00:42:00:01\r\n" " ip : 192.168.1.215\r\n" - " board : stm32h563 fw v0.3.0-dev rev v2 nrst_pin=no usb_cc=no\r\n" + " board : stm32h563 fw v4.0.0-dev rev v2 nrst_pin=no usb_cc=no\r\n" " fpga : gateware v31 (reachable) status_reg=0x04\r\n" " adc : 16-bit x1, 4096 mV full-scale\r\n" ) @@ -93,7 +94,7 @@ def _transport(**kw) -> SerialTransport: def test_parse_text_status(): s = parse_text_status("status\r\n" + STATUS + "> ") assert s["device"] == "benchpod" and s["board"] == "stm32h563" - assert s["version"] == "0.3.0-dev" and s["board_rev"] == "v2" and s["nrst_pin"] is False + assert s["version"] == "4.0.0-dev" and s["board_rev"] == "v2" and s["nrst_pin"] is False assert s["adc_bits"] == 16 and s["adc_fullscale_mv"] == 4096 and s["gateware"] == 31 @@ -111,28 +112,23 @@ def test_parse_text_status_boot_health(): assert clean["safe_mode"] is False and clean["safe_reason"] == "" -def test_status_ping_and_la_voltage_over_the_text_console(): +def test_status_and_ping_over_the_text_console(): t = _transport() assert t.status()["board"] == "stm32h563" assert t.json_supported is False assert t.ping() == "pong" - bp = BenchPod(transport=t, la_voltage=3.3) - assert bp.get_la_voltage().voltage == 3.3 + bp = BenchPod(transport=t, la_voltage=None) assert bp.capabilities.adc_bits == 16 -def test_la_voltage_refusal_is_a_firmware_error(): - bp = BenchPod(transport=_transport(), la_voltage=None) - with pytest.raises(FirmwareError, match="v3 pod"): - bp.set_la_voltage(1.8) - - -def test_power_uses_the_power_verb(): +def test_la_voltage_and_power_need_the_network(): t = _transport() - t.target_power(1, True) - assert t._port.lines[-1] == "power 1 on" - with pytest.raises(TransportError, match="delayed"): - t.target_power(1, True, delay_ms=500) + bp = BenchPod(transport=t, la_voltage=None) + with pytest.raises(TransportError, match="'usb'"): + bp.set_la_voltage(3.3) + with pytest.raises(TransportError, match="USB network"): + t.target_power(1, True) + assert not [ln for ln in t._port.lines if ln.startswith(("la-voltage", "power"))] def test_json_only_features_fail_fast_with_a_hint(): @@ -155,15 +151,6 @@ def test_flash_and_uart_proxy_fail_fast_with_a_hint(): assert time.monotonic() - start < 3 -def test_trimmed_console_points_at_the_usb_network(): - """Firmware 3.9.0 moved la-voltage and power off the console to the JSON API.""" - bp = BenchPod(transport=_transport(trimmed=True), la_voltage=None) - with pytest.raises(TransportError, match="'usb'"): - bp.get_la_voltage() - with pytest.raises(TransportError, match="USB network"): - bp.transport.target_power(1, True) - - def test_no_json_mode_probe(): """The console is a text shell: opening it never sends the old `json` mode switch.""" t = _transport() diff --git a/packages/embeddedci/tests/test_spi.py b/packages/embeddedci/tests/test_spi.py index faaf4b8..9d25992 100644 --- a/packages/embeddedci/tests/test_spi.py +++ b/packages/embeddedci/tests/test_spi.py @@ -114,7 +114,7 @@ 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.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) + bp = BenchPod(transport=SpiPod(gateware=44), 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.preset().with_changes(spi_sclk=7, spi_mosi=8, spi_miso=9, spi_cs=10)) @@ -220,7 +220,7 @@ def test_spi_flash_refuses_an_image_larger_than_the_part(pod): bp.spi_flash(bytes(4096), (1 << 20) - 100) -def test_capability_flag_parses_from_status_caps(): +def test_capability_flag_follows_the_gateware(): bp = BenchPod(transport=SpiPod()) assert bp.capabilities.spi_master - assert not BenchPod(transport=SpiPod(caps=["la"])).capabilities.spi_master + assert not BenchPod(transport=SpiPod(gateware=44)).capabilities.spi_master diff --git a/packages/embeddedci/tests/test_status_diag.py b/packages/embeddedci/tests/test_status_diag.py index 891c6e9..85d3827 100644 --- a/packages/embeddedci/tests/test_status_diag.py +++ b/packages/embeddedci/tests/test_status_diag.py @@ -91,16 +91,6 @@ def test_diag_reads_the_diag_command(): pod.close() -def test_diag_on_older_firmware_reads_status(): - old = dict(FULL, version="3.10.8", stacks={"hw": 7000}, lwip_mem_max=100) - pod = FakePod([old], has_diag=False) - try: - d = _bp(pod).diag() - assert d["stacks"] == {"hw": 7000} and d["lwip_mem_max"] == 100 and "version" not in d - finally: - pod.close() - - def test_short_status_once_is_read_again(caplog): """A busy send buffer can make one status the short form: the second read is whole, so the calibration is the pod's and nothing is logged.""" @@ -119,6 +109,6 @@ def test_short_status_over_lan_warns(caplog): try: with caplog.at_level(logging.WARNING): _bp(pod).capabilities - assert "short status over the network" in caplog.text and "3.10.9" in caplog.text + assert "short status over the network" in caplog.text finally: pod.close() diff --git a/packages/embeddedci/tests/test_trigger_power.py b/packages/embeddedci/tests/test_trigger_power.py index 2a5e8c0..9178767 100644 --- a/packages/embeddedci/tests/test_trigger_power.py +++ b/packages/embeddedci/tests/test_trigger_power.py @@ -26,9 +26,10 @@ def __init__(self, caps: Optional[List[str]] = None) -> None: self.requests: List[dict] = [] self.chunks: Dict[str, List[dict]] = {} self.error: Optional[str] = None + self.gateware = 59 def status(self) -> Dict[str, Any]: - return {"board": "stm32h563", "adc_bits": 16, "caps": self.caps} + return {"board": "stm32h563", "adc_bits": 16, "caps": self.caps, "gateware": self.gateware} def ping(self) -> Any: return "pong" @@ -104,8 +105,10 @@ def test_trigger_timeout_and_bounds(): bp.capture_la(8, trigger=Trigger(9), trigger_timeout=0) -def test_triggers_need_firmware_that_has_them(): - bp, pod = _bp(StreamPod(caps=["la"])) +def test_triggers_need_gateware_that_has_them(): + pod = StreamPod(caps=["la"]) + pod.gateware = 34 # capture triggers: gateware v35 + bp, pod = _bp(pod) with pytest.raises(BenchPodError, match="capture_trigger"): bp.capture_la(8, trigger=Trigger(9)) assert pod.requests == [] diff --git a/packages/embeddedci/tests/test_uart_frame.py b/packages/embeddedci/tests/test_uart_frame.py index 83d3ea2..3066cd4 100644 --- a/packages/embeddedci/tests/test_uart_frame.py +++ b/packages/embeddedci/tests/test_uart_frame.py @@ -26,8 +26,10 @@ def __init__(self, caps: List[str], version: str = "3.10.8") -> None: self.starts: List[Dict[str, Any]] = [] def status(self) -> Dict[str, Any]: + gw = 57 if "uart_hd" in self.caps else 56 if "uart_frame" in self.caps else 55 return {"board": "stm32h563", "adc_bits": 16, "version": self.version, "caps": self.caps, - "la_voltage": 3.3, "gateware": 56 if "uart_frame" in self.caps else 55} + "la_voltage": 3.3, "gateware": gw, + **({"nrst_pin": True} if "nrst_pin" in self.caps else {})} def ping(self) -> Any: return "pong" @@ -82,12 +84,12 @@ def test_parity_and_stop_bits_reach_the_transport(): ] -def test_old_firmware_is_refused_before_anything_is_sent(): - bp, pod = _bp(["la_pins"], "3.10.7") +def test_old_gateware_is_refused_before_anything_is_sent(): + bp, pod = _bp(["la_pins"], "4.0.0") with pytest.raises(UnsupportedFeatureError) as info: bp.open_uart(rx=5, tx=4, baud=19200, parity="even") msg = str(info.value) - assert "UART parity and stop bits need firmware 3.10.8+" in msg and "3.10.7" in msg + assert "UART parity and stop bits need gateware v56" in msg and "4.0.0" in msg assert info.value.feature == "uart_frame" with pytest.raises(UnsupportedFeatureError): bp.capture_uart(rx=5, tx=4, baud=19200, duration=0.1, stop_bits=2) diff --git a/packages/embeddedci/tests/test_unsupported_feature.py b/packages/embeddedci/tests/test_unsupported_feature.py index fd99ea0..2bf2487 100644 --- a/packages/embeddedci/tests/test_unsupported_feature.py +++ b/packages/embeddedci/tests/test_unsupported_feature.py @@ -21,13 +21,18 @@ class CapsPod: """A pod that only answers status, with the given capability names.""" - def __init__(self, caps: List[str], *, analog: Optional[bool] = None) -> None: + def __init__(self, caps: List[str], *, analog: Optional[bool] = None, gateware: int = 59, + hw: Optional[List[str]] = None) -> None: self.caps = caps self.analog = analog + self.gateware = gateware + self.hw = ["usb_cc"] if hw is None else hw self.commands: List[dict] = [] def status(self) -> Dict[str, Any]: - st: Dict[str, Any] = {"board": "stm32h563", "adc_bits": 16, "version": "3.1.0", "caps": self.caps} + st: Dict[str, Any] = {"board": "stm32h563", "adc_bits": 16, "version": "4.0.0", "api": 2, + "min_client_api": 2, "features_rev": 10, "gateware": self.gateware, + "fpga_image": "loop", "hw": self.hw, "nrst_pin": "nrst_pin" in self.caps} if self.analog is not None: st["analog"] = self.analog return st @@ -39,6 +44,8 @@ def close(self) -> None: pass def command(self, req: dict) -> Any: + if req["cmd"] in ("wiring_list", "la_dir"): # the connect's own + return {} self.commands.append(req) raise AssertionError(f"nothing should reach the pod: {req}") @@ -64,13 +71,13 @@ def test_other_refusals_are_not_unsupported(): def test_a_missing_capability_raises_before_sending(): - pod = CapsPod(["la"]) + pod = CapsPod(["la"], gateware=44) # SPI master needs gateware v45 bp = BenchPod(transport=pod, lease=False) with pytest.raises(UnsupportedFeatureError) as info: - bp.gpio(9) + bp.open_spi(sck=1, mosi=2, miso=3, cs=4) err = info.value - assert err.feature == "la_pins" and err.firmware_version == "3.1.0" - assert "'la_pins' capability is missing" in str(err) + assert err.feature == "spi_master" and err.firmware_version == "4.0.0" + assert "'spi_master' capability is missing" in str(err) assert isinstance(err, BenchPodError) # what it was before assert pod.commands == [] @@ -82,15 +89,16 @@ def test_can_properties_follow_the_capabilities(): assert full.can_calibrate and full.can_current_out and full.can_reset_target and full.can_analog assert full.supports("can") and full.supports("spi_master") - bare = BenchPod(transport=CapsPod([]), lease=False) - assert not any((bare.can_gpio, bare.can_trigger, bare.can_spi, bare.can_profile_power, - bare.can_calibrate, bare.can_current_out, bare.can_reset_target)) - assert not bare.supports("can") and not bare.supports("no_such_flag") + bare = BenchPod(transport=CapsPod([], analog=False, gateware=34), lease=False) + assert not any((bare.can_trigger, bare.can_spi, bare.can_calibrate, bare.can_current_out, + bare.can_reset_target)) + assert bare.can_gpio and bare.can_profile_power and bare.supports("can") + assert not bare.supports("no_such_flag") def test_can_analog_is_false_only_on_the_digital_board(): assert BenchPod(transport=CapsPod([], analog=True), lease=False).can_analog - assert BenchPod(transport=CapsPod([]), lease=False).can_analog # older firmware: analog boards + assert BenchPod(transport=CapsPod([]), lease=False).can_analog # no analog flag: analog assert not BenchPod(transport=CapsPod([], analog=False), lease=False).can_analog @@ -102,9 +110,6 @@ def test_digital_board_names_the_missing_front_end_not_old_firmware(call): call(pod) assert err.value.feature == "analog" and "newer" not in str(err.value) assert pod._transport.commands == [] - # Older firmware on an analog board still gets the update hint. - with pytest.raises(UnsupportedFeatureError, match="newer pod firmware"): - call(BenchPod(transport=CapsPod([]), lease=False)) @pytest.mark.parametrize("analog,outcome", [(True, "passed"), (None, "passed"), (False, "skipped")], diff --git a/packages/embeddedci/tests/test_usb_net.py b/packages/embeddedci/tests/test_usb_net.py index 74c73e4..9ff800a 100644 --- a/packages/embeddedci/tests/test_usb_net.py +++ b/packages/embeddedci/tests/test_usb_net.py @@ -32,12 +32,12 @@ def test_parse_usb_line_net_on(): s = parse_text_status("status\r\n" + STATUS + f" usb : {USB_ON}\r\n> ") - assert s["usb"] == {"net": "on", "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"} + assert s["usb"] == {"net": True, "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"} def test_parse_usb_line_wifi_configured(): assert parse_usb_status_line(USB_WIFI) == { - "net": "off", "link": False, "ip": "10.237.8.85", "host_ip": "10.237.8.86"} + "net": False, "link": False, "ip": "10.237.8.85", "host_ip": "10.237.8.86"} def test_parse_usb_line_from_older_firmware_is_left_alone(): @@ -48,11 +48,11 @@ def test_parse_usb_line_from_older_firmware_is_left_alone(): @pytest.mark.parametrize("status, want", [ - ({"usb": {"net": "on", "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"}}, "10.237.8.85"), - ({"usb": {"net": "off", "link": False, "ip": "10.237.8.85"}}, None), - ({"usb": {"net": "on", "link": False, "ip": "10.237.8.85"}}, None), - ({"usb": {"net": "on", "link": True, "ip": "0.0.0.0"}}, None), - ({"usb": {"net": "on", "link": True, "ip": "garbage"}}, None), + ({"usb": {"net": True, "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"}}, "10.237.8.85"), + ({"usb": {"net": False, "link": False, "ip": "10.237.8.85"}}, None), + ({"usb": {"net": True, "link": False, "ip": "10.237.8.85"}}, None), + ({"usb": {"net": True, "link": True, "ip": "0.0.0.0"}}, None), + ({"usb": {"net": True, "link": True, "ip": "garbage"}}, None), ({"usb": "cdc acm"}, None), ({"device": "benchpod"}, None), ("not a dict", None), @@ -141,7 +141,7 @@ def test_usb_name_selects_the_pod_and_upgrades(usb): def test_serial_keyword_also_upgrades(usb): usb["status"] = {"device": "benchpod", - "usb": {"net": "on", "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"}} + "usb": {"net": True, "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"}} assert isinstance(open_transport(parse_connection("serial")), TcpTransport) diff --git a/packages/embeddedci/tests/test_wiring_profiles.py b/packages/embeddedci/tests/test_wiring_profiles.py index bd6bb09..709609e 100644 --- a/packages/embeddedci/tests/test_wiring_profiles.py +++ b/packages/embeddedci/tests/test_wiring_profiles.py @@ -10,7 +10,7 @@ import pytest from embeddedci.benchpod import BenchPod, Wiring -from embeddedci.benchpod.errors import FirmwareError, UnsupportedFeatureError, WiringError, firmware_error +from embeddedci.benchpod.errors import FirmwareError, WiringError, firmware_error class ProfilePod: @@ -81,6 +81,11 @@ def command(self, req: dict) -> Any: self._fail("BP0013", "cannot delete the default profile", verb, name=name) del self.profiles[name] return {"name": name, "deleted": True} + if verb == "la_pull" and "la" in req: + on = req.get("pull", "off") != "off" + d = "down" if req["la"] in (7, 8) else "up" + return {"la": req["la"], "ohms": "4.7k", "state": d if on else "off", "dirs": [d], + "pullups_available": True} if verb == "la_voltage": if "mv" in req: self.la_mv = req["mv"] @@ -194,65 +199,30 @@ def test_power_on_with_nothing_wired_needs_a_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() - - def test_power_on_sets_the_profiles_pull_resistors(): pod = ProfilePod({"nrf": {**NRF, "pulls": [2, 1]}}, default="nrf") bp = BenchPod(transport=pod, lease=False) assert bp.wiring.pulls == (1, 2) bp.power_on() - sets = {c["la"]: c["pullup"] for c in pod.sent("la")} - assert sets == {1: "on", 2: "on", 3: "off", 4: "off", 5: "off", 6: "off", 7: "off", 8: "off"} + sets = {c["la"]: c["pull"] for c in pod.sent("la_pull")} + assert sets == {1: "up", 2: "up", 3: "off", 4: "off", 5: "off", 6: "off", 7: "off", 8: "off"} # Sent before the rail goes on. order = [c["cmd"] for c in pod.commands] - assert order.index("target_power") > max(i for i, c in enumerate(order) if c == "la") + assert order.index("target_power") > max(i for i, c in enumerate(order) if c == "la_pull") -def test_power_on_leaves_the_pulls_without_the_key_or_at_1v8(): - pod = ProfilePod({"nrf": NRF, "k66": {**K66, "pulls": [1]}}, default="nrf") +def test_power_on_leaves_the_pulls_without_the_key(): + pod = ProfilePod({"nrf": NRF}, default="nrf") bp = BenchPod(transport=pod, lease=False) bp.power_on() - bp.power_off() - bp.power_off(efuse=2) - pod.rails[1] = False - bp.power_on(wiring_profile="k66") - assert pod.sent("la") == [] - - -class PullsAt1v8Pod(ProfilePod): - """Firmware with la_pull_1v8 (features revision 4): pulls work with the bank at 1.8 V.""" - - def status(self) -> Dict[str, Any]: - return {"board": "stm32h563", "adc_bits": 16, "version": "3.10.13", "features_rev": 4, - "gateware": 58, "fpga_image": "deep", "hw": ["nrst_pin"]} - - def command(self, req: dict) -> Any: - if req["cmd"] == "la" and "la" in req: - self.commands.append(req) - on = req.get("pull", "off") != "off" - d = "down" if req["la"] in (7, 8) else "up" - return {"la": req["la"], "pullup": int(on), "ohms": "4.7k", "pull": d, - "state": d if on else "off", "dirs": [d], "pullups_available": 1} - return super().command(req) + assert pod.sent("la_pull") == [] -def test_power_on_applies_the_pulls_at_1v8_on_firmware_that_has_them(): - pod = PullsAt1v8Pod({"k66": {**K66, "pulls": [1]}}, default="k66") +def test_power_on_applies_the_pulls_at_1v8(): + pod = ProfilePod({"k66": {**K66, "pulls": [1]}}, default="k66") bp = BenchPod(transport=pod, lease=False) bp.power_on() - sets = {c["la"]: c["pull"] for c in pod.sent("la")} + sets = {c["la"]: c["pull"] for c in pod.sent("la_pull")} assert sets == {1: "up", 2: "off", 3: "off", 4: "off", 5: "off", 6: "off", 7: "off", 8: "off"} @@ -264,7 +234,7 @@ def test_pulls_key(): Wiring(pulls=[9]) assert not Wiring(i2c_sda=7, pulls=[]).warnings() assert Wiring(i2c_sda=7, pulls=[7]).warnings() - assert any("newer than 3.10.12" in x for x in Wiring(la_mv=1800, pulls=[1]).warnings()) + assert not Wiring(la_mv=1800, pulls=[1]).warnings() def test_connect_sets_the_io_voltage_from_the_pods_profile(): From 813462656ca3d18ff0976cea8c0bcf0b527d3de4 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 22:27:11 -0600 Subject: [PATCH 02/10] Refusals by error code only: every catalog code has a class Firmware 4.0 sends a code and its args with no message (BP0030 alone keeps one). The SDK and the MCP server never read a refusal's text any more: the text patterns, the raw-command rewrites, the la voltage text, status_too_large and la_pins_too_large are gone, and the client's i2c busy, reply too large, no module link and unknown sensor instance checks, and the cloud's device busy retry, use the codes. Every code BP0001 to BP0080 maps to an exception class with fields from its args (new ReplyTooLargeError, DacPinoutMismatchError; PinConflictError gets owner and instance); messages come from the catalog (fix.sdk, MCP fix.mcp). A refusal without a code keeps its text as it is. Error catalog synced (BP0080 dac_pinout_mismatch). ModuleInfo has dac_pinout_ok; the MCP status warns when it is false. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 5 + .../src/embeddedci_mcp/guide.py | 2 +- .../src/embeddedci_mcp/server.py | 95 +- packages/embeddedci-mcp/tests/conftest.py | 38 +- .../tests/test_bus_master_tools.py | 16 +- .../embeddedci-mcp/tests/test_gpio_tools.py | 14 +- .../embeddedci-mcp/tests/test_refusals.py | 145 ++-- packages/embeddedci-mcp/tests/test_tools.py | 13 +- .../tests/test_trigger_power_tools.py | 4 +- packages/embeddedci-openhtf/tests/_fake.py | 8 +- packages/embeddedci/CHANGELOG.md | 14 +- packages/embeddedci/README.md | 70 +- .../src/embeddedci/benchpod/__init__.py | 4 + .../src/embeddedci/benchpod/client.py | 21 +- .../embeddedci/benchpod/error_catalog.json | 814 +++++++++++++++++- .../src/embeddedci/benchpod/errors.py | 400 ++++----- .../src/embeddedci/benchpod/protocol.py | 9 +- .../embeddedci/benchpod/sensors/emulation.py | 3 +- .../src/embeddedci/benchpod/state.py | 9 +- .../embeddedci/benchpod/transport/cloud.py | 14 +- packages/embeddedci/tests/api_surface.json | 9 +- packages/embeddedci/tests/test_cloud.py | 17 +- .../embeddedci/tests/test_digital_v3r4.py | 7 +- packages/embeddedci/tests/test_error_codes.py | 233 +++-- packages/embeddedci/tests/test_gpio.py | 34 +- packages/embeddedci/tests/test_header.py | 4 +- packages/embeddedci/tests/test_i2c_master.py | 43 +- .../embeddedci/tests/test_image_switching.py | 19 +- packages/embeddedci/tests/test_module.py | 6 + .../embeddedci/tests/test_pin_directions.py | 4 +- .../embeddedci/tests/test_refusal_errors.py | 139 +-- packages/embeddedci/tests/test_sensors.py | 12 +- .../embeddedci/tests/test_trigger_power.py | 7 +- .../tests/test_unsupported_feature.py | 24 +- 34 files changed, 1427 insertions(+), 829 deletions(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index 493d819..e7fb0f3 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -9,6 +9,11 @@ Pairs with BenchPod firmware 4.0.0 and embeddedci 4.0. Breaking changes: (`benchpod flash-self` or the web app). The instructions say so too. - `generate` returns no `bits` (the pod always plays 16 bits). - A serial device path (the USB console) supports `status` only. +- **Refusals by code only.** Every coded refusal is rendered from the catalog with its MCP fix + (`fix.mcp`, naming this server's tools); the text rewrites of raw protocol commands are gone. A + refusal without a code keeps the pod's text. +- `status` warns when `module.dac_pinout_ok` is false: the DAC is off because the digital board + and the analog module do not belong together (`BP0080`). ## 3.0.6 diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index 7caedde..fca1f19 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -16,7 +16,7 @@ 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. ClientTooOldError means this MCP server is older than the pod's firmware: tell the user to update embeddedci-mcp (uvx embeddedci-mcp@latest, pip install -U embeddedci-mcp, or the benchpod plugin), then reconnect; retrying will not help. 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. +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 PinConflictError BP0031 ("LA4 is in use by gpio; free LA4 first: gpio_release(la=[4]) ..."): the error names the tools that free the channel (gpio_release, uart_close, sensor_stop); la_pins shows every channel's owner. Captures observe all 14 channels whatever owns them. More GPIOs: expansion(chip, addr, sda, scl) attaches an I2C/SPI expander breakout (tca9555, mcp23017, pcf8574, 74hc595, ...; expansion() lists them) on 2-5 LA channels and names its pins EXT1..EXTn. gpio_mode, gpio_write, gpio_read, gpio_wait and gpio_release then take 'EXTn' (or names given with names=) next to LA channels; each call is a bus transaction (milliseconds), so gpio_pulse, triggers and la_dir refuse EXT pins. expansion(detach=true) puts every EXT pin back to input. diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index 53f8892..c8db003 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -72,7 +72,7 @@ from embeddedci.benchpod.connection import CLOUD_PREFIX from embeddedci.benchpod import errors as _errors from embeddedci.benchpod import protocol as _protocol -from embeddedci.benchpod.errors import STATUS_FITS_FIRMWARE, FirmwareError, status_too_large +from embeddedci.benchpod.errors import FirmwareError from embeddedci.benchpod.errors import BenchPodError from embeddedci.benchpod.server_api import ServerApi @@ -159,72 +159,6 @@ def isa(name: str) -> bool: return "" -#: The firmware's "la voltage not set; ..." (any firmware version). -_LA_VOLTAGE_UNSET = "la voltage not set" -_LA_VOLTAGE_MCP = ("la voltage not set; the wiring profile sets no I/O voltage: ask the user " - "for the board's (1.8 or 3.3, 5.0 on a digital v3r4 pod), set it in the profile (set_wiring with la_mv " - "1800 or 3300, then save_wiring) or call set_la_voltage") - -#: Fixes the firmware spells as raw protocol commands (la_pins.c release_hint, the pull and -#: gpio-output checks, command_handler_dap.c, command_handler_dac.c), named as this server's -#: tools. Whole phrases first; anything not listed passes through unchanged. Kept here rather -#: than taken from the SDK so the text is the same with every supported embeddedci release. -_MCP_FIXES = ( - (re.compile(r'release it with \{"cmd":"gpio","la":(\d+),"mode":"off"\}'), - r"release it with gpio_release(la=[\1])"), - (re.compile(r"stop the uart proxy first"), - "close the UART session first with uart_close"), - (re.compile(r"end the SWD session first"), - "wait for the running flash (its SWD session) to finish"), - (re.compile(r'\{"cmd":"sensor_stop","all":true\} then \{"cmd":"fpga_image","image":"(loop|deep)"\}'), - lambda m: 'sensor_stop() then fpga_image(image="' - + ("loop" if m.group(1) == "loop" else "deep_replay") + '")'), - (re.compile(r'stop them first \(\{"cmd":"sensor_stop","all":true\}\)'), "stop them first with sensor_stop"), - (re.compile(r'\{"cmd":"sensor_stop","instance":"([a-z0-9_]+)"\}'), r'sensor_stop(instance="\1")'), - (re.compile(r'stop the sensor emulation first \(\{"cmd":"sensor_stop"(?:,"all":true)?\}\)'), - "stop the sensor emulation first with sensor_stop"), - (re.compile(r'stop the SPI session first \(\{"cmd":"spi_stop"\}\)'), - 'stop the SPI session first: another client holds it (the command tool can send ' - '{"cmd":"spi_stop"})'), - (re.compile(r'\(\{"cmd":"spi_stop"\}\)'), - '(another client holds the SPI session; the command tool can send {"cmd":"spi_stop"})'), - (re.compile(r'stop the I2C session first \(\{"cmd":"i2c_stop"\}\)'), - "close the I2C session first with i2c_close"), - (re.compile(r"send i2c_stop first"), "call i2c_close first"), - (re.compile(r"send i2c_start first"), "call i2c_open first"), - (re.compile(r"i2c_start again"), "call i2c_open again"), - (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup":"on|pull":"up)"\}'), r'set_pull(las=[\1], pull="up")'), - (re.compile(r'\{"cmd":"la","la":(\d+),"pull":"down"\}'), r'set_pull(las=[\1], pull="down")'), - (re.compile(r'pass "pullups":"external"'), 'pass pullups="external"'), - (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup|pull)":"off"\}'), r'set_pull(las=[\1], pull="off")'), - (re.compile(r'\{"cmd":"gpio","la":(\d+),"mode":"output"\}'), r'gpio_mode(la=[\1], mode="output")'), - (re.compile(r'\{"cmd":"fpga_image","image":0\}'), 'fpga_image(image="loop")'), - (re.compile(r'\{"cmd":"dac_loop_input"\}'), "loop_input"), -) - - -def _mcp_refusal_text(message: str) -> str: - """A pod refusal with its protocol-level fix named as this server's tool, or unchanged.""" - if message.startswith(_LA_VOLTAGE_UNSET): - return _LA_VOLTAGE_MCP - for pattern, repl in _MCP_FIXES: - message = pattern.sub(repl, message) - return message - - -def _error_text(exc: BenchPodError) -> str: - """``str(exc)``, with a firmware refusal's fix rewritten from the pod's own text (the SDK's - message names SDK calls; an agent here needs the tool names).""" - original = getattr(exc, "firmware_message", None) - if not isinstance(exc, _errors.FirmwareError) or not isinstance(original, str): - return str(exc) - text = _mcp_refusal_text(original) - if text == original: - return str(exc) - cmd = getattr(exc, "cmd", None) - return f"{cmd}: {text}" if cmd else text - - #: How to update this server, for a pod whose firmware is newer than it handles. _MCP_UPDATE = ("update embeddedci-mcp: uvx embeddedci-mcp@latest or pip install -U embeddedci-mcp, " "or update the benchpod plugin; then reconnect") @@ -269,7 +203,8 @@ def _client_too_old_text(exc: BenchPodError) -> Optional[str]: def _coded_text(exc: BenchPodError) -> Optional[str]: - """A refusal with a stable error code, rendered with the catalog's fix for an agent.""" + """A refusal with a stable error code, rendered from the catalog with its fix for an agent + (``fix.mcp``, naming this server's tools). The pod sends no text with a code.""" from embeddedci.benchpod.errors import error_catalog code = getattr(exc, "code", "") entry = error_catalog().get("codes", {}).get(code) if code else None @@ -278,9 +213,6 @@ def _coded_text(exc: BenchPodError) -> Optional[str]: 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) - if code == "BP0001": # this server's own text, as for firmware without codes - text = f"{code}: {_LA_VOLTAGE_MCP} (docs: {exc.docs_url})" - return f"{cmd}: {text}" if cmd else text text = f"{code}: {fill(entry['message'])}; {fill(entry['fix']['mcp'])} (docs: {exc.docs_url})" return f"{cmd}: {text}" if cmd else text @@ -306,7 +238,7 @@ 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)}" + msg = f"{type(exc).__name__}: {exc}" hint = _refusal_hint(exc) return ToolError(f"{msg}. {hint}" if hint else msg) @@ -443,16 +375,15 @@ def _status() -> m.StatusResult: try: firmware = pod.status() except FirmwareError as exc: - # Firmware 3.10.4's status can be too large for the cloud channel. The connection works: - # report the status as unknown with the fix, rather than failing the connect. - if not status_too_large(exc.firmware_message, exc.cmd): + # A status too large for the cloud channel (BP0054): the connection works, so report the + # status as unknown rather than failing. + if exc.code != "BP0054": raise firmware = {} - warnings.append(f"this pod's status is too large for the cloud channel (firmware " - f"{pod.capabilities.firmware_version or 'older'}): update the pod to firmware " - f"{STATUS_FITS_FIRMWARE} or later; the status fields are unknown until then") + warnings.append("this pod's status is too large for the cloud channel; the status fields " + "are unknown") if isinstance(firmware, dict) and firmware.get("short_form") and "lan_tls" not in firmware: - # The cloud status is the short form (firmware 3.10.5+): lan_tls is its own command there. + # The cloud status is the short form: lan_tls is its own command there. try: tls = pod.lan_tls() firmware["lan_tls"] = {"port": tls.port, "https_only": tls.https_only, "sha256": tls.sha256} @@ -462,6 +393,12 @@ def _status() -> m.StatusResult: boot = Capabilities.from_status(firmware).boot_warning() if boot: warnings.append(boot) + module = firmware.get("module") if isinstance(firmware, dict) else None + if isinstance(module, dict) and module.get("dac_pinout_ok") is False: + warnings.append("DAC off: the digital board and the analog module use different flat-cable " + "pinouts (module.dac_pinout_ok is false), so every DAC command is refused " + "(BP0080). Tell the user the two boards do not belong together: a digital " + "v3r4 or later board needs an analog module 3.5 or later") try: la = pod.get_la_voltage().voltage except BenchPodError: diff --git a/packages/embeddedci-mcp/tests/conftest.py b/packages/embeddedci-mcp/tests/conftest.py index a8053bb..40715b8 100644 --- a/packages/embeddedci-mcp/tests/conftest.py +++ b/packages/embeddedci-mcp/tests/conftest.py @@ -14,7 +14,7 @@ from embeddedci.benchpod import Wiring, BenchPod from embeddedci.benchpod.constants import PULL_TABLE -from embeddedci.benchpod.errors import FirmwareError +from embeddedci.benchpod.errors import FirmwareError, firmware_error from embeddedci.benchpod.transport.base import Transport import embeddedci_mcp.session as session_mod @@ -94,7 +94,7 @@ def __init__(self) -> None: #: Levels the "DUT" drives on channels the pod is not driving (bitmask, bit la-1). self.inputs = 0 #: Set to a firmware message to make the next streamed capture / power profile fail with it. - self.error: Optional[str] = None + self.error: Any = None self.power_profile_running = False #: The I2C master session (i2c_start) and the DUT directions (la_dir). self.i2c: Optional[Dict[str, Any]] = None @@ -154,7 +154,7 @@ def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", st self.function[la] = "none" for la in (rx, tx): if self.function[la] != "none": - raise FirmwareError(self._conflict(la), cmd="uart_proxy_start") + raise self._conflict(la, "uart_proxy_start") if half_duplex: self.function[rx] = "uart_hd" else: @@ -241,7 +241,7 @@ def _cmd_sensor_set(self, req): def _sensor(self, req): if req["instance"] not in self.sensors: - raise FirmwareError(f"unknown sensor instance '{req['instance']}'", cmd=req["cmd"]) + raise firmware_error("", cmd=req["cmd"], code="BP0055", values={"instance": req["instance"]}) return self.sensors[req["instance"]] def _cmd_sensor_fault(self, req): @@ -313,11 +313,11 @@ def _cmd_la_pull(self, req): "dirs": list(hw.dirs) if hw else [], "pullups_available": True} # -- LA pin ownership + GPIO (the firmware's la_pins / gpio contract) -- - def _conflict(self, la: int) -> str: + def _conflict(self, la: int, cmd: str) -> FirmwareError: + """The firmware's BP0031 (la_pin_in_use): a code and args, no text.""" fn = self.function[la] - how = (f'release it with {{"cmd":"gpio","la":{la},"mode":"off"}}' if fn == "gpio" - else "stop the uart proxy first") - return f"pin conflict: LA{la} is in use by {fn}; {how}" + return firmware_error("", cmd=cmd, code="BP0031", + values={"la": la, "owner": fn, "function": fn, "instance": ""}) def _pin(self, la: int) -> Dict[str, Any]: pull = None @@ -333,7 +333,7 @@ def _pin(self, la: int) -> Dict[str, Any]: # -- bus master (i2c_*, spi_start, la_dir) -- def _cmd_i2c_start(self, req): if self.i2c is not None: - raise FirmwareError("i2c busy: send i2c_stop first", cmd="i2c_start") + raise firmware_error("", cmd="i2c_start", code="BP0003") self.i2c = req self.function[req["sda"]], self.function[req["scl"]] = "i2cm_sda", "i2cm_scl" return {"sda": req["sda"], "scl": req["scl"], "hz": req["hz"], "pullups": req["pullups"]} @@ -346,7 +346,7 @@ def _cmd_i2c_stop(self, req): def _i2c_xfer(self, addr, write, read): if self.i2c is None: - raise FirmwareError("no I2C session: send i2c_start first", cmd="i2c_xfer") + raise firmware_error("", cmd="i2c_xfer", code="BP0062") if addr == 0x20: # a TCA9555 expander: input 0-1, output 2-3, polarity 4-5, config 6-7 if not hasattr(self, "tca"): self.tca, self.tca_ptr, self.tca_in = [0, 0, 0, 0, 0, 0, 0xFF, 0xFF], 0, 0 @@ -377,7 +377,7 @@ def _cmd_i2c_xfer(self, req): def _cmd_i2c_scan(self, req): if self.i2c is None: - raise FirmwareError("no I2C session: send i2c_start first", cmd="i2c_scan") + raise firmware_error("", cmd="i2c_scan", code="BP0062") return {"from": req.get("from", 8), "to": req.get("to", 119), "found": [0x76]} def _cmd_spi_start(self, req): @@ -424,12 +424,11 @@ def _cmd_gpio(self, req): if mode is not None: for la in las: # validate everything before changing anything if self.function[la] not in ("none", "gpio"): - raise FirmwareError(self._conflict(la), cmd="gpio") + raise self._conflict(la, "gpio") if mode == "open_drain" and la in (7, 8) and self.pull_on[la]: - raise FirmwareError( - f"pull conflict: LA{la} has its 10k pull-down engaged, which gpio open_drain " - "can't work with (a released line would read low); disable it with " - f'{{"cmd":"la","la":{la},"pullup":"off"}} or use another channel', cmd="gpio") + raise firmware_error("", cmd="gpio", code="BP0032", values={ + "la": la, "ohms": "10k", "function": "gpio open_drain", + "reason": "a released line would read low"}) for la in las: self.function[la], self.mode[la] = "gpio", mode self.level[la] = (None if mode == "input" @@ -437,9 +436,8 @@ def _cmd_gpio(self, req): return {"pins": [self._pin(la) for la in las]} for la in las: if self.mode[la] not in ("output", "open_drain"): - raise FirmwareError( - f"LA{la} is not a gpio output (function {self.function[la]}); configure it with " - f'{{"cmd":"gpio","la":{la},"mode":"output"}}', cmd="gpio") + raise firmware_error("", cmd="gpio", code="BP0036", + values={"la": la, "function": self.function[la]}) self.level[la] = req["level"] return {"pins": [self._pin(la) for la in las]} @@ -591,6 +589,8 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: self.requests.append(req) cmd = req["cmd"] if self.error: + if isinstance(self.error, tuple): # a coded refusal: (code, args) + raise firmware_error("", cmd=cmd, code=self.error[0], values=self.error[1]) raise FirmwareError(self.error, cmd=cmd) if cmd == "power_profile": self.power_profile_running = False diff --git a/packages/embeddedci-mcp/tests/test_bus_master_tools.py b/packages/embeddedci-mcp/tests/test_bus_master_tools.py index 2386a56..2350d70 100644 --- a/packages/embeddedci-mcp/tests/test_bus_master_tools.py +++ b/packages/embeddedci-mcp/tests/test_bus_master_tools.py @@ -37,15 +37,13 @@ def test_i2c_open_replaces_the_open_session(connected): assert connected.i2c["sda"] == 3 -def test_i2c_refusals_name_the_tools(): - from embeddedci_mcp.server import _mcp_refusal_text - - assert "i2c_close" in _mcp_refusal_text( - 'pin conflict: LA1 is in use by i2cm_sda; stop the I2C session first ({"cmd":"i2c_stop"})') - assert _mcp_refusal_text("no I2C session: send i2c_start first").endswith("call i2c_open first") - text = _mcp_refusal_text('I2C needs pull-ups: switch on LA1\'s with {"cmd":"la","la":1,"pullup":"on"}, ' - 'or pass "pullups":"external"') - assert 'set_pull(las=[1], pull="up")' in text and 'pullups="external"' in text +def test_i2c_refusals_name_the_tools(connected): + with pytest.raises(ToolError, match=r"no I2C session is open: call i2c_open first"): + call("i2c_scan") + call("i2c_open", sda=1, scl=2) + connected.i2c = None # the pod lost the session (an engine reset) + with pytest.raises(ToolError, match=r"BP0062: No I2C session is open; call i2c_open first"): + call("i2c_scan") def test_la_dir_sets_lists_and_follows_the_wiring(connected): diff --git a/packages/embeddedci-mcp/tests/test_gpio_tools.py b/packages/embeddedci-mcp/tests/test_gpio_tools.py index 4634b28..01250c9 100644 --- a/packages/embeddedci-mcp/tests/test_gpio_tools.py +++ b/packages/embeddedci-mcp/tests/test_gpio_tools.py @@ -71,7 +71,7 @@ def test_gpio_write_and_read_round_trip(connected): def test_gpio_write_on_an_unconfigured_channel_is_refused(connected): - with pytest.raises(ToolError, match="is not a gpio output"): + with pytest.raises(ToolError, match="BP0036: LA6 is not a GPIO output"): call("gpio_write", la=[6], level=1) @@ -106,24 +106,24 @@ def test_gpio_pulse_runs_a_step_train(connected): def test_pin_conflict_names_the_owner_and_how_to_free_it(connected): call("uart_open", rx=5, tx=4) - with pytest.raises(ToolError, match="PinConflictError: gpio: pin conflict: LA5 is in use by uart_rx; " - "close the UART session first with uart_close"): + with pytest.raises(ToolError, match="PinConflictError: gpio: BP0031: LA5 is in use by uart_rx; " + "free LA5 first: .*uart_close"): call("gpio_mode", la=[5]) call("uart_close") def test_a_gpio_channel_blocks_the_uart_until_it_is_released(connected): call("gpio_mode", la=[5], mode="output") - with pytest.raises(ToolError, match=r"PinConflictError:.*LA5 is in use by gpio; " - r"release it with gpio_release\(la=\[5\]\)$"): + with pytest.raises(ToolError, match=r"PinConflictError:.*BP0031: LA5 is in use by gpio; " + r"free LA5 first: gpio_release\(la=\[5\]\)"): call("uart_open", rx=5, tx=4) call("gpio_release", la=[5]) assert call("uart_open", rx=5, tx=4)["open"] is True def test_pull_conflict_reaches_the_agent(connected): - call("set_pull", las=[7], enabled=True) - with pytest.raises(ToolError, match="PullConflictError: .*pull-down engaged"): + call("set_pull", las=[7], pull="down") + with pytest.raises(ToolError, match="PullConflictError: .*BP0032: LA7 has its 10k pull-down on"): call("gpio_mode", la=[7], mode="open_drain") diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index 43c4b8e..e65a62c 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -15,114 +15,93 @@ FirmwareError, firmware_error = errors.FirmwareError, errors.firmware_error -def _refuse(transport, cmd, message): +def _refuse(transport, verb, code, **args): + """The pod refuses ``verb`` the way firmware 4.0 does: a code and its args, no message.""" real = transport.command def command(req): - if req["cmd"] == cmd: - raise firmware_error(message, cmd=cmd) + if req["cmd"] == verb: + raise firmware_error("", cmd=verb, code=code, values=args) return real(req) transport.command = command -def test_leased_names_the_holder_and_the_time_left(connected): - _refuse(connected, "la_step", "busy: a cloud job holds this pod (octo/ci run 9, 12 s left)") +def _pulse_error() -> str: with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) - msg = str(info.value) - assert "PodLeasedError: la_step: busy: a cloud job holds this pod (octo/ci run 9, 12 s left)" in msg - assert msg.endswith("Wait for that job to finish and retry; reads such as status still work " - "meanwhile.") + return str(info.value) -def test_locked_says_to_use_the_cloud_or_usb(connected): - _refuse(connected, "la_step", "locked: la needs the cloud or the USB console") - with pytest.raises(ToolError, match=r"PodLockedError: .*connect with 'embeddedci:'"): - call("gpio_pulse", la=3, width=0.001, count=5) +def test_leased_names_the_holder_and_the_time_left(connected): + _refuse(connected, "la_step", "BP0025", holder="octo/ci run 9", purpose="hil", left_s=12) + msg = _pulse_error() + assert "PodLeasedError: la_step: BP0025: octo/ci run 9 holds this pod (hil, 12 s left)" in msg -def test_forbidden_says_who_may(connected): - _refuse(connected, "la_step", "forbidden: la needs an organization owner or admin") - with pytest.raises(ToolError, match=r"PermissionDeniedError: .*benchpod:admin scope"): - call("gpio_pulse", la=3, width=0.001, count=5) +def test_locked_says_to_use_the_cloud_or_usb(connected): + _refuse(connected, "la_step", "BP0040", cmd="la_step") + assert "PodLockedError: la_step: BP0040: The pod's LAN is locked: la_step needs the cloud or USB" in _pulse_error() -needs_unsupported = pytest.mark.skipif(not hasattr(errors, "UnsupportedFeatureError"), - reason="needs UnsupportedFeatureError (embeddedci after 2.7.0)") +def test_forbidden_says_who_may(connected): + _refuse(connected, "la_step", "BP0045", cmd="la_step") + assert "PermissionDeniedError: la_step: BP0045: la_step needs an organization owner or admin" in _pulse_error() -@needs_unsupported def test_unknown_command_says_the_firmware_lacks_it(connected): - _refuse(connected, "la_step", "unknown cmd") - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - msg = str(info.value) - assert "UnsupportedFeatureError: la_step: unknown cmd" in msg - assert "firmware or gateware lacks the feature" in msg and "retrying will not help" in msg + _refuse(connected, "la_step", "BP0002", cmd="la_step") + msg = _pulse_error() + assert "UnsupportedFeatureError: la_step: BP0002: " in msg and "la_step" in msg -@needs_unsupported def test_digital_board_says_it_has_no_analog(connected): - # The hint goes by the refusal's text, whichever command drew it. - _refuse(connected, "la_step", "this BenchPod has no analog front end (digital board): no DAC, ADC or " - "analog outputs. Restart the pod after fitting an analog add-on") - with pytest.raises(ToolError, match=r"UnsupportedFeatureError: .*digital-only board"): - call("gpio_pulse", la=3, width=0.001, count=5) + _refuse(connected, "la_step", "BP0046", cmd="la_step") + assert "UnsupportedFeatureError: la_step: BP0046: This BenchPod has no analog front end" in _pulse_error() -def test_other_firmware_errors_have_no_hint(connected): +def test_free_text_refusals_keep_their_text(connected): def command(req): - raise FirmwareError("unknown target", cmd=req["cmd"]) + raise FirmwareError("missing steps", cmd=req["cmd"]) connected.command = command - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - assert str(info.value).endswith("FirmwareError: la_step: unknown target") + assert _pulse_error().endswith("FirmwareError: la_step: missing steps") -# -- the firmware's protocol-level fixes, named as tools --------------------------------------- -# Texts: benchpod-firmware stm32h563/src/command_handler.c (require_la_voltage) and la_pins.c. - def test_la_voltage_not_set_names_set_la_voltage(connected): - _refuse(connected, "la_step", "la voltage not set; set it with la_voltage (mv 1800 or 3300) first") - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - assert str(info.value).endswith("FirmwareError: la_step: la voltage not set; the wiring profile sets no " - "I/O voltage: ask the user for the board's (1.8 or 3.3, 5.0 on a digital v3r4 pod), set it in " - "the profile (set_wiring with la_mv 1800 or 3300, then save_wiring) " - "or call set_la_voltage") - - -@pytest.mark.parametrize("function, hint, fix", [ - ("gpio", 'release it with {"cmd":"gpio","la":3,"mode":"off"}', "release it with gpio_release(la=[3])"), - ("uart_rx", "stop the uart proxy first", "close the UART session first with uart_close"), - ("swd_dio", "end the SWD session first", "wait for the running flash (its SWD session) to finish"), - ("i2c_scl", 'stop the sensor emulation first ({"cmd":"sensor_stop"})', - "stop the sensor emulation first with sensor_stop"), - ("sensor:env", 'stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})', - 'stop the sensor emulation first (sensor_stop(instance="env"))'), - ("spi_cs", 'stop the SPI session first ({"cmd":"spi_stop"})', - 'stop the SPI session first: another client holds it (the command tool can send {"cmd":"spi_stop"})'), - ("step", "wait for the step train to finish", "wait for the step train to finish"), - ("can_rx", 'stop it with {"cmd":"can_stop"}', 'stop it with {"cmd":"can_stop"}'), # unknown: as is -]) -def test_pin_conflict_names_the_tool(connected, function, hint, fix): - _refuse(connected, "la_step", f"pin conflict: LA3 is in use by {function}; {hint}") - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - assert str(info.value).endswith( - f"PinConflictError: la_step: pin conflict: LA3 is in use by {function}; {fix}") + _refuse(connected, "la_step", "BP0001") + msg = _pulse_error() + assert "FirmwareError: la_step: BP0001: The I/O voltage is not set; " in msg + assert "set_la_voltage" in msg + + +def test_pin_conflict_names_the_tool(connected): + _refuse(connected, "la_step", "BP0031", la=3, owner="gpio", function="gpio", instance="") + msg = _pulse_error() + assert "PinConflictError: la_step: BP0031: LA3 is in use by gpio; free LA3 first: gpio_release(la=[3])" in msg def test_pull_conflict_names_set_pull(connected): - _refuse(connected, "la_step", "pull conflict: LA7 has its 10k pull-down engaged, which gpio open_drain " - "can't work with (a released line would read low); disable it with " - '{"cmd":"la","la":7,"pullup":"off"} or use another channel') - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - assert "PullConflictError: la_step: pull conflict: LA7" in str(info.value) - assert str(info.value).endswith('disable it with set_pull(las=[7], pull="off") or use another channel') + _refuse(connected, "la_step", "BP0032", la=7, ohms="10k", function="gpio open_drain", + reason="a released line would read low") + msg = _pulse_error() + assert "PullConflictError: la_step: BP0032: LA7 has its 10k pull-down on" in msg + assert 'set_pull(las=[7], pull="off")' in msg + + +def test_dac_pinout_mismatch(connected): + _refuse(connected, "la_step", "BP0080", cmd="dac_out", digital="v3r4+", module="3.4") + msg = _pulse_error() + assert "DacPinoutMismatchError: la_step: BP0080: dac_out refused, the DAC is off" in msg + assert "the digital board and the analog module do not belong together" in msg + + +def test_status_warns_about_a_dac_pinout_mismatch(connected): + real = connected.status + connected.status = lambda: dict(real(), module={"present": True, "dac_pinout_ok": False}) + assert any("flat-cable pinouts" in w and "BP0080" in w for w in call("status")["warnings"]) + connected.status = lambda: dict(real(), module={"present": True, "dac_pinout_ok": True}) + assert not any("flat-cable" in w for w in call("status")["warnings"]) def test_efuse_rails_are_named_the_same_everywhere(): @@ -152,9 +131,9 @@ def test_status_warns_about_a_cloud_lease_and_a_locked_lan(connected): def test_status_warns_about_a_weak_usb_port(connected): real = connected.status - connected.status = lambda: dict(real(), usb={"net": "on", "link": True, "source": "default", "source_ma": 500}) + connected.status = lambda: dict(real(), usb={"net": True, "link": True, "source": "default", "source_ma": 500}) assert any("default USB power (500 mA)" in w for w in call("status")["warnings"]) - connected.status = lambda: dict(real(), usb={"net": "on", "link": True, "source": "3.0A", "source_ma": 3000}) + connected.status = lambda: dict(real(), usb={"net": True, "link": True, "source": "3.0A", "source_ma": 3000}) assert not any("USB power" in w for w in call("status")["warnings"]) @@ -224,15 +203,3 @@ def command(req): assert "ClientTooOldError: la_step: this BenchPod MCP server" in msg assert "needs client API 2 or newer, this server sent 1" in msg assert "uvx embeddedci-mcp@latest" in msg - - -def test_coded_la_voltage_keeps_this_servers_text(connected): - def command(req): - raise firmware_error("la voltage not set; set la_mv ...", cmd=req["cmd"], code="BP0001") - - connected.command = command - with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) - msg = str(info.value) - assert "la_step: BP0001: la voltage not set; the wiring profile sets no I/O voltage" in msg - assert "call set_la_voltage" in msg diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index 47ddd85..c8a1e52 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -76,7 +76,7 @@ def test_every_tool_is_described_annotated_and_structured(): def test_instructions_carry_the_session_start(): assert mcp.instructions == INSTRUCTIONS for needle in ("connect", "set_la_voltage", "LA7/LA8", "flash runs OpenOCD", - "Call `wiring` first", "gpio_release", "pin conflict", "trigger_la", + "Call `wiring` first", "gpio_release", "PinConflictError", "trigger_la", "measure_power"): assert needle in INSTRUCTIONS @@ -131,16 +131,15 @@ def test_status_warns_about_safe_mode_and_crashes(fake_open, fake_transport, mon def test_status_too_large_for_the_cloud_keeps_the_connection(fake_open, fake_transport, monkeypatch): - # Firmware 3.10.4 over the cloud: its status did not fit the cloud channel and connect failed. - from embeddedci.benchpod.errors import FirmwareError + # A status that does not fit the cloud channel (BP0054): connect still works. + from embeddedci.benchpod.errors import firmware_error def too_large(): - raise FirmwareError("reply too large for the cloud channel (1838 bytes, limit 1791)", - cmd="status") + raise firmware_error("", cmd="status", code="BP0054", values={"bytes": 1838, "limit": 1791}) monkeypatch.setattr(fake_transport, "status", too_large) result = call("connect", connection="192.168.1.50", la_voltage=3.3) assert result["connected"] is True and result["firmware"] == {} - assert any("too large for the cloud channel" in w and "3.10.5" in w for w in result["warnings"]) + assert any("too large for the cloud channel" in w for w in result["warnings"]) def test_short_form_status_gets_lan_tls_from_its_command(fake_open, fake_transport, monkeypatch): @@ -558,7 +557,7 @@ def test_sensor_flow_from_a_library_name_and_inline_yaml(connected): with pytest.raises(ToolError): call("sensor_set", instance="a" * 17, values={"x": 1}) - with pytest.raises(ToolError, match="unknown sensor instance 'nope'"): + with pytest.raises(ToolError, match="BP0055: The pod has no emulated sensor nope"): call("sensor_set", instance="nope", values={"x": 1}) assert call("sensor_stop", instance="probe") == {"stopped": True, "instances": ["probe"]} assert call("sensor_stop") == {"stopped": True, "instances": ["env"]} diff --git a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py index 009f6ef..0cd3ef3 100644 --- a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py +++ b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py @@ -42,8 +42,8 @@ def test_captures_without_a_trigger_are_unchanged(connected): def test_a_trigger_that_never_fires_is_a_tool_error(connected): - connected.error = "trigger timeout: no rising edge on LA9 within 10000 ms" - with pytest.raises(ToolError, match="TriggerTimeout: .*no rising edge on LA9"): + connected.error = ("BP0038", {"la": 9, "edge": "rising", "timeout_ms": 10000}) + with pytest.raises(ToolError, match="TriggerTimeout: .*BP0038: No rising edge on LA9 within 10000 ms"): call("capture_la", samples=100, sample_rate_hz=1e6, trigger_la=9) diff --git a/packages/embeddedci-openhtf/tests/_fake.py b/packages/embeddedci-openhtf/tests/_fake.py index fde3381..4c26164 100644 --- a/packages/embeddedci-openhtf/tests/_fake.py +++ b/packages/embeddedci-openhtf/tests/_fake.py @@ -14,7 +14,7 @@ import threading from typing import Any, Dict, List, Optional -from embeddedci.benchpod.errors import FirmwareError, TransportError +from embeddedci.benchpod.errors import FirmwareError, TransportError, firmware_error from embeddedci.benchpod.transport.base import RawLink, Transport @@ -183,9 +183,9 @@ def _gpio(self, req: dict): elif mode is not None: for la in las: if self.function[la] not in ("none", "gpio"): - raise FirmwareError( - f"pin conflict: LA{la} is in use by {self.function[la]}; " - "stop it first", cmd="gpio") + fn = self.function[la] + raise firmware_error("", cmd="gpio", code="BP0031", values={ + "la": la, "owner": fn, "function": fn, "instance": ""}) for la in las: self.function[la], self.mode[la] = "gpio", mode self.level[la] = (None if mode == "input" diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 131bf84..83b82f0 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -27,7 +27,19 @@ Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: - Pull resistors use `la_pull` and step trains `la_step` (firmware 4.0 split the `la` command). `PullState` reads the 4.0 reply (`state`, `dirs`, `pullups_available` as a boolean); the resistor value comes from the board table, `la_pins` reports it on every board. -- Features table revision 11. +- **Refusals are classified by code only.** Firmware 4.0 sends a code and its args and no text + (`BP0030` alone carries one). Every catalog code (`BP0001` to `BP0080`) maps to an exception + class whose fields come from the args, and the message is the catalog's message and SDK fix. The + text patterns, the raw-command rewrites (`{"cmd":"gpio",...}` to `bp.release_gpio(4)`) and the + `la voltage not set` text are gone; a refusal without a code is a plain `FirmwareError` with the + pod's text, whatever it says. `errors.status_too_large`, `errors.la_pins_too_large` and + `STATUS_FITS_FIRMWARE` are gone. New classes: `ReplyTooLargeError` (`BP0053`, `BP0054`) and + `DacPinoutMismatchError` (`BP0080`, `digital`, `module`). `PinConflictError` has `owner` and + `instance` (`BP0031`). Over the cloud the transport retries on `BP0052` (it matched the text + "device busy"). +- `ModuleInfo.dac_pinout_ok`: `False` when the digital board and the analog module use different + flat-cable DAC pinouts (the DAC is off). +- Error catalog synced (`BP0031` to `BP0080`); features table revision 11. ## 3.0.6 diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 6b605ca..f67d910 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -170,10 +170,9 @@ and firmware 3.10.10+ takes it from the active profile itself on the first LA op profile that sets its I/O voltage needs nothing else. `la_voltage` (1.8 or 3.3) still sets it right after connecting for this session, and `bp.set_la_voltage(3.3)` at any time; `bp.get_la_voltage()` returns a `LaVoltage` whose `voltage` is `None` until one is chosen. 1.8 V needs a rev3 pod. With -no voltage anywhere, a refused command raises `FirmwareError` with the message `la voltage not set; -the wiring profile sets no I/O voltage: set la_mv in it (bp.save_wiring(bp.wiring.with_changes(la_mv=3300)), -1800 for a 1.8 V board), or pass BenchPod(conn, la_voltage=3.3), or call bp.set_la_voltage(3.3)` -(prefixed with the command, as every `FirmwareError` is). +no voltage anywhere, a refused command raises `FirmwareError` with code `BP0001`: `The I/O voltage +is not set; set the board's I/O voltage first: BenchPod(conn, la_voltage=3.3) ...` (prefixed with +the command, as every `FirmwareError` is). **5 V I/O (digital board v3r4).** On a pod with the digital board v3r4 (`bp.supports("la_5v")`, `bp.capabilities.vref_out`), `bp.set_la_voltage(5.0)` (or `la_mv: 5000` in the profile) keeps the @@ -363,10 +362,10 @@ macs = bp.mac_addresses() # MacAddresses(eth_mac='02:35:c7:76:b7:9b', wifi_ ## 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: +When the pod refuses a request it can explain, it sends a stable code and its values, and no text +(firmware 4.0). The SDK puts them on the exception: `FirmwareError.code` (`"BP0009"`), `.values` +(`{"name": "k66", "rev": 2}`) and `.docs_url`, and renders the message from the error catalog it +ships (benchpod-firmware's `errors/errors.json`): 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); @@ -375,27 +374,34 @@ load it again (bp.load_wiring("k66")), redo your change and save, or save under ``` A code never changes meaning and is never reused, so match on `exc.code` (or the exception -class) in tests and scripts, not on the text: the text may change between releases. -`embeddedci.benchpod.errors.explain("BP0009")` prints a code's entry offline. -[embeddedci.com/docs/errors](https://embeddedci.com/docs/errors) lists every code. +class) in tests and scripts, not on the text: the text may change between releases. The SDK itself +never reads a refusal's text. `embeddedci.benchpod.errors.explain("BP0009")` prints a code's entry +offline. [embeddedci.com/docs/errors](https://embeddedci.com/docs/errors) lists every code. The code also picks the exception class, and the code's values fill its fields: | Codes | Class | Fields | |---|---|---| -| `BP0002` unknown command, `BP0017` gateware too old | `UnsupportedFeatureError` | `feature` (the command, or the feature the gateware lacks) | -| `BP0003`, `BP0004` I2C / SPI session open, `BP0005` SWD/SPI/I2C engine busy, `BP0016` storage busy | `PodBusyError` | | +| `BP0002` unknown command, `BP0017` gateware too old, `BP0046` no analog front end, `BP0056` no module link, `BP0058`, `BP0059` not in the running image, `BP0060` unknown update target, `BP0064` sweep with an input map, `BP0076` to `BP0078` USB host | `UnsupportedFeatureError` | `feature` (the command, the feature, `"analog"`, `"module"`, ...) | +| `BP0080` the board and module flat-cable pinouts differ (the DAC is off) | `DacPinoutMismatchError` (an `UnsupportedFeatureError`) | `digital`, `module` | +| `BP0003`, `BP0004`, `BP0049`, `BP0050` an I2C, SPI, UART or SWD session is open, `BP0005` the bus engine is busy, `BP0016`, `BP0048` storage busy, `BP0047` another long command, `BP0051` an update, `BP0052` the previous cloud command, `BP0066` a step train | `PodBusyError` | | | `BP0007` to `BP0015` wiring profiles | `WiringError` | `name` | | `BP0023`, `BP0024` pull resistors | `PullDirectionError` | `la`, `want`, `have` | | `BP0025` lease held by someone else | `PodLeasedError` | `holder`, `purpose`, `left_s` | | `BP0026` lease stopped | `PodLeaseLostError` | `by` | | `BP0030` client too old | `ClientTooOldError` | `client_api`, `min_client_api`, `api` | -| every other code (`BP0001` I/O voltage not set, `BP0006` missing argument, `BP0018` to `BP0022` UART options, `BP0027` lease not held, `BP0028`, `BP0029` pin 21) | `FirmwareError` | | - -Older firmware sends no code (`.code == ""`): the SDK then classifies the refusal from its text into -the same classes. Refusals that have no code yet (pin, pull and direction conflicts, a LAN policy -lock, `forbidden`, a trigger timeout, a reply too large) are classified from their text on every -firmware. A code newer than this SDK is kept on `.code`, and its class comes from the text. +| `BP0031` pin in use | `PinConflictError` | `la`, `function`, `owner`, `instance` | +| `BP0032`, `BP0033` pull-down conflicts | `PullConflictError` | `la` | +| `BP0034`, `BP0035` DUT output conflicts | `DirectionConflictError` | `la` | +| `BP0038`, `BP0039` trigger timeouts | `TriggerTimeout` | `la`, `edge` (`"start"` for `BP0039`) | +| `BP0040` to `BP0044` LAN lock and settings the LAN may not change, `BP0075` plaintext 8080 off | `PodLockedError` | | +| `BP0045` owner or admin only | `PermissionDeniedError` | | +| `BP0053`, `BP0054` reply too large | `ReplyTooLargeError` | | +| every other code (`BP0001` I/O voltage not set, `BP0006` missing argument, UART options, capture limits, ...) | `FirmwareError` | | + +A refusal without a code (an argument the pod checks itself, such as `"missing steps"`) keeps the +pod's text as its message and is a plain `FirmwareError` (`.code == ""`). A code newer than this +SDK is kept on `.code`, with a message that says to update the SDK. ## API conventions and stability @@ -1322,13 +1328,14 @@ silently override the other, and the message names the SDK call that frees the c bp.gpio(4) try: bp.open_uart(rx=3, tx=4) -except PinConflictError as exc: # pin conflict: LA4 is in use by gpio; release it with bp.release_gpio(4) +except PinConflictError as exc: # open_uart: BP0031: LA4 is in use by gpio; free LA4 first: bp.release_gpio(4) ... bp.release_gpio(exc.la) ``` -The other owners point to `bp.sensors.stop("")`, closing the session from -`bp.open_uart()` or `bp.open_spi()`, or waiting for a flash or step train to finish. The pod's own -text, with its raw protocol command, stays in `exc.firmware_message`. +`exc.function` and `exc.owner` say who holds it (`exc.instance` names an emulated sensor); the +message lists the ways to free a channel: `bp.release_gpio(la)`, `bp.sensors.stop("")`, +closing the session from `bp.open_uart()` or `bp.open_spi()`, or waiting for a flash or step train +to finish. `bp.la_pins()` lists every channel's `LaPinState` (`function`, `gpio` mode, `level`, `pull`, `pull_on`, `pull_dirs`); `bp.la_pins(la=[3, 4])` only those channels. A listing too large for one cloud reply (a long @@ -1817,7 +1824,10 @@ bp.set_module_id("am-3f9a1c07b2e4", "3.3") # serial (up to 16 characters) and `ModuleInfo` has the live `present` flag, `analog` (the module is the pod's analog front end), the two rails (`power`, `bridge_power`), the EEPROM state (`eeprom`: `"ok"`, `"blank"`, `"bad magic"`, `"bad crc"`, `"bad length"`, `"none"`), and with `"ok"` the `type`, `rev` and `serial`, plus the stored -calibration blob's `cal_len` and `cal_ok`. `set_module_id(serial, rev, module_type="analog")` writes +calibration blob's `cal_len` and `cal_ok`. `dac_pinout_ok` is `False` when the digital board and +the module use different flat-cable DAC pinouts (a digital v3r4 or later board needs analog module +3.5 or later): the DAC is then off and every command that drives it raises +`DacPinoutMismatchError` (`BP0080`). `set_module_id(serial, rev, module_type="analog")` writes the identity and keeps the calibration. A serial names one module for life: a module that already has another serial is refused unless `replace=True`. The revision (`"3.3"` for analog-v3r3) decides features such as the ADC low range (3.4 and later) after the pod's next restart. Other boards answer @@ -2508,18 +2518,20 @@ Match a pod refusal on its code or class, not its text: see [Error codes](#error | `TransportTimeout` (a `TransportError` and a `TimeoutError`) | the pod or tunnel did not answer in time | | | `ConnectionClosedError` (a `TransportError`) | the connection ended or reset before the reply | | | `TlsPinMismatchError` (a `TransportError`) | the pod's TLS certificate is not the one pinned for it (see [TLS on the LAN](#tls-on-the-lan)) | `addr`, `pinned`, `got` | -| `FirmwareError` | the pod replied with an error (e.g. "la voltage not set"); a fix the firmware spells as a raw protocol command is rewritten into the SDK call in the message, and `firmware_message` keeps the pod's own text | `firmware_message`, `cmd` | +| `FirmwareError` | the pod replied with an error: a coded refusal (see [Error codes](#error-codes)), rendered from the catalog, or a refusal without a code, with the pod's text | `code`, `values`, `docs_url`, `firmware_message` (the pod's text, `""` for a coded refusal), `cmd` | | `FlashError` | OpenOCD failed, is missing, or lacks the TCP backend | | | `TargetUnreachableError` (a `FlashError`) | the probe worked but no target answered on SWD | | | `DeviceBusyError` | a device lease was not granted within `lease_wait` | | | `CloudAuthError` | no session token: API key rejected, OIDC unavailable, exchange failed | | | `ServerApiError` | an embeddedci server API call failed | `status` (HTTP) | -| `PodLockedError` (a `FirmwareError`) | the pod's LAN policy keeps the command for the cloud or the USB console | `firmware_message`, `cmd` | -| `PodBusyError` (a `FirmwareError`) | the pod is busy (`busy: …`), e.g. a capture or upload is running; an I2C or SPI session is already open (`BP0003`, `BP0004`), the engine that runs SWD, SPI and I2C is in use (`BP0005`), the storage cannot save while the DAC or a capture runs (`BP0016`) | `firmware_message`, `cmd` | +| `PodLockedError` (a `FirmwareError`) | the pod's LAN policy keeps the command for the cloud or USB (`BP0040` to `BP0044`), or plaintext 8080 is off on the LAN (`BP0075`) | `code`, `cmd` | +| `PodBusyError` (a `FirmwareError`) | the pod is busy: a session is already open (`BP0003`, `BP0004`, `BP0049`, `BP0050`), the bus engine or the storage is in use (`BP0005`, `BP0016`, `BP0048`), another long command, update or cloud command runs (`BP0047`, `BP0051`, `BP0052`), a step train runs (`BP0066`) | `code`, `cmd` | +| `ReplyTooLargeError` (a `FirmwareError`) | the reply did not fit the pod's reply buffer (`BP0053`) or the cloud channel (`BP0054`) | `code`, `values` | +| `DacPinoutMismatchError` (an `UnsupportedFeatureError`) | the DAC is off: the digital board and the analog module use different flat-cable pinouts (`BP0080`) | `digital`, `module` | | `PodLeasedError` (a `PodBusyError`, `DeviceBusyError` and `TransportError`) | someone else holds the pod's lease (`BP0025`), a cloud job holds the pod (its refusal on the LAN, or the server's HTTP 409), or the lease did not free within `lease_wait` | `holder`, `purpose`, `left_s`, `expires_at`, `status` | | `PodLeaseLostError` (a `FirmwareError`) | the pod's lease this session held was stopped from the web app or the cloud (`BP0026`); the command did not run | `by` | -| `PermissionDeniedError` (a `FirmwareError` and `TransportError`) | the pod's `forbidden: …` on a cloud tunnel, or a server HTTP 403 (`ServerPermissionDeniedError`, also a `ServerApiError`, from `ServerApi`) | `status` | -| `UnsupportedFeatureError` (a `FirmwareError`) | the pod lacks the feature: its capabilities say so (raised before anything is sent), it answers `unknown cmd` (`BP0002`), its gateware is too old (`BP0017`; `feature` names it), or the digital-only board has no analog front end | `feature`, `firmware_version`, `firmware_message`, `cmd` | +| `PermissionDeniedError` (a `FirmwareError` and `TransportError`) | the pod's `BP0045` (owner or admin only) on a cloud tunnel, or a server HTTP 403 (`ServerPermissionDeniedError`, also a `ServerApiError`, from `ServerApi`) | `status` | +| `UnsupportedFeatureError` (a `FirmwareError`) | the pod lacks the feature: its capabilities say so (raised before anything is sent), it does not know the command (`BP0002`), its gateware is too old (`BP0017`; `feature` names it), or the digital-only board has no analog front end (`BP0046`, `feature="analog"`) | `feature`, `firmware_version`, `code`, `cmd` | | `WiringError` (a `FirmwareError`) | a wiring-profile operation was refused (`BP0007` to `BP0015`): no such profile, a bad name, a revision conflict, the store is full, too large, not a JSON object, the default cannot be deleted, an upload out of order, the storage failed | `name`, `code`, `values` | | `ClientTooOldError` (a `FirmwareError`) | this SDK is too old for the pod's firmware: the pod announces a client API level above `CLIENT_API` (raised on connect), or refuses the SDK's level (`BP0030`). Update the SDK: `pip install -U embeddedci` | `client_api`, `api`, `min_client_api`, `firmware_version` | | `FirmwareTooOldError` (an `UnsupportedFeatureError`) | the pod runs firmware 3.x (client API below 2), which this SDK does not drive (raised on connect). Update the pod: `benchpod flash-self`, or the firmware update in the web app; or use embeddedci 3.x with it | `api`, `firmware_version`, `feature` (`"client_api"`) | diff --git a/packages/embeddedci/src/embeddedci/benchpod/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/__init__.py index a595aac..d86064e 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/__init__.py @@ -98,6 +98,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin BenchPodError, CanTimeout, ClientTooOldError, + DacPinoutMismatchError, FirmwareTooOldError, CloudAuthError, ConnectionClosedError, @@ -113,6 +114,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin PodLeaseLostError, PodLockedError, PullConflictError, + ReplyTooLargeError, PullDirectionError, TargetUnreachableError, TlsPinMismatchError, @@ -362,6 +364,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin "PodLeaseLostError", "WiringError", "ClientTooOldError", + "DacPinoutMismatchError", "FirmwareTooOldError", "PermissionDeniedError", "UartTimeout", @@ -369,6 +372,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin "CanTimeout", "PinConflictError", "PullConflictError", + "ReplyTooLargeError", "PullDirectionError", "DirectionConflictError", "TriggerTimeout", diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 6476fd8..7695f3c 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -280,16 +280,14 @@ def _one_or_many(las: List[int]) -> Any: @contextmanager def _classified_errors() -> Iterator[None]: - """Re-raise a pod refusal as its specific error (PinConflictError, PullConflictError, TriggerTimeout).""" + """Re-raise a coded pod refusal that reached here as a plain FirmwareError as its specific + error (PinConflictError, PullConflictError, TriggerTimeout, ...), from its code.""" try: yield except FirmwareError as exc: 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 @@ -648,7 +646,8 @@ def capabilities(self) -> Capabilities: self._check_client_api(caps) return caps self._caps = caps - self._check_client_api(self._caps) + if self._caps.api or self._caps.firmware_version: # nothing to check without a status + self._check_client_api(self._caps) return self._caps def _check_client_api(self, caps: Capabilities) -> None: @@ -2074,11 +2073,9 @@ def board_header(self) -> Optional[str]: try: self.command({"cmd": "module"}) header = "front" - except UnsupportedFeatureError: - header = None except BenchPodError as e: - # No code yet ("no module link"): firmware PR 2 of the codes plan. - header = "j1" if "no module link" in str(e).lower() else None + # BP0056: a digital board without the module link, so its header is J1. + header = "j1" if getattr(e, "code", "") == "BP0056" else None if header is None: try: header = header_from_status(self.status()) @@ -2535,8 +2532,7 @@ def _start_i2c(self, sda: int, scl: int, *, hz: int, pullups: str) -> _i2c_maste with _classified_errors(): info = _dict(self.command(req)) except FirmwareError as exc: - # BP0003; the text for firmware without codes. - if exc.code == "BP0003" or (not exc.code and exc.firmware_message.startswith("i2c busy")): + if exc.code == "BP0003": # i2c_session_open exc.args = (self._i2c_busy_text(exc),) raise return _i2c_master.I2CMaster(self._classified_command, info) @@ -3494,8 +3490,7 @@ def la_pins(self, la: Union[Pin, int, str, Sequence[Union[Pin, int, str]], None] try: return self._la_pins_query(None) except FirmwareError as e: - # No code yet ("reply too large"): firmware PR 2 of the codes plan. - if "reply too large" not in str(getattr(e, "firmware_message", "") or e): + if e.code not in ("BP0053", "BP0054"): # reply_too_large, cloud_reply_too_large raise first = self._la_pins_query(list(range(1, 8))) return first + [p for p in self._la_pins_query(list(range(8, 15))) if p.la >= 8] diff --git a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json index 9549d8d..68567af 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json +++ b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "1fdf57bcda663e4e263d034fc81e30b23d565347daafb03b09b5cd7d7e63a332", + "catalog_sha256": "ceaaf830950d2109f3322d4045471f1677c40d668f98ffa875c9343780b49769", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -467,8 +467,8 @@ "name": "client_too_old", "area": "protocol", "since": "next", - "message": "This client is too old for the pod's firmware: it needs client API {min_client_api} or newer (this client sent {client_api})", - "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. status, diag, ping and lease_release still work.", + "message": "Update the BenchPod SDK, MCP or CLI: this firmware needs client API {min_client_api} or newer (this client sent {client_api})", + "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. These still run for any client: ping, status, diag, identity_public, lease_release, ota_status, ota_begin, ota_data, ota_end, ota_commit, ota_abort, ota_selftest and blob_status, so a client can see the levels, let go of the pod, and update the pod's firmware and blobs or roll them back.", "args": { "client_api": "int", "min_client_api": "int", @@ -480,6 +480,814 @@ "mcp": "tell the user the BenchPod MCP server is too old for this pod's firmware; they can update it (run `uvx embeddedci-mcp@latest`, or pip install -U embeddedci-mcp; with the benchpod plugin, update the plugin), then reconnect", "web": "Reload the page to get the latest web app." } + }, + "BP0031": { + "name": "la_pin_in_use", + "area": "io", + "since": "next", + "message": "LA{la} is in use by {owner}", + "cause": "Each LA channel has one owner at a time: a GPIO, a UART, SWD, SPI or I2C session, a step train or an emulated sensor. {owner} holds LA{la}, so the pod refuses to give it to anything else until that owner lets it go. function is the owner's function (gpio, uart_tx, i2c_sda, ...), and instance the emulated sensor's name, empty for anything else.", + "args": { + "la": "int", + "owner": "str", + "function": "str", + "instance": "str" + }, + "fix": { + "sdk": "free LA{la} first: bp.release_gpio({la}) for a GPIO, close the UART, SPI or I2C session that uses it, wait for the flash or step train, or stop the emulated sensor (bp.sensors.stop(name)); bp.la_pins() shows each channel's owner", + "cli": "free LA{la} where it was taken (the web app, a test or an MCP session holds it), or stop an emulated sensor with `benchpod sensor stop `; `benchpod la pins` shows each channel's owner", + "mcp": "free LA{la} first: gpio_release(la=[{la}]) for a GPIO, uart_close, spi or i2c_close for a session, sensor_stop with the sensor's instance for an emulated sensor, or wait for a flash; la_pins shows each channel's owner", + "web": "LA{la} is in use by {owner}. Free it there first (the Pins pane shows each pin's owner)." + } + }, + "BP0032": { + "name": "la_pull_down_engaged", + "area": "io", + "since": "next", + "message": "LA{la} has its {ohms} pull-down on, which {function} cannot work with ({reason})", + "cause": "A pull-down holds the line low. An open-drain bus (I2C), an idle-high UART line or SWDIO needs the line to rest high, so the pod refuses to start {function} on LA{la} while its pull-down is on.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "switch the pull-down off with bp.set_pull({la}, \"off\"), or use another channel", + "cli": "switch the pull-down off with `benchpod la pull {la} off`, or use another channel", + "mcp": "call set_pull(las=[{la}], pull=\"off\"), or use another channel", + "web": "Switch off LA{la}'s pull-down in the Pins pane, or pick another pin." + } + }, + "BP0033": { + "name": "la_pull_down_conflict", + "area": "io", + "since": "next", + "message": "LA{la} is used by {function}, which cannot work with the {ohms} pull-down ({reason})", + "cause": "A pull-down holds the line low. {function} on LA{la} needs the line to rest high, so the pod refuses to switch the pull-down on under it.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "stop what uses LA{la} first (bp.la_pins() shows it), or pull another channel down", + "cli": "stop what uses LA{la} first (`benchpod la pins` shows it), or pull another channel down", + "mcp": "stop what uses LA{la} first (la_pins shows it), or pull another channel down", + "web": "LA{la} is in use by {function}. Stop it before you switch on the pull-down." + } + }, + "BP0034": { + "name": "la_dut_output", + "area": "io", + "since": "next", + "message": "LA{la} is wired to a DUT output, and {function} would drive against it", + "cause": "The wiring marks LA{la} as a pin the DUT drives (la_dir dut_output). Two push-pull outputs on one wire fight each other, which can damage either side, so the pod refuses to drive it. There is no override.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "use an open_drain GPIO on LA{la}, or fix the wiring (bp.la_dir) if LA{la} is not a DUT output", + "cli": "use an open-drain GPIO on LA{la}, or fix the pin's direction in the wiring profile if it is not a DUT output", + "mcp": "use gpio_mode(mode=\"open_drain\") on LA{la}, or fix the wiring with la_dir if LA{la} is not a DUT output", + "web": "LA{la} is wired to a DUT output. Use open drain, or fix the pin's direction in the wiring." + } + }, + "BP0035": { + "name": "la_driven_pin", + "area": "io", + "since": "next", + "message": "LA{la} is driven by {function}, so it cannot be marked as a DUT output", + "cause": "{function} drives LA{la} from the pod. Marking the pin as one the DUT drives would put two outputs on one wire, so the pod refuses until the pod's side stops driving it.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "stop what drives LA{la} first (bp.la_pins() shows it), then set its direction", + "cli": "stop what drives LA{la} first (`benchpod la pins` shows it), then set its direction", + "mcp": "stop what drives LA{la} first (la_pins shows it), then call la_dir again", + "web": "LA{la} is driven by {function}. Stop it before you mark the pin as a DUT output." + } + }, + "BP0036": { + "name": "la_not_gpio_output", + "area": "io", + "since": "next", + "message": "LA{la} is not a GPIO output (it is {function})", + "cause": "Writing a level or sending a gpio step needs the channel set up as a GPIO output or open drain first.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "make it an output first: bp.gpio({la}, \"output\") (or \"open_drain\")", + "cli": "make LA{la} a GPIO output first", + "mcp": "call gpio_mode(la=[{la}], mode=\"output\") (or \"open_drain\") first", + "web": "Set LA{la} to output in the Pins pane first." + } + }, + "BP0037": { + "name": "la_voltage_pins_in_use", + "area": "io", + "since": "next", + "message": "The I/O voltage cannot change while pins are in use: {pins}", + "cause": "Changing the I/O voltage under a running GPIO, UART, flash or sensor would put the wrong level on the DUT's pins, so the pod refuses until they are free.", + "args": { + "pins": "str" + }, + "fix": { + "sdk": "stop what uses those pins first (release the GPIOs, close the sessions, bp.sensors.stop()), then set the voltage", + "cli": "stop what uses those pins first, then set the voltage again", + "mcp": "stop what uses those pins first (gpio_release, uart_close, sensor_stop), then call set_la_voltage again", + "web": "Stop what uses those pins first, then change the I/O voltage." + } + }, + "BP0038": { + "name": "trigger_timeout", + "area": "capture", + "since": "next", + "message": "No {edge} edge on LA{la} within {timeout_ms} ms", + "cause": "A triggered capture waits for its trigger condition before it records. The DUT never made a {edge} edge on LA{la} in the time given, so the pod stopped waiting and recorded nothing.", + "args": { + "la": "int", + "edge": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger_timeout_ms", + "cli": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger timeout", + "mcp": "check the DUT drives LA{la} and the edge is right, or retry with a longer trigger timeout", + "web": "Nothing happened on LA{la} in time. Check the wiring and the edge, or wait longer." + } + }, + "BP0039": { + "name": "sensor_trigger_timeout", + "area": "capture", + "since": "next", + "message": "No I2C start on LA{la} (SDA of {instance}) within {timeout_ms} ms: the DUT did not use the I2C bus", + "cause": "A sensor bus capture with trigger \"start\" waits for the DUT's first I2C start condition on the emulated sensor's SDA. None came in time.", + "args": { + "la": "int", + "instance": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "make the DUT talk to the sensor during the capture (reset it, or start the capture first), or pass trigger=\"none\"", + "cli": "make the DUT talk to the sensor during the capture, or capture without the start trigger", + "mcp": "make the DUT talk to the sensor during the capture (reset_target), or call sensor_capture with trigger \"none\"", + "web": "The DUT did not talk to the sensor in time. Reset it during the capture, or capture without the trigger." + } + }, + "BP0040": { + "name": "lan_locked", + "area": "policy", + "since": "next", + "message": "The pod's LAN is locked: {cmd} needs the cloud or USB", + "cause": "The pod's LAN policy is locked, so commands that change settings, flash or update (tiers T2 and T3) only run from the cloud or over USB. Reads and tests still run on the LAN.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") for {cmd}, or open the LAN policy over USB", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud ('embeddedci:') for {cmd}; ask the user before opening the LAN policy", + "web": "The pod's LAN is locked. Use the pod from the cloud or over USB for this." + } + }, + "BP0041": { + "name": "policy_not_from_lan", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or the USB console", + "cause": "Policies that decide who may change the pod are only changed by someone with the pod's cloud account or its USB cable, never by anyone on the network.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "change {setting} from the cloud or the USB console", + "cli": "change {setting} over USB (`--connection usb`) or from the cloud", + "mcp": "tell the user {setting} is changed from the cloud or the USB console", + "web": "Change {setting} from the cloud or over the pod's USB console." + } + }, + "BP0042": { + "name": "setting_cloud_or_usb", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or over USB", + "cause": "Settings that decide what the pod trusts (LAN TLS, the cloud CA, the cloud proxy) are not changed from the network. TLS on port 8443 has no client authentication, so it does not count either.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") to change {setting}", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud to change {setting}", + "web": "Change {setting} from the cloud or over USB." + } + }, + "BP0043": { + "name": "setting_device_only", + "area": "policy", + "since": "next", + "message": "{setting} can only be changed on the device: the USB console, or over the USB link", + "cause": "This setting changes how the pod can be reached or updated, so it needs someone at the pod: its USB console or its USB network link. Neither the LAN nor the cloud may change it.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) to change {setting}", + "cli": "run this over USB with --connection usb", + "mcp": "connect over USB ('usb') to change {setting}, or ask the user to do it at the pod", + "web": "Change {setting} with the pod plugged in over USB." + } + }, + "BP0044": { + "name": "policy_loosen_usb_only", + "area": "policy", + "since": "next", + "message": "Only the USB console can loosen {setting} (now {now})", + "cause": "The cloud may make the pod stricter but never looser: a stolen cloud account must not be able to lower the pod's firmware signature policy.", + "args": { + "setting": "str", + "now": "str" + }, + "fix": { + "sdk": "loosen {setting} on the pod's USB console", + "cli": "loosen {setting} over USB with `benchpod policy` and --connection usb", + "mcp": "tell the user {setting} can only be loosened on the pod's USB console", + "web": "Loosen {setting} on the pod's USB console." + }, + "retired": "4.0.0", + "replaced_by": "BP0074" + }, + "BP0045": { + "name": "role_required", + "area": "policy", + "since": "next", + "message": "{cmd} needs an organization owner or admin", + "cause": "A cloud session runs commands up to the tier the server allows its user. {cmd} changes or updates the pod, which needs an owner or admin of the pod's organization.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use an API key or session of an organization owner or admin (API keys need the benchpod:admin scope)", + "cli": "sign in as an organization owner or admin; API keys need the benchpod:admin scope", + "mcp": "tell the user {cmd} needs an organization owner or admin (an API key with the benchpod:admin scope)", + "web": "Ask an owner or admin of your organization to do this." + } + }, + "BP0046": { + "name": "no_analog_front_end", + "area": "board", + "since": "next", + "message": "This BenchPod has no analog front end, so it cannot run {cmd}", + "cause": "The digital board has no DAC, ADC or analog outputs. The pod checks at boot; after fitting an analog add-on, restart it.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use a pod with an analog front end (bp.capabilities shows it), or leave out the analog step", + "cli": "use a pod with an analog front end", + "mcp": "this pod has no analog front end; skip the analog step or use another pod", + "web": "This pod has no analog front end." + } + }, + "BP0047": { + "name": "pod_busy", + "area": "busy", + "since": "next", + "message": "The pod is running another long command (a capture, measurement, upload or update)", + "cause": "Captures, measurements, waveform uploads and firmware updates share the pod's sample memory, so one runs at a time. Light commands (status, GPIO, ...) still run.", + "args": {}, + "fix": { + "sdk": "wait for the other command to finish, then try again", + "cli": "the pod is running another long command; try again when it ends", + "mcp": "wait for the other call to finish, then try again", + "web": "The pod is busy with another capture or upload. Try again when it ends." + } + }, + "BP0048": { + "name": "storage_bus_busy", + "area": "busy", + "since": "next", + "message": "The pod's storage bus is in use: {what}", + "cause": "The flash that holds settings, gateware and update images shares a bus with the sample memory. While {what}, the pod cannot write it.", + "args": { + "what": "str" + }, + "fix": { + "sdk": "try again when it ends", + "cli": "try again when it ends", + "mcp": "wait until it ends, then try again", + "web": "Try again when it ends." + } + }, + "BP0049": { + "name": "uart_session_open", + "area": "uart", + "since": "next", + "message": "A UART session is already open", + "cause": "The pod runs one UART at a time: the web app's Terminal, a test, an MCP session or a flash over the UART holds it.", + "args": {}, + "fix": { + "sdk": "close the open UART session first (session.close(), or leave its with block)", + "cli": "close the other UART session (the web app's Terminal, a test or an MCP session) first", + "mcp": "call uart_close first", + "web": "Close the open terminal session first." + } + }, + "BP0050": { + "name": "swd_session_open", + "area": "flash", + "since": "next", + "message": "An SWD session is already running", + "cause": "The pod runs one SWD session (a flash or a debug run) at a time.", + "args": {}, + "fix": { + "sdk": "wait for the running flash to finish, then try again", + "cli": "wait for the running flash to finish, then try again", + "mcp": "wait for the running flash to finish, then try again", + "web": "Wait for the running flash to finish." + } + }, + "BP0051": { + "name": "update_in_progress", + "area": "update", + "since": "next", + "message": "A {target} update from {holder} is in progress", + "cause": "The pod takes one update at a time, from one place. Another one is running.", + "args": { + "target": "str", + "holder": "str" + }, + "fix": { + "sdk": "wait for the other update to finish (or ota_abort it from where it runs), then try again", + "cli": "wait for the other update to finish, then try again", + "mcp": "tell the user another update is running and wait for it", + "web": "Another update is running. Wait for it to finish." + } + }, + "BP0052": { + "name": "cloud_command_busy", + "area": "busy", + "since": "next", + "message": "The pod is still running the previous cloud command", + "cause": "Over the cloud command channel the pod runs one command at a time. The server retries, so this is usually brief.", + "args": {}, + "fix": { + "sdk": "try again in a moment", + "cli": "try again in a moment", + "mcp": "retry in a moment", + "web": "Try again in a moment." + } + }, + "BP0053": { + "name": "reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply did not fit the pod's reply buffer", + "cause": "The command worked, but its answer is larger than the pod can send at once. Commands that can grow (la_pins) take a subset.", + "args": {}, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset); update the SDK if it keeps happening", + "cli": "ask for less at once; update the CLI if it keeps happening", + "mcp": "ask for fewer channels or less data per call", + "web": "Reload the page; if it keeps happening, update the pod's firmware." + } + }, + "BP0054": { + "name": "cloud_reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply is too large for the cloud channel ({bytes} bytes, limit {limit})", + "cause": "Cloud command replies travel in one frame of at most {limit} bytes. This one is {bytes}. Large data (captures) go through the cloud byte tunnel instead.", + "args": { + "bytes": "int", + "limit": "int" + }, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset), or connect over the LAN or USB", + "cli": "ask for less at once, or connect over the LAN or USB", + "mcp": "ask for fewer channels or less data per call", + "web": "Ask for less at once." + } + }, + "BP0055": { + "name": "sensor_instance_unknown", + "area": "sensors", + "since": "next", + "message": "The pod has no emulated sensor {instance}", + "cause": "The instance was never defined or started on this pod, was stopped, or the pod restarted.", + "args": { + "instance": "str" + }, + "fix": { + "sdk": "list the running sensors with bp.sensors.status(), or start {instance} first", + "cli": "list the running sensors with `benchpod sensor status`, or start {instance} first", + "mcp": "call sensor_status to list the running sensors, or sensor_start {instance} first", + "web": "{instance} is not running. Start it first." + } + }, + "BP0056": { + "name": "no_module_link", + "area": "board", + "since": "next", + "message": "This BenchPod has no module link, so it cannot run {cmd}", + "cause": "Only boards with a module header (digital v3r3) talk to an add-on module.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "skip the module step on this board", + "cli": "this board has no module link", + "mcp": "this pod has no module link; skip the module step", + "web": "This pod has no module link." + } + }, + "BP0057": { + "name": "image_switch_sensors_running", + "area": "sensors", + "since": "next", + "message": "The emulated sensors {sensors} need the emulation image; stop them before switching", + "cause": "I2C, SPI and UART sensors run in the emulation gateware image. Switching to another image would stop them mid-run, so the pod refuses.", + "args": { + "sensors": "str" + }, + "fix": { + "sdk": "stop them with bp.sensors.stop(), then switch the image", + "cli": "stop them with `benchpod sensor stop` first", + "mcp": "call sensor_stop (all) first, then fpga_image", + "web": "Stop the emulated sensors first." + } + }, + "BP0058": { + "name": "fpga_image_required", + "area": "firmware", + "since": "next", + "message": "{feature} is not in the running gateware image; it needs the {image} image", + "cause": "The pod's FPGA runs one of three images (loop, deep replay, emulation), and each has some features. {feature} is in the {image} image.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "switch with bp.fpga_image(FpgaImage.LOOP) (or DEEP_REPLAY for the deep image), then try again", + "cli": "switch with `benchpod sensor image {image}`, then try again", + "mcp": "call fpga_image(image=\"{image}\"), then try again", + "web": "Switch the FPGA image to {image} first." + } + }, + "BP0059": { + "name": "fpga_image_sensors_first", + "area": "sensors", + "since": "next", + "message": "{feature} is not in the emulation image the emulated sensors use; stop them, then switch to the {image} image", + "cause": "Emulated I2C, SPI and UART sensors run in the emulation gateware image, which has no room for {feature}. It needs the {image} image, and switching stops the sensors.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "bp.sensors.stop(), then bp.fpga_image(...) for the {image} image", + "cli": "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image {image}`", + "mcp": "call sensor_stop (all), then fpga_image(image=\"{image}\")", + "web": "Stop the emulated sensors, then switch to the {image} image." + } + }, + "BP0060": { + "name": "ota_unknown_target", + "area": "update", + "since": "next", + "message": "{target} is not an update target this firmware knows", + "cause": "The firmware on the pod is older than the tool, or the target name is wrong.", + "args": { + "target": "str" + }, + "fix": { + "sdk": "update the pod's firmware first (`benchpod flash-self`)", + "cli": "update the pod's firmware with `benchpod flash-self` first", + "mcp": "tell the user the pod's firmware does not know this update target; update the firmware first", + "web": "Update the pod's firmware first." + } + }, + "BP0061": { + "name": "i2c_needs_pullups", + "area": "i2c", + "since": "next", + "message": "I2C needs pull-ups: LA{la} has none switched on", + "cause": "I2C lines are open drain: something must pull them high. The pod can do it with its own pull-ups, or the board has its own.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "switch the pull-up on (bp.enable_pullup({la})), or pass pullups=\"external\" when the board has its own", + "cli": "pull LA{la} up with `benchpod la pull {la} up`, or pass --pullups external when the board has its own", + "mcp": "call set_pull(las=[{la}], pull=\"up\"), or pass pullups=\"external\" when the board has its own", + "web": "Switch on LA{la}'s pull-up, or say the board has its own." + } + }, + "BP0062": { + "name": "i2c_session_not_open", + "area": "i2c", + "since": "next", + "message": "No I2C session is open", + "cause": "I2C transactions run inside a session that i2c_start opens.", + "args": {}, + "fix": { + "sdk": "open one with bp.open_i2c() first", + "cli": "start the I2C master first", + "mcp": "call i2c_open first", + "web": "Open an I2C session first." + } + }, + "BP0063": { + "name": "i2c_engine_reset", + "area": "i2c", + "since": "next", + "message": "The I2C engine was reset, which ended the session", + "cause": "A gateware reload (an image switch, a recovery) resets the I2C engine, so the open session is gone.", + "args": {}, + "fix": { + "sdk": "open the session again with bp.open_i2c()", + "cli": "start the I2C command again", + "mcp": "call i2c_open again", + "web": "Open the I2C session again." + } + }, + "BP0064": { + "name": "loop_sweep_with_map", + "area": "dac", + "since": "next", + "message": "The sweep input cannot be combined with an input map on this gateware", + "cause": "The sweep spans the raw count range, not the mapped window, so most of each pass would sit at one end of the curve.", + "args": {}, + "fix": { + "sdk": "step the input with bp.loop_input() instead of the sweep", + "cli": "step the loop input instead of using the sweep", + "mcp": "step the input with loop_input instead", + "web": "Step the input instead of sweeping it." + } + }, + "BP0065": { + "name": "output_used_by_sensor", + "area": "sensors", + "since": "next", + "message": "The {output} output is played by the emulated sensor {instance}", + "cause": "An analog emulated sensor drives the pod's {output} output, so a DAC or current command would fight it.", + "args": { + "output": "str", + "instance": "str" + }, + "fix": { + "sdk": "stop it first with bp.sensors.stop(\"{instance}\")", + "cli": "stop it first with `benchpod sensor stop {instance}`", + "mcp": "call sensor_stop(instance=\"{instance}\") first", + "web": "Stop the emulated sensor {instance} first." + } + }, + "BP0066": { + "name": "step_busy", + "area": "io", + "since": "next", + "message": "A step pulse train is running", + "cause": "The pod runs one step train at a time.", + "args": {}, + "fix": { + "sdk": "wait for the step train to finish (or stop it), then try again", + "cli": "wait for the step train to finish, then try again", + "mcp": "wait for the la_step train to finish, then try again", + "web": "Wait for the step train to finish." + } + }, + "BP0067": { + "name": "samples_out_of_range", + "area": "capture", + "since": "next", + "message": "samples must be 1 to {max} for this capture", + "cause": "Each capture holds a fixed number of samples: the shallow ADC capture what fits the RAM buffer, the deep ones what fits their PSRAM region at the rate asked for. A deep ADC capture is capture_dual with la_samples 0.", + "args": { + "max": "int" + }, + "fix": { + "sdk": "ask for at most {max} samples, or use a deep capture (capture_dual) for more", + "cli": "ask for at most {max} samples", + "mcp": "ask for at most {max} samples, or use capture_correlated / a deep capture for more", + "web": "Capture at most {max} samples." + } + }, + "BP0068": { + "name": "la_rate_above_ceiling", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit: with ADC samples in the capture the raw LA runs at most {max_mhz} MS/s on this gateware, {fit_mhz} MS/s for {samples} samples", + "cause": "On gateware before v53 the raw LA runs at most {max_mhz} MS/s when the same capture records ADC samples: faster, the PSRAM writer starved the ADC. The pod refuses an explicit rate it cannot run instead of slowing it down. {fit_mhz} MS/s is the fastest rate that fits {samples} samples. Above 12 MS/s the LA records its changes instead.", + "args": { + "rate_mhz": "str", + "max_mhz": "str", + "fit_mhz": "str", + "samples": "int" + }, + "fix": { + "sdk": "ask for at most {max_mhz} MS/s ({fit_mhz} MS/s for {samples} samples), leave the rate out for the fastest that fits, or update the pod's gateware", + "cli": "ask for at most {max_mhz} MS/s, or leave the rate out for the fastest that fits", + "mcp": "retry with la_sample_rate_hz at most {fit_mhz} MHz in Hz (or leave it out for the fastest that fits)", + "web": "Pick {fit_mhz} MS/s or less, or leave the rate on automatic." + } + }, + "BP0069": { + "name": "la_rate_too_deep", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit {samples} samples: at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples", + "cause": "The raw LA samples into a burst buffer that drains to the PSRAM more slowly than the fastest rates. A capture deeper than the buffer holds at {rate_mhz} MS/s would drop samples, so the pod refuses it instead of slowing it down. Either way out works: fewer samples at this rate, or a lower rate for this depth.", + "args": { + "rate_mhz": "str", + "samples": "int", + "max_samples": "int", + "fit_mhz": "str" + }, + "fix": { + "sdk": "capture at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples (leave the rate out for the fastest that fits)", + "cli": "capture at most {max_samples} samples at {rate_mhz} MS/s, or ask for {fit_mhz} MS/s or less (or leave the rate out)", + "mcp": "retry with at most {max_samples} samples, or with the rate at most {fit_mhz} MS/s (or leave it out for the fastest that fits)", + "web": "Capture at most {max_samples} samples at {rate_mhz} MS/s, or pick {fit_mhz} MS/s or less." + } + }, + "BP0070": { + "name": "capture_dual_too_deep", + "area": "capture", + "since": "next", + "message": "capture_dual takes at most {la_max} LA and {adc_max} ADC samples", + "cause": "Each stream of a capture_dual has its own PSRAM region of a fixed size. A deeper LA-only capture fits la_capture, which takes up to {la_capture_max} LA samples.", + "args": { + "la_max": "int", + "adc_max": "int", + "la_capture_max": "int" + }, + "fix": { + "sdk": "ask for at most {la_max} LA and {adc_max} ADC samples, or use la_capture for up to {la_capture_max} LA samples", + "cli": "ask for at most {la_max} LA and {adc_max} ADC samples", + "mcp": "ask for at most {la_max} LA and {adc_max} ADC samples, or use capture_la for up to {la_capture_max} LA samples", + "web": "Capture at most {la_max} LA and {adc_max} ADC samples." + } + }, + "BP0071": { + "name": "capture_overflowed", + "area": "capture", + "since": "next", + "message": "The capture overflowed: the PSRAM could not keep up with LA {la_ksps} kS/s and ADC {adc_ksps} kS/s", + "cause": "The capture started, but its streams wrote to the PSRAM faster than it could take them, so samples were lost and the pod returns none.", + "args": { + "la_ksps": "int", + "adc_ksps": "int" + }, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or capture fewer samples", + "cli": "lower the LA or ADC rate, or capture fewer samples", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or fewer samples", + "web": "Lower the LA or ADC rate, or capture fewer samples." + } + }, + "BP0072": { + "name": "psram_too_small", + "area": "capture", + "since": "next", + "message": "The capture is too deep: LA, ADC and a loaded DAC waveform together exceed the 8 MB PSRAM", + "cause": "A capture_dual packs its LA region, its ADC region and any deep-replay waveform still loaded into the pod's 8 MB PSRAM, and refuses up front when they do not fit.", + "args": {}, + "fix": { + "sdk": "capture fewer LA or ADC samples, or free the replay waveform (bp.dac_stop()) first", + "cli": "capture fewer samples", + "mcp": "retry with fewer la_samples or adc_samples, or call dac_stop to free a loaded replay waveform", + "web": "Capture fewer samples, or stop the DAC replay first." + } + }, + "BP0073": { + "name": "psram_bandwidth", + "area": "capture", + "since": "next", + "message": "The combined sample rate is more than the PSRAM bus can take", + "cause": "The LA, the ADC and a running deep replay share one PSRAM bus. The pod adds up their sustained rates and refuses a capture that would overrun it, instead of losing samples.", + "args": {}, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or stop the DAC replay first", + "cli": "lower the LA or ADC rate", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or call dac_stop first", + "web": "Lower the LA or ADC rate, or stop the DAC replay first." + } + }, + "BP0074": { + "name": "signatures_always_required", + "area": "policy", + "since": "next", + "message": "{setting} cannot be set to {want}: this firmware installs only signed images", + "cause": "Firmware 4.0.0 and later take an update (firmware, gateware, the Wi-Fi chip's image) only with a good signature, on every path: the LAN, the USB network adapter and the cloud. No command loosens that. Dev builds also take images signed with the developer key. Firmware you built yourself goes in over USB DFU (`benchpod flash-self`), which needs the pod on a USB cable.", + "args": { + "setting": "str", + "want": "str" + }, + "fix": { + "sdk": "install a signed release, or install self-built firmware over USB DFU (`benchpod flash-self`)", + "cli": "install a signed release, or install self-built firmware over USB DFU with `benchpod flash-self` (without --network)", + "mcp": "tell the user the pod takes only signed images; self-built firmware goes in over USB DFU (`benchpod flash-self`)", + "web": "The pod takes only signed images. Install self-built firmware over USB with `benchpod flash-self`." + } + }, + "BP0075": { + "name": "lan_plaintext_off", + "area": "policy", + "since": "next", + "message": "The pod serves its JSON API on the LAN over TLS only (port 8443): plaintext port 8080 is off", + "cause": "Firmware 4.0.0 and later serve the JSON API over Ethernet and Wi-Fi on TLS port 8443 only. Plaintext port 8080 still answers on the USB network adapter, and from the LAN when SCPI is switched on, but only for SCPI there. Plaintext JSON on the LAN comes back only when it is switched on over USB or from the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod by its address without a port (the SDK uses TLS on 8443 and pins the pod's certificate), or over USB ('usb')", + "cli": "connect by the pod's address without a port (the CLI uses TLS on 8443), or with --connection usb", + "mcp": "connect to the pod's address without :8080 (TLS on 8443 is used), or to 'usb'", + "web": "Connect to the pod over TLS (port 8443) or USB." + } + }, + "BP0076": { + "name": "usb_host_over_usb", + "area": "usb", + "since": "next", + "message": "USB host mode cannot start over the pod's own USB link", + "cause": "While the pod hosts a board on its USB port it is off the computer's USB, so the connection that asked would drop before the answer arrives. USB host mode starts only over the network (LAN or Wi-Fi) or the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod over the network or the cloud (Client(host) or 'embeddedci:'), not 'usb', then start USB host mode again", + "cli": "connect to the pod over the network or the cloud (--connection or embeddedci:), not usb, then run the command again", + "mcp": "connect to the pod over the network or the cloud (connect with its host or 'embeddedci:'), not 'usb', then try again", + "web": "Connect to the pod over the network or the cloud to use USB host mode." + } + }, + "BP0077": { + "name": "usb_host_port_unavailable", + "area": "usb", + "since": "next", + "message": "This pod has no USB host port {port}", + "cause": "Only pods with a USB-A host port can host a board there. Every pod can host on its USB-C port, but only on a bench rig with an adapter cable that powers the pod and carries the data lines to the board under test.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "use port='usb_c' with a USB-C adapter rig, or a pod with the USB-A host port", + "cli": "use --port usb_c with a USB-C adapter rig, or a pod with the USB-A host port", + "mcp": "tell the user this pod has no USB-A host port; port 'usb_c' works only with a USB-C adapter rig", + "web": "This pod has no USB-A host port." + } + }, + "BP0078": { + "name": "usb_host_no_crystal", + "area": "usb", + "since": "next", + "message": "USB host mode needs the pod's crystal clock, which is not running", + "cause": "A USB host keeps the bus timing itself and needs a precise clock. The pod runs on its internal oscillator because the crystal did not start at boot.", + "args": {}, + "fix": { + "sdk": "power cycle the pod; if bp.status() still shows the internal clock, contact support", + "cli": "power cycle the pod; if `benchpod status` still shows the internal clock, contact support", + "mcp": "ask the user to power cycle the pod; if it keeps happening, the pod needs support", + "web": "Power cycle the pod. If this keeps happening, contact support." + } + }, + "BP0079": { + "name": "usb_host_other_port", + "area": "usb", + "since": "next", + "message": "USB host mode is already running on {port}", + "cause": "The pod hosts one port at a time. A start for the same port renews the timeout; another port needs a stop first.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "stop USB host mode first (enabled=False), then start it on the other port", + "cli": "stop USB host mode first, then start it on the other port", + "mcp": "stop USB host mode first, then start it on the other port", + "web": "Stop USB host mode first." + } + }, + "BP0080": { + "name": "dac_pinout_mismatch", + "area": "analog", + "since": "next", + "message": "{cmd} refused, the DAC is off: the digital board ({digital}) and the analog module ({module}) use different flat-cable pinouts", + "cause": "The flat cable between the two boards carries the DAC's clock and data. Digital board v3r4 and analog module 3.5 swapped those two lines, so a newer board paired with an older one would send the DAC scrambled data and its outputs could jump to any voltage. The pod refuses every command that drives the DAC and sends it nothing; everything else keeps working. The module's revision comes from its EEPROM, so a module that was never programmed counts as an older one.", + "args": { + "cmd": "str", + "digital": "str", + "module": "str" + }, + "fix": { + "sdk": "pair a digital v3r4 or later board with an analog module 3.5 or later (or both older), or, if the module's EEPROM revision is wrong, program the revision printed on its board and restart the pod", + "cli": "pair a digital v3r4 or later board with an analog module 3.5 or later (or both older); `benchpod status` shows both. If the module's revision is wrong, program the one printed on its board and restart the pod", + "mcp": "tell the user the digital board and the analog module do not belong together (status shows both revisions): a digital v3r4+ board needs an analog module 3.5+, and an older digital board an older module", + "web": "The digital board and the analog module do not belong together, so the analog outputs are off. A digital v3r4 or later board needs an analog module 3.5 or later." + } } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/errors.py b/packages/embeddedci/src/embeddedci/benchpod/errors.py index 30d74da..9fb55da 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/errors.py +++ b/packages/embeddedci/src/embeddedci/benchpod/errors.py @@ -67,14 +67,15 @@ class CloudAuthError(BenchPodError): class FirmwareError(BenchPodError): """The pod accepted the request but replied ``{"status":"error"}``. - :attr:`firmware_message` is the pod's own text, unchanged. The exception's message is that - text with any fix the firmware spells as a raw protocol command (``{"cmd":"gpio",...}``) - rewritten into the SDK call that does it (``bp.release_gpio(4)``); the leading words the - firmware uses (``la voltage not set``, ``pin conflict: LA4 is in use by gpio``) stay as they are. + A refusal the SDK can act on carries a stable :attr:`code` (``"BP0009"``) and its + :attr:`values`, and no text (firmware 4.0): the exception's message is the code's message and + the SDK's fix from the bundled catalog (:func:`error_catalog`). A refusal without a code keeps + the pod's own text. :attr:`firmware_message` is the text the pod sent (``""`` for a coded + refusal, except ``BP0030``). """ - #: 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. + #: The pod's stable error code (``"BP0009"``), "" for a refusal without one. Match on this, + #: never 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] = {} @@ -85,18 +86,7 @@ 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 " - "the pod (`benchpod flash-self`, or the firmware update in the web app)") - elif la_pins_too_large(message, cmd): - text += ("; firmware after 3.10.12 reads this list in parts (la_pins with la): update " - "the pod (`benchpod flash-self`, or the firmware update in the web app), or ask " - "for fewer channels with bp.la_pins(la=[...])") - if cmd: - super().__init__(f"{cmd}: {text}") - else: - super().__init__(text) + super().__init__(f"{cmd}: {message}" if cmd else message) class UnsupportedFeatureError(FirmwareError): @@ -104,8 +94,10 @@ class UnsupportedFeatureError(FirmwareError): lacks the hardware (the digital-only board has no analog front end). Raised before anything is sent when the pod's :attr:`~embeddedci.benchpod.BenchPod.capabilities` - lack the feature, and for the pod's own answer when it does not know a command - (``unknown cmd``) or has no analog front end. :attr:`feature` names the capability flag (or the + lack the feature, and for the pod's own refusals: a command it does not know (``BP0002``), + gateware too old (``BP0017``), no analog front end (``BP0046``), no module link (``BP0056``), + the gateware image lacks it (``BP0058``, ``BP0059``), an update target it does not know + (``BP0060``). :attr:`feature` names the capability flag (or the command) that is missing, ``""`` when unknown; :attr:`firmware_version` is the pod's firmware when known. Check ahead with the ``can_*`` properties or :meth:`BenchPod.supports `. @@ -171,22 +163,25 @@ def __init__(self, message: str, *, frames=None) -> None: class PinConflictError(FirmwareError): """The pod refused because an LA channel is already used by another function. - ``la`` is the channel and ``function`` its owner (``gpio``, ``uart_tx``, ``i2c_sda``, ``swd_clk``, - ``step``, …). The message names the SDK call that frees it (``release it with - bp.release_gpio(4)``, ``bp.sensors.stop("env")``, close the UART or SPI session); - :attr:`firmware_message` keeps the pod's own text. + ``BP0031``: ``la`` is the channel, ``function`` the function that holds it (``gpio``, + ``uart_tx``, ``i2c_sda``, ``swd_clk``, ``step``, ...), ``owner`` who holds it (``gpio``, or + ``sensor: ()``) and ``instance`` the emulated sensor's name (``""`` for + none). The message names the SDK call that frees it. """ def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0, - function: str = "") -> None: + function: str = "", owner: str = "", instance: str = "") -> None: super().__init__(message, cmd=cmd) self.la = la self.function = function + self.owner = owner + self.instance = instance class PullConflictError(FirmwareError): - """A bias resistor and a channel's function can't be combined — e.g. LA7's pull-down under a UART - line or an open-drain output. ``la`` is the channel; the message says what to disable.""" + """A bias resistor and a channel's function can't be combined, e.g. LA7's pull-down under a + UART line or an open-drain output (``BP0032``, ``BP0033``). ``la`` is the channel; the message + says what to disable.""" def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0) -> None: super().__init__(message, cmd=cmd) @@ -211,8 +206,9 @@ class DirectionConflictError(FirmwareError): """The pod refused to drive a pin that :meth:`BenchPod.la_dir ` marks as wired to a DUT output (a push-pull GPIO output, UART TX, SPI SCK / MOSI / CS, SWD, ...), because two push-pull outputs would drive against each - other. ``la`` is the channel. Use an ``open_drain`` GPIO, or fix the wiring if the pin is not a - DUT output. There is no override.""" + other (``BP0034``), or refused to mark a driven pin as a DUT output (``BP0035``). ``la`` is the + channel. Use an ``open_drain`` GPIO, or fix the wiring if the pin is not a DUT output. There is + no override.""" def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0) -> None: super().__init__(message, cmd=cmd) @@ -220,7 +216,8 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0) -> N class TriggerTimeout(FirmwareError): - """A triggered capture's condition (``edge`` on LA ``la``) never happened within its timeout.""" + """A triggered capture's condition (``edge`` on LA ``la``) never happened within its timeout + (``BP0038``; ``BP0039`` for an emulated sensor's bus capture, ``edge`` ``"start"``).""" def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0, edge: str = "") -> None: @@ -230,18 +227,19 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0, class PodLockedError(FirmwareError): - """The pod refused a command on its LAN connection: its LAN policy is ``locked`` (or the - command changes a policy), so the command needs the cloud (``embeddedci:``) or USB. - Firmware text: ``locked: needs the cloud or USB`` (before 3.9.0: ``... or the USB - console``).""" + """The pod refused a command on its LAN connection: its LAN policy is ``locked`` (``BP0040``) + or the command changes a setting the LAN may not (``BP0041`` to ``BP0043``), so it needs the + cloud (``embeddedci:``) or USB; or plaintext 8080 is off on the LAN (``BP0075``: use + TLS on 8443, the SDK's default).""" class PodBusyError(FirmwareError): - """The pod refused because it is busy (``busy: …``): a capture or upload is running, or a - cloud job holds it (:class:`PodLeasedError`). With error codes: an I2C or SPI session is - already open (``BP0003``, ``BP0004``), the engine that runs SWD, SPI and I2C is in use - (``BP0005``), or the storage cannot save while the DAC or a capture uses its bus - (``BP0016``).""" + """The pod refused because it is busy: an I2C, SPI, UART or SWD session is already open + (``BP0003``, ``BP0004``, ``BP0049``, ``BP0050``), the engine that runs SWD, SPI and I2C is in + use (``BP0005``), the storage or its bus is busy (``BP0016``, ``BP0048``), another long + command or an update runs (``BP0047``, ``BP0051``), the previous cloud command still runs + (``BP0052``), a step train runs (``BP0066``), or a cloud job holds the pod + (:class:`PodLeasedError`).""" class PodLeasedError(PodBusyError, DeviceBusyError, TransportError): @@ -330,8 +328,8 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, api: int = 0, class PermissionDeniedError(FirmwareError, TransportError): - """The caller is not allowed to do this: the pod's ``forbidden: needs an organization - owner or admin`` on a cloud tunnel, or an HTTP 403 from the server (the API key lacks a + """The caller is not allowed to do this: the pod's ``BP0045`` (the command needs an + organization owner or admin) on a cloud tunnel, or an HTTP 403 from the server (the API key lacks a scope, the session token does not cover the device, the user is not an owner or admin). :attr:`status` is the HTTP status (403) when the server refused, else ``None``. Also a @@ -344,179 +342,32 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, self.status = status -# -- text fallbacks ---------------------------------------------------------------------------- -# -# Firmware with error codes (3.10.8+) sends a code with every refusal that has one, and -# firmware_error() classifies by that code (_BY_CODE below). The texts here classify a refusal that -# comes without a code the SDK knows: older firmware, and refusals that have no code yet. Each says -# what replaces it: a code, or "no code yet" (firmware PR 2 of the codes plan gives them codes). - -#: No code yet: firmware PR 2 of the codes plan. -_PIN_CONFLICT = re.compile(r"pin conflict: LA(\d+) is in use by ([\w:]+)") -#: No code yet: firmware PR 2 of the codes plan. -_PULL_CONFLICT = re.compile(r"pull conflict: LA(\d+)") -#: No code yet: firmware PR 2 of the codes plan. -_DIRECTION_CONFLICT = re.compile(r"direction conflict: LA(\d+)") -#: "the I2C master needs gateware v55+", "SPI modes 1 and 2 need gateware v55+". BP0017 for the -#: UART options; no code yet for the others: firmware PR 2 of the codes plan. -_NEEDS_GATEWARE = re.compile(r"needs? gateware v\d+") -#: No code yet: firmware PR 2 of the codes plan. -_TRIGGER_TIMEOUT = re.compile(r"trigger timeout: no (\w+) \w+ on LA(\d+)") -#: "busy: a cloud job holds this pod (, s left)" (command_handler.c dispatch_line). -#: Replaced by BP0025. -_LEASED = re.compile(r"busy: a cloud job holds this pod \((.*), (\d+) s left\)") -#: Policy changes the LAN may not make (pod_policy.c), and "locked: ...". No code yet: firmware -#: PR 2 of the codes plan. -_POLICY_ELSEWHERE = ("change it from the cloud or the USB console", - "change it over TLS (port 8443), over USB or from the cloud", - "change it from the cloud or over USB", - "change it on the device", - "only the USB console can loosen") -#: Older firmware's answer to a command it does not have (command_handler.c). Replaced by BP0002. -_UNKNOWN_CMD = "unknown cmd" -#: The digital-only board refusing an analog command (cmd_gate.c cmd_gate_check). No code yet: -#: firmware PR 2 of the codes plan. -_NO_ANALOG = "this BenchPod has no analog front end" -#: "busy: ..." without a lease. BP0016 for the storage; no code yet for the others (a capture or -#: upload running): firmware PR 2 of the codes plan. -_BUSY = "busy:" -#: "forbidden: needs an organization owner or admin". No code yet: firmware PR 2. -_FORBIDDEN = "forbidden:" - - -#: The firmware's "la voltage not set; set la_mv ... in the active wiring profile, or call -#: la_voltage ..." (older firmware: "...; set it with la_voltage (mv 1800 or 3300) first") -#: (command_handler.c require_la_voltage). Matched on the leading words only. Replaced by BP0001, -#: which gets the same SDK text (_SDK_TEXT). -_LA_VOLTAGE_UNSET = "la voltage not set" - -#: Firmware 3.10.4 and older could answer ``status`` over the cloud with more than the cloud -#: channel takes ("reply too large for the cloud channel (1838 bytes, limit 1791)"). From this -#: version a cloud ``status`` is a short form that always fits. No code yet ("reply too large"): -#: firmware PR 2 of the codes plan. -STATUS_FITS_FIRMWARE = "3.10.5" -_STATUS_TOO_LARGE = "too large for the cloud channel" - - -def status_too_large(message: str, cmd: Optional[str] = "status") -> bool: - """Whether a pod refusal is a ``status`` reply that did not fit the cloud channel.""" - return cmd == "status" and _STATUS_TOO_LARGE in message - - -def la_pins_too_large(message: str, cmd: Optional[str] = "la_pins") -> bool: - """Whether a pod refusal is a full ``la_pins`` listing too large for one reply (LAN - ``reply too large``, cloud ``... for the cloud channel``). Only older firmware leaves it there: - newer firmware takes ``la`` and the SDK reads the list in parts. No code yet: firmware PR 2.""" - return cmd == "la_pins" and "reply too large" in message - - -_LA_VOLTAGE_SDK = ("la voltage not set; the wiring profile sets no I/O voltage: set la_mv in it " - "(bp.save_wiring(bp.wiring.with_changes(la_mv=3300)), 1800 for a 1.8 V board), " - "or pass BenchPod(conn, la_voltage=3.3), or call bp.set_la_voltage(3.3)") - -#: Fixes the firmware spells as raw protocol commands (la_pins.c release_hint and the pull and -#: gpio-output checks, command_handler_dap.c, command_handler_dac.c), in the caller's SDK terms. -#: Whole phrases first, so a hint reads naturally; anything not listed passes through unchanged. -_SDK_FIXES = ( - (re.compile(r'release it with \{"cmd":"gpio","la":(\d+),"mode":"off"\}'), - r"release it with bp.release_gpio(\1)"), - (re.compile(r"stop the uart proxy first"), - "close the UART session from bp.open_uart() first (session.close(), or leave its with block)"), - (re.compile(r"end the SWD session first"), - "wait for the running flash (its SWD session) to finish"), - (re.compile(r'\{"cmd":"sensor_stop","all":true\} then \{"cmd":"fpga_image","image":"(loop|deep)"\}'), - lambda m: "bp.sensors.stop() then bp.fpga_image(FpgaImage." - + ("LOOP" if m.group(1) == "loop" else "DEEP_REPLAY") + ")"), - (re.compile(r'stop them first \(\{"cmd":"sensor_stop","all":true\}\)'), - "stop them first with bp.sensors.stop()"), - (re.compile(r'\{"cmd":"sensor_stop","instance":"([a-z0-9_]+)"\}'), r'bp.sensors.stop("\1")'), - (re.compile(r'stop the sensor emulation first \(\{"cmd":"sensor_stop"(?:,"all":true)?\}\)'), - "stop the sensor emulation first with bp.sensors.stop()"), - (re.compile(r'stop the SPI session first \(\{"cmd":"spi_stop"\}\)'), - "close the SPI session from bp.open_spi() first (spi.close(), or leave its with block)"), - (re.compile(r'\(\{"cmd":"spi_stop"\}\)'), - "(close the SPI session from bp.open_spi() first)"), - (re.compile(r'stop the I2C session first \(\{"cmd":"i2c_stop"\}\)'), - "close the I2C session from bp.open_i2c() first (i2c.close(), or leave its with block)"), - (re.compile(r"i2c busy: send i2c_stop first"), - "i2c busy: close the I2C session from bp.open_i2c() first"), - (re.compile(r"send i2c_start first"), "open one with bp.open_i2c() first"), - (re.compile(r"i2c_start again"), "open it again with bp.open_i2c()"), - (re.compile(r'switch on LA(\d+)\'s with \{"cmd":"la","la":\d+,"(?:pullup":"on|pull":"up)"\}'), - r"switch on LA\1's with bp.enable_pullup(\1)"), - (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup":"on|pull":"up)"\}'), r"bp.enable_pullup(\1)"), - (re.compile(r'\{"cmd":"la","la":(\d+),"pull":"down"\}'), r'bp.set_pull(\1, "down")'), - (re.compile(r'pass "pullups":"external"'), 'pass pullups="external"'), - (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup|pull)":"off"\}'), r'bp.set_pull(\1, "off")'), - (re.compile(r'\{"cmd":"gpio","la":(\d+),"mode":"output"\}'), r'bp.gpio(\1, "output")'), - (re.compile(r'\{"cmd":"fpga_image","image":([012])\}'), r"bp.fpga_image(\1)"), - (re.compile(r'\{"cmd":"dac_loop_input"\}'), "bp.loop_input()"), -) - - -def _sdk_refusal_text(message: str) -> str: - """``message`` (a pod refusal) with its protocol-level fix rewritten into the SDK call. - - ``"pin conflict: LA4 is in use by gpio; release it with {"cmd":"gpio","la":4,"mode":"off"}"`` - becomes ``"pin conflict: LA4 is in use by gpio; release it with bp.release_gpio(4)"``. Text - with nothing to rewrite comes back unchanged. - """ - if message.startswith(_LA_VOLTAGE_UNSET): - return _LA_VOLTAGE_SDK - for pattern, repl in _SDK_FIXES: - message = pattern.sub(repl, message) - return message +class ReplyTooLargeError(FirmwareError): + """The pod's reply did not fit its reply buffer (``BP0053``) or the cloud channel + (``BP0054``, with ``bytes`` and ``limit``). The SDK reads such lists in parts where it can + (``la_pins``).""" -def classify_firmware_error(exc: FirmwareError) -> FirmwareError: - """The specific :class:`FirmwareError` subclass for a pod refusal, or ``exc`` itself. +class DacPinoutMismatchError(UnsupportedFeatureError): + """The DAC is off because the digital board and the analog module use different flat-cable + pinouts (``BP0080``): ``digital`` is the digital board's (``"v3r4+"`` or ``"v3r3"``), + ``module`` the module's revision from its EEPROM (``"3.4"``, ``"not programmed"``, ...). + Every command that drives the DAC is refused; the rest works. ``ModuleInfo.dac_pinout_ok`` + says the same ahead. An :class:`UnsupportedFeatureError` (``feature="dac"``).""" - A refusal with a code the SDK knows was classified by :func:`firmware_error` from that code - and comes back unchanged; only one without (older firmware, or a code newer than this SDK) is - classified from its text.""" - if type(exc) is not FirmwareError or exc.code in _BY_CODE: - return exc - return _classify_text(exc) - - -def _classify_text(exc: FirmwareError) -> FirmwareError: - """The text fallback: the class a refusal's text names (see the patterns above).""" - msg = exc.firmware_message - m = _PIN_CONFLICT.search(msg) - if m: - return PinConflictError(msg, cmd=exc.cmd, la=int(m.group(1)), function=m.group(2)) - m = _PULL_CONFLICT.search(msg) - if m: - return PullConflictError(msg, cmd=exc.cmd, la=int(m.group(1))) - m = _DIRECTION_CONFLICT.search(msg) - if m: - return DirectionConflictError(msg, cmd=exc.cmd, la=int(m.group(1))) - if _NEEDS_GATEWARE.search(msg): - return UnsupportedFeatureError(msg, cmd=exc.cmd, feature=exc.cmd or "") - m = _TRIGGER_TIMEOUT.search(msg) - if m: - return TriggerTimeout(msg, cmd=exc.cmd, la=int(m.group(2)), edge=m.group(1)) - if msg.startswith("locked:") or any(p in msg for p in _POLICY_ELSEWHERE): - return PodLockedError(msg, cmd=exc.cmd) - m = _LEASED.search(msg) - if m: - return PodLeasedError(msg, cmd=exc.cmd, holder=m.group(1), left_s=int(m.group(2))) - if msg.startswith(_BUSY): - return PodBusyError(msg, cmd=exc.cmd) - if msg.startswith(_FORBIDDEN): - return PermissionDeniedError(msg, cmd=exc.cmd) - if msg.strip() == _UNKNOWN_CMD: - return UnsupportedFeatureError(msg, cmd=exc.cmd, feature=exc.cmd or "") - if msg.startswith(_NO_ANALOG): - return UnsupportedFeatureError(msg, cmd=exc.cmd, feature="analog") - return exc + def __init__(self, message: str, *, cmd: Optional[str] = None, digital: str = "", + module: str = "") -> None: + super().__init__(message, cmd=cmd, feature="dac") + self.digital = digital + self.module = module # -- 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. +# Firmware 4.0 sends {"status":"error","code":"BP0009","args":{...}} and no message (BP0030 alone +# carries one, for clients from before the codes). 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. The SDK never reads a refusal's text. _CATALOG: Optional[Dict[str, Any]] = None @@ -553,21 +404,24 @@ def explain(code: str, surface: str = "sdk") -> str: 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)``.""" + """Put the pod's code and values on exc and render its message from the catalog: ``cmd: + BP0009: The wiring profile k66 changed ...; load it again ... + (https://embeddedci.com/docs/errors#BP0009)``. A code this SDK's catalog does not have keeps + the pod's text, if any, and says to update the SDK.""" 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 code in _SDK_TEXT: - text = f"{code}: {_SDK_TEXT[code]} ({exc.docs_url})" - exc.args = (f"{exc.cmd}: {text}" if exc.cmd else text,) - elif 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}]",) + if not code: + return exc + entry = error_catalog().get("codes", {}).get(code) + if entry: + text = (f"{code}: {_fill(entry['message'], exc.values)}; " + f"{_fill(entry['fix']['sdk'], exc.values)} ({exc.docs_url})") + else: + said = f"{exc.firmware_message}; " if exc.firmware_message else "" + text = (f"{code}: {said}this SDK does not know this code yet: update it (pip install -U " + f"embeddedci) or see {exc.docs_url}") + exc.args = (f"{exc.cmd}: {text}" if exc.cmd else text,) return exc @@ -593,14 +447,27 @@ def _leased(v: Mapping[str, Any], cmd: Optional[str]) -> Dict[str, Any]: _NO_FIELDS: Callable[[Mapping[str, Any], Optional[str]], Dict[str, Any]] = lambda v, cmd: {} # noqa: E731 _WIRING = (lambda v, cmd: {"name": _str(v.get("name"))}) _FieldsFn = Callable[[Mapping[str, Any], Optional[str]], Dict[str, Any]] +_LA = (lambda v, cmd: {"la": _int(v.get("la"))}) +_PULL_DIR = (lambda v, cmd: {"la": _int(v.get("la")), "want": _str(v.get("want")), + "have": _str(v.get("have"))}) + + +def _feature(key: str) -> _FieldsFn: + return lambda v, cmd: {"feature": _str(v.get(key)) or cmd or ""} + + +def _pin_conflict(v: Mapping[str, Any], cmd: Optional[str]) -> Dict[str, Any]: + owner, function = _str(v.get("owner")), _str(v.get("function")) + return {"la": _int(v.get("la")), "function": function or owner, "owner": owner, + "instance": _str(v.get("instance"))} + #: Every code in the catalog: the exception class it raises and how its args fill that class's #: fields (``values`` keeps them all). A code missing here (newer than this SDK) is a plain -#: :class:`FirmwareError`, classified by its text like a refusal without a code. +#: :class:`FirmwareError` with the code on it. _BY_CODE: Dict[str, Tuple[type, _FieldsFn]] = { "BP0001": (FirmwareError, _NO_FIELDS), # la_voltage_not_set - "BP0002": (UnsupportedFeatureError, # unknown_command - lambda v, cmd: {"feature": _str(v.get("cmd")) or cmd or ""}), + "BP0002": (UnsupportedFeatureError, _feature("cmd")), # unknown_command "BP0003": (PodBusyError, _NO_FIELDS), # i2c_session_open "BP0004": (PodBusyError, _NO_FIELDS), # spi_session_open "BP0005": (PodBusyError, _NO_FIELDS), # bus_engine_busy {want} @@ -615,19 +482,14 @@ def _leased(v: Mapping[str, Any], cmd: Optional[str]) -> Dict[str, Any]: "BP0014": (WiringError, _WIRING), # wiring_upload_out_of_order "BP0015": (WiringError, _WIRING), # wiring_storage_failed "BP0016": (PodBusyError, _NO_FIELDS), # storage_busy - "BP0017": (UnsupportedFeatureError, # gateware_too_old {feature, min} - lambda v, cmd: {"feature": _str(v.get("feature")) or cmd or ""}), + "BP0017": (UnsupportedFeatureError, _feature("feature")), # gateware_too_old {feature, min} "BP0018": (FirmwareError, _NO_FIELDS), # uart_same_pin {la} "BP0019": (FirmwareError, _NO_FIELDS), # uart_half_duplex_two_pins "BP0020": (FirmwareError, _NO_FIELDS), # uart_entry_no_reset_pin "BP0021": (FirmwareError, _NO_FIELDS), # uart_entry_invalid {arg, max} "BP0022": (FirmwareError, _NO_FIELDS), # uart_de_pin {la} - "BP0023": (PullDirectionError, # la_no_pull {la} - lambda v, cmd: {"la": _int(v.get("la")), "want": _str(v.get("want")), - "have": _str(v.get("have"))}), - "BP0024": (PullDirectionError, # la_pull_direction {la, want, have} - lambda v, cmd: {"la": _int(v.get("la")), "want": _str(v.get("want")), - "have": _str(v.get("have"))}), + "BP0023": (PullDirectionError, _PULL_DIR), # la_no_pull {la} + "BP0024": (PullDirectionError, _PULL_DIR), # la_pull_direction {la, want, have} "BP0025": (PodLeasedError, _leased), # lease_busy "BP0026": (PodLeaseLostError, lambda v, cmd: {"by": _str(v.get("by"))}), # lease_lost "BP0027": (FirmwareError, _NO_FIELDS), # lease_not_held {id} @@ -636,24 +498,90 @@ def _leased(v: Mapping[str, Any], cmd: Optional[str]) -> Dict[str, Any]: "BP0030": (ClientTooOldError, # client_too_old lambda v, cmd: {"client_api": _int(v.get("client_api")), "api": _int(v.get("api")), "min_client_api": _int(v.get("min_client_api"))}), + "BP0031": (PinConflictError, _pin_conflict), # la_pin_in_use + "BP0032": (PullConflictError, _LA), # la_pull_down_engaged + "BP0033": (PullConflictError, _LA), # la_pull_down_conflict + "BP0034": (DirectionConflictError, _LA), # la_dut_output + "BP0035": (DirectionConflictError, _LA), # la_driven_pin + "BP0036": (FirmwareError, _NO_FIELDS), # la_not_gpio_output {la, function} + "BP0037": (FirmwareError, _NO_FIELDS), # la_voltage_pins_in_use {pins} + "BP0038": (TriggerTimeout, # trigger_timeout + lambda v, cmd: {"la": _int(v.get("la")), "edge": _str(v.get("edge"))}), + "BP0039": (TriggerTimeout, # sensor_trigger_timeout + lambda v, cmd: {"la": _int(v.get("la")), "edge": "start"}), + "BP0040": (PodLockedError, _NO_FIELDS), # lan_locked {cmd} + "BP0041": (PodLockedError, _NO_FIELDS), # policy_not_from_lan {setting} + "BP0042": (PodLockedError, _NO_FIELDS), # setting_cloud_or_usb {setting} + "BP0043": (PodLockedError, _NO_FIELDS), # setting_device_only {setting} + "BP0044": (PodLockedError, _NO_FIELDS), # policy_loosen_usb_only (retired) + "BP0045": (PermissionDeniedError, _NO_FIELDS), # role_required {cmd} + "BP0046": (UnsupportedFeatureError, # no_analog_front_end {cmd} + lambda v, cmd: {"feature": "analog"}), + "BP0047": (PodBusyError, _NO_FIELDS), # pod_busy + "BP0048": (PodBusyError, _NO_FIELDS), # storage_bus_busy {what} + "BP0049": (PodBusyError, _NO_FIELDS), # uart_session_open + "BP0050": (PodBusyError, _NO_FIELDS), # swd_session_open + "BP0051": (PodBusyError, _NO_FIELDS), # update_in_progress {target, holder} + "BP0052": (PodBusyError, _NO_FIELDS), # cloud_command_busy + "BP0053": (ReplyTooLargeError, _NO_FIELDS), # reply_too_large + "BP0054": (ReplyTooLargeError, _NO_FIELDS), # cloud_reply_too_large {bytes, limit} + "BP0055": (FirmwareError, _NO_FIELDS), # sensor_instance_unknown {instance} + "BP0056": (UnsupportedFeatureError, # no_module_link {cmd} + lambda v, cmd: {"feature": "module"}), + "BP0057": (FirmwareError, _NO_FIELDS), # image_switch_sensors_running {sensors} + "BP0058": (UnsupportedFeatureError, _feature("feature")), # fpga_image_required {feature, image} + "BP0059": (UnsupportedFeatureError, _feature("feature")), # fpga_image_sensors_first + "BP0060": (UnsupportedFeatureError, _feature("target")), # ota_unknown_target {target} + "BP0061": (FirmwareError, _NO_FIELDS), # i2c_needs_pullups {la} + "BP0062": (FirmwareError, _NO_FIELDS), # i2c_session_not_open + "BP0063": (FirmwareError, _NO_FIELDS), # i2c_engine_reset + "BP0064": (UnsupportedFeatureError, # loop_sweep_with_map + lambda v, cmd: {"feature": "dac_loop_input_map"}), + "BP0065": (FirmwareError, _NO_FIELDS), # output_used_by_sensor {output, instance} + "BP0066": (PodBusyError, _NO_FIELDS), # step_busy + "BP0067": (FirmwareError, _NO_FIELDS), # samples_out_of_range {max} + "BP0068": (FirmwareError, _NO_FIELDS), # la_rate_above_ceiling + "BP0069": (FirmwareError, _NO_FIELDS), # la_rate_too_deep + "BP0070": (FirmwareError, _NO_FIELDS), # capture_dual_too_deep + "BP0071": (FirmwareError, _NO_FIELDS), # capture_overflowed + "BP0072": (FirmwareError, _NO_FIELDS), # psram_too_small + "BP0073": (FirmwareError, _NO_FIELDS), # psram_bandwidth + "BP0074": (FirmwareError, _NO_FIELDS), # signatures_always_required + "BP0075": (PodLockedError, _NO_FIELDS), # lan_plaintext_off + "BP0076": (UnsupportedFeatureError, # usb_host_over_usb + lambda v, cmd: {"feature": "usb_host"}), + "BP0077": (UnsupportedFeatureError, # usb_host_port_unavailable {port} + lambda v, cmd: {"feature": "usb_host"}), + "BP0078": (UnsupportedFeatureError, # usb_host_no_crystal + lambda v, cmd: {"feature": "usb_host"}), + "BP0079": (FirmwareError, _NO_FIELDS), # usb_host_other_port {port} + "BP0080": (DacPinoutMismatchError, # dac_pinout_mismatch + lambda v, cmd: {"digital": _str(v.get("digital")), "module": _str(v.get("module"))}), } -#: Codes whose message is the SDK's own text rather than the catalog's message and fix. -_SDK_TEXT = {"BP0001": _LA_VOLTAGE_SDK} + +def classify_firmware_error(exc: FirmwareError) -> FirmwareError: + """The specific :class:`FirmwareError` subclass for a pod refusal, from its code (a plain + FirmwareError with a known code, as a fake transport might raise, gets its class); a refusal + without a code, or already classified, comes back unchanged. Never reads the text.""" + if type(exc) is not FirmwareError or _BY_CODE.get(exc.code, (FirmwareError,))[0] is FirmwareError: + return exc + return firmware_error(exc.firmware_message, cmd=exc.cmd, code=exc.code, values=exc.values) 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. + ``code`` / ``values``: the pod's stable error code and its args. - A code in the SDK's table decides the class (:data:`_BY_CODE`); the text only decides it for a - refusal without one (older firmware) or with a code newer than this SDK.""" + The code decides the class (:data:`_BY_CODE`) and the message (the catalog's message and SDK + fix; the pod sends none). A refusal without a code is a plain :class:`FirmwareError` with the + pod's text.""" v = dict(values or {}) known = _BY_CODE.get(code) if code else None if known is not None: cls, fields = known exc: FirmwareError = cls(message, cmd=cmd, **fields(v, cmd)) else: - exc = _classify_text(FirmwareError(message, cmd=cmd)) + exc = FirmwareError(message, cmd=cmd) 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 857cd07..e88b810 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/protocol.py +++ b/packages/embeddedci/src/embeddedci/benchpod/protocol.py @@ -96,14 +96,15 @@ def parse_reply(line: bytes) -> Reply: def raise_for_status(reply: Reply, cmd: Optional[str] = None) -> Reply: - """Raise :class:`FirmwareError` (its specific subclass, see - :func:`~embeddedci.benchpod.errors.classify_firmware_error`) if the reply is an error packet. + """Raise :class:`FirmwareError` (its specific subclass, from the reply's code, see + :func:`~embeddedci.benchpod.errors.firmware_error`) if the reply is an error packet. 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, code=reply.code, - values=reply.args) + # A coded refusal carries no text (firmware 4.0): the catalog renders it. + message = reply.message if reply.code else (reply.message or "unknown firmware error") + raise firmware_error(message, 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/sensors/emulation.py b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py index 5502487..9d94add 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py +++ b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py @@ -220,8 +220,7 @@ def status(self) -> Dict[str, Any]: try: st = self._emulation.status(self.instance) except BenchPodError as exc: - # No code yet ("unknown sensor instance"): firmware PR 2 of the codes plan. - if "unknown sensor instance" in str(exc): + if getattr(exc, "code", "") == "BP0055": # sensor_instance_unknown return {} raise for entry in st.get("instances") or []: diff --git a/packages/embeddedci/src/embeddedci/benchpod/state.py b/packages/embeddedci/src/embeddedci/benchpod/state.py index abe80bb..f071562 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/state.py +++ b/packages/embeddedci/src/embeddedci/benchpod/state.py @@ -621,6 +621,11 @@ class ModuleInfo: #: The stored calibration blob's length in bytes (0 = none) and whether its CRC matched. cal_len: int = 0 cal_ok: bool = False + #: The digital board and the module use the same flat-cable DAC pinout. ``False``: the DAC is + #: off and every command that drives it is refused + #: (:class:`~embeddedci.benchpod.errors.DacPinoutMismatchError`, ``BP0080``); a digital v3r4 or + #: later board needs analog module 3.5 or later. ``None`` when the pod does not report it. + dac_pinout_ok: Optional[bool] = None raw: Dict[str, Any] = _raw() @classmethod @@ -630,7 +635,9 @@ def from_reply(cls, reply: Any) -> "ModuleInfo": return cls(present=d.get("present") is True, analog=d.get("analog") is True, power=d.get("power") is True, bridge_power=d.get("bridge_power") is True, eeprom=str(d.get("eeprom", "none")), type=s("type"), rev=s("rev"), serial=s("serial"), - cal_len=_opt_int(d, "cal_len") or 0, cal_ok=d.get("cal_ok") is True, raw=d) + cal_len=_opt_int(d, "cal_len") or 0, cal_ok=d.get("cal_ok") is True, + dac_pinout_ok=d["dac_pinout_ok"] if isinstance(d.get("dac_pinout_ok"), bool) else None, + raw=d) @dataclass(frozen=True) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py index 0e0ef7b..e608cb7 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py @@ -42,7 +42,8 @@ #: The pod runs one cloud command at a time and refuses a second with exactly this error, #: BEFORE running it (cloud_client.c), so any command can be sent again. The other side is #: usually a short server push (power reconcile, pin directions) or a browser's power poll. -_DEVICE_BUSY = "device busy" +#: The pod is still running the previous cloud command (cloud_command_busy): retried. +_DEVICE_BUSY = "BP0052" _BUSY_RETRY_WAIT = 0.3 #: How long one command keeps asking again while the pod answers "device busy". _BUSY_RETRY_BUDGET = 15.0 @@ -431,15 +432,20 @@ def command(self, req: dict) -> Any: # type: ignore[override] while True: payload = self._command_once(url, body, req, cmd, timeout) if (payload.get("status") == "error" - and str(payload.get("error") or "").strip().lower() == _DEVICE_BUSY + and str(payload.get("code") or "") == _DEVICE_BUSY and time.monotonic() + _BUSY_RETRY_WAIT < busy_until): self.busy_retries = getattr(self, "busy_retries", 0) + 1 time.sleep(_BUSY_RETRY_WAIT) continue break if payload.get("status") == "error": - raise firmware_error(payload.get("error") or "device returned an error", cmd=cmd, - code=str(payload.get("code") or ""), + code = str(payload.get("code") or "") + # The envelope's error is the pod's message, or the code itself when it sent none. + message = str(payload.get("error") or "") + if code and message == code: + message = "" + raise firmware_error(message if code else (message or "device returned an error"), + cmd=cmd, code=code, values=payload.get("args") if isinstance(payload.get("args"), dict) else None) return payload.get("data") diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index d015937..6f7a177 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -469,6 +469,9 @@ }, "DacOutputPath": "Literal['3v3', '5v', '12v', 'off']", "DacPath": "Literal['3v3', '5v', '12v', 'current_out']", + "DacPinoutMismatchError": { + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, digital: 'str' = '', module: 'str' = '') -> 'None'" + }, "DecodeProtocol": "Literal['i2c', 'uart', 'spi']", "DefinitionError": { "__init__": "(self, message: 'str', *, path: 'Optional[str]' = None) -> 'None'" @@ -842,6 +845,7 @@ "serial", "cal_len", "cal_ok", + "dac_pinout_ok", "raw" ], "from_reply": "(cls, reply: 'Any') -> \"'ModuleInfo'\"" @@ -919,7 +923,7 @@ } }, "PinConflictError": { - "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, la: 'int' = 0, function: 'str' = '') -> 'None'" + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, la: 'int' = 0, function: 'str' = '', owner: 'str' = '', instance: 'str' = '') -> 'None'" }, "PodBusyError": {}, "PodLeaseLostError": { @@ -1003,6 +1007,7 @@ "__init__": "(self, *, stop: 'Callable[[], Any]', samples: 'int' = 0, sample_rate_hz: 'float' = 0.0, dac_path: 'str' = '', deep: 'bool' = False, data: 'Optional[dict]' = None, cotrig: 'bool' = False, switched_image: \"Optional['FpgaImageInfo']\" = None) -> 'None'" }, "ReplayMapping": "Literal['faithful', 'fit']", + "ReplyTooLargeError": {}, "ResetState": { "__fields__": [ "asserted", @@ -1381,6 +1386,7 @@ "DacOutput", "DacOutputPath", "DacPath", + "DacPinoutMismatchError", "DecodeProtocol", "DefinitionError", "DeviceBusyError", @@ -1462,6 +1468,7 @@ "RailPower", "ReplayHandle", "ReplayMapping", + "ReplyTooLargeError", "ResetState", "SENSOR_LIBRARY_VERSION", "Segment", diff --git a/packages/embeddedci/tests/test_cloud.py b/packages/embeddedci/tests/test_cloud.py index c3c493b..a0c7dc7 100644 --- a/packages/embeddedci/tests/test_cloud.py +++ b/packages/embeddedci/tests/test_cloud.py @@ -282,12 +282,13 @@ def __exit__(self, *a): def test_cloud_transport_command_retries_device_busy(monkeypatch): - """The pod refuses a second cloud command with "device busy" before running it (a server - push or a browser poll is ahead of it), so the transport asks again instead of failing.""" + """The pod refuses a second cloud command with BP0052 (cloud_command_busy) before running it + (a server push or a browser poll is ahead of it), so the transport asks again instead of + failing. The envelope's error is the code itself: the pod sends no message.""" from embeddedci.benchpod.transport import cloud t = CloudTransport("dev-a", api_base="https://example.test", token="x") - replies = [b'{"status":"error","error":"device busy"}'] * 2 + \ + replies = [b'{"status":"error","error":"BP0052","code":"BP0052"}'] * 2 + \ [b'{"status":"ok","data":{"range":"low"}}'] sent = [] @@ -318,17 +319,17 @@ def sleep(s): def fake_urlopen(req, *a, **k): calls.append(1) - return _JsonResp(b'{"status":"error","error":"device busy"}') + return _JsonResp(b'{"status":"error","error":"BP0052","code":"BP0052"}') monkeypatch.setattr(_http, "urlopen", fake_urlopen) - with pytest.raises(FirmwareError, match="device busy"): + with pytest.raises(FirmwareError, match="BP0052: The pod is still running the previous cloud command"): t.command({"cmd": "dac_out", "path": "5v", "volts": 1.0}) assert 10 < len(calls) <= cloud._BUSY_RETRY_BUDGET / cloud._BUSY_RETRY_WAIT + 1 def test_cloud_transport_command_other_busy_is_not_retried(monkeypatch): - """Only the cloud channel's "device busy" is a refusal before running; "swd busy" and the - like come from the command itself and are raised at once.""" + """Only BP0052 is a refusal before running; another busy refusal (BP0047) comes from the + command itself and is raised at once.""" from embeddedci.benchpod.errors import FirmwareError t = CloudTransport("dev-a", api_base="https://example.test", token="x") @@ -336,7 +337,7 @@ def test_cloud_transport_command_other_busy_is_not_retried(monkeypatch): def fake_urlopen(req, *a, **k): calls.append(1) - return _JsonResp(b'{"status":"error","error":"busy: a capture or upload is running"}') + return _JsonResp(b'{"status":"error","error":"BP0047","code":"BP0047"}') monkeypatch.setattr(_http, "urlopen", fake_urlopen) with pytest.raises(FirmwareError): diff --git a/packages/embeddedci/tests/test_digital_v3r4.py b/packages/embeddedci/tests/test_digital_v3r4.py index 9a9aafa..ed4061e 100644 --- a/packages/embeddedci/tests/test_digital_v3r4.py +++ b/packages/embeddedci/tests/test_digital_v3r4.py @@ -77,7 +77,7 @@ def command(self, req: dict) -> Any: if req["cmd"] == "la_pins": want = req.get("la") if self.subset else None if want is None and self.too_large: - raise firmware_error("reply too large", cmd="la_pins") + raise firmware_error("", cmd="la_pins", code="BP0054", values={"bytes": 1900, "limit": 1791}) pins = [self._entry(n) for n in range(1, 15) if want is None or n in want] return {"pins": pins, "pull_dirs": ["up", "down"], "levels": None} if req["cmd"] in ("la_dir", "gpio"): # the same entries, without pull_dirs @@ -178,11 +178,6 @@ def test_la_pins_too_large_reads_in_two_parts(): assert [p.la for p in pins] == list(range(1, 15)) assert pod.sent[-2:] == [{"cmd": "la_pins", "la": [1, 2, 3, 4, 5, 6, 7]}, {"cmd": "la_pins", "la": [8, 9, 10, 11, 12, 13, 14]}] - # Firmware without the subset cannot help: the error stands. - pod.subset = False - with pytest.raises(FirmwareError, match="reply too large") as e: - bp.la_pins() - assert "firmware after 3.10.12 reads this list in parts" in str(e.value) def test_la_dir_and_gpio_entries_pull_both_ways_on_v3r4(): diff --git a/packages/embeddedci/tests/test_error_codes.py b/packages/embeddedci/tests/test_error_codes.py index 4041cfb..6fbce9a 100644 --- a/packages/embeddedci/tests/test_error_codes.py +++ b/packages/embeddedci/tests/test_error_codes.py @@ -1,15 +1,20 @@ -"""Pod refusals are classified by their stable error code; the text only decides without one. +"""Pod refusals are classified by their stable error code only; firmware 4.0 sends no text with +one (BP0030 alone carries a message, for clients from before the codes). -One coded reply per catalog code gives the class and fields of ``errors._BY_CODE``; one text-only -reply (firmware without codes) per text pattern gives the class it always did.""" +One coded reply without a message per catalog code gives the class and fields of +``errors._BY_CODE`` and a message rendered from the catalog; a refusal without a code keeps its +text and is never classified from it.""" from __future__ import annotations +from typing import Any, Dict + import pytest from embeddedci.benchpod import errors from embeddedci.benchpod.errors import ( ClientTooOldError, + DacPinoutMismatchError, DirectionConflictError, FirmwareError, PermissionDeniedError, @@ -20,6 +25,7 @@ PodLockedError, PullConflictError, PullDirectionError, + ReplyTooLargeError, TriggerTimeout, UnsupportedFeatureError, WiringError, @@ -27,108 +33,153 @@ error_catalog, firmware_error, ) - -#: code -> (args the pod sends, the class, the fields it fills) -CODED = { - "BP0001": ({}, FirmwareError, {}), - "BP0002": ({"cmd": "i2c_start"}, UnsupportedFeatureError, {"feature": "i2c_start"}), - "BP0003": ({}, PodBusyError, {}), - "BP0004": ({}, PodBusyError, {}), - "BP0005": ({"want": "i2c"}, PodBusyError, {}), - "BP0006": ({"arg": "name"}, FirmwareError, {}), - "BP0007": ({"name": "k66"}, WiringError, {"name": "k66"}), - "BP0008": ({"name": "K 66"}, WiringError, {"name": "K 66"}), - "BP0009": ({"name": "k66", "rev": 2}, WiringError, {"name": "k66"}), - "BP0010": ({"max": 8}, WiringError, {"name": ""}), - "BP0011": ({"bytes": 5000, "max": 4096}, WiringError, {"name": ""}), - "BP0012": ({}, WiringError, {"name": ""}), - "BP0013": ({"name": "default"}, WiringError, {"name": "default"}), - "BP0014": ({"expected": 0}, WiringError, {"name": ""}), - "BP0015": ({}, WiringError, {"name": ""}), - "BP0016": ({}, PodBusyError, {}), - "BP0017": ({"feature": "half_duplex", "min": 57}, UnsupportedFeatureError, {"feature": "half_duplex"}), - "BP0018": ({"la": 4}, FirmwareError, {}), - "BP0019": ({"rx": 4, "tx": 5}, FirmwareError, {}), - "BP0020": ({}, FirmwareError, {}), - "BP0021": ({"arg": "hold_ms", "max": 5000}, FirmwareError, {}), - "BP0022": ({"la": 4}, FirmwareError, {}), - "BP0023": ({"la": 9}, PullDirectionError, {"la": 9, "want": "", "have": ""}), - "BP0024": ({"la": 7, "want": "up", "have": "down"}, PullDirectionError, - {"la": 7, "want": "up", "have": "down"}), - "BP0025": ({"holder": "ci run 7", "purpose": "hil", "left_s": 42}, PodLeasedError, - {"holder": "ci run 7", "purpose": "hil", "left_s": 42}), - "BP0026": ({"by": "ward"}, PodLeaseLostError, {"by": "ward"}), - "BP0027": ({"id": "abc"}, FirmwareError, {}), - "BP0028": ({"mv": 4120}, FirmwareError, {}), - "BP0029": ({"mv": 120}, FirmwareError, {}), - "BP0030": ({"client_api": 0, "min_client_api": 1, "api": 1}, ClientTooOldError, - {"client_api": 0, "min_client_api": 1, "api": 1}), +from embeddedci.benchpod.protocol import Reply, raise_for_status + +#: code -> (the class, the fields its args fill). The args come from the catalog (_args). +CODED: Dict[str, Any] = { + "BP0001": (FirmwareError, {}), + "BP0002": (UnsupportedFeatureError, {"feature": "v_cmd"}), + "BP0003": (PodBusyError, {}), + "BP0004": (PodBusyError, {}), + "BP0005": (PodBusyError, {}), + "BP0006": (FirmwareError, {}), + **{f"BP00{n:02d}": (WiringError, {"name": "v_name" if n in (7, 8, 9, 13) else ""}) + for n in range(7, 16)}, + "BP0016": (PodBusyError, {}), + "BP0017": (UnsupportedFeatureError, {"feature": "v_feature"}), + **{f"BP00{n}": (FirmwareError, {}) for n in range(18, 23)}, + "BP0023": (PullDirectionError, {"la": 7, "want": "", "have": ""}), + "BP0024": (PullDirectionError, {"la": 7, "want": "v_want", "have": "v_have"}), + "BP0025": (PodLeasedError, {"holder": "v_holder", "purpose": "v_purpose", "left_s": 7}), + "BP0026": (PodLeaseLostError, {"by": "v_by"}), + "BP0027": (FirmwareError, {}), + "BP0028": (FirmwareError, {}), + "BP0029": (FirmwareError, {}), + "BP0030": (ClientTooOldError, {"client_api": 7, "min_client_api": 7, "api": 7}), + "BP0031": (PinConflictError, {"la": 7, "function": "v_function", "owner": "v_owner", + "instance": "v_instance"}), + "BP0032": (PullConflictError, {"la": 7}), + "BP0033": (PullConflictError, {"la": 7}), + "BP0034": (DirectionConflictError, {"la": 7}), + "BP0035": (DirectionConflictError, {"la": 7}), + "BP0036": (FirmwareError, {}), + "BP0037": (FirmwareError, {}), + "BP0038": (TriggerTimeout, {"la": 7, "edge": "v_edge"}), + "BP0039": (TriggerTimeout, {"la": 7, "edge": "start"}), + **{f"BP00{n}": (PodLockedError, {}) for n in (40, 41, 42, 43, 44)}, + "BP0045": (PermissionDeniedError, {}), + "BP0046": (UnsupportedFeatureError, {"feature": "analog"}), + **{f"BP00{n}": (PodBusyError, {}) for n in (47, 48, 49, 50, 51, 52)}, + "BP0053": (ReplyTooLargeError, {}), + "BP0054": (ReplyTooLargeError, {}), + "BP0055": (FirmwareError, {}), + "BP0056": (UnsupportedFeatureError, {"feature": "module"}), + "BP0057": (FirmwareError, {}), + "BP0058": (UnsupportedFeatureError, {"feature": "v_feature"}), + "BP0059": (UnsupportedFeatureError, {"feature": "v_feature"}), + "BP0060": (UnsupportedFeatureError, {"feature": "v_target"}), + **{f"BP00{n}": (FirmwareError, {}) for n in (61, 62, 63)}, + "BP0064": (UnsupportedFeatureError, {"feature": "dac_loop_input_map"}), + "BP0065": (FirmwareError, {}), + "BP0066": (PodBusyError, {}), + **{f"BP00{n}": (FirmwareError, {}) for n in range(67, 75)}, + "BP0075": (PodLockedError, {}), + **{f"BP00{n}": (UnsupportedFeatureError, {"feature": "usb_host"}) for n in (76, 77, 78)}, + "BP0079": (FirmwareError, {}), + "BP0080": (DacPinoutMismatchError, {"digital": "v_digital", "module": "v_module", + "feature": "dac"}), } +def _args(code: str) -> Dict[str, Any]: + """The args a pod sends with ``code``: every arg the catalog names, "v_" or 7.""" + spec = error_catalog()["codes"][code].get("args") or {} + return {name: (7 if kind == "int" else f"v_{name}") for name, kind in spec.items()} + + def test_every_catalog_code_has_a_class(): - """A sync that adds a code fails here until the code is in the table.""" + """A sync that adds a code fails here until the code is in both tables.""" assert set(error_catalog()["codes"]) == set(errors._BY_CODE) == set(CODED) @pytest.mark.parametrize("code", sorted(CODED)) -def test_coded_reply(code): - args, cls, fields = CODED[code] - # The text is one that would classify as something else, so only the code can decide. - err = firmware_error("pin conflict: LA4 is in use by gpio", cmd="x", code=code, values=args) +def test_coded_reply_without_a_message(code): + """The firmware 4.0 reply: code and args, no message. The class, its fields and the message + all come from the code.""" + args = _args(code) + with pytest.raises(FirmwareError) as info: + raise_for_status(Reply(status="error", code=code, args=args), cmd="x") + err = info.value + cls, fields = CODED[code] assert type(err) is cls assert err.code == code and err.values == args and err.docs_url.endswith("#" + code) + assert err.firmware_message == "" for name, want in fields.items(): assert getattr(err, name) == want, name - assert classify_firmware_error(err) is err # the client's re-classification keeps it - assert str(err).startswith(f"x: {code}: ") + assert classify_firmware_error(err) is err + entry = error_catalog()["codes"][code] + msg = str(err) + assert msg.startswith(f"x: {code}: ") + assert errors._fill(entry["message"], args) in msg and errors._fill(entry["fix"]["sdk"], args) in msg + assert "{" not in msg.replace(err.docs_url, "") and "unknown firmware error" not in msg + + +def test_a_plain_firmware_error_with_a_code_is_classified(): + """A fake transport may raise FirmwareError and attach the code: the client's + re-classification gives the code's class.""" + plain = FirmwareError("", cmd="gpio") + errors._attach_code(plain, "BP0031", {"la": 4, "owner": "gpio", "function": "gpio", "instance": ""}) + err = classify_firmware_error(plain) + assert type(err) is PinConflictError and err.la == 4 and err.function == "gpio" + + +def test_bp0030_keeps_its_message_and_names_the_update(): + err = firmware_error("Update the BenchPod SDK, MCP or CLI: this firmware needs client API 3", + cmd="gpio", code="BP0030", + values={"client_api": 2, "min_client_api": 3, "api": 3}) + assert type(err) is ClientTooOldError and err.min_client_api == 3 + assert err.firmware_message.startswith("Update the BenchPod SDK") + assert "pip install -U embeddedci" in str(err) -def test_la_voltage_keeps_the_sdk_text(): - err = firmware_error("la voltage not set; set la_mv ...", cmd="uart_proxy_start", code="BP0001") - assert "bp.set_la_voltage(3.3)" in str(err) and "set la_mv in it" in str(err) - assert str(err).startswith("uart_proxy_start: BP0001: la voltage not set") +def test_la_voltage_names_the_sdk_ways_to_set_it(): + err = firmware_error("", cmd="uart_proxy_start", code="BP0001") + assert str(err).startswith("uart_proxy_start: BP0001: The I/O voltage is not set") + assert "bp.set_la_voltage(3.3)" in str(err) -def test_client_too_old_names_the_update(): - err = firmware_error("update the BenchPod SDK", cmd="gpio", code="BP0030", - values={"client_api": 0, "min_client_api": 1, "api": 1}) - assert "pip install -U embeddedci" in str(err) - assert not isinstance(err, UnsupportedFeatureError) - - -def test_unknown_code_falls_back_to_the_text(): - """A code newer than this SDK: the text still classifies it, the code is kept.""" - err = firmware_error("pin conflict: LA4 is in use by gpio", cmd="gpio", code="BP0999") - assert type(err) is PinConflictError and err.la == 4 and err.code == "BP0999" - - -# -- text only (firmware without codes): the classes they always had --------------------------- - -TEXT_ONLY = [ - ("pin conflict: LA4 is in use by gpio; release it with x", PinConflictError, {"la": 4, "function": "gpio"}), - ("pull conflict: LA7 pull-down under a UART line", PullConflictError, {"la": 7}), - ("direction conflict: LA3 is a DUT output", DirectionConflictError, {"la": 3}), - ("the I2C master needs gateware v55+: update the pod's firmware", UnsupportedFeatureError, - {"feature": "cmd"}), - ("trigger timeout: no rising edge on LA2", TriggerTimeout, {"la": 2, "edge": "rising"}), - ("locked: generate needs the cloud or USB", PodLockedError, {}), - ("busy: a cloud job holds this pod (octo run 7, 42 s left)", PodLeasedError, - {"holder": "octo run 7", "left_s": 42}), - ("busy: stop the DAC or wait for the capture, then save", PodBusyError, {}), - ("forbidden: generate needs an organization owner or admin", PermissionDeniedError, {}), - ("unknown cmd", UnsupportedFeatureError, {"feature": "cmd"}), - ("this BenchPod has no analog front end", UnsupportedFeatureError, {"feature": "analog"}), - ("la voltage not set; set la_mv (1800 or 3300) in the active wiring profile", FirmwareError, {}), - ("i2c busy: send i2c_stop first", FirmwareError, {}), - ("no such profile", FirmwareError, {}), -] - - -@pytest.mark.parametrize("text,cls,fields", TEXT_ONLY, ids=[t[0][:24] for t in TEXT_ONLY]) -def test_text_only_reply(text, cls, fields): +def test_a_code_newer_than_the_sdk(): + err = firmware_error("", cmd="gpio", code="BP0999", values={"la": 4}) + assert type(err) is FirmwareError and err.code == "BP0999" and err.values == {"la": 4} + assert "update it (pip install -U embeddedci)" in str(err) and "#BP0999" in str(err) + said = firmware_error("something new", cmd="gpio", code="BP0999") + assert "something new" in str(said) + + +@pytest.mark.parametrize("text", [ + "pin conflict: LA4 is in use by gpio", + "locked: generate needs the cloud or USB", + "busy: a cloud job holds this pod (octo run 7, 42 s left)", + "unknown cmd", + "this BenchPod has no analog front end", + "la voltage not set", + "missing steps", +]) +def test_text_without_a_code_is_never_classified(text): + """Free-text refusals keep their message as it is, and their class is plain FirmwareError.""" err = firmware_error(text, cmd="cmd") - assert type(err) is cls and err.code == "" - for name, want in fields.items(): - assert getattr(err, name) == want, name - assert err.firmware_message == text + assert type(err) is FirmwareError and err.code == "" + assert err.firmware_message == text and str(err) == f"cmd: {text}" + with pytest.raises(FirmwareError) as info: + raise_for_status(Reply(status="error", message=text), cmd="cmd") + assert type(info.value) is FirmwareError and str(info.value) == f"cmd: {text}" + + +def test_a_reply_without_code_or_message(): + with pytest.raises(FirmwareError, match="unknown firmware error"): + raise_for_status(Reply(status="error"), cmd="x") + + +def test_explain(): + assert "BP0080 dac_pinout_mismatch" in errors.explain("bp0080") + assert "not in this SDK's catalog" in errors.explain("BP0999") diff --git a/packages/embeddedci/tests/test_gpio.py b/packages/embeddedci/tests/test_gpio.py index 2d97fa8..bb5bccd 100644 --- a/packages/embeddedci/tests/test_gpio.py +++ b/packages/embeddedci/tests/test_gpio.py @@ -18,7 +18,7 @@ TriggerTimeout, Wiring, ) -from embeddedci.benchpod.errors import classify_firmware_error +from embeddedci.benchpod.errors import classify_firmware_error, firmware_error class PinPod: @@ -48,7 +48,7 @@ def close(self) -> None: def uart_proxy_start(self, rx: int, tx: int, baud: int): for la in (rx, tx): if self.function[la] != "none": - raise FirmwareError(self._conflict(la), cmd="uart_proxy_start") + raise self._conflict(la, "uart_proxy_start") self.uart_starts.append((rx, tx, baud)) raise AssertionError("not needed") @@ -64,11 +64,10 @@ def command(self, req: dict) -> Any: return {} # -- behaviour -- - def _conflict(self, la: int) -> str: + def _conflict(self, la: int, cmd: str) -> FirmwareError: fn = self.function[la] - how = (f'release it with {{"cmd":"gpio","la":{la},"mode":"off"}}' if fn == "gpio" - else "stop the uart proxy first") - return f"pin conflict: LA{la} is in use by {fn}; {how}" + return firmware_error("", cmd=cmd, code="BP0031", + values={"la": la, "owner": fn, "function": fn, "instance": ""}) def _entry(self, la: int) -> Dict[str, Any]: pull = None @@ -98,18 +97,19 @@ def _gpio(self, req: dict) -> Any: if mode is not None: for la in las: if self.function[la] not in ("none", "gpio"): - raise FirmwareError(self._conflict(la), cmd="gpio") + raise self._conflict(la, "gpio") if mode == "open_drain" and la in (7, 8) and self.pull_on[la]: - raise FirmwareError( - f"pull conflict: LA{la} has its 10k pull-down engaged, which gpio open_drain can't " - "work with (a released line would read low)", cmd="gpio") + raise firmware_error("", cmd="gpio", code="BP0032", values={ + "la": la, "ohms": "10k", "function": "gpio open_drain", + "reason": "a released line would read low"}) for la in las: self.function[la], self.mode[la] = "gpio", mode self.level[la] = None if mode == "input" else req.get("level", 1 if mode == "open_drain" else 0) return {"pins": [self._entry(la) for la in las]} for la in las: if self.mode[la] not in ("output", "open_drain"): - raise FirmwareError(f"LA{la} is not a gpio output (function {self.function[la]})", cmd="gpio") + raise firmware_error("", cmd="gpio", code="BP0036", + values={"la": la, "function": self.function[la]}) self.level[la] = req["level"] return {"pins": [self._entry(la) for la in las]} @@ -158,9 +158,8 @@ def test_pin_conflicts_are_their_own_error(): bp.gpio(4) with pytest.raises(PinConflictError) as ei: bp.open_uart(rx=3, tx=4) - assert ei.value.la == 4 and ei.value.function == "gpio" - assert str(ei.value).endswith("pin conflict: LA4 is in use by gpio; release it with bp.release_gpio(4)") - assert 'release it with {"cmd":"gpio","la":4,"mode":"off"}' in ei.value.firmware_message + assert ei.value.la == 4 and ei.value.function == "gpio" and ei.value.code == "BP0031" + assert "LA4 is in use by gpio; free LA4 first: bp.release_gpio(4)" in str(ei.value) assert isinstance(ei.value, FirmwareError) @@ -226,8 +225,9 @@ def test_pin_levels_fall_back_to_a_capture_without_gpio_read(): def test_error_classification(): plain = FirmwareError("la voltage not set", cmd="gpio") - assert classify_firmware_error(plain) is plain - trig = classify_firmware_error(FirmwareError("trigger timeout: no rising edge on LA9 within 100 ms")) + assert classify_firmware_error(plain) is plain # text alone decides nothing + trig = firmware_error("", code="BP0038", values={"la": 9, "edge": "rising", "timeout_ms": 100}) assert isinstance(trig, TriggerTimeout) and (trig.la, trig.edge) == (9, "rising") - pull = classify_firmware_error(FirmwareError("pull conflict: LA8 is used by uart_rx, which can't ...")) + pull = firmware_error("", code="BP0033", values={"la": 8, "ohms": "10k", "function": "uart_rx", + "reason": "x"}) assert isinstance(pull, PullConflictError) and pull.la == 8 diff --git a/packages/embeddedci/tests/test_header.py b/packages/embeddedci/tests/test_header.py index 96560d1..f39f80a 100644 --- a/packages/embeddedci/tests/test_header.py +++ b/packages/embeddedci/tests/test_header.py @@ -6,6 +6,8 @@ import pytest +from embeddedci.benchpod.errors import firmware_error + from embeddedci.benchpod import BenchPod, Wiring, header_map from embeddedci.benchpod.errors import BenchPodError, UnsupportedFeatureError from embeddedci.benchpod.header import connections, header_from_status @@ -72,7 +74,7 @@ def status(self) -> Dict[str, Any]: @pytest.mark.parametrize("module,status,want", [ ({"present": True}, {}, "front"), - (BenchPodError("module: this BenchPod has no module link (digital v3r3 only)"), {}, "j1"), + (firmware_error("", cmd="module", code="BP0056", values={"cmd": "module"}), {}, "j1"), (UnsupportedFeatureError("unknown command: module"), {"board_rev": "v3r2"}, "j1"), (UnsupportedFeatureError("unknown command: module"), {"board_rev": "v3"}, None), ]) diff --git a/packages/embeddedci/tests/test_i2c_master.py b/packages/embeddedci/tests/test_i2c_master.py index fe5016d..eb8963f 100644 --- a/packages/embeddedci/tests/test_i2c_master.py +++ b/packages/embeddedci/tests/test_i2c_master.py @@ -40,10 +40,9 @@ class BusPod: TARGET = 0x42 - def __init__(self, *, gateware: Optional[int] = 55, coded: bool = False) -> None: + def __init__(self, *, gateware: Optional[int] = 55) -> None: self.gateware = gateware #: Answer like firmware with error codes (BP0003), else like older firmware (text only). - self.coded = coded self.commands: List[dict] = [] self.session: Optional[dict] = None self.mem = bytearray(range(256)) @@ -89,13 +88,11 @@ def command(self, req: dict) -> Any: cmd = req["cmd"] if cmd == "i2c_start": if (self.gateware or 0) < 55: - raise FirmwareError("the I2C master needs gateware v55+: update the pod's firmware", cmd=cmd) + raise firmware_error("", cmd=cmd, code="BP0017", values={"feature": "I2C master", "min": 55}) if req["pullups"] == "pod" and req["sda"] > 6: raise FirmwareError(f"LA{req['sda']} has no pod pull-up (only LA1..LA6 do)", cmd=cmd) if self.session: - if self.coded: - raise firmware_error("i2c busy: send i2c_stop first", cmd=cmd, code="BP0003") - raise FirmwareError("i2c busy: send i2c_stop first", cmd=cmd) + raise firmware_error("", cmd=cmd, code="BP0003") self.session = req self.driven[req["sda"]] = "i2cm_sda" self.driven[req["scl"]] = "i2cm_scl" @@ -111,7 +108,7 @@ def command(self, req: dict) -> Any: return {"active": True, "sda": self.session["sda"], "scl": self.session["scl"], "hz": self.session["hz"], "pullups": self.session["pullups"]} if cmd in ("i2c_xfer", "i2c_scan") and not self.session: - raise FirmwareError("no I2C session: send i2c_start first", cmd=cmd) + raise firmware_error("", cmd=cmd, code="BP0062") if cmd == "i2c_xfer": write = unb64(req.get("write", "")) assert len(write) <= 128 and req.get("read", 0) <= 248 @@ -126,17 +123,16 @@ def command(self, req: dict) -> Any: req["la"] if isinstance(req["la"], list) else [req["la"]]) for la in las: if req["dir"] == "dut_output" and self.driven.get(la) == "gpio_output": - raise FirmwareError(f"direction conflict: LA{la} is driven by gpio output, so it " - "can't be wired to a DUT output; stop that first", cmd=cmd) + raise firmware_error("", cmd=cmd, code="BP0035", + values={"la": la, "function": "gpio output"}) for la in las: self.dirs[la] = req["dir"] return {"pins": [self._pin(la) for la in las]} if cmd == "gpio" and req.get("mode") == "output": la = req["la"] if self.dirs.get(la) == "dut_output": - raise FirmwareError(f"direction conflict: LA{la} is wired to a DUT output and gpio " - "output would drive against it; use gpio open_drain, or fix the " - f"wiring if LA{la} is not a DUT output", cmd=cmd) + raise firmware_error("", cmd=cmd, code="BP0034", + values={"la": la, "function": "gpio output"}) self.driven[la] = "gpio_output" return {"pins": [{"la": la, "function": "gpio", "gpio": "output", "level": 0}]} if cmd == "la_pins": @@ -150,7 +146,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: result = None if send and send["bus"] == "i2c": if not self.session: - raise FirmwareError("send: no I2C session: send i2c_start first", cmd="la_capture") + raise firmware_error("", cmd="la_capture", code="BP0062") r = self._xfer(send["addr"], unb64(send.get("write", "")), send.get("read", 0)) result = {"bus": "i2c", **{k: v for k, v in r.items() if k != "addr"}} elif send and send["bus"] == "spi": @@ -198,27 +194,22 @@ def test_open_i2c_accepts_wiring_names_and_validates(): bp.open_i2c(1, 1) -@pytest.mark.parametrize("coded", [True, False]) -def test_busy_names_another_connection_as_the_holder(coded): +def test_busy_names_another_connection_as_the_holder(): """Another client (the desktop app, the web app) holds the pod's I2C master: the refusal says so and where, instead of pointing at an open_i2c() this script never called.""" - bp, fake = pod(coded=coded) + bp, fake = pod() fake.session = {"sda": 1, "scl": 2, "hz": 100_000, "pullups": "pod"} with pytest.raises(FirmwareError) as e: bp.open_i2c() msg = str(e.value) assert "another connection to this pod holds its I2C master (LA1 SDA, LA2 SCL, 100000 Hz)" in msg assert "desktop app" in msg and "bp.open_i2c() first" not in msg - if coded: - assert e.value.code == "BP0003" and isinstance(e.value, PodBusyError) - else: # firmware without codes: the text decides - assert e.value.firmware_message == "i2c busy: send i2c_stop first" + assert e.value.code == "BP0003" and isinstance(e.value, PodBusyError) assert fake.session["hz"] == 100_000 # nothing was stopped -@pytest.mark.parametrize("coded", [True, False]) -def test_busy_names_this_benchpods_own_open_session(coded): - bp, fake = pod(coded=coded) +def test_busy_names_this_benchpods_own_open_session(): + bp, fake = pod() i2c = bp.open_i2c() with pytest.raises(FirmwareError, match="this BenchPod already has an I2C session open .LA1 SDA, LA2 SCL.: close it first"): bp.open_i2c() @@ -436,7 +427,7 @@ def test_send_without_session_names_open_i2c(): def test_pin_conflict_with_i2c_master_names_the_session(): from embeddedci.benchpod.errors import firmware_error - e = firmware_error('pin conflict: LA1 is in use by i2cm_sda; stop the I2C session first ' - '({"cmd":"i2c_stop"})', cmd="gpio") + e = firmware_error("", cmd="gpio", code="BP0031", + values={"la": 1, "owner": "i2cm_sda", "function": "i2cm_sda", "instance": ""}) assert isinstance(e, PinConflictError) and e.function == "i2cm_sda" - assert "bp.open_i2c()" in str(e) + assert "close the UART, SPI or I2C session that uses it" in str(e) diff --git a/packages/embeddedci/tests/test_image_switching.py b/packages/embeddedci/tests/test_image_switching.py index 5822591..c8d596a 100644 --- a/packages/embeddedci/tests/test_image_switching.py +++ b/packages/embeddedci/tests/test_image_switching.py @@ -156,16 +156,15 @@ def test_deep_replay_switches_from_the_emulation_image(): assert {"cmd": "fpga_image", "image": 1} in pod.commands and handle.deep -def test_the_emulation_image_refusal_reads_as_sdk_calls(): - from embeddedci.benchpod.errors import _sdk_refusal_text - - msg = ('control loop is not in the emulation image, which the emulated sensors use: ' - '{"cmd":"sensor_stop","all":true} then {"cmd":"fpga_image","image":"loop"}') - assert _sdk_refusal_text(msg).endswith( - "use: bp.sensors.stop() then bp.fpga_image(FpgaImage.LOOP)") - msg = ('image switch refused: the emulated sensors env, imu need the emulation image; stop ' - 'them first ({"cmd":"sensor_stop","all":true})') - assert _sdk_refusal_text(msg).endswith("stop them first with bp.sensors.stop()") +def test_the_emulation_image_refusals_read_as_sdk_calls(): + from embeddedci.benchpod.errors import UnsupportedFeatureError, firmware_error + + e = firmware_error("", cmd="dac_control_loop", code="BP0059", + values={"feature": "control loop", "image": "loop"}) + assert isinstance(e, UnsupportedFeatureError) and e.feature == "control loop" + assert "bp.sensors.stop()" in str(e) + e = firmware_error("", cmd="fpga_image", code="BP0057", values={"sensors": "env, imu"}) + assert "env, imu" in str(e) and "bp.sensors.stop()" in str(e) # -- replay -------------------------------------------------------------------------------- diff --git a/packages/embeddedci/tests/test_module.py b/packages/embeddedci/tests/test_module.py index 7244049..c5e8d98 100644 --- a/packages/embeddedci/tests/test_module.py +++ b/packages/embeddedci/tests/test_module.py @@ -53,6 +53,12 @@ def test_blank_module() -> None: assert isinstance(m, ModuleInfo) assert m.present and m.analog and m.eeprom == "blank" assert m.serial is None and m.cal_len == 0 and not m.cal_ok + assert m.dac_pinout_ok is None # the fake does not report it + + +def test_dac_pinout_ok_is_read() -> None: + assert ModuleInfo.from_reply({"present": True, "dac_pinout_ok": False}).dac_pinout_ok is False + assert ModuleInfo.from_reply({"present": True, "dac_pinout_ok": True}).dac_pinout_ok is True def test_set_module_id_writes_once() -> None: diff --git a/packages/embeddedci/tests/test_pin_directions.py b/packages/embeddedci/tests/test_pin_directions.py index 034c152..e90a2bc 100644 --- a/packages/embeddedci/tests/test_pin_directions.py +++ b/packages/embeddedci/tests/test_pin_directions.py @@ -1,5 +1,5 @@ """Pin directions by default: the wiring profile's DUT direction per role and signal (dut_dirs), -sent to the pod with la_dir on connect and on a new profile (firmware 3.10.4+).""" +sent to the pod with la_dir on connect and on a new profile.""" from __future__ import annotations @@ -86,7 +86,7 @@ def test_a_driven_pin_does_not_fail_the_connect_or_the_assignment(): 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.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 + assert "BP0035" in bp.pin_directions_status and "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" with pytest.raises(DirectionConflictError): diff --git a/packages/embeddedci/tests/test_refusal_errors.py b/packages/embeddedci/tests/test_refusal_errors.py index 6280885..5e6e8d1 100644 --- a/packages/embeddedci/tests/test_refusal_errors.py +++ b/packages/embeddedci/tests/test_refusal_errors.py @@ -1,7 +1,5 @@ -"""Typed errors for the pod's policy refusals (locked/busy/forbidden) and the server's 403/409. - -The texts are the firmware's (benchpod-firmware stm32h563/src/command_handler.c dispatch_line, -pod_policy.c) and the server's (writeLeaseBusy, writeJSONError).""" +"""Typed errors for the server's 403 and 409 (writeLeaseBusy, writeJSONError). The pod's own +refusals are classified by their code: test_error_codes.py.""" from __future__ import annotations @@ -14,84 +12,13 @@ from embeddedci.benchpod.errors import ( DeviceBusyError, - FirmwareError, PermissionDeniedError, - PinConflictError, - PodBusyError, PodLeasedError, - PodLockedError, - PullConflictError, TransportError, - firmware_error, ) -from embeddedci.benchpod.protocol import Reply, raise_for_status from embeddedci.benchpod.transport.cloud import CloudTransport -@pytest.mark.parametrize("text", [ - "locked: generate needs the cloud or the USB console", - "locked: generate needs the cloud or USB", - "sig_policy: change it from the cloud or the USB console", - "lan_policy: change it from the cloud or the USB console", - "cloud_ca: change it from the cloud or the USB console", - "cloud_proxy: change it from the cloud or over USB", - "usb_network: change it on the device (the USB console, or over the USB link)", - "sig_policy: only the USB console can loosen the policy (now required)", -]) -def test_locked(text): - err = firmware_error(text, cmd="x") - assert type(err) is PodLockedError and isinstance(err, FirmwareError) - - -def test_leased_carries_holder_and_time_left(): - err = firmware_error("busy: a cloud job holds this pod (octo/repo run 7, 42 s left)", cmd="gpio") - assert type(err) is PodLeasedError - assert err.holder == "octo/repo run 7" and err.left_s == 42 - assert isinstance(err, PodBusyError) and isinstance(err, FirmwareError) - assert isinstance(err, DeviceBusyError) - assert err.firmware_message.startswith("busy:") and err.cmd == "gpio" - - -def test_status_too_large_for_the_cloud_names_the_fix(): - err = firmware_error("reply too large for the cloud channel (1838 bytes, limit 1791)", cmd="status") - assert isinstance(err, FirmwareError) - assert "too large for the cloud channel" in str(err) and "firmware 3.10.5" in str(err) - # Other commands' size refusals are left as they are. - other = firmware_error("reply too large for the cloud channel (1900 bytes, limit 1791)", cmd="la_pins") - assert "3.10.5" not in str(other) - - -def test_la_pins_too_large_names_the_update(): - for msg in ("reply too large", "reply too large for the cloud channel (2288 bytes, limit 1791)"): - err = firmware_error(msg, cmd="la_pins") - assert err.firmware_message == msg - assert "firmware after 3.10.12 reads this list in parts" in str(err) - assert "benchpod flash-self" in str(err) and "la_pins(la=" in str(err) - assert "3.10.12" not in str(firmware_error("reply too large", cmd="gpio")) - - -def test_busy_without_a_lease(): - err = firmware_error("busy: a capture or upload is running") - assert type(err) is PodBusyError - - -def test_forbidden(): - err = firmware_error("forbidden: generate needs an organization owner or admin", cmd="generate") - assert type(err) is PermissionDeniedError and isinstance(err, FirmwareError) - assert err.status is None - - -def test_raise_for_status_raises_the_typed_error(): - with pytest.raises(PodLockedError): - raise_for_status(Reply(status="error", message="locked: la needs the cloud or the USB console"), - cmd="la") - - -def test_other_refusals_stay_plain(): - assert type(firmware_error("la voltage not set")) is FirmwareError - assert type(firmware_error("swd busy: an SPI session is using the engine")) is FirmwareError - - def test_server_api_403_is_permission_denied(monkeypatch): from embeddedci.benchpod.server_api import ServerApi, ServerApiError @@ -147,65 +74,3 @@ def test_cloud_command_409_is_leased(monkeypatch): # command_handler_dac.c. LA_VOLTAGE_FW = "la voltage not set; set it with la_voltage (mv 1800 or 3300) first" - - -def test_la_voltage_not_set_names_the_sdk_ways_to_set_it(): - err = firmware_error(LA_VOLTAGE_FW, cmd="uart_proxy_start") - assert type(err) is FirmwareError - assert str(err) == ("uart_proxy_start: la voltage not set; the wiring profile sets no I/O voltage: " - "set la_mv in it (bp.save_wiring(bp.wiring.with_changes(la_mv=3300)), 1800 " - "for a 1.8 V board), or pass BenchPod(conn, la_voltage=3.3), or call " - "bp.set_la_voltage(3.3)") - assert err.firmware_message == LA_VOLTAGE_FW and err.cmd == "uart_proxy_start" - assert "la voltage not set" in str(err) # what callers match on - - -@pytest.mark.parametrize("function, hint, fix", [ - ("gpio", 'release it with {"cmd":"gpio","la":4,"mode":"off"}', "release it with bp.release_gpio(4)"), - ("uart_tx", "stop the uart proxy first", - "close the UART session from bp.open_uart() first (session.close(), or leave its with block)"), - ("swd_clk", "end the SWD session first", "wait for the running flash (its SWD session) to finish"), - ("i2c_sda", 'stop the sensor emulation first ({"cmd":"sensor_stop"})', - "stop the sensor emulation first with bp.sensors.stop()"), - ("sensor:env", 'stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})', - 'stop the sensor emulation first (bp.sensors.stop("env"))'), - ("spi_sck", 'stop the SPI session first ({"cmd":"spi_stop"})', - "close the SPI session from bp.open_spi() first (spi.close(), or leave its with block)"), - ("step", "wait for the step train to finish", "wait for the step train to finish"), - ("can_rx", 'stop it with {"cmd":"can_stop"}', 'stop it with {"cmd":"can_stop"}'), # unknown: as is -]) -def test_pin_conflict_names_the_sdk_call(function, hint, fix): - fw = f"pin conflict: LA4 is in use by {function}; {hint}" - err = firmware_error(fw, cmd="gpio") - assert type(err) is PinConflictError and isinstance(err, FirmwareError) - assert err.la == 4 and err.function == function - assert str(err) == f"gpio: pin conflict: LA4 is in use by {function}; {fix}" - assert err.firmware_message == fw - - -def test_pull_conflict_names_set_pull(): - fw = ("pull conflict: LA7 has its 10k pull-down engaged, which uart_rx can't work with (the line " - 'idles high); disable it with {"cmd":"la","la":7,"pullup":"off"} or use another channel') - err = firmware_error(fw, cmd="uart_proxy_start") - assert type(err) is PullConflictError and err.la == 7 - assert str(err).endswith('disable it with bp.set_pull(7, "off") or use another channel') - assert err.firmware_message == fw - - -@pytest.mark.parametrize("fw, fixed", [ - ('LA4 is not a gpio output (function gpio, gpio input); configure it with ' - '{"cmd":"gpio","la":4,"mode":"output"}', 'configure it with bp.gpio(4, "output")'), - ('swd busy: an SPI session is using the engine ({"cmd":"spi_stop"})', - "using the engine (close the SPI session from bp.open_spi() first)"), - ('control loop not in the running gateware image (switch with {"cmd":"fpga_image","image":0})', - "(switch with bp.fpga_image(0))"), -]) -def test_other_protocol_fixes_name_the_sdk_call(fw, fixed): - err = firmware_error(fw) - assert str(err).endswith(fixed) and err.firmware_message == fw - - -def test_unknown_text_passes_through(): - for text in ("unknown target", 'something odd {"cmd":"mystery"}'): - err = FirmwareError(text, cmd="x") - assert str(err) == f"x: {text}" and err.firmware_message == text diff --git a/packages/embeddedci/tests/test_sensors.py b/packages/embeddedci/tests/test_sensors.py index 3fc2935..6f8f739 100644 --- a/packages/embeddedci/tests/test_sensors.py +++ b/packages/embeddedci/tests/test_sensors.py @@ -10,7 +10,7 @@ import pytest from embeddedci.benchpod import BenchPod, Sensor, load_definition, load_stimulus, sensors -from embeddedci.benchpod.errors import FirmwareError, UnsupportedFeatureError +from embeddedci.benchpod.errors import firmware_error, FirmwareError, UnsupportedFeatureError from embeddedci.benchpod.sensors import yaml12 from embeddedci.benchpod.sensors.definition import DefinitionError @@ -152,7 +152,7 @@ def samples(self, req: dict) -> List[int]: def _known(self, req: dict) -> str: name = req["instance"] if name not in self.instances: - raise FirmwareError(f"unknown sensor instance '{name}'", cmd=req["cmd"]) + raise firmware_error("", cmd=req["cmd"], code="BP0055", values={"instance": name}) return name def command(self, req: dict) -> Any: @@ -294,7 +294,7 @@ def test_handle_drives_set_fault_regs_capture_and_stop(): s.set(temperature_c="hot") assert fake.commands[-1] == {"cmd": "sensor_stop", "instance": "bmp280"} assert bp.sensors.status()["instances"] == [] - with pytest.raises(FirmwareError, match="unknown sensor instance 'bmp280'"): + with pytest.raises(FirmwareError, match="BP0055: The pod has no emulated sensor bmp280"): bp.sensors.set("bmp280", temperature_c=1) @@ -330,9 +330,9 @@ def test_capture_waits_for_the_dut_on_firmware_with_sensor_la_trigger(): with pytest.raises(ValueError, match="timeout_s"): s.capture(16, timeout_s=601) # the pod's answer when the DUT stays quiet is a TriggerTimeout on the SDA channel - err = classify_firmware_error(FirmwareError( - "trigger timeout: no falling edge on LA2 (SDA of probe) within 2000 ms; the DUT did not use the I2C bus")) - assert isinstance(err, TriggerTimeout) and (err.la, err.edge) == (2, "falling") + err = firmware_error("", cmd="sensor_la", code="BP0039", + values={"la": 2, "instance": "probe", "timeout_ms": 2000}) + assert isinstance(err, TriggerTimeout) and (err.la, err.edge) == (2, "start") def test_capture_of_a_uart_or_spi_sensor_points_at_la_capture(): diff --git a/packages/embeddedci/tests/test_trigger_power.py b/packages/embeddedci/tests/test_trigger_power.py index 9178767..493e907 100644 --- a/packages/embeddedci/tests/test_trigger_power.py +++ b/packages/embeddedci/tests/test_trigger_power.py @@ -16,6 +16,7 @@ TriggerTimeout, Wiring, ) +from embeddedci.benchpod.errors import firmware_error class StreamPod: @@ -25,7 +26,7 @@ def __init__(self, caps: Optional[List[str]] = None) -> None: self.caps = ["la", "capture_trigger", "power_profile"] if caps is None else caps self.requests: List[dict] = [] self.chunks: Dict[str, List[dict]] = {} - self.error: Optional[str] = None + self.error: Any = None self.gateware = 59 def status(self) -> Dict[str, Any]: @@ -44,6 +45,8 @@ def command(self, req: dict) -> Any: def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: self.requests.append(req) if self.error: + if isinstance(self.error, tuple): + raise firmware_error("", cmd=req["cmd"], code=self.error[0], values=self.error[1]) raise FirmwareError(self.error, cmd=req["cmd"]) if "rate_hz" in req and isinstance(req["rate_hz"], float): # The firmware's parser refuses a non-integer here ("rate_hz must be a whole @@ -97,7 +100,7 @@ def test_triggered_adc_capture_uses_the_streaming_path(): def test_trigger_timeout_and_bounds(): bp, pod = _bp() - pod.error = "trigger timeout: no rising edge on LA9 within 10000 ms" + pod.error = ("BP0038", {"la": 9, "edge": "rising", "timeout_ms": 10000}) with pytest.raises(TriggerTimeout) as ei: bp.capture_la(8, trigger=Trigger(9)) assert ei.value.la == 9 and ei.value.edge == "rising" diff --git a/packages/embeddedci/tests/test_unsupported_feature.py b/packages/embeddedci/tests/test_unsupported_feature.py index 2bf2487..1ff3305 100644 --- a/packages/embeddedci/tests/test_unsupported_feature.py +++ b/packages/embeddedci/tests/test_unsupported_feature.py @@ -1,7 +1,7 @@ """UnsupportedFeatureError and the can_* capability checks on BenchPod. -The pod's texts are the firmware's: ``unknown cmd`` (command_handler.c) and the digital board's -analog refusal (cmd_gate.c cmd_gate_check).""" +The pod refuses an unknown command with BP0002 and an analog command on the digital board with +BP0046; their old texts decide nothing.""" from __future__ import annotations @@ -50,24 +50,24 @@ def command(self, req: dict) -> Any: raise AssertionError(f"nothing should reach the pod: {req}") -def test_unknown_cmd_is_an_unsupported_feature(): - err = firmware_error("unknown cmd", cmd="can_config") +def test_unknown_command_is_an_unsupported_feature(): + err = firmware_error("", cmd="can_start", code="BP0002", values={"cmd": "can_start"}) assert type(err) is UnsupportedFeatureError - assert err.feature == "can_config" and err.cmd == "can_config" - # Still what it was before: a FirmwareError with the pod's text. - assert isinstance(err, FirmwareError) and err.firmware_message == "unknown cmd" + assert err.feature == "can_start" and err.cmd == "can_start" + assert isinstance(err, FirmwareError) with pytest.raises(UnsupportedFeatureError): - raise_for_status(Reply(status="error", message="unknown cmd"), cmd="sensor_start") + raise_for_status(Reply(status="error", code="BP0002", args={"cmd": "sensor_start"}), + cmd="sensor_start") def test_the_digital_board_refusing_analog_is_an_unsupported_feature(): - err = firmware_error(NO_ANALOG, cmd="capture") + err = firmware_error("", cmd="capture", code="BP0046", values={"cmd": "capture"}) assert type(err) is UnsupportedFeatureError and err.feature == "analog" -def test_other_refusals_are_not_unsupported(): - for text in ("la voltage not set", "unknown target", "unknown cmd here"): - assert not isinstance(firmware_error(text), UnsupportedFeatureError), text +def test_the_old_texts_are_not_classified(): + for text in ("unknown cmd", NO_ANALOG, "la voltage not set", "unknown target"): + assert type(firmware_error(text)) is FirmwareError, text def test_a_missing_capability_raises_before_sending(): From 5d23079d02ac2e0fe0d6ef368c4dff19f00c2304 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 22:39:05 -0600 Subject: [PATCH 03/10] TLS on 8443 by default for LAN addresses, no plaintext fallback Firmware 4.0 serves the JSON API on Ethernet and Wi-Fi over TLS only. A network address without a port now means 8443 over TLS (pinned on first use); plaintext 8080 only on the USB network adapter (10.237.x) or when the address names :8080, with a hint when that fails. The TLS-then-plaintext probe is gone. The usb LAN fallback uses TLS. mDNS discovery reads api, tls and https_only from the TXT record, connects to the TLS port and refuses a pod with firmware 3.x. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 2 + packages/embeddedci-mcp/README.md | 9 +-- .../src/embeddedci_mcp/server.py | 8 ++- .../src/embeddedci_mcp/session.py | 2 +- packages/embeddedci-mcp/tests/test_tools.py | 9 +-- .../embeddedci-mcp/tests/tools_surface.json | 2 +- packages/embeddedci/CHANGELOG.md | 8 +++ packages/embeddedci/README.md | 20 +++--- .../src/embeddedci/benchpod/connection.py | 35 +++++++++-- .../src/embeddedci/benchpod/discovery.py | 36 +++++++++-- .../embeddedci/benchpod/transport/__init__.py | 30 ++++----- .../src/embeddedci/benchpod/transport/tcp.py | 30 +++------ .../src/embeddedci/benchpod/transport/tls.py | 59 +++++++----------- packages/embeddedci/tests/api_surface.json | 4 +- packages/embeddedci/tests/test_connection.py | 35 +++++++++-- packages/embeddedci/tests/test_lan_tls.py | 61 +++++++++++-------- packages/embeddedci/tests/test_one_source.py | 8 +-- packages/embeddedci/tests/test_usb_net.py | 42 +++---------- 18 files changed, 224 insertions(+), 176 deletions(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index e7fb0f3..cba0df0 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -12,6 +12,8 @@ Pairs with BenchPod firmware 4.0.0 and embeddedci 4.0. Breaking changes: - **Refusals by code only.** Every coded refusal is rendered from the catalog with its MCP fix (`fix.mcp`, naming this server's tools); the text rewrites of raw protocol commands are gone. A refusal without a code keeps the pod's text. +- `connect` to a LAN address uses TLS on 8443 by default; mDNS discovery connects to the pod's + TLS port and refuses a pod with firmware 3.x. - `status` warns when `module.dac_pinout_ok` is false: the DAC is off because the digital board and the analog module do not belong together (`BP0080`). diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index 395c868..dfed421 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -57,9 +57,10 @@ lists the pods it heard (name and address) and what to pass instead: `host[:port `claude mcp add benchpod -- uvx embeddedci-mcp` is enough for a single pod on your network: just ask the agent to connect. -**TLS.** A network address uses TLS on port 8443 when the pod has it (firmware 3.9.3+) and pins -the pod's certificate on first use, in the same `known_pods.json` as `benchpod-cli`; older pods -stay on plaintext 8080. `BENCHPOD_TLS=on|off` and `BENCHPOD_TLS_CA` work as in the SDK. A changed +**TLS.** A network address uses TLS on port 8443 (firmware 4.0 serves the LAN API only there by +default) and pins the pod's certificate on first use, in the same `known_pods.json` as +`benchpod-cli`. Plaintext 8080 is used only on the pod's USB network adapter or when the address +names `:8080`. `BENCHPOD_TLS=on|off` and `BENCHPOD_TLS_CA` work as in the SDK. A changed certificate stops `connect` with both fingerprints: after a deliberate change, the user runs `benchpod lan-tls trust`. The `lan_tls` tool shows the certificate and switches HTTPS-only. @@ -304,7 +305,7 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | --- | --- | --- | | `set_pull` | Pull LA channels `up` or `down`, or switch their resistor `off`; the pod picks the value. Today LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none; another direction is refused (BP0024, BP0023). `enabled` is the older on/off form. | **`las`**, `pull`, `enabled` | | `pull_status` | Every LA channel's pull resistor: state (`up`, `down` or `off`), the directions it supports and its value. | none | -| `lan_tls` | The pod's LAN API over TLS (firmware 3.9.3+): port 8443, the HTTPS-only setting and the certificate's sha256 (what clients pin). Turning HTTPS-only off and regenerating need a TLS, USB or cloud connection. | `https_only`, `regenerate` | +| `lan_tls` | The pod's LAN API over TLS: port 8443, the HTTPS-only setting and the certificate's sha256 (what clients pin). Turning HTTPS-only off and regenerating need a TLS, USB or cloud connection. | `https_only`, `regenerate` | | `usb_network` | Read the pod's USB network setting (firmware 3.9.0+), or turn the adapter off over the USB link. Only the device changes it; turning it back on is `benchpod usb-network on` on the USB console. | `set=off` | | `log_level` | Read or set how much the pod prints on its USB console (firmware newer than 3.10.12): `error`, `warn`, `info` (the default) or `debug`, which adds every command trace and the reconnect retry detail. Stored on the pod. | `level` | diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index c8db003..b981635 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -473,8 +473,10 @@ def _local_lease(pod: Any) -> Optional[Dict[str, Any]]: @mcp.tool(annotations=_ann("Connect to a BenchPod", idempotent=True, cloud=True)) async def connect( connection: Annotated[Optional[str], Field(description=( - "host[:port] (TCP, default port 8080), a serial device path (the USB console only), 'usb' " - "(auto-detect: the pod's USB network adapter with the full API on firmware 3.9.0+, else " + "host[:port] (TCP: TLS on 8443 by default, with the pod's certificate pinned on first use; " + "plaintext only with an explicit :8080 or on the USB network adapter), a serial device " + "path (the USB console, status only), 'usb' " + "(auto-detect: the pod's USB network adapter with the full API, else " "its console), 'usb:' (one of several pods on USB, by name: 'usb:benchpod-baea06'), " "'discover' (mDNS) or 'embeddedci:' (cloud). Omit to use the server default " "(--connection, else BENCHPOD_CONNECTION, else the connection saved with `benchpod " @@ -1767,7 +1769,7 @@ async def lan_tls( "True: the pod makes a new key and self-signed certificate. Clients that pinned the old one " "must trust the new one (`benchpod lan-tls trust`); this server's pin follows."))] = False, ) -> m.LanTlsResult: - """The pod's LAN API over TLS (firmware 3.9.3+): port 8443, HTTPS-only, and the certificate + """The pod's LAN API over TLS: port 8443 (this server's default for a LAN address), HTTPS-only, and the certificate clients pin (sha256). Connections to a network address use TLS by default when the pod has it. Installing your own certificate: `benchpod lan-tls set-cert` or the SDK's set_lan_tls_cert.""" def op() -> m.LanTlsResult: diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/session.py b/packages/embeddedci-mcp/src/embeddedci_mcp/session.py index 90e156f..6cb5ff5 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/session.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/session.py @@ -98,7 +98,7 @@ def saved_connection() -> Optional[str]: #: What to pass instead when mDNS finds no single pod. CONNECTION_HELP = ( - "pass connection= one of: host[:port] (a pod on the LAN, default port 8080), 'usb' (a pod on " + "pass connection= one of: host[:port] (a pod on the LAN: TLS on 8443 by default), 'usb' (a pod on " "this machine's USB), or 'embeddedci:' for a cloud pod (cloud_list_devices lists " "them). The user can also make one the default with `benchpod set-connection `, " + ENV_VAR + " or --connection." diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index c8a1e52..78a7eaf 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -220,16 +220,17 @@ def _mdns(monkeypatch, *pods): from embeddedci.benchpod import discovery found = [discovery.DiscoveredPod(name=name, hostname=f"{name}.local", addresses=[ip], port=8080, - pod_id="abcdefghijklmnop") for name, ip in pods] + pod_id="abcdefghijklmnop", tls_port=8443, api=2) + for name, ip in pods] monkeypatch.setattr(discovery, "discover", lambda timeout=discovery.DEFAULT_TIMEOUT: found) def test_connect_without_any_connection_finds_the_pod_over_mdns(fake_open, monkeypatch): _mdns(monkeypatch, ("benchpod-baea06", "192.168.1.220")) result = call("connect") - assert fake_open["connection"] == "192.168.1.220:8080" + assert fake_open["connection"] == "192.168.1.220:8443" # TLS, from the TXT record assert result["connected"] is True and result["kind"] == "tcp" - assert result["connection"] == "192.168.1.220:8080" + assert result["connection"] == "192.168.1.220:8443" @pytest.mark.parametrize("configured", ["env", "server"]) @@ -266,7 +267,7 @@ def test_connect_with_several_pods_lists_them(fake_open, monkeypatch): call("connect") msg = str(err.value) assert "2 BenchPods found" in msg - for needle in ("benchpod-baea06", "192.168.1.220:8080", "benchpod-435dca", "192.168.1.221:8080", + for needle in ("benchpod-baea06", "192.168.1.220:8443", "benchpod-435dca", "192.168.1.221:8443", "host[:port]", "'usb'", "cloud_list_devices"): assert needle in msg assert not SESSION.connected and "connection" not in fake_open diff --git a/packages/embeddedci-mcp/tests/tools_surface.json b/packages/embeddedci-mcp/tests/tools_surface.json index bd70962..3573dcf 100644 --- a/packages/embeddedci-mcp/tests/tools_surface.json +++ b/packages/embeddedci-mcp/tests/tools_surface.json @@ -1533,7 +1533,7 @@ } ], "default": null, - "description": "host[:port] (TCP, default port 8080), a serial device path (the USB console only), 'usb' (auto-detect: the pod's USB network adapter with the full API on firmware 3.9.0+, else its console), 'usb:' (one of several pods on USB, by name: 'usb:benchpod-baea06'), 'discover' (mDNS) or 'embeddedci:' (cloud). Omit to use the server default (--connection, else BENCHPOD_CONNECTION, else the connection saved with `benchpod set-connection`), else to find the one pod on the LAN over mDNS.", + "description": "host[:port] (TCP: TLS on 8443 by default, with the pod's certificate pinned on first use; plaintext only with an explicit :8080 or on the USB network adapter), a serial device path (the USB console, status only), 'usb' (auto-detect: the pod's USB network adapter with the full API, else its console), 'usb:' (one of several pods on USB, by name: 'usb:benchpod-baea06'), 'discover' (mDNS) or 'embeddedci:' (cloud). Omit to use the server default (--connection, else BENCHPOD_CONNECTION, else the connection saved with `benchpod set-connection`), else to find the one pod on the LAN over mDNS.", "title": "Connection" }, "la_voltage": { diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 83b82f0..9b4ad3b 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -37,6 +37,14 @@ Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: `DacPinoutMismatchError` (`BP0080`, `digital`, `module`). `PinConflictError` has `owner` and `instance` (`BP0031`). Over the cloud the transport retries on `BP0052` (it matched the text "device busy"). +- **TLS on the LAN by default.** A network address without a port goes to 8443 over TLS (the + pod's certificate pinned on first use, as before); the TLS-then-plaintext fallback is gone. + Plaintext 8080 is used only on the USB network adapter (`10.237.x.y`) or when the address names + `:8080`; a failed plaintext connect to a LAN address says to drop the port. `connection.TLS_PORT` + and `connection.default_port(host)` are new; `trust_lan_tls`, `forget_lan_tls` and the pin + helpers default to port 8443. `connection 'usb'` falls back to the pod's LAN address over TLS. + mDNS: `DiscoveredPod` has `tls_port`, `api`, `https_only` and `supported`; its `addr` uses the + TLS port, and `discover` refuses a single pod with firmware 3.x (`FirmwareTooOldError`). - `ModuleInfo.dac_pinout_ok`: `False` when the digital board and the analog module use different flat-cable DAC pinouts (the DAC is off). - Error catalog synced (`BP0031` to `BP0080`); features table revision 11. diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index f67d910..30ddb4d 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -215,7 +215,8 @@ explicitly. The pytest plugin does **not** fall back to it (see [pytest plugin]( | Form | Transport | |---|---| -| `192.168.1.213`, `host:8080`, `[fe80::1]:8080` | network (JSON over TCP, port 8080 by default) | +| `192.168.1.213`, `benchpod-baea06.local`, `[fe80::1]` | network: JSON over TLS on port 8443 (see [TLS on the LAN](#tls-on-the-lan)); an address on the pod's USB network adapter (`10.237.x.y`) is plaintext 8080 | +| `host:8080`, `host:8443` | network on that port: `:8080` is plaintext (refused on Ethernet and Wi-Fi unless the pod's HTTPS-only is off), `:8443` TLS | | `/dev/ttyACM0`, `COM3`, `\\.\COM10` | USB console, explicit device path | | `usb` | USB pod, auto-detected by probing the serial ports (`serial` also accepted): its USB network adapter on firmware 3.9.0 and later (full API), else its USB console | | `usb:` | the USB pod with that name when several are plugged into one computer: `usb:baea06`, `usb:benchpod-baea06` (any case, optional `.local`); otherwise as `usb` | @@ -283,12 +284,15 @@ client API check: firmware 3.x raises `FirmwareTooOldError` there too. ### TLS on the LAN -Pods with firmware 3.9.3 or later also serve the API on port 8443 with TLS. For a network address -on the default port (`192.168.1.5`, `:8080`, a pod name) the SDK connects to 8443 first and falls -back to plaintext 8080 only when the pod has no TLS port and nothing is pinned for it, so older -pods keep working. `:8443` means TLS only; any other port and the USB network adapter (`usb`, a -physical link) stay plaintext. `BENCHPOD_TLS=on|off` overrides (`auto` is the default). -`bp.transport.last_tls` says which one the last connection used. +Firmware 4.0 serves the JSON API on Ethernet and Wi-Fi over TLS only, on port 8443 (HTTPS-only is +on by default; plaintext 8080 stays on the USB network adapter). A network address without a port +(`192.168.1.5`, a pod name, an mDNS discovery) goes to 8443 over TLS; there is no fallback to +plaintext. Plaintext 8080 is used only when you name the port (`host:8080`, for a pod whose +HTTPS-only you turned off) and on the USB network adapter (`usb`, or a `10.237.x.y` address: a +physical link). Any other explicit port is plaintext too. `BENCHPOD_TLS=on|off` overrides (`auto` +is the default). `bp.transport.last_tls` says which one the last connection used. mDNS discovery +reads the pod's TLS port and client API level from its TXT record (`tls`, `api`) and refuses a pod +with firmware 3.x (`FirmwareTooOldError`). The pod's certificate is its own, so the SDK pins its SHA-256 the first time (trust on first use) in `known_pods.json` next to `benchpod-cli`'s config; the CLI reads and writes the same file. A @@ -2720,7 +2724,7 @@ timeout=60.0, lease_id=None)`. Errors raise `ServerApiError` (`status`), and an |---|---| | `parse_connection(raw)` | parse a connection string into a `ConnSpec` (raises `ConnectionConfigError`) | | `resolve_connection(connection=None)` | the same, falling back to `BENCHPOD_CONNECTION` | -| `trust_lan_tls(host, port=8080, *, sha256=None)`, `forget_lan_tls(host, port=8080)` | pin the TLS certificate the pod presents now (returns its SHA-256), or drop the pin (see [TLS on the LAN](#tls-on-the-lan)) | +| `trust_lan_tls(host, port=8443, *, sha256=None)`, `forget_lan_tls(host, port=8443)` | pin the TLS certificate the pod presents now (returns its SHA-256), or drop the pin (see [TLS on the LAN](#tls-on-the-lan)) | | `sensor_library(version=None, *, cache_dir=None, offline=False, refresh=False, timeout=30.0)` | the sensor library (see [The sensor library](#the-sensor-library)); `SENSOR_LIBRARY_VERSION` is the pinned version | | `load_definition(source, *, library=None, base_dir=None)`, `load_stimulus(source, *, library=None, base_dir=None)` | a definition or stimulus (name, path, dict or YAML/JSON text) as the dict the pod receives; header problems raise `DefinitionError` | | `make_build_reporter(*, api_base=None, audience=None, target="", name="")` | a `BuildReporter` inside GitHub Actions, else a `NoopBuildReporter` | diff --git a/packages/embeddedci/src/embeddedci/benchpod/connection.py b/packages/embeddedci/src/embeddedci/benchpod/connection.py index 67870a2..eebd113 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/connection.py +++ b/packages/embeddedci/src/embeddedci/benchpod/connection.py @@ -2,7 +2,9 @@ Mirrors the Go CLI's ``connection.go``, plus a cloud destination: -* ``host`` or ``host:port`` -> TCP/wifi (default port 8080) +* ``host`` or ``host:port`` -> TCP/wifi: TLS on 8443 by default (plaintext 8080 on the pod's + USB network adapter, 10.237.0.0/16, or when ``:8080`` is + given) * ``/dev/tty*`` / ``COM3`` / ``\\\\.\\COM3`` -> serial device path * ``usb`` -> USB pod, auto-detected by probing the ports (``serial`` is accepted as a legacy spelling); on @@ -31,7 +33,11 @@ from .cli_config import SAVED_KEYWORD, config_path, saved_connection from .errors import ConnectionConfigError +#: The pod's plaintext JSON API: its USB network adapter, or a LAN address given with ``:8080``. DEFAULT_PORT = 8080 +#: The pod's JSON API over TLS: the default for a LAN address (firmware 4.0 serves only this on +#: Ethernet and Wi-Fi unless HTTPS-only is turned off). +TLS_PORT = 8443 ENV_VAR = "BENCHPOD_CONNECTION" CLOUD_PREFIX = "embeddedci:" DISCOVER_KEYWORDS = ("discover", "mdns", "auto") @@ -83,15 +89,23 @@ def _is_device_path(s: str) -> bool: return False +def default_port(host: str) -> int: + """The port for an address given without one: 8080 on the pod's USB network adapter (a + physical link, plaintext), else 8443 (TLS).""" + from .transport.tls import is_usb_link + + return DEFAULT_PORT if is_usb_link(host.strip("[]")) else TLS_PORT + + def _normalize_addr(s: str) -> str: # Bracketed IPv6 literal, optionally with a port. if s.startswith("["): - return s if "]:" in s else f"{s}:{DEFAULT_PORT}" + return s if "]:" in s else f"{s}:{default_port(s)}" # A single colon means host:port; more than one and no brackets means a bare # IPv6 address, which needs the default port appended as-is. if s.count(":") == 1: return s - return f"{s}:{DEFAULT_PORT}" + return f"{s}:{default_port(s)}" def parse_connection(raw: str) -> ConnSpec: @@ -148,13 +162,24 @@ def _discover_one() -> ConnSpec: ) if len(pods) > 1: listing = "\n".join( - f" - {p.name} {p.addr} id={p.pod_id[:12]}…" for p in pods + f" - {p.name} {p.addr} id={p.pod_id[:12]}…" + + ("" if p.supported else " (firmware 3.x: update it)") for p in pods ) raise ConnectionConfigError( f"{len(pods)} BenchPods found — disambiguate with an address or " f"hostname (e.g. {pods[0].hostname}):\n{listing}" ) - return ConnSpec(kind="tcp", addr=_normalize_addr(pods[0].addr)) + pod = pods[0] + if not pod.supported: + from .errors import FirmwareTooOldError + from .feature_map import MIN_FIRMWARE + + raise FirmwareTooOldError( + f"the BenchPod found on the LAN ({pod.name}, {pod.hostname}) announces no client API " + f"2: it runs firmware 3.x, and this SDK needs firmware {MIN_FIRMWARE} or later. Update " + "it with the BenchPod CLI (`benchpod flash-self`) or the firmware update in the web " + "app, or use embeddedci 3.x with it", api=pod.api or 1) + return ConnSpec(kind="tcp", addr=_normalize_addr(pod.addr)) def resolve_connection(connection: "str | None" = None) -> ConnSpec: diff --git a/packages/embeddedci/src/embeddedci/benchpod/discovery.py b/packages/embeddedci/src/embeddedci/benchpod/discovery.py index 3f5a6b6..9c41479 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/discovery.py +++ b/packages/embeddedci/src/embeddedci/benchpod/discovery.py @@ -7,7 +7,8 @@ The firmware advertises the same service type from every pod, with a unique hostname/instance derived from a slice of its Ed25519 public key and the full -public key carried in the TXT ``id=`` item. See bench-pod-firmware +public key carried in the TXT ``id=`` item; firmware 4.0 adds ``api=2`` (its +client API level), ``tls=8443`` and ``https_only=1``. See bench-pod-firmware ``stm32h563/src/net_server.c`` (mDNS responder). ``zeroconf`` is an optional dependency (``pip install embeddedci[discovery]``); @@ -36,21 +37,36 @@ class DiscoveredPod: name: str # DNS-SD instance, e.g. "BenchPod a1b2c3" hostname: str # "benchpod-a1b2c3.local" addresses: List[str] = field(default_factory=list) # all A-record IPs - port: int = 8080 + port: int = 8080 # the SRV port: plaintext 8080, which the LAN takes only with HTTPS-only off pod_id: str = "" # full base64url Ed25519 pubkey (TXT id=) + #: The TLS port (TXT ``tls=``, 8443); 0 when the pod does not announce one. + tls_port: int = 0 + #: The pod's client API level (TXT ``api=``); 0 when the pod does not announce one (firmware + #: 3.x, which this SDK does not drive). + api: int = 0 + #: TXT ``https_only=1``: plaintext 8080 is off on the LAN. + https_only: bool = False + + @property + def supported(self) -> bool: + """Whether this SDK drives the pod: it announces client API 2 or later (firmware 4.0).""" + from .feature_map import MIN_POD_API + + return self.api >= MIN_POD_API @property def addr(self) -> str: """A ``host:port`` string ready for :func:`parse_connection`. Prefers a numeric address (avoids depending on the OS mDNS resolver), and of those the - pod's USB network link (firmware 3.9.0+) when this computer heard it there: a pod - advertises itself on each of its interfaces. Falls back to the ``.local`` hostname if no - address was resolved. + pod's USB network link when this computer heard it there: a pod advertises itself on each + of its interfaces. Falls back to the ``.local`` hostname if no address was resolved. The + port is the plaintext one on the USB link, else the TLS one (TXT ``tls``, 8443). """ usb = [a for a in self.addresses if _on_usb_link(a)] host = (usb or self.addresses or [self.hostname])[0] - return f"{host}:{self.port}" + port = self.port if usb else (self.tls_port or 8443) + return f"[{host}]:{port}" if ":" in host else f"{host}:{port}" @property def on_usb(self) -> bool: @@ -62,6 +78,11 @@ def on_usb(self) -> bool: USB_LINK_NET = ipaddress.IPv4Network("10.237.0.0/16") +def _txt_int(txt: Dict[str, str], key: str) -> int: + v = txt.get(key, "").strip() + return int(v) if v.isdigit() else 0 + + def _on_usb_link(addr: str) -> bool: try: return ipaddress.ip_address(addr) in USB_LINK_NET @@ -104,6 +125,9 @@ def _record(zeroconf, type_: str, name: str) -> None: addresses=addresses, port=info.port or 8080, pod_id=txt.get("id", ""), + tls_port=_txt_int(txt, "tls"), + api=_txt_int(txt, "api"), + https_only=txt.get("https_only", "") == "1", ) class _Listener: diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py index 0c2887e..a00670f 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py @@ -19,9 +19,8 @@ import socket from typing import Any, Callable, Optional -from ..connection import DEFAULT_PORT, ConnSpec +from ..connection import DEFAULT_PORT, TLS_PORT, ConnSpec from ..errors import ConnectionConfigError -from ..protocol import encode_request from .base import RawLink, Transport __all__ = [ @@ -115,21 +114,16 @@ def _tcp_reachable(host: str, port: int, timeout: float = USB_NET_PROBE_TIMEOUT) return False -def _api_answers(host: str, port: int, timeout: float = USB_NET_PROBE_TIMEOUT) -> bool: - """Whether the pod answers a JSON ``ping`` at ``host:port``. A TCP connect is not enough on the - pod's external LAN: with the LAN policy ``off`` it accepts the connection and resets it.""" +def _tls_api_answers(host: str, timeout: float) -> bool: + """Whether the pod answers a ``ping`` over TLS at ``host:8443`` (the LAN API of firmware 4.0; + the certificate is pinned on first use as for any LAN connection).""" + from .tcp import TcpTransport + + probe = TcpTransport(f"{host}:{TLS_PORT}", timeout=min(timeout, USB_NET_PROBE_TIMEOUT * 2), + dial_timeout=USB_NET_PROBE_TIMEOUT) try: - with socket.create_connection((host, port), timeout=timeout) as s: - s.settimeout(timeout) - s.sendall(encode_request({"cmd": "ping"})) - buf = b"" - while b"\n" not in buf: - chunk = s.recv(256) - if not chunk: - return False - buf += chunk - return b'"pong"' in buf - except OSError: + return probe.ping() == "pong" + except Exception: # noqa: BLE001 - any failure keeps the console return False @@ -183,8 +177,8 @@ def _open_usb(device: str, *, timeout: float, pod: str = "") -> Transport: # USB network the way in is the pod's Ethernet or Wi-Fi address when this computer reaches # it (the pod's external LAN policy applies there). lan = usb_lan_fallback_address(status) - if lan and _api_answers(lan, DEFAULT_PORT): - tcp = TcpTransport(f"{lan}:{DEFAULT_PORT}", timeout=timeout) + if lan and _tls_api_answers(lan, timeout): + tcp = TcpTransport(f"{lan}:{TLS_PORT}", timeout=timeout) tcp.usb_lan_fallback = why console.close() _log.warning("usb: %s; using the pod's network address %s (its external LAN policy " diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index 7e02751..d415a86 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -1,5 +1,5 @@ -"""JSON-over-TCP transport (wifi/network), port 8080 by default, TLS on 8443 when the pod has it -(firmware 3.9.3+, see :mod:`.tls`). +"""JSON-over-TCP transport (wifi/network): TLS on 8443 for a LAN address, plaintext 8080 on the +pod's USB network adapter or when the port is given (see :mod:`.tls`). Mirrors the Go ``tcpclient``: each command dials a fresh connection (the firmware serves one client at a time), disables Nagle, sends one JSON line and @@ -30,9 +30,6 @@ DEFAULT_DIAL_TIMEOUT = 10.0 # total budget to establish a connection _DIAL_ATTEMPT_TIMEOUT = 0.5 -#: The 8443 probe outlasts the host's first SYN retransmit (1 s on macOS and Linux): a pod can let -#: the first SYN go unanswered, and its reset (or TLS handshake) then comes at about 1 s. -_TLS_PROBE_TIMEOUT = 1.5 _DIAL_RETRY_BACKOFF = 0.1 #: Floor for an upload's timeout (``load_bin``): the pod acknowledges a large upload slowly. _UPLOAD_TIMEOUT = 60.0 @@ -145,24 +142,11 @@ def _dial(self, timeout: Optional[float] = None, kind: Optional[str] = None) -> io_timeout = self.timeout if timeout is None else timeout p = _tls.plan(host, port, self.tls) tls_to = p.tls - if p.fallback and _tls.known_no_tls(p.plain) and not _tls.get_pin(host, port): - tls_to = None if tls_to is None: + assert p.plain is not None self.last_tls = False return self._connect(p.plain, self.dial_timeout, io_timeout) - if p.fallback and not _tls.get_pin(host, port): - # One probe per pod and process: a pod without LAN TLS answers 8443 with a reset. A - # probe that times out is remembered too, or every command would wait for it again. - try: - raw = self._connect(tls_to, _TLS_PROBE_TIMEOUT, io_timeout, retry=False, - attempt_timeout=_TLS_PROBE_TIMEOUT) - except TransportError as exc: - if isinstance(exc.__cause__, (ConnectionRefusedError, TimeoutError)): - _tls.remember_no_tls(p.plain) - self.last_tls = False - return self._connect(p.plain, self.dial_timeout, io_timeout) - else: - raw = self._connect(tls_to, self.dial_timeout, io_timeout) + raw = self._connect(tls_to, self.dial_timeout, io_timeout) try: sock = _tls.wrap(raw, tls_to[0], tls_to[1], ca=self.tls_ca) except BenchPodError: @@ -191,7 +175,11 @@ def _connect(self, addr: "tuple[str, int]", budget: float, io_timeout: Optional[ if not retry or time.monotonic() >= deadline: break time.sleep(_DIAL_RETRY_BACKOFF) - raise TransportError(f"could not connect to {addr[0]}:{addr[1]}: {last}") from last + hint = "" + if addr[1] == _tls.PLAIN_PORT and not _tls.is_usb_link(addr[0]): + hint = ("; firmware 4.0 serves its API on the LAN over TLS only: connect without :8080 " + "(TLS on 8443), or over USB") + raise TransportError(f"could not connect to {addr[0]}:{addr[1]}: {last}{hint}") from last @staticmethod def _recv_line(sock: socket.socket, buf: bytearray) -> bytes: diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tls.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tls.py index a52cbb7..013cc41 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tls.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tls.py @@ -1,15 +1,16 @@ -"""The pod's LAN API over TLS (firmware 3.9.3+), as ``benchpod`` does it (its ``tcpclient/tls.go``). +"""The pod's LAN API over TLS, as ``benchpod`` does it (its ``tcpclient/tls.go``). -The pod serves the same API on TCP 8443 with TLS 1.2 and its own certificate (self-signed on first -boot, or one the user installed). How :class:`~.tcp.TcpTransport` connects: +The pod serves the API on TCP 8443 with TLS 1.2 and its own certificate (self-signed on first +boot, or one the user installed). Firmware 4.0 serves only that on Ethernet and Wi-Fi by default +(HTTPS-only); plaintext 8080 stays on its USB network adapter. How :class:`~.tcp.TcpTransport` +connects in ``"auto"`` (the default): -- port 8443: TLS only. -- port 8080 (the default): TLS on 8443 first; when 8443 refuses the connection (firmware without - LAN TLS) and nothing is pinned for the pod, plaintext 8080 as before. With a pin, a pod that stops - answering TLS is an error, never a silent downgrade. -- any other port, and the pod's USB network adapter (10.237.0.0/16, a physical link): plaintext. +- port 8443 (the default for a LAN address, see :func:`~..connection.default_port`): TLS. +- any other port given explicitly (``host:8080``), and the pod's USB network adapter + (10.237.0.0/16, a physical link): plaintext. There is no fallback from TLS to plaintext. -``tls="on"`` / ``"off"`` (or ``BENCHPOD_TLS``) overrides ``"auto"``. +``tls="on"`` sends TLS to 8443 whatever the port; ``"off"`` plaintext (8080 for an address on +8443). ``BENCHPOD_TLS`` sets the mode too. Trust: the SHA-256 of the pod's certificate (DER) is pinned on first use per address in ``known_pods.json`` next to ``benchpod-cli``'s config (the CLI reads and writes the same file). A @@ -38,8 +39,6 @@ TLS_PORT = 8443 _USB_LINK = ipaddress.ip_network("10.237.0.0/16") _lock = threading.Lock() -#: Pods (host:port) that refused 8443 in this process, so each command does not probe again. -_no_tls: set = set() def tls_mode(value: Optional[str] = None) -> str: @@ -69,30 +68,18 @@ def tls_addr(host: str, port: int) -> Tuple[str, int]: class DialPlan(NamedTuple): - tls: Optional[Tuple[str, int]] # None: no TLS attempt - plain: Optional[Tuple[str, int]] # None: no plaintext - fallback: bool # plaintext only when TLS is refused and nothing is pinned + tls: Optional[Tuple[str, int]] # None: plaintext + plain: Optional[Tuple[str, int]] # None: TLS def plan(host: str, port: int, mode: str) -> DialPlan: - """How to reach ``host:port`` in ``mode`` (see the module docstring).""" + """How to reach ``host:port`` in ``mode`` (see the module docstring): exactly one of TLS or + plaintext, never both.""" if mode == "off": - return DialPlan(None, (host, port), False) - if port == TLS_PORT: - return DialPlan((host, port), None, False) - if mode == "on": - return DialPlan(tls_addr(host, port), None, False) - if port != PLAIN_PORT or is_usb_link(host): - return DialPlan(None, (host, port), False) - return DialPlan((host, TLS_PORT), (host, port), True) - - -def remember_no_tls(addr: Tuple[str, int]) -> None: - _no_tls.add(addr) - - -def known_no_tls(addr: Tuple[str, int]) -> bool: - return addr in _no_tls + return DialPlan(None, (host, PLAIN_PORT if port == TLS_PORT else port)) + if mode == "on" or port == TLS_PORT: + return DialPlan(tls_addr(host, port), None) + return DialPlan(None, (host, port)) # -- pins --------------------------------------------------------------------------------------- @@ -138,7 +125,7 @@ def _save(path: Path, data: Dict) -> None: raise -def get_pin(host: str, port: int = PLAIN_PORT) -> Optional[str]: +def get_pin(host: str, port: int = TLS_PORT) -> Optional[str]: """The pinned SHA-256 (lowercase hex) for the pod at ``host``, if any.""" with _lock: try: @@ -148,7 +135,7 @@ def get_pin(host: str, port: int = PLAIN_PORT) -> Optional[str]: return pod.get("sha256") if isinstance(pod, dict) else None -def set_pin(host: str, sha256: str, port: int = PLAIN_PORT, subject: str = "") -> None: +def set_pin(host: str, sha256: str, port: int = TLS_PORT, subject: str = "") -> None: """Pin ``sha256`` for the pod at ``host`` (what ``benchpod lan-tls trust`` does).""" _sessions.clear() with _lock: @@ -162,7 +149,7 @@ def set_pin(host: str, sha256: str, port: int = PLAIN_PORT, subject: str = "") - _save(path, data) -def delete_pin(host: str, port: int = PLAIN_PORT) -> bool: +def delete_pin(host: str, port: int = TLS_PORT) -> bool: """Forget the pod's pin. ``False`` when there was none.""" with _lock: path = pin_store_path() @@ -263,7 +250,7 @@ def forget_sessions() -> None: _sessions.clear() -def trust_lan_tls(host: str, port: int = PLAIN_PORT, *, sha256: Optional[str] = None, +def trust_lan_tls(host: str, port: int = TLS_PORT, *, sha256: Optional[str] = None, timeout: float = 10.0) -> str: """Pin the certificate the pod at ``host`` presents now (after a deliberate change), like ``benchpod lan-tls trust``. With ``sha256`` only that certificate is trusted. Returns the @@ -276,7 +263,7 @@ def trust_lan_tls(host: str, port: int = PLAIN_PORT, *, sha256: Optional[str] = return got -def peer_certificate(host: str, port: int = PLAIN_PORT, *, timeout: float = 10.0) -> bytes: +def peer_certificate(host: str, port: int = TLS_PORT, *, timeout: float = 10.0) -> bytes: """The certificate (DER) the pod at ``host`` presents on its TLS port, unchecked.""" th, tp = tls_addr(host, port) sock = socket.create_connection((th, tp), timeout=timeout) diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 6f7a177..0761d67 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -1541,7 +1541,7 @@ "dsp": "module", "encode_curve_b64url": "(codes: 'Sequence[int]') -> 'str'", "expansion_chip": "(name: 'str') -> 'ExpansionChip'", - "forget_lan_tls": "(host: 'str', port: 'int' = 8080) -> 'bool'", + "forget_lan_tls": "(host: 'str', port: 'int' = 8443) -> 'bool'", "header_map": "(w: 'Wiring', header: 'Optional[str]' = None) -> 'str'", "i2c": "module", "input_percent_to_code": "(percent: 'float') -> 'int'", @@ -1553,5 +1553,5 @@ "resolve_connection": "(connection: \"'str | None'\" = None) -> 'ConnSpec'", "sensor_library": "(version: 'Optional[str]' = None, *, cache_dir: \"Union[str, 'os.PathLike[str]', None]\" = None, offline: 'bool' = False, refresh: 'bool' = False, timeout: 'float' = 30.0) -> 'SensorLibrary'", "sensors": "module", - "trust_lan_tls": "(host: 'str', port: 'int' = 8080, *, sha256: 'Optional[str]' = None, timeout: 'float' = 10.0) -> 'str'" + "trust_lan_tls": "(host: 'str', port: 'int' = 8443, *, sha256: 'Optional[str]' = None, timeout: 'float' = 10.0) -> 'str'" } diff --git a/packages/embeddedci/tests/test_connection.py b/packages/embeddedci/tests/test_connection.py index a60b0af..20643df 100644 --- a/packages/embeddedci/tests/test_connection.py +++ b/packages/embeddedci/tests/test_connection.py @@ -8,9 +8,13 @@ @pytest.mark.parametrize( "raw, kind, addr, device", [ - ("192.168.1.213", "tcp", "192.168.1.213:8080", ""), + ("192.168.1.213", "tcp", "192.168.1.213:8443", ""), # LAN: TLS by default + ("192.168.1.213:8080", "tcp", "192.168.1.213:8080", ""), # a port given: as given ("192.168.1.213:9000", "tcp", "192.168.1.213:9000", ""), - ("host.local", "tcp", "host.local:8080", ""), + ("host.local", "tcp", "host.local:8443", ""), + ("10.237.8.85", "tcp", "10.237.8.85:8080", ""), # the USB network: plaintext + ("fe80::1", "tcp", "fe80::1:8443", ""), + ("[fe80::1]", "tcp", "[fe80::1]:8443", ""), ("/dev/ttyACM0", "serial", "", "/dev/ttyACM0"), ("COM3", "serial", "", "COM3"), ("serial", "serial", "", ""), @@ -56,7 +60,7 @@ def test_resolve_prefers_explicit_over_env(monkeypatch): monkeypatch.setenv(ENV_VAR, "/dev/ttyACM0") spec = resolve_connection("192.168.1.5") assert spec.is_wifi() - assert spec.addr == "192.168.1.5:8080" + assert spec.addr == "192.168.1.5:8443" def test_resolve_falls_back_to_env(monkeypatch): @@ -82,13 +86,36 @@ def test_discover_single_pod(keyword, monkeypatch): addresses=["192.168.1.7"], port=8080, pod_id="abc", + tls_port=8443, + api=2, ) monkeypatch.setattr(conn, "_discover_one", conn._discover_one) monkeypatch.setattr("embeddedci.benchpod.discovery.discover", lambda timeout=3.0: [pod]) spec = parse_connection(keyword) assert spec.kind == "tcp" - assert spec.addr == "192.168.1.7:8080" + assert spec.addr == "192.168.1.7:8443" # the TXT tls port, not the SRV's 8080 + + +def test_discover_takes_the_usb_link_plaintext(monkeypatch): + from embeddedci.benchpod.discovery import DiscoveredPod + + pod = DiscoveredPod(name="BenchPod a1", hostname="benchpod-a1.local", + addresses=["192.168.1.7", "10.237.8.85"], port=8080, tls_port=8443, api=2) + monkeypatch.setattr("embeddedci.benchpod.discovery.discover", lambda timeout=3.0: [pod]) + assert parse_connection("discover").addr == "10.237.8.85:8080" + + +def test_discover_refuses_firmware_3(monkeypatch): + from embeddedci.benchpod.discovery import DiscoveredPod + from embeddedci.benchpod.errors import FirmwareTooOldError + + pod = DiscoveredPod(name="BenchPod a1", hostname="benchpod-a1.local", + addresses=["192.168.1.7"], port=8080) # no api, no tls in TXT + assert not pod.supported and pod.addr == "192.168.1.7:8443" + monkeypatch.setattr("embeddedci.benchpod.discovery.discover", lambda timeout=3.0: [pod]) + with pytest.raises(FirmwareTooOldError, match="firmware 3.x.*benchpod flash-self"): + parse_connection("discover") def test_discover_none_found(monkeypatch): diff --git a/packages/embeddedci/tests/test_lan_tls.py b/packages/embeddedci/tests/test_lan_tls.py index ec5dbba..d11695a 100644 --- a/packages/embeddedci/tests/test_lan_tls.py +++ b/packages/embeddedci/tests/test_lan_tls.py @@ -24,12 +24,15 @@ def pin_dir(tmp_path, monkeypatch): def test_plan(): - assert T.plan("192.168.1.5", 8080, "auto") == T.DialPlan(("192.168.1.5", 8443), ("192.168.1.5", 8080), True) - assert T.plan("192.168.1.5", 8443, "auto") == T.DialPlan(("192.168.1.5", 8443), None, False) - assert T.plan("192.168.1.5", 9000, "auto") == T.DialPlan(None, ("192.168.1.5", 9000), False) - assert T.plan("10.237.8.85", 8080, "auto") == T.DialPlan(None, ("10.237.8.85", 8080), False) - assert T.plan("192.168.1.5", 8443, "off") == T.DialPlan(None, ("192.168.1.5", 8443), False) - assert T.plan("10.237.8.85", 8080, "on") == T.DialPlan(("10.237.8.85", 8443), None, False) + # 8443 (the default port of a LAN address) is TLS; a port given explicitly is plaintext, with + # no fallback either way. + assert T.plan("192.168.1.5", 8443, "auto") == T.DialPlan(("192.168.1.5", 8443), None) + assert T.plan("192.168.1.5", 8080, "auto") == T.DialPlan(None, ("192.168.1.5", 8080)) + assert T.plan("192.168.1.5", 9000, "auto") == T.DialPlan(None, ("192.168.1.5", 9000)) + assert T.plan("10.237.8.85", 8080, "auto") == T.DialPlan(None, ("10.237.8.85", 8080)) + assert T.plan("192.168.1.5", 8443, "off") == T.DialPlan(None, ("192.168.1.5", 8080)) + assert T.plan("192.168.1.5", 8080, "on") == T.DialPlan(("192.168.1.5", 8443), None) + assert T.plan("10.237.8.85", 8080, "on") == T.DialPlan(("10.237.8.85", 8443), None) assert T.tls_mode("ON") == "on" and T.tls_mode("") == "auto" with pytest.raises(ValueError): T.tls_mode("maybe") @@ -124,28 +127,34 @@ def test_pin_key_for_the_default_port_is_the_tls_port(): assert T.get_pin("192.168.1.5", 8443) == "ab" * 32 -@pytest.mark.parametrize("probe_error", [ConnectionRefusedError, TimeoutError]) -def test_a_pod_without_tls_is_probed_once_per_process(monkeypatch, probe_error): - """A pod without LAN TLS refuses 8443 or, when it lets the first SYN go unanswered, the probe - times out: either way it is probed once, not on every command (each one dials anew).""" - server = socket.socket() - server.bind(("127.0.0.1", 0)) - server.listen() - real = socket.create_connection +def test_a_lan_address_is_tls_on_8443_with_no_fallback(monkeypatch): + """A LAN address without a port goes to 8443 over TLS; when 8443 does not answer, the SDK + never falls back to plaintext 8080.""" + from embeddedci.benchpod.connection import parse_connection + from embeddedci.benchpod.errors import TransportError + dialed = [] def fake_create_connection(addr, timeout=None): - dialed.append((addr[1], timeout)) - if addr[1] == 8443: - raise probe_error("no TLS here") - return real(server.getsockname(), timeout=timeout) + dialed.append(addr[1]) + raise ConnectionRefusedError("refused") + + monkeypatch.setattr(socket, "create_connection", fake_create_connection) + t = TcpTransport(parse_connection("192.0.2.10").addr, dial_timeout=0.05) + with pytest.raises(TransportError): + t._dial() + assert set(dialed) == {8443} + + +def test_an_explicit_8080_is_plaintext_and_says_what_to_do(monkeypatch): + from embeddedci.benchpod.errors import TransportError + + def fake_create_connection(addr, timeout=None): + raise ConnectionResetError("reset") monkeypatch.setattr(socket, "create_connection", fake_create_connection) - host = "192.0.2.%d" % (10 + [ConnectionRefusedError, TimeoutError].index(probe_error)) - t = TcpTransport(f"{host}:8080") - for _ in range(3): - t._dial().close() - assert [port for port, _ in dialed] == [8443, 8080, 8080, 8080] - assert dialed[0][1] >= 1.2, "the probe must outlast the host's 1 s SYN retransmit" - assert not t.last_tls - server.close() + with pytest.raises(TransportError, match="over TLS only: connect without :8080"): + TcpTransport("192.0.2.10:8080", dial_timeout=0.05)._dial() + with pytest.raises(TransportError) as e: # the USB link: no such hint + TcpTransport("10.237.8.85:8080", dial_timeout=0.05)._dial() + assert "TLS only" not in str(e.value) diff --git a/packages/embeddedci/tests/test_one_source.py b/packages/embeddedci/tests/test_one_source.py index 3ee36c6..0c50c3f 100644 --- a/packages/embeddedci/tests/test_one_source.py +++ b/packages/embeddedci/tests/test_one_source.py @@ -84,11 +84,11 @@ def test_config_path_without_xdg_is_under_home(monkeypatch, tmp_path): def test_connection_precedence_argument_env_saved(monkeypatch, tmp_path): _save_config(tmp_path, {"connection": "10.0.0.3"}) - assert resolve_connection().addr == "10.0.0.3:8080" # saved + assert resolve_connection().addr == "10.0.0.3:8443" # saved monkeypatch.setenv("BENCHPOD_CONNECTION", "10.0.0.2") - assert resolve_connection().addr == "10.0.0.2:8080" # env beats saved - assert resolve_connection("10.0.0.1").addr == "10.0.0.1:8080" # argument beats both - assert resolve_connection("saved").addr == "10.0.0.3:8080" # explicit keyword + assert resolve_connection().addr == "10.0.0.2:8443" # env beats saved + assert resolve_connection("10.0.0.1").addr == "10.0.0.1:8443" # argument beats both + assert resolve_connection("saved").addr == "10.0.0.3:8443" # explicit keyword def test_no_connection_anywhere_says_how_to_save_one(): diff --git a/packages/embeddedci/tests/test_usb_net.py b/packages/embeddedci/tests/test_usb_net.py index 9ff800a..891ab9b 100644 --- a/packages/embeddedci/tests/test_usb_net.py +++ b/packages/embeddedci/tests/test_usb_net.py @@ -4,7 +4,6 @@ from __future__ import annotations -import socket import pytest @@ -111,7 +110,7 @@ def probe(host, port, timeout=transport_mod.USB_NET_PROBE_TIMEOUT): monkeypatch.setattr(usblink, "local_usb_links", lambda: list(cfg["links"])) monkeypatch.setattr(usblink, "_short_id", lambda host, port, timeout: cfg["ids"].get(host, "")) monkeypatch.setattr(transport_mod, "_tcp_reachable", probe) - monkeypatch.setattr(transport_mod, "_api_answers", probe) + monkeypatch.setattr(transport_mod, "_tls_api_answers", lambda host, timeout: probe(host, 8443)) cfg["probes"] = probes return cfg @@ -146,16 +145,16 @@ def test_serial_keyword_also_upgrades(usb): @pytest.mark.parametrize("line", [USB_WIFI, USB_DOWN]) -def test_usb_falls_back_to_the_pods_network_address_on_3_9(usb, line, caplog): - """3.9.0+ with USB networking off or down: its console has no la-voltage or power any more, - so the way in is the pod's Ethernet or Wi-Fi address from its status.""" +def test_usb_falls_back_to_the_pods_network_address(usb, line, caplog): + """USB networking off or down: the console answers status only, so the way in is the pod's + Ethernet or Wi-Fi address from its status, over TLS.""" usb["status"] = _status(line) with caplog.at_level("WARNING", logger="embeddedci.benchpod"): t = open_transport(parse_connection("usb")) - assert isinstance(t, TcpTransport) and t.addr == "192.168.1.215:8080" + assert isinstance(t, TcpTransport) and t.addr == "192.168.1.215:8443" # the LAN: TLS assert t.usb_lan_fallback and not t.usb_console assert FakeConsole.instances[0].closed - assert "192.168.1.215:8080" in caplog.text and "clear-wifi" in caplog.text + assert "192.168.1.215:8443" in caplog.text and "clear-wifi" in caplog.text @pytest.mark.parametrize("line", [USB_WIFI, USB_DOWN]) @@ -187,7 +186,7 @@ def test_usb_network_not_answering_falls_back_to_the_lan(usb): usb["status"] = _status(USB_ON) usb["reachable"] = {"192.168.1.215"} t = open_transport(parse_connection("usb")) - assert isinstance(t, TcpTransport) and t.addr == "192.168.1.215:8080" + assert isinstance(t, TcpTransport) and t.addr == "192.168.1.215:8443" def test_usb_keeps_the_console_when_status_fails(usb): @@ -229,32 +228,9 @@ def test_discovered_pod_prefers_the_usb_link(): assert both.addr == "10.237.8.85:8080" and both.on_usb lan = DiscoveredPod(name="BenchPod baea06", hostname="benchpod-baea06.local", addresses=["192.168.1.221"]) - assert lan.addr == "192.168.1.221:8080" and not lan.on_usb + assert lan.addr == "192.168.1.221:8443" and not lan.on_usb # the LAN: TLS none = DiscoveredPod(name="BenchPod baea06", hostname="benchpod-baea06.local") - assert none.addr == "benchpod-baea06.local:8080" - - -def test_api_answers_needs_a_pong(): - """The LAN fallback pings: a pod whose external LAN policy is off accepts and resets.""" - import threading - - def serve(reply): - srv = socket.socket() - srv.bind(("127.0.0.1", 0)) - srv.listen(1) - - def run(): - c, _ = srv.accept() - c.recv(64) - if reply: - c.sendall(reply) - c.close() - srv.close() - threading.Thread(target=run, daemon=True).start() - return srv.getsockname()[1] - - assert transport_mod._api_answers("127.0.0.1", serve(b'{"status":"ok","data":"pong"}\n')) - assert not transport_mod._api_answers("127.0.0.1", serve(b"")) + assert none.addr == "benchpod-baea06.local:8443" def test_usb_takes_the_local_usb_link_without_the_console(usb): From 4030ea45b752fae3953e8c218b96c4f9e03c4d8b Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 22:50:56 -0600 Subject: [PATCH 04/10] Firmware 4.0 JSON names on the wire; the SDK's own names stay Rates in hertz (sample_rate_hz, adc_sample_rate_hz, la_sample_rate_hz, freq_hz), clock_hz for the I2C and SPI masters, dac_out v with code16 replies, code16 in the loop replies, can_start/can_stop and ts_ms, booleans for target_power, target_status and usb_network, and power_profile sample_rate_hz. test_wire_names_4.py asserts the JSON sent for each renamed command and the renamed reply fields read. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/tests/conftest.py | 26 +-- packages/embeddedci-mcp/tests/test_tools.py | 4 +- .../tests/test_trigger_power_tools.py | 6 +- packages/embeddedci-openhtf/tests/_fake.py | 9 +- .../embeddedci-openhtf/tests/test_analog.py | 8 +- .../embeddedci-openhtf/tests/test_power.py | 6 +- packages/embeddedci/CHANGELOG.md | 8 + packages/embeddedci/README.md | 2 +- .../embeddedci/src/embeddedci/benchpod/can.py | 2 +- .../src/embeddedci/benchpod/capture.py | 47 +++--- .../src/embeddedci/benchpod/client.py | 28 ++-- .../src/embeddedci/benchpod/i2c_master.py | 2 +- .../src/embeddedci/benchpod/power.py | 5 +- .../embeddedci/src/embeddedci/benchpod/spi.py | 2 +- .../src/embeddedci/benchpod/state.py | 16 +- .../src/embeddedci/benchpod/transport/tcp.py | 2 +- packages/embeddedci/tests/test_adc_range.py | 2 +- packages/embeddedci/tests/test_can.py | 16 +- packages/embeddedci/tests/test_capture.py | 22 +-- packages/embeddedci/tests/test_client_v2.py | 14 +- packages/embeddedci/tests/test_cloud.py | 4 +- .../embeddedci/tests/test_control_loop.py | 12 +- .../tests/test_current_out_waveforms.py | 2 +- packages/embeddedci/tests/test_expansion.py | 4 +- packages/embeddedci/tests/test_gpio.py | 2 +- packages/embeddedci/tests/test_i2c_master.py | 10 +- .../embeddedci/tests/test_motor_emulator.py | 6 +- packages/embeddedci/tests/test_replay.py | 4 +- packages/embeddedci/tests/test_spi.py | 6 +- .../embeddedci/tests/test_tcp_transport.py | 2 +- packages/embeddedci/tests/test_timed_power.py | 6 +- .../tests/test_transport_failures.py | 2 +- .../embeddedci/tests/test_trigger_power.py | 12 +- packages/embeddedci/tests/test_usb_net.py | 4 +- .../embeddedci/tests/test_wire_names_4.py | 158 ++++++++++++++++++ .../embeddedci/tests/test_wiring_profiles.py | 6 +- 36 files changed, 316 insertions(+), 151 deletions(-) create mode 100644 packages/embeddedci/tests/test_wire_names_4.py diff --git a/packages/embeddedci-mcp/tests/conftest.py b/packages/embeddedci-mcp/tests/conftest.py index 40715b8..b085cdb 100644 --- a/packages/embeddedci-mcp/tests/conftest.py +++ b/packages/embeddedci-mcp/tests/conftest.py @@ -111,7 +111,7 @@ def __init__(self) -> None: "bus_mv": [5010, 4990, 5000, 5005]} #: The statistics its last chunk carries (µA / mV / µJ / µC, as the firmware sends them). self.power_stats: Dict[str, Any] = { - "rate_hz": 364.0, "adc_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52_000, "min_ua": 40_000, + "sample_rate_hz": 364.0, "adc_sample_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52_000, "min_ua": 40_000, "peak_ua": 180_000, "avg_mv": 5010, "min_mv": 4990, "max_mv": 5030, "energy_uj": 260_500, "charge_uc": 52_000, "fault": False, "truncated": False} @@ -336,7 +336,7 @@ def _cmd_i2c_start(self, req): raise firmware_error("", cmd="i2c_start", code="BP0003") self.i2c = req self.function[req["sda"]], self.function[req["scl"]] = "i2cm_sda", "i2cm_scl" - return {"sda": req["sda"], "scl": req["scl"], "hz": req["hz"], "pullups": req["pullups"]} + return {"sda": req["sda"], "scl": req["scl"], "clock_hz": req["clock_hz"], "pullups": req["pullups"]} def _cmd_i2c_stop(self, req): if self.i2c is not None: @@ -382,7 +382,7 @@ def _cmd_i2c_scan(self, req): def _cmd_spi_start(self, req): self.spi = req - return {k: req[k] for k in ("sck", "mosi", "miso", "cs", "hz", "mode")} + return {k: req[k] for k in ("sck", "mosi", "miso", "cs", "clock_hz", "mode")} def _cmd_spi_xfer(self, req): return {"rx": req["tx"], "cs": "released"} @@ -450,15 +450,15 @@ def _cmd_power_profile(self, req): "elapsed_ms": 100, "n": 95} self.power_profile_running = True self.power_efuse = int(req.get("efuse", 1)) - return {"started": True, "efuse": self.power_efuse, "rate_hz": 950.0} + return {"started": True, "efuse": self.power_efuse, "sample_rate_hz": 950.0} def _cmd_analog_path(self, req): return {"path": req["path"], "u55": 3, "u58": 9} def _cmd_dac_out(self, req): - has_v = "volts" in req - return {"path": req["path"], "mv": int(round(req["volts"] * 1000)) if has_v else 0, - "code": 128 if has_v else -1} + has_v = "v" in req + return ({"path": req["path"], "mv": int(round(req["v"] * 1000)), "code16": 32768} + if has_v else {"path": req["path"]}) def _cmd_current_out(self, req): rng = {"min_ua": 4016, "max_ua": 20078} @@ -554,16 +554,16 @@ def _cmd_dac_control_loop(self, req): def _cmd_dac_loop_input(self, req): return {"source": req.get("source", "fixed"), "input": req.get("input", 0), - "step": req.get("step", 0), "v": 1234} + "step": req.get("step", 0), "code16": 1234} def _cmd_dac_loop_probe(self, req): - return {"i": 64000, "in": 32768, "source": "fixed", "v": 20000} + return {"i": 64000, "in": 32768, "source": "fixed", "code16": 20000} def _cmd_can_write(self, req): fd = len(req["data"]) > 8 or req.get("fd", False) self.can_rx.append({"id": req["id"], "data": req["data"], "ext": req["ext"], "rtr": req["rtr"], "fd": fd, "brs": fd and req.get("brs", True), - "ts": 100 + len(self.can_rx)}) + "ts_ms": 100 + len(self.can_rx)}) return {"queued": True} def _cmd_can_read(self, req): @@ -600,14 +600,14 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: yield {"status": "ok", "t_us": [], "current_ua": [], "bus_mv": [], "stats": dict(self.power_stats, efuse=self.power_efuse), "more": False} elif cmd == "capture": - yield {"status": "ok", "data": sine_counts(req["samples"]), "adc_rate_hz": 100_000.0, + yield {"status": "ok", "data": sine_counts(req["samples"]), "adc_sample_rate_hz": 100_000.0, "more": False} elif cmd == "la_capture": n = req["samples"] # LA1 toggles every 50 samples (10 kHz at 1 MS/s); LA3 stays high. edges = [[i, (0b100 | ((i // 50) % 2))] for i in range(0, n, 50)] last = {"status": "ok", "la": True, "la_edges": edges, "la_upto": n, - "la_rate_hz": 1_000_000.0, "more": False} + "la_sample_rate_hz": 1_000_000.0, "more": False} send = req.get("send") if send and send["bus"] == "i2c": r = self._i2c_xfer(send["addr"], send.get("write", ""), send.get("read", 0)) @@ -619,7 +619,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: yield last elif cmd == "capture_dual": yield {"status": "ok", "data": sine_counts(req["adc_samples"]), - "adc_rate_hz": 100_000.0, "la_rate_hz": 1_000_000.0, "more": True} + "adc_sample_rate_hz": 100_000.0, "la_sample_rate_hz": 1_000_000.0, "more": True} yield {"status": "ok", "la": True, "la_edges": [[0, 1]], "la_upto": req["la_samples"], "more": False} diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index 78a7eaf..8858889 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -608,7 +608,7 @@ def test_pulls(connected): def test_analog_tools(connected): assert call("analog_path", path="cal1") == {"path": "cal1", "range": None} out = call("dac_output", path="5v", volts=2.5) - assert out == {"path": "5v", "voltage": 2.5, "code": 128, "code16": None} + assert out == {"path": "5v", "voltage": 2.5, "code": 128, "code16": 32768} assert call("dac_output", path="off")["voltage"] is None assert call("adc_read", source="ext")["voltage"] == pytest.approx(3.301) assert call("adc_read", source="ext")["offset"] is None @@ -852,7 +852,7 @@ def test_can_fd_tools(connected): SESSION.require().refresh_capabilities() opened = call("can_open", mode="internal", bitrate=500_000, data_bitrate=2_000_000) assert opened["fd"] is True and opened["data_bitrate"] == 2_000_000 - cfg = [r for r in connected.requests if r["cmd"] == "can_config"][-1] + cfg = [r for r in connected.requests if r["cmd"] == "can_start"][-1] assert cfg["data_bitrate"] == 2_000_000 call("can_write", can_id=0x123, data=list(range(64)), brs=False) req = [r for r in connected.requests if r["cmd"] == "can_write"][-1] diff --git a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py index 0cd3ef3..7ad82b0 100644 --- a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py +++ b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py @@ -67,7 +67,7 @@ def test_the_schema_bounds_the_trigger_arguments(connected): def test_measure_power_reports_statistics_in_si_units(connected): result = call("measure_power", duration=1.0) - assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "rate_hz": 500, + assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 0, "duration_ms": 1000} assert result["efuse"] == 1 and result["n"] == 950 # the delivered rate, with the sensor's configured conversion rate beside it @@ -85,7 +85,7 @@ def test_measure_power_reports_statistics_in_si_units(connected): def test_measure_power_returns_a_trace_when_points_are_asked_for(connected): result = call("measure_power", duration=1.0, points=4, efuse=2, rate_hz=500) assert connected.requests[-1]["keep_samples"] == 4 and connected.requests[-1]["efuse"] == 2 - assert connected.requests[-1]["rate_hz"] == 500.0 + assert connected.requests[-1]["sample_rate_hz"] == 500 assert result["trace_current"] == [0.04, 0.18, 0.05, 0.048] assert result["trace_voltage"] == [5.01, 4.99, 5.0, 5.005] assert result["trace_step"] == pytest.approx(0.25) @@ -101,7 +101,7 @@ def test_measure_power_downsamples_a_long_trace(connected): def test_power_profile_session_brackets_other_calls(connected): started = call("power_profile_start", rate_hz=500, max_duration=5) assert started == {"running": True, "efuse": 1, "rate_hz": 500.0, "max_duration": 5.0} - assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "rate_hz": 500.0, + assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 4096, "max_duration_ms": 5000, "action": "start"} assert call("status")["session"]["power_profile_running"] is True diff --git a/packages/embeddedci-openhtf/tests/_fake.py b/packages/embeddedci-openhtf/tests/_fake.py index 4c26164..d2d4d5d 100644 --- a/packages/embeddedci-openhtf/tests/_fake.py +++ b/packages/embeddedci-openhtf/tests/_fake.py @@ -83,7 +83,7 @@ def __init__(self, banner: bytes = b"reset\r\nAPP_OK build 1\r\n", self.inputs = 0 #: The statistics a power_profile reply carries (µA / mV / µJ / µC, as the firmware sends). self.power_stats: Dict[str, Any] = { - "efuse": 1, "rate_hz": 364.0, "adc_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52_000, + "efuse": 1, "sample_rate_hz": 364.0, "adc_sample_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52_000, "min_ua": 40_000, "peak_ua": 180_000, "avg_mv": 5010, "min_mv": 4990, "max_mv": 5030, "energy_uj": 260_500, "charge_uc": 52_000, "fault": False, "truncated": False} #: The bin-averaged trace it carries (µs / µA / mV). @@ -122,10 +122,9 @@ def command(self, req: dict): if cmd == "analog_path": return {"path": req.get("path"), "u55": 0x03, "u58": 0x09} if cmd == "dac_out": - has_v = "volts" in req + has_v = "v" in req return {"path": req.get("path"), - "mv": int(round(float(req["volts"]) * 1000)) if has_v else 0, - "code": 128 if has_v else -1} + **({"mv": int(round(float(req["v"]) * 1000)), "code16": 32768} if has_v else {})} if cmd == "generate": return {"cotrig": bool(req.get("on_capture", False))} if cmd == "current_out": @@ -144,7 +143,7 @@ def command(self, req: dict): return {"armed": True, "k": req.get("k"), "vmin": req.get("vmin"), "vmax": req.get("vmax"), "tick_div": req.get("tick_div"), "curve_pts": 256} if cmd == "dac_loop_probe": - return {"i": 4096, "v": 51000} + return {"i": 4096, "code16": 51000} if cmd == "fpga_image": if self.image is not None: self.image = req.get("image") diff --git a/packages/embeddedci-openhtf/tests/test_analog.py b/packages/embeddedci-openhtf/tests/test_analog.py index d11ec5d..38163ea 100644 --- a/packages/embeddedci-openhtf/tests/test_analog.py +++ b/packages/embeddedci-openhtf/tests/test_analog.py @@ -123,7 +123,7 @@ def test_adc_capture_phase_source_none_leaves_routing_and_passes_rate(): sample_rate_hz=100_000, prefix="rail", attachment=None)) assert rec.outcome == tr.Outcome.PASS assert "analog_path" not in _cmds(tx) - assert tx.commands[-1] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.1, "enc": "dec"} + assert tx.commands[-1] == {"cmd": "capture", "samples": 8, "sample_rate_hz": 100000, "enc": "dec"} p = _phase(rec, "adc_capture") assert _value(p, "rail_pp_v") == pytest.approx(3.3) assert "adc.json" not in p.attachments @@ -168,7 +168,7 @@ def test_loopback_measure_phase_generates_captures_then_stops(): assert tx.commands[0] == {"cmd": "generate", "waveform": "sine", "freq_hz": 100, "path": "3v3", "amplitude_v": 1.0, "offset_v": 1.65} assert tx.commands[1] == {"cmd": "analog_path", "path": "adc_ext"} - assert tx.commands[2] == {"cmd": "capture", "samples": 8, "sample_rate_mhz": 0.05, "enc": "dec"} + assert tx.commands[2] == {"cmd": "capture", "samples": 8, "sample_rate_hz": 50000, "enc": "dec"} p = _phase(rec, "loopback_measure") assert _value(p, "adc_pp_v") == pytest.approx(3.3) assert _value(p, "adc_mean_v") == pytest.approx(sum(TRI_V) / 8) @@ -241,14 +241,14 @@ def test_dac_output_phase_routes_and_sets_volts(): tx = FakeTransport() rec = _run(dac_output_phase(benchpod_plug(transport=tx), path="5v", volts=2.5)) assert rec.outcome == tr.Outcome.PASS - assert tx.commands[-1] == {"cmd": "dac_out", "path": "5v", "volts": 2.5} + assert tx.commands[-1] == {"cmd": "dac_out", "path": "5v", "v": 2.5} def test_dac_output_helper_returns_typed_result(): tx = FakeTransport() plug = benchpod_plug(transport=tx)() out = dac_output(plug, "5v", volts=2.5) - assert out == DacOutput(path="5v", voltage=2.5, code=128) + assert out == DacOutput(path="5v", voltage=2.5, code=128, code16=32768) routed = dac_output(plug, "off") assert routed.voltage is None and routed.code is None assert tx.commands[-1] == {"cmd": "dac_out", "path": "off"} diff --git a/packages/embeddedci-openhtf/tests/test_power.py b/packages/embeddedci-openhtf/tests/test_power.py index ad65665..b2569c9 100644 --- a/packages/embeddedci-openhtf/tests/test_power.py +++ b/packages/embeddedci-openhtf/tests/test_power.py @@ -40,7 +40,7 @@ def test_measure_power_returns_si_units(): 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, + assert _request(tx) == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 0, "duration_ms": 1000} assert profile.avg_current == pytest.approx(0.052) assert profile.peak_current == pytest.approx(0.18) @@ -54,7 +54,7 @@ def test_measure_power_passes_its_keywords_through(): 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 + assert req["efuse"] == 2 and req["sample_rate_hz"] == 500 and req["keep_samples"] == 2 assert req["duration_ms"] == 500 assert profile.samples == ((0.0, 0.04, 5.01), (0.5, 0.06, 5.0)) @@ -104,7 +104,7 @@ def test_measure_power_phase_attaches_the_kept_samples(): assert _value(phase, "sleep_avg_current_a") == pytest.approx(0.052) payload = json.loads(phase.attachments["power.json"].data) assert payload["efuse"] == 2 and payload["samples"][0] == [0.0, 0.04, 5.01] - assert _request(tx)["rate_hz"] == 500.0 + assert _request(tx)["sample_rate_hz"] == 500 def test_measure_power_phase_can_skip_the_attachment(): diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 9b4ad3b..64e24e0 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -45,6 +45,14 @@ Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: helpers default to port 8443. `connection 'usb'` falls back to the pod's LAN address over TLS. mDNS: `DiscoveredPod` has `tls_port`, `api`, `https_only` and `supported`; its `addr` uses the TLS port, and `discover` refuses a single pod with firmware 3.x (`FirmwareTooOldError`). +- **Firmware 4.0 JSON names.** The public SDK names stay; the wire follows the firmware: rates in + hertz (`sample_rate_hz` on capture, la_capture, replay, sensor_la and generate; + `adc_sample_rate_hz`/`la_sample_rate_hz` on capture_dual and in the chunk replies; + `sample_rate_hz` for power profiles), `freq_hz`, `clock_hz` (i2c_start, spi_start and their + replies), `dac_out` `v` and reply `code16` (`DacOutput.code` is now its high byte), + `code16` in the loop probe and input replies, `can_start`/`can_stop`, CAN `ts_ms`, + `target_power` `enabled` (booleans in `target_status` too), `usb_network` `enabled` (a boolean + in and out; `status.usb.enabled` and `status.usb.net` are booleans). - `ModuleInfo.dac_pinout_ok`: `False` when the digital board and the analog module use different flat-cable DAC pinouts (the DAC is off). - Error catalog synced (`BP0031` to `BP0080`); features table revision 11. diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 30ddb4d..bc803b5 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -250,7 +250,7 @@ its external LAN policy. `bp.usb_network()` reads it (`True` = on) over any conn `bp.usb_network(False)` turns the adapter off, which only works over the USB link itself: the pod replies, then re-enumerates as its USB console only, which ends the connection. Over Ethernet, Wi-Fi or the cloud the pod refuses the change (`PodLockedError`). Turning it back on needs the USB -console: `benchpod usb-network on`. Status reports it as `usb.setting` and, when the adapter is +console: `benchpod usb-network on`. Status reports it as `usb.enabled` (a boolean, as `usb.net` is) and, when the adapter is off, `usb.off_reason` (`"setting"` or `"wifi"`). **When the USB network is off.** `usb` is the full API over the USB network adapter when it is diff --git a/packages/embeddedci/src/embeddedci/benchpod/can.py b/packages/embeddedci/src/embeddedci/benchpod/can.py index 1ce8f86..85730c6 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/can.py +++ b/packages/embeddedci/src/embeddedci/benchpod/can.py @@ -66,7 +66,7 @@ def from_dict(cls, d: dict) -> "CanFrame": data=bytes(d.get("data", []) or []), ext=bool(d.get("ext", False)), rtr=bool(d.get("rtr", False)), - ts=int(d.get("ts", 0)), + ts=int(d.get("ts_ms", 0)), fd=bool(d.get("fd", False)), brs=bool(d.get("brs", False)), ) diff --git a/packages/embeddedci/src/embeddedci/benchpod/capture.py b/packages/embeddedci/src/embeddedci/benchpod/capture.py index 119fdb2..8a4894c 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/capture.py +++ b/packages/embeddedci/src/embeddedci/benchpod/capture.py @@ -6,8 +6,8 @@ — mirroring the server's ADC affine model — so a test gets calibrated volts regardless of transport, without needing the server's orchestration endpoints. -The public API speaks hertz and seconds; the firmware's ``*_rate_mhz`` / ``*_us`` wire fields are -produced only here. +The public API speaks hertz and seconds, as the firmware's ``*_sample_rate_hz`` wire fields do; +its ``*_us`` fields are produced only here. """ from __future__ import annotations @@ -55,7 +55,8 @@ def _apply_trigger(req: dict, trigger: Optional[Trigger], timeout: float) -> Non def rate_mhz(rate_hz: Optional[float]) -> Optional[float]: - """Hertz → the firmware's ``sample_rate_mhz`` (``None`` stays ``None`` = device default).""" + """Hertz → the embeddedci.com server's ``sample_rate_mhz`` (``None`` stays ``None`` = the + default). The pod itself takes hertz (:func:`rate_hz`).""" if rate_hz is None: return None if rate_hz <= 0: @@ -150,14 +151,14 @@ def capture_adc(transport: Any, caps: Capabilities, *, samples: int = 4096, adc.source = source return adc req: dict = {"cmd": "capture", "samples": n} - mhz = rate_mhz(sample_rate_hz) - if mhz is not None: - req["sample_rate_mhz"] = mhz + rate_req = rate_hz(sample_rate_hz) + if rate_req is not None: + req["sample_rate_hz"] = rate_req counts: List[int] = [] rate = 0.0 for chunk in _stream_or_samples(transport, req): - if chunk.get("adc_rate_hz"): - rate = float(chunk["adc_rate_hz"]) + if chunk.get("adc_sample_rate_hz"): + rate = float(chunk["adc_sample_rate_hz"]) counts.extend(_dense(chunk)) volts = [caps.counts_to_volts(c) for c in counts] return Capture(counts=counts, volts=volts, sample_rate_hz=_rate_hz(rate, sample_rate_hz), @@ -231,9 +232,9 @@ def capture_la(transport: Any, *, samples: int = 4096, sample_rate_hz: Optional[ gateware < v21. """ req: dict = {"cmd": "la_capture", "samples": _check_samples(samples)} - mhz = rate_mhz(sample_rate_hz) - if mhz is not None: - req["sample_rate_mhz"] = mhz + rate_req = rate_hz(sample_rate_hz) + if rate_req is not None: + req["sample_rate_hz"] = rate_req stop_us = _us(stop_dac_after, "stop_dac_after") if stop_us > 0: req["stop_dac_after_us"] = stop_us @@ -250,8 +251,8 @@ def capture_la(transport: Any, *, samples: int = 4096, sample_rate_hz: Optional[ for chunk in _stream_or_samples(transport, req): if isinstance(chunk.get("send"), dict): sent = SendResult.from_reply(chunk["send"]) - if chunk.get("la_rate_hz"): - rate = float(chunk["la_rate_hz"]) + if chunk.get("la_sample_rate_hz"): + rate = float(chunk["la_sample_rate_hz"]) if chunk.get("pre_samples"): pre = int(chunk["pre_samples"]) if chunk.get("truncated"): @@ -319,12 +320,12 @@ def capture_correlated(transport: Any, caps: Capabilities, *, adc_samples: int = if getattr(transport, "stream_chunks", None) is None: raise BenchPodError("capture_correlated needs a streaming transport (TCP, serial or cloud)") req: dict = {"cmd": "capture_dual", "adc_samples": adc_samples, "la_samples": la_samples} - adc_mhz = rate_mhz(adc_sample_rate_hz) - la_mhz = rate_mhz(la_sample_rate_hz) - if adc_mhz is not None: - req["adc_rate_mhz"] = adc_mhz - if la_mhz is not None: - req["la_rate_mhz"] = la_mhz + adc_rate = rate_hz(adc_sample_rate_hz) + la_rate = rate_hz(la_sample_rate_hz) + if adc_rate is not None: + req["adc_sample_rate_hz"] = adc_rate + if la_rate is not None: + req["la_sample_rate_hz"] = la_rate stop_us = _us(stop_dac_after, "stop_dac_after") if stop_us > 0: req["stop_dac_after_us"] = stop_us @@ -335,10 +336,10 @@ def capture_correlated(transport: Any, caps: Capabilities, *, adc_samples: int = la_dense: List[int] = [] adc_rate = la_rate = 0.0 for chunk in transport.stream_chunks(req): - if chunk.get("adc_rate_hz"): - adc_rate = float(chunk["adc_rate_hz"]) - if chunk.get("la_rate_hz"): - la_rate = float(chunk["la_rate_hz"]) + if chunk.get("adc_sample_rate_hz"): + adc_rate = float(chunk["adc_sample_rate_hz"]) + if chunk.get("la_sample_rate_hz"): + la_rate = float(chunk["la_sample_rate_hz"]) if chunk.get("la"): edges = chunk.get("la_edges") or [] la_edges.extend([int(e[0]), int(e[1])] for e in edges) diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 7695f3c..aaba825 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -1226,7 +1226,7 @@ def power_on(self, efuse: Optional[Union[Efuse, int]] = None, self._apply_profile_pulls(w) 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, + req: Dict[str, Any] = {"cmd": "target_power", "efuse": rail, "enabled": True, "delay_ms": _seconds_to_ms(delay, "delay"), "profile": w.profile_name} with _classified_errors(): cmd(req) @@ -1305,9 +1305,9 @@ def usb_network(self, on: Optional[bool] = None) -> bool: """ req: Dict[str, Any] = {"cmd": "usb_network"} if on is not None: - req["set"] = "on" if on else "off" + req["enabled"] = bool(on) data = self.command(req) - return isinstance(data, dict) and data.get("setting") == "on" + return isinstance(data, dict) and data.get("enabled") is True # -- console log level -------------------------------------------------- @@ -1810,7 +1810,7 @@ def dac_output(self, path: DacOutputPath, *, volts: Optional[float] = None) -> D if volts is not None: if path == "off": raise ValueError("volts cannot be set on the 'off' path") - req["volts"] = float(volts) + req["v"] = float(volts) out = DacOutput.from_reply(self.command(req)) self._routed_dac_path = None if path == "off" else path self._dac_routed() @@ -2142,7 +2142,7 @@ def can_config(self, *, bitrate: int = 500_000, mode: CanMode = "normal", 8 Mbit/s. ``fd=True`` without ``data_bitrate`` is CAN FD without bit-rate switching (``data_bitrate=bitrate``). Without either, the bus is classic CAN.""" check_choice(mode, CAN_MODES, "mode") - msg: Dict[str, Any] = {"cmd": "can_config", "bitrate": int(bitrate), "mode": mode, + msg: Dict[str, Any] = {"cmd": "can_start", "bitrate": int(bitrate), "mode": mode, "term": bool(term)} if data_bitrate is None and fd: data_bitrate = bitrate @@ -2214,7 +2214,7 @@ def can_respond_clear(self) -> Dict[str, Any]: def can_disable(self) -> Dict[str, Any]: """Stop FDCAN1 and release the peripheral.""" - return _dict(self.command({"cmd": "can_disable"})) + return _dict(self.command({"cmd": "can_stop"})) def open_can(self, *, bitrate: int = 500_000, mode: CanMode = "normal", term: bool = False, fd: bool = False, @@ -2481,7 +2481,7 @@ def _start_spi(self, sck: int, mosi: int, miso: int, cs: int, *, hz: int, """``spi_start`` on four resolved channels (open_spi, and an expander's own session).""" self._require_capability("spi_master", "the SPI master") req = {"cmd": "spi_start", "sck": sck, "mosi": mosi, "miso": miso, "cs": cs, - "hz": int(hz), "mode": int(mode)} + "clock_hz": int(hz), "mode": int(mode)} stage = getattr(self._transport, "stage_psram", None) with _classified_errors(): info = _dict(self.command(req)) @@ -2525,7 +2525,7 @@ def _start_i2c(self, sda: int, scl: int, *, hz: int, pullups: str) -> _i2c_maste if isinstance(hz, bool) or not _i2c_master.HZ_MIN <= int(hz) <= _i2c_master.HZ_MAX: raise ValueError(f"hz must be {_i2c_master.HZ_MIN}..{_i2c_master.HZ_MAX}, got {hz!r}") self._require_gateware(BUS_MASTER_GATEWARE, "the I2C master") - req = {"cmd": "i2c_start", "sda": sda, "scl": scl, "hz": int(hz), "pullups": pullups} + req = {"cmd": "i2c_start", "sda": sda, "scl": scl, "clock_hz": int(hz), "pullups": pullups} if req["sda"] == req["scl"]: raise ValueError("sda and scl must be different LA pins") try: @@ -2549,7 +2549,7 @@ def _i2c_busy_text(self, exc: FirmwareError) -> str: try: st = _dict(self.command({"cmd": "i2c_status"})) if st.get("active"): - where = f" (LA{st.get('sda')} SDA, LA{st.get('scl')} SCL, {st.get('hz')} Hz)" + where = f" (LA{st.get('sda')} SDA, LA{st.get('scl')} SCL, {st.get('clock_hz')} Hz)" except Exception: pass return (f"{prefix}i2c busy: another connection to this pod holds its I2C master{where}, " @@ -3069,7 +3069,7 @@ def loop_probe(self) -> _control_loop.IVPoint: d = _dict(self.command({"cmd": "dac_loop_probe"})) raw_in = d.get("in") return _control_loop.IVPoint( - i=int(d.get("i", 0)), v=int(d.get("v", 0)), + i=int(d.get("i", 0)), v=int(d.get("code16", 0)), input_code=None if raw_in is None else int(raw_in), source=d.get("source"), tripped=None if d.get("tripped") is None else bool(d.get("tripped"))) @@ -3217,9 +3217,9 @@ def _arm_replay(self, code_bytes: bytes, *, bits: int, dac_path: str, if dac_path and route: self._route_output(dac_path) replay_req: Dict[str, Any] = {"cmd": "replay", "samples": n_samples} - mhz = _capture.rate_mhz(sample_rate_hz) - if mhz is not None: - replay_req["sample_rate_mhz"] = mhz + rate = _capture.rate_hz(sample_rate_hz) + if rate is not None: + replay_req["sample_rate_hz"] = rate if on_capture: replay_req["on_capture"] = True d = _dict(fn(data=code_bytes, replay=replay_req, psram=deep)) @@ -4122,7 +4122,7 @@ def _power_request(self, efuse: Optional[Union[Efuse, int]], rate_hz: float, self._require_capability("power_profile", "power profiles") # The API takes hertz as a float like every other rate, but the firmware's JSON parser # wants a whole number here — send 1000, not 1000.0. - return {"cmd": "power_profile", "efuse": rail, "rate_hz": int(round(rate_hz)), + return {"cmd": "power_profile", "efuse": rail, "sample_rate_hz": int(round(rate_hz)), "keep_samples": int(keep_samples)} def _power_profile_chunks(self, req: Dict[str, Any]) -> Iterator[Dict[str, Any]]: diff --git a/packages/embeddedci/src/embeddedci/benchpod/i2c_master.py b/packages/embeddedci/src/embeddedci/benchpod/i2c_master.py index 2bf8865..741aef7 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/i2c_master.py +++ b/packages/embeddedci/src/embeddedci/benchpod/i2c_master.py @@ -128,7 +128,7 @@ def __init__(self, command: Callable[[Dict[str, Any]], Any], info: Dict[str, Any #: The SCL rate the pod runs (at or below the one asked for). A real bus runs somewhat #: slower: the SCL rise time adds to each period (400 kHz measured about 333 kHz with the #: pod's pull-ups on a short cable). - self.hz = int(info.get("hz", 0)) + self.hz = int(info.get("clock_hz", 0)) #: ``pod`` or ``external``. self.pullups = str(info.get("pullups", "pod")) self._closed = False diff --git a/packages/embeddedci/src/embeddedci/benchpod/power.py b/packages/embeddedci/src/embeddedci/benchpod/power.py index 62f9c48..17e4f94 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/power.py +++ b/packages/embeddedci/src/embeddedci/benchpod/power.py @@ -79,8 +79,9 @@ def from_chunks(cls, chunks: Iterable[Dict[str, Any]]) -> "PowerProfile": raise BenchPodError("the pod's power_profile reply carried no statistics") samples = tuple((t / 1e6, i / 1e6, v / 1000.0) for t, i, v in zip(t_us, ua, mv)) return cls( - efuse=int(stats.get("efuse", 0) or 0), rate_hz=float(stats.get("rate_hz", 0) or 0), - adc_rate_hz=float(stats.get("adc_rate_hz", stats.get("rate_hz", 0)) or 0), + efuse=int(stats.get("efuse", 0) or 0), + rate_hz=float(stats.get("sample_rate_hz", 0) or 0), + adc_rate_hz=float(stats.get("adc_sample_rate_hz", stats.get("sample_rate_hz", 0)) or 0), n=int(stats.get("n", 0) or 0), duration=float(stats.get("duration_ms", 0) or 0) / 1000.0, avg_current=_ua(stats, "avg_ua"), min_current=_ua(stats, "min_ua"), peak_current=_ua(stats, "peak_ua"), avg_voltage=_mv(stats, "avg_mv"), diff --git a/packages/embeddedci/src/embeddedci/benchpod/spi.py b/packages/embeddedci/src/embeddedci/benchpod/spi.py index f40cbda..b04813d 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/spi.py +++ b/packages/embeddedci/src/embeddedci/benchpod/spi.py @@ -88,7 +88,7 @@ def __init__(self, command: Callable[[Dict[str, Any]], Any], info: Dict[str, Any self.miso = int(info.get("miso", 0)) self.cs = int(info.get("cs", 0)) #: The SCK rate the pod picked (at or below the one asked for). - self.hz = int(info.get("hz", 0)) + self.hz = int(info.get("clock_hz", 0)) self.mode = int(info.get("mode", 0)) self._closed = False diff --git a/packages/embeddedci/src/embeddedci/benchpod/state.py b/packages/embeddedci/src/embeddedci/benchpod/state.py index f071562..a72652d 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/state.py +++ b/packages/embeddedci/src/embeddedci/benchpod/state.py @@ -379,28 +379,26 @@ class DacOutput: #: The voltage the calibrated DAC actually produces (the nearest code to what was asked), #: or ``None`` when the call only routed the path. voltage: Optional[float] - #: The DAC code driving it as an 8-bit level (0..255), or ``None`` when only routed. + #: The DAC code driving it as an 8-bit level (0..255: the high byte of :attr:`code16`), or + #: ``None`` when only routed. code: Optional[int] - #: The full 16-bit DAC code driving it, or ``None`` when only routed or on firmware that - #: drives ``dac_out`` at 8 bits (before 3.8.1). + #: The 16-bit DAC code driving it, or ``None`` when only routed. code16: Optional[int] = None raw: Dict[str, Any] = _raw() @classmethod def from_reply(cls, reply: Any) -> "DacOutput": d = _d(reply) - code = _opt_int(d, "code") - routed_only = code is None or code < 0 + code16 = _opt_int(d, "code16") # The firmware answers with the analog-path name (dac_5v); report the output-path name the # caller used (5v) so the result speaks the same vocabulary as dac_output's argument. path = str(d.get("path", "")) path = path[len("dac_"):] if path.startswith("dac_") else path - if routed_only: + if code16 is None or code16 < 0: # only routed return cls(path=path, voltage=None, code=None, raw=d) - # A 16-bit pod also answers in microvolts: one step is well under a millivolt. uv = _opt_int(d, "uv") voltage = uv / 1e6 if uv is not None else (_opt_int(d, "mv") or 0) / 1000.0 - return cls(path=path, voltage=voltage, code=code, code16=_opt_int(d, "code16"), raw=d) + return cls(path=path, voltage=voltage, code=code16 >> 8, code16=code16, raw=d) @dataclass(frozen=True) @@ -673,7 +671,7 @@ class LoopState: def from_reply(cls, reply: Any) -> "LoopState": d = _d(reply) return cls(source=d.get("source"), input_code=_opt_int(d, "input") or 0, - step=_opt_int(d, "step") or 0, output_code=_opt_int(d, "v") or 0, raw=d) + step=_opt_int(d, "step") or 0, output_code=_opt_int(d, "code16") or 0, raw=d) __all__: List[str] = [ diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index d415a86..b6b1b20 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -430,7 +430,7 @@ def ping(self) -> Any: return self.command({"cmd": "ping"}) def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: - req: dict = {"cmd": "target_power", "efuse": efuse, "state": 1 if on else 0} + req: dict = {"cmd": "target_power", "efuse": efuse, "enabled": bool(on)} if delay_ms: req["delay_ms"] = int(delay_ms) self.command(req) diff --git a/packages/embeddedci/tests/test_adc_range.py b/packages/embeddedci/tests/test_adc_range.py index 2d6f76d..3f48ab4 100644 --- a/packages/embeddedci/tests/test_adc_range.py +++ b/packages/embeddedci/tests/test_adc_range.py @@ -78,7 +78,7 @@ def command(self, req: dict) -> Any: self.range = "normal" return d if cmd == "capture": - return {"samples": [0x8000, 59538], "adc_rate_hz": 400000} + return {"samples": [0x8000, 59538], "adc_sample_rate_hz": 400000} return {} def samples(self, req: dict) -> List[int]: diff --git a/packages/embeddedci/tests/test_can.py b/packages/embeddedci/tests/test_can.py index ade7658..6782e65 100644 --- a/packages/embeddedci/tests/test_can.py +++ b/packages/embeddedci/tests/test_can.py @@ -58,7 +58,7 @@ def _reply(self, req): cmd = req.get("cmd") if cmd == "status": return {"status": "ok", "data": {"firmware_version": "3.10.2", "caps": list(self.caps)}} - if cmd == "can_config": + if cmd == "can_start": self._data_bitrate = int(req.get("data_bitrate", 0)) self._enabled = True self._mode = req.get("mode", "normal") @@ -80,7 +80,7 @@ def _reply(self, req): brs = fd and bool(req.get("brs", True)) and self._data_bitrate > self._bitrate frame = {"id": int(req["id"]), "ext": bool(req.get("ext", False)), "rtr": bool(req.get("rtr", False)), "fd": fd, "brs": brs, - "data": data, "ts": self._next_ts()} + "data": data, "ts_ms": self._next_ts()} frame["dlc"] = len(frame["data"]) if self._mode in ("internal", "external"): self._rx.append(frame) # loopback: echo back to RX @@ -90,7 +90,7 @@ def _reply(self, req): self._rx.append({ "id": r["reply_id"], "ext": r["reply_ext"], "rtr": False, "data": list(r["reply_data"]), - "dlc": len(r["reply_data"]), "ts": self._next_ts()}) + "dlc": len(r["reply_data"]), "ts_ms": self._next_ts()}) self._resp_hits += 1 break return {"status": "ok", "data": { @@ -120,7 +120,7 @@ def _reply(self, req): if cmd == "can_term": self._term = bool(req.get("on", False)) return {"status": "ok", "data": {"term": self._term}} - if cmd == "can_disable": + if cmd == "can_stop": self._enabled = False return {"status": "ok", "data": {"enabled": False}} return {"status": "error", "message": "unknown cmd"} @@ -167,7 +167,7 @@ def bp(pod): # -- CanFrame --------------------------------------------------------------- def test_canframe_from_dict_roundtrip(): - f = CanFrame.from_dict({"id": 0x123, "data": [1, 2, 3], "ext": True, "ts": 7}) + f = CanFrame.from_dict({"id": 0x123, "data": [1, 2, 3], "ext": True, "ts_ms": 7}) assert f.id == 0x123 and f.data == b"\x01\x02\x03" and f.dlc == 3 and f.ext assert "0x123" in str(f) @@ -177,7 +177,7 @@ def test_canframe_from_dict_roundtrip(): def test_can_config_request_shape(bp, pod): bp.can_config(bitrate=250_000, mode="external", term=True) assert pod.requests[-1] == { - "cmd": "can_config", "bitrate": 250_000, "mode": "external", + "cmd": "can_start", "bitrate": 250_000, "mode": "external", "term": True} @@ -227,7 +227,7 @@ def test_open_can_expect_times_out(bp): def test_open_can_disables_on_exit(bp, pod): with bp.open_can(mode="internal"): pass - assert [r["cmd"] for r in pod.requests[-2:]] == ["can_disable", "can_term"] + assert [r["cmd"] for r in pod.requests[-2:]] == ["can_stop", "can_term"] assert pod.requests[-1]["on"] is False assert pod._enabled is False @@ -340,7 +340,7 @@ def test_can_capability_flag_from_status_and_cloud_parameters(): def test_can_config_data_bitrate_means_fd(bp, pod): bp.can_config(bitrate=500_000, data_bitrate=2_000_000, mode="internal") assert pod.requests[-1] == { - "cmd": "can_config", "bitrate": 500_000, "mode": "internal", "term": False, + "cmd": "can_start", "bitrate": 500_000, "mode": "internal", "term": False, "data_bitrate": 2_000_000} diff --git a/packages/embeddedci/tests/test_capture.py b/packages/embeddedci/tests/test_capture.py index 348eec2..cb63fd4 100644 --- a/packages/embeddedci/tests/test_capture.py +++ b/packages/embeddedci/tests/test_capture.py @@ -30,7 +30,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: def test_capture_adc_scales_to_volts_and_reads_rate(): t = FakeCaptureTransport({"capture": [ - {"status": "ok", "data": [0, 128, 255], "adc_rate_hz": 400000.0, "more": True}, + {"status": "ok", "data": [0, 128, 255], "adc_sample_rate_hz": 400000.0, "more": True}, {"status": "ok", "data": [255], "more": False}, ]}) cap = cap_mod.capture_adc(t, NAIVE, samples=4, sample_rate_hz=500_000) @@ -40,7 +40,7 @@ def test_capture_adc_scales_to_volts_and_reads_rate(): assert cap.volts[0] == pytest.approx(0.0) assert cap.volts[2] == pytest.approx(2.55, rel=1e-6) # The public API speaks hertz; the wire field stays the firmware's MHz. - assert t.sent[0] == {"cmd": "capture", "samples": 4, "sample_rate_mhz": 0.5} + assert t.sent[0] == {"cmd": "capture", "samples": 4, "sample_rate_hz": 500000} def test_capture_adc_falls_back_to_requested_rate(): @@ -53,7 +53,7 @@ def test_capture_adc_falls_back_to_requested_rate(): def test_capture_adc_above_the_shallow_buffer_streams_from_psram(): n = cap_mod.ADC_SHALLOW_MAX_SAMPLES + 1 t = FakeCaptureTransport({"capture_dual": [ - {"status": "ok", "data": [7] * n, "adc_rate_hz": 400000.0, "more": False}, + {"status": "ok", "data": [7] * n, "adc_sample_rate_hz": 400000.0, "more": False}, ]}) cap = cap_mod.capture_adc(t, NAIVE, samples=n, source="ext") assert t.sent[0]["cmd"] == "capture_dual" @@ -98,7 +98,7 @@ def test_capture_adc_decodes_b64_chunks(): # Chunk lengths that leave every base64 remainder (1, 2, 0 bytes mod 3) and the extremes. words = [0, 1, 255, 256, 0x1234, 32767, 32768, 65534, 65535] t = FakeCaptureTransport({"capture": [ - {"status": "ok", "bits": 16, "b64": _b64(words[:1]), "adc_rate_hz": 400000.0, "more": True}, + {"status": "ok", "bits": 16, "b64": _b64(words[:1]), "adc_sample_rate_hz": 400000.0, "more": True}, {"status": "chunk", "b64": _b64(words[1:4]), "more": True}, {"status": "chunk", "b64": _b64(words[4:]), "more": False}, ]}) @@ -109,7 +109,7 @@ def test_capture_adc_decodes_b64_chunks(): def test_capture_correlated_decodes_b64_adc_alongside_rle_la(): t = FakeCaptureTransport({"capture_dual": [ - {"status": "ok", "bits": 16, "adc_rate_hz": 400000, "la_rate_hz": 1000000, + {"status": "ok", "bits": 16, "adc_sample_rate_hz": 400000, "la_sample_rate_hz": 1000000, "b64": _b64([10, 20, 30]), "more": True}, {"status": "chunk", "la": True, "la_edges": [[0, 5], [2, 6]], "la_upto": 4, "more": False}, ]}) @@ -147,7 +147,7 @@ def test_capture_rejects_bad_counts_and_rates(): def test_capture_la_collects_words(): t = FakeCaptureTransport({"la_capture": [ - {"status": "ok", "data": [1, 2, 4, 8], "la_rate_hz": 1e6, "more": False}, + {"status": "ok", "data": [1, 2, 4, 8], "la_sample_rate_hz": 1e6, "more": False}, ]}) la = cap_mod.capture_la(t, samples=4, sample_rate_hz=1e6) assert isinstance(la, LaCapture) @@ -155,7 +155,7 @@ def test_capture_la_collects_words(): assert la.channel(1) == [1, 0, 0, 0] assert la.channel(4) == [0, 0, 0, 1] assert la.edges(1) == 1 - assert t.sent[0]["sample_rate_mhz"] == 1.0 + assert t.sent[0]["sample_rate_hz"] == 1000000 def test_capture_la_expands_rle_frames(): @@ -169,14 +169,14 @@ def test_capture_la_expands_rle_frames(): def test_capture_la_pre_trigger_and_truncated(): # gateware v50: the pre-trigger count and an early stop ride the first frame t = FakeCaptureTransport({"la_capture": [ - {"status": "ok", "bits": 16, "la_rate_hz": 48000000, "pre_samples": 2, "la": True, + {"status": "ok", "bits": 16, "la_sample_rate_hz": 48000000, "pre_samples": 2, "la": True, "la_edges": [[0, 1], [2, 3]], "la_upto": 5, "more": False}, ]}) la = cap_mod.capture_la(t, samples=3, sample_rate_hz=48e6, trigger=Trigger(3, "falling", pre_samples=2)) assert t.sent[0]["trigger"] == {"la": 3, "edge": "falling", "pre_samples": 2} assert la.words == [1, 1, 3, 3, 3] and la.pre_samples == 2 and la.truncated == "" t = FakeCaptureTransport({"la_capture": [ - {"status": "ok", "bits": 16, "la_rate_hz": 48000000, "truncated": "busy", "la": True, + {"status": "ok", "bits": 16, "la_sample_rate_hz": 48000000, "truncated": "busy", "la": True, "la_edges": [[0, 1]], "la_upto": 2, "more": False}, ]}) la = cap_mod.capture_la(t, samples=1000, sample_rate_hz=48e6) @@ -192,7 +192,7 @@ def test_trigger_pre_samples_must_be_a_count(): def test_capture_correlated_expands_rle_la_edges(): # ADC dense (2 samples) + LA as RLE transitions covering 5 samples. t = FakeCaptureTransport({"capture_dual": [ - {"status": "ok", "data": [10, 20], "adc_rate_hz": 400000.0, "la_rate_hz": 1e6, "more": True}, + {"status": "ok", "data": [10, 20], "adc_sample_rate_hz": 400000.0, "la_sample_rate_hz": 1e6, "more": True}, {"status": "ok", "la": True, "la_edges": [[0, 3], [2, 7]], "la_upto": 5, "more": False}, ]}) ac = cap_mod.capture_correlated(t, NAIVE, adc_samples=2, adc_sample_rate_hz=400_000, @@ -203,7 +203,7 @@ def test_capture_correlated_expands_rle_la_edges(): assert ac.la.words == [3, 3, 7, 7, 7] assert ac.adc.sample_rate_hz == 400000.0 assert ac.la.sample_rate_hz == 1e6 - assert t.sent[0]["adc_rate_mhz"] == pytest.approx(0.4) and t.sent[0]["la_rate_mhz"] == 1.0 + assert t.sent[0]["adc_sample_rate_hz"] == 400000 and t.sent[0]["la_sample_rate_hz"] == 1000000 def test_capture_correlated_dense_la_fallback(): diff --git a/packages/embeddedci/tests/test_client_v2.py b/packages/embeddedci/tests/test_client_v2.py index a197328..1b38c04 100644 --- a/packages/embeddedci/tests/test_client_v2.py +++ b/packages/embeddedci/tests/test_client_v2.py @@ -219,11 +219,11 @@ def test_analog_paths_take_canonical_names(): def test_dac_output_reports_achieved_volts(): - bp, t = _bp({"dac_out": lambda req: {"path": req["path"], "mv": 2498 if "volts" in req else 0, - "code": 127 if "volts" in req else -1}}) + bp, t = _bp({"dac_out": lambda req: ({"path": req["path"], "mv": 2498, "uv": 2498000, + "code16": 32700} if "v" in req else {"path": req["path"]})}) out = bp.dac_output("5v", volts=2.5) - assert out == DacOutput(path="5v", voltage=2.498, code=127) - assert t.commands[-1] == {"cmd": "dac_out", "path": "5v", "volts": 2.5} + assert out == DacOutput(path="5v", voltage=2.498, code=127, code16=32700) + assert t.commands[-1] == {"cmd": "dac_out", "path": "5v", "v": 2.5} routed = bp.dac_output("12v") assert routed.voltage is None and routed.code is None # The firmware names the analog path (dac_5v); the result uses dac_output's own vocabulary. @@ -231,8 +231,8 @@ def test_dac_output_reports_achieved_volts(): assert DacOutput.from_reply({"path": "off", "mv": 0, "code": -1}).path == "off" # Firmware that drives the full 16 bits answers in microvolts too. fine = DacOutput.from_reply({"path": "dac_5v", "mv": 2500, "uv": 2499985, "code": 128, "code16": 32723}) - assert fine.voltage == pytest.approx(2.499985, abs=1e-9) and fine.code == 128 and fine.code16 == 32723 - assert out.code16 is None + assert fine.voltage == pytest.approx(2.499985, abs=1e-9) and fine.code == 127 and fine.code16 == 32723 + assert out.code16 == 32700 with pytest.raises(ValueError): bp.dac_output("off", volts=1.0) @@ -420,7 +420,7 @@ def test_capture_adc_routes_the_source_first(): bp, t = _bp({"analog_path": {"path": "cal1"}}) cap = bp.capture_adc(2, source="cal1", sample_rate_hz=100_000) assert t.commands[0] == {"cmd": "analog_path", "path": "cal1"} - assert t.commands[1] == {"cmd": "capture", "samples": 2, "sample_rate_mhz": 0.1, "enc": "dec"} + assert t.commands[1] == {"cmd": "capture", "samples": 2, "sample_rate_hz": 100000, "enc": "dec"} assert cap.source == "cal1" and len(cap) == 2 diff --git a/packages/embeddedci/tests/test_cloud.py b/packages/embeddedci/tests/test_cloud.py index a0c7dc7..2875d57 100644 --- a/packages/embeddedci/tests/test_cloud.py +++ b/packages/embeddedci/tests/test_cloud.py @@ -323,7 +323,7 @@ def fake_urlopen(req, *a, **k): monkeypatch.setattr(_http, "urlopen", fake_urlopen) with pytest.raises(FirmwareError, match="BP0052: The pod is still running the previous cloud command"): - t.command({"cmd": "dac_out", "path": "5v", "volts": 1.0}) + t.command({"cmd": "dac_out", "path": "5v", "v": 1.0}) assert 10 < len(calls) <= cloud._BUSY_RETRY_BUDGET / cloud._BUSY_RETRY_WAIT + 1 @@ -553,7 +553,7 @@ def test_cloud_command_retries_other_instance(monkeypatch): {"cmd": "la_step", "la": 1, "steps": 5, "delay_us": 100}, {"cmd": "spi_xfer", "tx": "9f"}, {"cmd": "generate", "waveform": "sine"}, - {"cmd": "target_power", "efuse": 1, "state": 1, "delay_ms": 500}, + {"cmd": "target_power", "efuse": 1, "enabled": True, "delay_ms": 500}, {"cmd": "dac_stop"}, {"cmd": "la_voltage", "mv": 3300}, {"cmd": "dac_limits", "path": "dac_out", "min_mv": 0}, diff --git a/packages/embeddedci/tests/test_control_loop.py b/packages/embeddedci/tests/test_control_loop.py index cec601b..ee6ca4a 100644 --- a/packages/embeddedci/tests/test_control_loop.py +++ b/packages/embeddedci/tests/test_control_loop.py @@ -129,7 +129,7 @@ def test_control_loop_raises_if_not_armed(): def test_loop_probe_returns_ivpoint(): - bp, t = _bp({"dac_loop_probe": {"i": 4321, "v": 51000}}) + bp, t = _bp({"dac_loop_probe": {"i": 4321, "code16": 51000}}) pt = bp.loop_probe() assert isinstance(pt, IVPoint) and pt.i == 4321 and pt.v == 51000 assert t.commands[-1] == {"cmd": "dac_loop_probe"} @@ -159,7 +159,7 @@ def test_control_loop_sends_the_input_map(): def test_handle_probe_delegates_to_client(): - bp, t = _bp({"dac_control_loop": {"armed": True}, "dac_loop_probe": {"i": 7, "v": 9}}) + bp, t = _bp({"dac_control_loop": {"armed": True}, "dac_loop_probe": {"i": 7, "code16": 9}}) with bp.control_loop(voc_code=1000) as loop: pt = loop.probe() assert pt.i == 7 and pt.v == 9 @@ -326,7 +326,7 @@ def test_control_loop_rejects_a_bad_source_before_sending(): def test_loop_input_steps_a_running_loop(): - bp, t = _bp({"dac_loop_input": {"source": "fixed", "input": 65535, "step": 0, "v": 123}}) + bp, t = _bp({"dac_loop_input": {"source": "fixed", "input": 65535, "step": 0, "code16": 123}}) out = bp.loop_input(65535, source="fixed") assert t.commands[-1] == {"cmd": "dac_loop_input", "input": 65535, "source": "fixed"} assert isinstance(out, LoopState) and out.input_code == 65535 and out.output_code == 123 @@ -337,7 +337,7 @@ def test_loop_input_steps_a_running_loop(): def test_handle_set_input_updates_its_view(): bp, t = _bp({"dac_control_loop": {"armed": True, "source": "fixed", "input": 0}, - "dac_loop_input": {"source": "fixed", "input": 32768, "step": 0, "v": 9}}) + "dac_loop_input": {"source": "fixed", "input": 32768, "step": 0, "code16": 9}}) loop = bp.control_loop(curve=[1, 2], source="fixed", input_code=0) loop.set_input(32768) assert loop.input_code == 32768 and loop.source == "fixed" @@ -347,11 +347,11 @@ def test_handle_set_input_updates_its_view(): def test_loop_probe_reports_the_loops_own_input(): # In a fixed/sweep run `i` is an ADC reading nothing is using; `in` is what the loop indexed # the curve with. loop_input must prefer it — that is the value a test asserts against. - bp, _ = _bp({"dac_loop_probe": {"i": 64000, "in": 32768, "source": "fixed", "v": 20000}}) + bp, _ = _bp({"dac_loop_probe": {"i": 64000, "in": 32768, "source": "fixed", "code16": 20000}}) pt = bp.loop_probe() assert pt.loop_input == 32768 and pt.source == "fixed" and pt.i == 64000 # Older firmware omits both: there the ADC IS the input by construction. - bp2, _ = _bp({"dac_loop_probe": {"i": 4321, "v": 51000}}) + bp2, _ = _bp({"dac_loop_probe": {"i": 4321, "code16": 51000}}) pt2 = bp2.loop_probe() assert pt2.input_code is None and pt2.loop_input == 4321 diff --git a/packages/embeddedci/tests/test_current_out_waveforms.py b/packages/embeddedci/tests/test_current_out_waveforms.py index be93429..4f280b9 100644 --- a/packages/embeddedci/tests/test_current_out_waveforms.py +++ b/packages/embeddedci/tests/test_current_out_waveforms.py @@ -48,7 +48,7 @@ def samples(self, req: dict) -> List[int]: def stream_chunks(self, req: dict): self.commands.append(req) - yield {"status": "ok", "data": list(self.counts), "adc_rate_hz": 100000.0, "la_rate_hz": 1e6, "more": True} + yield {"status": "ok", "data": list(self.counts), "adc_sample_rate_hz": 100000.0, "la_sample_rate_hz": 1e6, "more": True} yield {"status": "ok", "la": True, "la_edges": [[0, 1], [2, 3]], "la_upto": 4, "more": False} def load_replay(self, *, data, replay, psram=False): diff --git a/packages/embeddedci/tests/test_expansion.py b/packages/embeddedci/tests/test_expansion.py index 2d2528d..fefbcbe 100644 --- a/packages/embeddedci/tests/test_expansion.py +++ b/packages/embeddedci/tests/test_expansion.py @@ -151,7 +151,7 @@ def command(self, req: dict) -> Any: if req["pullups"] == "pod": assert {req["sda"], req["scl"]} <= self.pullups, "pod pull-ups must be on first" self.session = req - return {k: req[k] for k in ("sda", "scl", "hz", "pullups")} + return {k: req[k] for k in ("sda", "scl", "clock_hz", "pullups")} if cmd == "i2c_stop": self.session = None return "i2c stopped" @@ -619,7 +619,7 @@ def command(self, req: dict) -> Any: if self.spi: raise FirmwareError("spi busy: send spi_stop first", cmd=cmd) self.spi = req - return {k: req[k] for k in ("sck", "mosi", "miso", "cs", "hz", "mode")} + return {k: req[k] for k in ("sck", "mosi", "miso", "cs", "clock_hz", "mode")} if cmd == "spi_stop": self.commands.append(req) self.spi = None diff --git a/packages/embeddedci/tests/test_gpio.py b/packages/embeddedci/tests/test_gpio.py index bb5bccd..9b0091b 100644 --- a/packages/embeddedci/tests/test_gpio.py +++ b/packages/embeddedci/tests/test_gpio.py @@ -216,7 +216,7 @@ def test_wait_for_level_times_out(): def test_pin_levels_fall_back_to_a_capture_without_gpio_read(): pod = PinPod(caps=["la", "la_pins"]) - pod.stream_chunks = lambda req: iter([{"status": "ok", "data": [0, 0b100000000], "la_rate_hz": 1e6, + pod.stream_chunks = lambda req: iter([{"status": "ok", "data": [0, 0b100000000], "la_sample_rate_hz": 1e6, "more": False}]) # type: ignore[attr-defined] bp, _ = _bp(pod) levels = bp.pin_levels() diff --git a/packages/embeddedci/tests/test_i2c_master.py b/packages/embeddedci/tests/test_i2c_master.py index eb8963f..ee2974c 100644 --- a/packages/embeddedci/tests/test_i2c_master.py +++ b/packages/embeddedci/tests/test_i2c_master.py @@ -96,7 +96,7 @@ def command(self, req: dict) -> Any: self.session = req self.driven[req["sda"]] = "i2cm_sda" self.driven[req["scl"]] = "i2cm_scl" - return {"sda": req["sda"], "scl": req["scl"], "hz": 363636 if req["hz"] == 400_000 else req["hz"], + return {"sda": req["sda"], "scl": req["scl"], "clock_hz": 363636 if req["clock_hz"] == 400_000 else req["clock_hz"], "pullups": req["pullups"]} if cmd == "i2c_stop": self.session = None @@ -106,7 +106,7 @@ def command(self, req: dict) -> Any: if not self.session: return {"active": False} return {"active": True, "sda": self.session["sda"], "scl": self.session["scl"], - "hz": self.session["hz"], "pullups": self.session["pullups"]} + "clock_hz": self.session["clock_hz"], "pullups": self.session["pullups"]} if cmd in ("i2c_xfer", "i2c_scan") and not self.session: raise firmware_error("", cmd=cmd, code="BP0062") if cmd == "i2c_xfer": @@ -177,7 +177,7 @@ def test_open_i2c_pins_from_wiring_and_rate_reply(): bp, fake = pod() with bp.open_i2c(hz=400_000) as i2c: assert (i2c.sda, i2c.scl, i2c.hz, i2c.pullups) == (1, 2, 363636, "pod") - assert fake.commands[-1] == {"cmd": "i2c_start", "sda": 1, "scl": 2, "hz": 400_000, "pullups": "pod"} + assert fake.commands[-1] == {"cmd": "i2c_start", "sda": 1, "scl": 2, "clock_hz": 400_000, "pullups": "pod"} assert fake.commands[-1] == {"cmd": "i2c_stop"} assert fake.session is None @@ -198,14 +198,14 @@ def test_busy_names_another_connection_as_the_holder(): """Another client (the desktop app, the web app) holds the pod's I2C master: the refusal says so and where, instead of pointing at an open_i2c() this script never called.""" bp, fake = pod() - fake.session = {"sda": 1, "scl": 2, "hz": 100_000, "pullups": "pod"} + fake.session = {"sda": 1, "scl": 2, "clock_hz": 100_000, "pullups": "pod"} with pytest.raises(FirmwareError) as e: bp.open_i2c() msg = str(e.value) assert "another connection to this pod holds its I2C master (LA1 SDA, LA2 SCL, 100000 Hz)" in msg assert "desktop app" in msg and "bp.open_i2c() first" not in msg assert e.value.code == "BP0003" and isinstance(e.value, PodBusyError) - assert fake.session["hz"] == 100_000 # nothing was stopped + assert fake.session["clock_hz"] == 100_000 # nothing was stopped def test_busy_names_this_benchpods_own_open_session(): diff --git a/packages/embeddedci/tests/test_motor_emulator.py b/packages/embeddedci/tests/test_motor_emulator.py index ca479ef..9cb62d5 100644 --- a/packages/embeddedci/tests/test_motor_emulator.py +++ b/packages/embeddedci/tests/test_motor_emulator.py @@ -106,9 +106,9 @@ def command(self, req: dict) -> Any: self.commands.append(req) cmd = req["cmd"] if cmd == "spi_start": - assert self.armed is None and req["mode"] == 0 and req["hz"] <= 6_000_000 + assert self.armed is None and req["mode"] == 0 and req["clock_hz"] <= 6_000_000 self.armed = req - return {**{k: req[k] for k in ("sck", "mosi", "miso", "cs", "mode")}, "hz": 6_000_000} + return {**{k: req[k] for k in ("sck", "mosi", "miso", "cs", "mode")}, "clock_hz": 6_000_000} if cmd == "spi_stop": self.armed = None return "spi stopped" @@ -419,7 +419,7 @@ def command(req): cmds.append(req) return {"sent": req["len"], "ms": 250, "cs": "held"} - spi = SpiSession(command, {"hz": 6_000_000}, stage=lambda d: staged.append(d) or len(d)) + spi = SpiSession(command, {"clock_hz": 6_000_000}, stage=lambda d: staged.append(d) or len(d)) r = spi.stream(b"\x01" * 1000, head=b"\x7a\0\0\0", hold_cs=True) assert r == SpiStreamResult(sent=1000, seconds=0.25) assert staged == [b"\x01" * 1000] diff --git a/packages/embeddedci/tests/test_replay.py b/packages/embeddedci/tests/test_replay.py index 8b07b10..77c2b08 100644 --- a/packages/embeddedci/tests/test_replay.py +++ b/packages/embeddedci/tests/test_replay.py @@ -49,7 +49,7 @@ def test_replay_capture_maps_volts_and_routes_path(): cap = Capture(counts=[], volts=[0.0, 2.5, 5.0], sample_rate_hz=1000.0) handle = bp.replay(cap, dac_path="5v", sample_rate_hz=400_000) assert isinstance(handle, ReplayHandle) - assert t.uploads[-1]["replay"]["sample_rate_mhz"] == pytest.approx(0.4) + assert t.uploads[-1]["replay"]["sample_rate_hz"] == 400000 assert handle.sample_rate_hz == 400_000 # routed the DAC path first assert {"cmd": "dac_out", "path": "5v"} in t.commands @@ -92,7 +92,7 @@ def test_replay_handle_context_manager_stops(): def test_replay_capture_defaults_to_its_own_rate(): bp, t = _bp() bp.replay(Capture(counts=[], volts=[1.0, 2.0], sample_rate_hz=200_000.0), dac_path="5v") - assert t.uploads[-1]["replay"]["sample_rate_mhz"] == pytest.approx(0.2) + assert t.uploads[-1]["replay"]["sample_rate_hz"] == 200000 def test_replay_rejects_unknown_path_and_mapping(): diff --git a/packages/embeddedci/tests/test_spi.py b/packages/embeddedci/tests/test_spi.py index 9d25992..99cb6b9 100644 --- a/packages/embeddedci/tests/test_spi.py +++ b/packages/embeddedci/tests/test_spi.py @@ -57,8 +57,8 @@ def command(self, req: dict) -> Any: assert len(set(pins)) == 4 and all(1 <= p <= 14 for p in pins) assert self.armed is None, "spi busy" self.armed = req - half = max(2, min(63, -(-24_000_000 // (2 * req["hz"])))) - return {**{k: req[k] for k in ("sck", "mosi", "miso", "cs", "mode")}, "hz": 24_000_000 // (2 * half)} + half = max(2, min(63, -(-24_000_000 // (2 * req["clock_hz"])))) + return {**{k: req[k] for k in ("sck", "mosi", "miso", "cs", "mode")}, "clock_hz": 24_000_000 // (2 * half)} if cmd == "spi_stop": self.armed = None return "spi stopped" @@ -194,7 +194,7 @@ def test_spi_flash_programs_verifies_and_reports_progress(pod, tmp_path): assert res.length == len(img) and res.verified and res.erased == 12288 and res.jedec_id == "ef4014" assert seen[-1] == (2 * len(img), 2 * len(img)) and all(d <= t for d, t in seen) assert fake.armed is None - assert fake.commands[0]["cmd"] == "spi_start" and fake.commands[0]["hz"] == 6_000_000 + assert fake.commands[0]["cmd"] == "spi_start" and fake.commands[0]["clock_hz"] == 6_000_000 def test_spi_flash_holds_reset_and_releases_it_on_failure(pod): diff --git a/packages/embeddedci/tests/test_tcp_transport.py b/packages/embeddedci/tests/test_tcp_transport.py index 1020662..082f2c2 100644 --- a/packages/embeddedci/tests/test_tcp_transport.py +++ b/packages/embeddedci/tests/test_tcp_transport.py @@ -76,7 +76,7 @@ def handler(conn, line): try: t = TcpTransport(pod.addr, timeout=2) t.target_power(1, True) - assert seen == {"cmd": "target_power", "efuse": 1, "state": 1} + assert seen == {"cmd": "target_power", "efuse": 1, "enabled": True} finally: pod.close() diff --git a/packages/embeddedci/tests/test_timed_power.py b/packages/embeddedci/tests/test_timed_power.py index eebe427..9740d56 100644 --- a/packages/embeddedci/tests/test_timed_power.py +++ b/packages/embeddedci/tests/test_timed_power.py @@ -51,7 +51,7 @@ def test_target_power_no_delay_omits_field(): pod = FakePod() try: TcpTransport(pod.addr, timeout=2).target_power(1, True) - assert pod.requests[-1] == {"cmd": "target_power", "efuse": 1, "state": 1} + assert pod.requests[-1] == {"cmd": "target_power", "efuse": 1, "enabled": True} finally: pod.close() @@ -61,7 +61,7 @@ def test_target_power_with_delay_sends_delay_ms(): try: TcpTransport(pod.addr, timeout=2).target_power(2, True, 2000) assert pod.requests[-1] == { - "cmd": "target_power", "efuse": 2, "state": 1, "delay_ms": 2000 + "cmd": "target_power", "efuse": 2, "enabled": True, "delay_ms": 2000 } finally: pod.close() @@ -73,6 +73,6 @@ def test_client_power_on_delay_seconds_to_ms(): device = BenchPod(transport=TcpTransport(pod.addr, timeout=2)) device.power_on(bp.INTERNAL, delay=1.5) assert pod.requests[-1]["delay_ms"] == 1500 - assert pod.requests[-1]["state"] == 1 + assert pod.requests[-1]["enabled"] is True finally: pod.close() diff --git a/packages/embeddedci/tests/test_transport_failures.py b/packages/embeddedci/tests/test_transport_failures.py index a650a8c..cb38b61 100644 --- a/packages/embeddedci/tests/test_transport_failures.py +++ b/packages/embeddedci/tests/test_transport_failures.py @@ -412,7 +412,7 @@ def handler(conn, line): return seen.update(req) time.sleep(req["duration_ms"] / 1000.0 + 0.1) # the pod samples for the whole duration - stats = {"n": 400, "duration_ms": req["duration_ms"], "rate_hz": 500, + stats = {"n": 400, "duration_ms": req["duration_ms"], "sample_rate_hz": 500, "i_avg_ua": 12000, "i_min_ua": 10000, "i_max_ua": 15000, "v_avg_mv": 5000, "energy_uj": 48000} conn.sendall((json.dumps({"status": "ok", "data": {"stats": stats}, "more": False}) diff --git a/packages/embeddedci/tests/test_trigger_power.py b/packages/embeddedci/tests/test_trigger_power.py index 493e907..46fa5d0 100644 --- a/packages/embeddedci/tests/test_trigger_power.py +++ b/packages/embeddedci/tests/test_trigger_power.py @@ -48,7 +48,7 @@ def stream_chunks(self, req: dict) -> Iterator[Dict[str, Any]]: if isinstance(self.error, tuple): raise firmware_error("", cmd=req["cmd"], code=self.error[0], values=self.error[1]) raise FirmwareError(self.error, cmd=req["cmd"]) - if "rate_hz" in req and isinstance(req["rate_hz"], float): + if "sample_rate_hz" in req and isinstance(req["sample_rate_hz"], float): # The firmware's parser refuses a non-integer here ("rate_hz must be a whole # number 0..1000000") — a float used to reach the pod and fail only on hardware. raise FirmwareError("power_profile: rate_hz must be a whole number 0..1000000", @@ -76,7 +76,7 @@ def test_trigger_validates_itself(): def test_triggered_la_capture_request_and_result(): bp, pod = _bp() pod.chunks["la_capture"] = [{"status": "ok", "la": True, "la_edges": [[0, 256]], "la_upto": 4, - "la_rate_hz": 1e6, "more": False}] + "la_sample_rate_hz": 1e6, "more": False}] la = bp.capture_la(4, sample_rate_hz=1e6, trigger=Trigger(9, "falling"), trigger_timeout=2.5) req = pod.requests[-1] assert req["trigger"] == {"la": 9, "edge": "falling"} and req["trigger_timeout_ms"] == 2500 @@ -91,7 +91,7 @@ def test_trigger_names_come_from_the_wiring_profile(): def test_triggered_adc_capture_uses_the_streaming_path(): bp, pod = _bp() - pod.chunks["capture_dual"] = [{"status": "ok", "data": [1, 2, 3], "adc_rate_hz": 1e5, "more": False}] + pod.chunks["capture_dual"] = [{"status": "ok", "data": [1, 2, 3], "adc_sample_rate_hz": 1e5, "more": False}] cap = bp.capture_adc(3, trigger=Trigger(2, "low")) req = pod.requests[-1] assert req["cmd"] == "capture_dual" and req["la_samples"] == 0 and req["trigger"]["edge"] == "low" @@ -119,7 +119,7 @@ def test_triggers_need_gateware_that_has_them(): # -- power profiles --------------------------------------------------------------------- -STATS = {"efuse": 1, "rate_hz": 364.0, "adc_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52000, +STATS = {"efuse": 1, "sample_rate_hz": 364.0, "adc_sample_rate_hz": 950.0, "n": 950, "duration_ms": 1000, "avg_ua": 52000, "min_ua": 40000, "peak_ua": 180000, "avg_mv": 5010, "min_mv": 4990, "max_mv": 5030, "energy_uj": 260500, "charge_uc": 52000, "fault": False, "truncated": False} @@ -132,7 +132,7 @@ def test_measure_power_request_and_units(): {"status": "ok", "t_us": [], "current_ua": [], "bus_mv": [], "stats": STATS, "more": False}, ] prof = bp.measure_power(1.0, keep_samples=2) - assert pod.requests[-1] == {"cmd": "power_profile", "efuse": 2, "rate_hz": 500, + assert pod.requests[-1] == {"cmd": "power_profile", "efuse": 2, "sample_rate_hz": 500, "keep_samples": 2, "duration_ms": 1000} assert isinstance(prof, PowerProfile) assert prof.avg_current == pytest.approx(0.052) and prof.peak_current == pytest.approx(0.18) @@ -151,7 +151,7 @@ def test_power_profile_session_start_stop(): with session as prof: with pytest.raises(BenchPodError, match="still running"): _ = prof.result - assert pod.requests[0] == {"cmd": "power_profile", "efuse": 1, "rate_hz": 500, "keep_samples": 0, + assert pod.requests[0] == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 0, "max_duration_ms": 5000, "action": "start"} assert pod.requests[-1] == {"cmd": "power_profile", "action": "stop"} assert prof.result.n == 950 and prof.stop() is prof.result diff --git a/packages/embeddedci/tests/test_usb_net.py b/packages/embeddedci/tests/test_usb_net.py index 891ab9b..7d32cb0 100644 --- a/packages/embeddedci/tests/test_usb_net.py +++ b/packages/embeddedci/tests/test_usb_net.py @@ -277,9 +277,9 @@ def test_usb_network_method_reads_and_turns_off(): class T: def command(self, req, **kw): sent.append(req) - return {"setting": "off" if req.get("set") == "off" else "on"} + return {"enabled": req.get("enabled", True)} pod = BenchPod.__new__(BenchPod) pod.command = T().command # the method only needs command() assert pod.usb_network() is True and sent[-1] == {"cmd": "usb_network"} - assert pod.usb_network(False) is False and sent[-1] == {"cmd": "usb_network", "set": "off"} + assert pod.usb_network(False) is False and sent[-1] == {"cmd": "usb_network", "enabled": False} diff --git a/packages/embeddedci/tests/test_wire_names_4.py b/packages/embeddedci/tests/test_wire_names_4.py new file mode 100644 index 0000000..ffdcd50 --- /dev/null +++ b/packages/embeddedci/tests/test_wire_names_4.py @@ -0,0 +1,158 @@ +"""The JSON the SDK sends for every command firmware 4.0 renamed (benchpod-firmware docs/API.md, +features json_names_4, json_booleans_4, can_start_stop, la_step_pull_split, generate_volts_only), +and the renamed reply fields it reads. The public SDK names (volts, seconds, hertz) are unchanged.""" + +from __future__ import annotations + +from typing import Any, Dict, Iterator, List + +from embeddedci.benchpod import BenchPod, Wiring +from embeddedci.benchpod.state import DacOutput + + +class Pod: + """Records every request; replies come from ``replies`` (by command) as firmware 4.0 sends them.""" + + def __init__(self) -> None: + self.sent: List[Dict[str, Any]] = [] + self.power: List[Any] = [] + self.replies: Dict[str, Any] = { + "i2c_start": lambda r: {"sda": r["sda"], "scl": r["scl"], "clock_hz": r["clock_hz"], + "pullups": r["pullups"]}, + "spi_start": lambda r: {**{k: r[k] for k in ("sck", "mosi", "miso", "cs", "mode")}, + "clock_hz": 4_000_000}, + "dac_out": lambda r: {"path": "dac_" + r["path"], "mv": 2500, "uv": 2500000, "code16": 40000}, + "dac_loop_probe": {"i": 1, "in": 2, "source": "adc", "code16": 1234, "tripped": False}, + "dac_loop_input": {"source": "fixed", "input": 5, "step": 0, "code16": 99}, + "can_read": {"frames": [{"id": 1, "ext": False, "rtr": False, "fd": False, "brs": False, + "dlc": 1, "data": [7], "ts_ms": 4242}], "overflow": 0}, + "usb_network": lambda r: {"enabled": r.get("enabled", True)}, + "la_pull": lambda r: ({"la": r["la"], "state": r.get("pull", "off"), "dirs": ["up"], + "pullups_available": True} if "la" in r + else {"la_pullup_mask": 1, "pullups_available": True}), + "la_step": lambda r: {"la": r["la"], "steps": r["steps"], "delay_us": r["delay_us"], + "status": "started"}, + } + + def status(self) -> Dict[str, Any]: + return {"version": "4.0.0", "board": "stm32h563", "adc_bits": 16, "api": 2, "min_client_api": 2, + "features_rev": 11, "gateware": 59, "fpga_image": "deep", "hw": [], "analog": True} + + def command(self, req: Dict[str, Any]) -> Any: + if req["cmd"] in ("wiring_list", "la_dir"): + return {} + self.sent.append(req) + r = self.replies.get(req["cmd"], {}) + return r(req) if callable(r) else r + + def stream_chunks(self, req: Dict[str, Any]) -> Iterator[Dict[str, Any]]: + self.sent.append(req) + yield {"status": "ok", "data": [1, 2], "adc_sample_rate_hz": 400000, + "la_sample_rate_hz": 1000000, "more": False} + + def load_replay(self, *, data: bytes, replay: Dict[str, Any], psram: bool = False) -> Any: + self.sent.append(replay) + return {"samples": replay["samples"], "sample_rate_hz": 100000} + + def target_power(self, efuse: int, on: bool, delay_ms: int = 0) -> None: + self.power.append((efuse, on)) + + def ping(self) -> Any: + return "pong" + + def close(self) -> None: + pass + + +def _bp() -> "tuple[BenchPod, Pod]": + pod = Pod() + return BenchPod(transport=pod, lease=False, wiring=Wiring(i2c_sda=1, i2c_scl=2)), pod + + +def test_rates_are_hertz(): + bp, pod = _bp() + bp.generate("sine", freq_hz=1000, amplitude=1.0, dac_path="3v3", sample_rate_hz=500_000) + assert pod.sent[-1] == {"cmd": "generate", "waveform": "sine", "freq_hz": 1000, "path": "3v3", + "amplitude_v": 1.0, "offset_v": 1.65, "sample_rate_hz": 500000} + bp.capture_la(16, sample_rate_hz=2e6) + assert pod.sent[-1]["cmd"] == "la_capture" and pod.sent[-1]["sample_rate_hz"] == 2000000 + cap = bp.capture_correlated(adc_samples=2, la_samples=2, adc_sample_rate_hz=1e5, + la_sample_rate_hz=1e6) + req = pod.sent[-1] + assert req["cmd"] == "capture_dual" and req["adc_sample_rate_hz"] == 100000 + assert req["la_sample_rate_hz"] == 1000000 and "adc_rate_mhz" not in req + assert cap.adc.sample_rate_hz == 400000 # read from adc_sample_rate_hz + bp.replay([0, 100], are_codes=True, dac_path="5v", sample_rate_hz=100_000) + assert pod.sent[-1]["sample_rate_hz"] == 100000 and "sample_rate_mhz" not in pod.sent[-1] + + +def test_clock_hz_for_the_bus_masters(): + bp, pod = _bp() + i2c = bp.open_i2c(hz=100_000) + assert pod.sent[-1] == {"cmd": "i2c_start", "sda": 1, "scl": 2, "clock_hz": 100000, "pullups": "pod"} + assert i2c.hz == 100000 + spi = bp.open_spi(sck=7, mosi=8, miso=9, cs=10, hz=4_000_000) + assert pod.sent[-1]["cmd"] == "spi_start" and pod.sent[-1]["clock_hz"] == 4000000 + assert spi.hz == 4000000 + + +def test_dac_out_takes_v_and_replies_code16(): + bp, pod = _bp() + out = bp.dac_output("5v", volts=2.5) + assert pod.sent[-1] == {"cmd": "dac_out", "path": "5v", "v": 2.5} + assert out.voltage == 2.5 and out.code16 == 40000 and out.code == 40000 >> 8 + assert DacOutput.from_reply({"path": "dac_5v"}).voltage is None # routed only + + +def test_loop_replies_are_code16(): + bp, pod = _bp() + assert bp.loop_probe().v == 1234 + assert bp.loop_input(input_code=5, source="fixed").output_code == 99 + + +def test_power_profile_sample_rate_hz(): + bp, pod = _bp() + req = bp._power_request(1, 400.0, 0) + assert req["cmd"] == "power_profile" and req["sample_rate_hz"] == 400 and "rate_hz" not in req + + +def test_can_start_stop_and_ts_ms(): + bp, pod = _bp() + bp.can_config(bitrate=500_000, mode="internal") + assert pod.sent[-1]["cmd"] == "can_start" + assert bp.can_read().frames[0].ts == 4242 + bp.can_disable() + assert pod.sent[-1] == {"cmd": "can_stop"} + + +def test_la_step_and_la_pull(): + bp, pod = _bp() + bp.la_step(3, steps=10, delay=0.001) + assert pod.sent[-1]["cmd"] == "la_step" and pod.sent[-1]["steps"] == 10 + bp.set_pull(1, "up") + assert pod.sent[-1] == {"cmd": "la_pull", "la": 1, "pull": "up"} + assert bp.enabled_pulls() == [1] and pod.sent[-1] == {"cmd": "la_pull"} + + +def test_booleans(): + bp, pod = _bp() + assert bp.usb_network(False) is False + assert pod.sent[-1] == {"cmd": "usb_network", "enabled": False} + assert bp.usb_network() is True and pod.sent[-1] == {"cmd": "usb_network"} + pod.replies["target_status"] = {"efuse1": {"enabled": True, "fault": False, "valid": True}, + "efuse2": {"enabled": False, "fault": True, "valid": True}} + st = bp.target_status() + assert st.internal.enabled and not st.internal.fault and st.external.fault + + +def test_target_power_over_tcp_sends_enabled(): + import json + from embeddedci.benchpod.transport.tcp import TcpTransport + + sent: List[Dict[str, Any]] = [] + t = TcpTransport("10.237.8.85:8080") + t.command = lambda req: sent.append(json.loads(json.dumps(req))) # type: ignore[method-assign] + t.target_power(2, True, delay_ms=5) + t.target_power(1, False) + assert sent == [{"cmd": "target_power", "efuse": 2, "enabled": True, "delay_ms": 5}, + {"cmd": "target_power", "efuse": 1, "enabled": False}] diff --git a/packages/embeddedci/tests/test_wiring_profiles.py b/packages/embeddedci/tests/test_wiring_profiles.py index 709609e..5d8b033 100644 --- a/packages/embeddedci/tests/test_wiring_profiles.py +++ b/packages/embeddedci/tests/test_wiring_profiles.py @@ -91,10 +91,10 @@ def command(self, req: dict) -> Any: 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)} + return {f"efuse{n}": {"enabled": self.rails[n], "fault": False, "valid": True} 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} + self.rails[req["efuse"]] = req["enabled"] is True + return {"efuse": req["efuse"], "enabled": req["enabled"], "delay_ms": 0} return {} def sent(self, verb: str) -> List[dict]: From 9a233a67df49216306f77100f568d4903c54076f Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 06:49:57 -0600 Subject: [PATCH 05/10] Public API removals for 4.0; MCP tool parameters in units SDK: set_pull takes a direction only (no True/False, no enabled=); REFERENCE_BENCH, PRESET_ALIASES, the embeddedci-reference preset and Wiring.defaults() are gone, as are PULL_OHMS, PULLUP_CHANNELS, PULLDOWN_CHANNELS (PULL_TABLE stays), RP_VID, the serial connection keyword, the bench_pod_addr config key, a channel number as the upload reset input, and CanBus.expect/read_until can_id=. MCP: every seconds parameter ends in _s, the I/O voltage is la_voltage, set_pull takes la and pull, replay takes waveform_id (replay_waveform is gone), usb_network takes and returns enabled. Tool surface snapshot refreshed. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 13 + packages/embeddedci-mcp/README.md | 49 ++- .../src/embeddedci_mcp/guide.py | 10 +- .../src/embeddedci_mcp/models.py | 4 +- .../src/embeddedci_mcp/server.py | 238 ++++++-------- .../src/embeddedci_mcp/summaries.py | 6 +- packages/embeddedci-mcp/tests/test_e2e_mcp.py | 20 +- .../tests/test_expansion_tools.py | 4 +- .../embeddedci-mcp/tests/test_gpio_tools.py | 8 +- .../embeddedci-mcp/tests/test_refusals.py | 4 +- packages/embeddedci-mcp/tests/test_tools.py | 60 ++-- .../tests/test_trigger_power_tools.py | 20 +- .../embeddedci-mcp/tests/test_wiring_tools.py | 4 +- .../embeddedci-mcp/tests/tools_surface.json | 310 +++++------------- packages/embeddedci-openhtf/README.md | 2 +- packages/embeddedci/CHANGELOG.md | 8 + packages/embeddedci/README.md | 18 +- .../embeddedci/src/embeddedci/benchpod/can.py | 22 +- .../src/embeddedci/benchpod/cli_config.py | 9 +- .../src/embeddedci/benchpod/client.py | 35 +- .../src/embeddedci/benchpod/connection.py | 11 +- .../src/embeddedci/benchpod/constants.py | 6 +- .../src/embeddedci/benchpod/header.py | 4 +- .../src/embeddedci/benchpod/pytest_plugin.py | 6 +- .../src/embeddedci/benchpod/wiring.py | 21 +- .../embeddedci/src/embeddedci/upload_build.py | 9 +- packages/embeddedci/tests/api_surface.json | 7 +- packages/embeddedci/tests/e2e/test_e2e_pod.py | 12 +- .../tests/examples/test_can_ecu_demo.py | 8 +- .../tests/examples/test_can_loopback_hil.py | 8 +- packages/embeddedci/tests/test_can.py | 20 +- packages/embeddedci/tests/test_connection.py | 8 +- packages/embeddedci/tests/test_one_source.py | 4 +- .../embeddedci/tests/test_pull_direction.py | 24 +- .../embeddedci/tests/test_upload_build.py | 10 + packages/embeddedci/tests/test_usb_net.py | 6 - packages/embeddedci/tests/test_wiring.py | 9 +- 37 files changed, 402 insertions(+), 615 deletions(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index cba0df0..ea585f7 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -14,6 +14,19 @@ Pairs with BenchPod firmware 4.0.0 and embeddedci 4.0. Breaking changes: refusal without a code keeps the pod's text. - `connect` to a LAN address uses TLS on 8443 by default; mDNS discovery connects to the pod's TLS port and refuses a pod with firmware 3.x. +- **Tool parameters in units.** Seconds end in `_s`: `connect` `lease_wait_s`, `power_on`/ + `power_off` `delay_s`, `measure_power` `duration_s`, `power_profile_start` `max_duration_s`, + `reset_target` `pulse_s`, `flash` `timeout_s`, `capture_uart` `duration_s`, + `power_cycle_and_capture` `delay_s`/`duration_s`/`off_settle_s`, `uart_read` `timeout_s`, + `gpio_wait` `timeout_s`, `gpio_pulse` `width_s`, `capture_adc`/`capture_la`/ + `capture_correlated` `trigger_timeout_s` and `stop_dac_after_s`, `generate` `duration_s`, + `can_read` `timeout_s`, `la_step` `delay_s` (as `sensor_fault` `duration_s` and the vision + tools already were). The I/O voltage is `la_voltage` everywhere (`set_la_voltage` took + `voltage`). +- `set_pull` takes `la` (a list of channels) and a required `pull`; `las` and `enabled` are gone. +- `replay` takes `waveform_id` (with `window_start`, `window_len`, `target_samples`) for a + cloud-library waveform; the `replay_waveform` tool is gone. +- `usb_network` takes `enabled=false` (was `set="off"`) and returns `enabled` (was `setting`). - `status` warns when `module.dac_pinout_ok` is false: the DAC is off because the digital board and the analog module do not belong together (`BP0080`). diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index dfed421..39d38ce 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -186,10 +186,10 @@ 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. `wiring_profile` names a profile stored on the pod (default: the pod's default profile). | `connection`, `la_voltage`, `lease_wait=30`, `wiring_profile` | +| `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_s=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). Usually not needed: `connect` sets it from the wiring profile's `la_mv`. | **`voltage`** | +| `set_la_voltage` | Select the LA I/O voltage to match the DUT (1.8 V needs a rev3 pod). Usually not needed: `connect` sets it from the wiring profile's `la_mv`. | `la_voltage` (omit to read) | ### Cloud (embeddedci.com) @@ -216,24 +216,24 @@ description, ranges and enums, so an agent sees more than this table. | Tool | Purpose | Parameters | | --- | --- | --- | -| `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), its pull resistors (`pulls`, at 3.3 V), 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_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), its pull resistors (`pulls`, at 3.3 V), 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_s`, `wiring_profile` | +| `power_off` | Switch the target's power rail off. | `efuse`, `delay_s` | | `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` | +| `reset_target` | Drive the DUT's reset line from the pod's reset pin. | `action=pulse`, `pulse_s=0.1` | ### Power profiles | Tool | Purpose | Parameters | | --- | --- | --- | -| `measure_power` | Sample supply current and voltage for a window: average, min, peak, energy and charge. | **`duration`**, `efuse`, `rate_hz=500`, `points=0` | -| `power_profile_start` | Start sampling the rail in the background while other tools run. | `efuse`, `rate_hz=500`, `max_duration=60` | +| `measure_power` | Sample supply current and voltage for a window: average, min, peak, energy and charge. | **`duration_s`**, `efuse`, `rate_hz=500`, `points=0` | +| `power_profile_start` | Start sampling the rail in the background while other tools run. | `efuse`, `rate_hz=500`, `max_duration_s=60` | | `power_profile_stop` | Stop the running profile and return its statistics (and a trace). | `points=0` | ### Flash | Tool | Purpose | Parameters | | --- | --- | --- | -| `flash` | Program the DUT over SWD through the pod's CMSIS-DAP probe: a local `file` (OpenOCD runs next to the server), or a build uploaded to embeddedci.com (`build` id or `latest`, `repo`, `ref`; embeddedci.com runs OpenOCD on a cloud connection, LAN/USB downloads it). With `target` `esp32` (or `esp32s3`, `esp32c3`, ...) the pod flashes an ESP32-family target over its UART ROM bootloader instead: `file` is a `.bin` or an ESP-IDF `flasher_args.json`, TXD0/RXD0 on `rx`/`tx` (default: the profile's `uart_rx`/`uart_tx`), IO0 on `boot`, EN on the pod's reset pin (`nreset`), a `.bin` at `load_address`. | `swclk`, `swdio`, `target`, `file`, `nreset`, `load_address`, `target_power`, `verify=true`, `reset=true`, `connect_under_reset`, `extra_configs`, `extra_args`, `timeout=300`, `connect_attempts=5`, `build`, `repo`, `ref`, `artifact`, `server_side`, `rx`, `tx`, `boot` | +| `flash` | Program the DUT over SWD through the pod's CMSIS-DAP probe: a local `file` (OpenOCD runs next to the server), or a build uploaded to embeddedci.com (`build` id or `latest`, `repo`, `ref`; embeddedci.com runs OpenOCD on a cloud connection, LAN/USB downloads it). With `target` `esp32` (or `esp32s3`, `esp32c3`, ...) the pod flashes an ESP32-family target over its UART ROM bootloader instead: `file` is a `.bin` or an ESP-IDF `flasher_args.json`, TXD0/RXD0 on `rx`/`tx` (default: the profile's `uart_rx`/`uart_tx`), IO0 on `boot`, EN on the pod's reset pin (`nreset`), a `.bin` at `load_address`. | `swclk`, `swdio`, `target`, `file`, `nreset`, `load_address`, `target_power`, `verify=true`, `reset=true`, `connect_under_reset`, `extra_configs`, `extra_args`, `timeout_s=300`, `connect_attempts=5`, `build`, `repo`, `ref`, `artifact`, `server_side`, `rx`, `tx`, `boot` | ### SPI flash and SPI devices @@ -263,11 +263,11 @@ the board's with `pullups="external"`. | Tool | Purpose | Parameters | | --- | --- | --- | -| `capture_uart` | Record the DUT's UART for a window, or until a regex matches. | **`duration`**, `rx`, `tx`, `baud`, `until_regex`, `parity`, `stop_bits`, `half_duplex`, `entry`, `de`, `de_active_low` | -| `power_cycle_and_capture` | Power-cycle the target and capture UART across the boot. | `rx`, `tx`, `efuse`, `delay=1`, `duration=4`, `baud`, `until_regex`, `off_settle=0.3`, `parity`, `stop_bits` | +| `capture_uart` | Record the DUT's UART for a window, or until a regex matches. | **`duration_s`**, `rx`, `tx`, `baud`, `until_regex`, `parity`, `stop_bits`, `half_duplex`, `entry`, `de`, `de_active_low` | +| `power_cycle_and_capture` | Power-cycle the target and capture UART across the boot. | `rx`, `tx`, `efuse`, `delay_s=1`, `duration_s=4`, `baud`, `until_regex`, `off_settle_s=0.3`, `parity`, `stop_bits` | | `uart_open` | Start buffering the DUT's UART in the background. The frame is the profile's (`uart_parity`, `uart_stop_bits`; 8N1 unless set) unless `parity` (`none`/`even`/`odd`) or `stop_bits` (1/2) say otherwise; anything but 8N1 needs firmware 3.10.8+. `half_duplex` runs it on one wire (`rx`; `tx` defaults to it) and `entry` (`reset_ms`, `tx_low`, `hold_ms`, `idle_ms`, `data_hex`) runs a pod-timed boot-mode entry first: reset with TX held low, release, the first bytes (gateware v57, for boot-ROM pins such as RL78 TOOL0). | `rx`, `tx`, `baud`, `parity`, `stop_bits`, `half_duplex`, `entry`, `de`, `de_active_low` | | `uart_write` | Send text to the DUT through the open UART session. | **`text`**, `line_ending=lf` | -| `uart_read` | Return output received since the last read, optionally waiting for a match. | `until_regex`, `timeout=2` | +| `uart_read` | Return output received since the last read, optionally waiting for a match. | `until_regex`, `timeout_s=2` | | `uart_close` | Stop the background UART session. | none | ### Emulated sensors @@ -303,10 +303,10 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | Tool | Purpose | Parameters | | --- | --- | --- | -| `set_pull` | Pull LA channels `up` or `down`, or switch their resistor `off`; the pod picks the value. Today LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none; another direction is refused (BP0024, BP0023). `enabled` is the older on/off form. | **`las`**, `pull`, `enabled` | +| `set_pull` | Pull LA channels `up` or `down`, or switch their resistor `off`; the pod picks the value. Today LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none; another direction is refused (BP0024, BP0023). | **`la`**, **`pull`** | | `pull_status` | Every LA channel's pull resistor: state (`up`, `down` or `off`), the directions it supports and its value. | none | | `lan_tls` | The pod's LAN API over TLS: port 8443, the HTTPS-only setting and the certificate's sha256 (what clients pin). Turning HTTPS-only off and regenerating need a TLS, USB or cloud connection. | `https_only`, `regenerate` | -| `usb_network` | Read the pod's USB network setting (firmware 3.9.0+), or turn the adapter off over the USB link. Only the device changes it; turning it back on is `benchpod usb-network on` on the USB console. | `set=off` | +| `usb_network` | Read the pod's USB network setting, or turn the adapter off over the USB link. Only the device changes it; turning it back on is `benchpod usb-network on` on the USB console. | `enabled=false` | | `log_level` | Read or set how much the pod prints on its USB console (firmware newer than 3.10.12): `error`, `warn`, `info` (the default) or `debug`, which adds every command trace and the reconnect retry detail. Stored on the pod. | `level` | ### GPIO on the LA pins @@ -317,8 +317,8 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | `gpio_mode` | Claim LA channels as GPIO (input, output or open drain). | **`la`**, `mode=output`, `level` | | `gpio_write` | Set the level of GPIO output and open-drain channels (and EXT pins); `level` is one level or a list, one per channel. | **`la`**, **`level`** | | `gpio_read` | The live level of LA channels and EXT pins (all of them when `la` is omitted). | `la` | -| `gpio_wait` | Wait until an LA channel reads a level (`reached: false` on timeout). | **`la`**, `level=1`, `timeout=5` | -| `gpio_pulse` | FPGA-timed pulses on an LA channel: `width` 4 us to 65.535 ms, `count` up to 65535. | **`la`**, **`width`**, `count=1` | +| `gpio_wait` | Wait until an LA channel reads a level (`reached: false` on timeout). | **`la`**, `level=1`, `timeout_s=5` | +| `gpio_pulse` | FPGA-timed pulses on an LA channel: `width_s` 4 us to 65.535 ms, `count` up to 65535. | **`la`**, **`width_s`**, `count=1` | | `gpio_release` | Return channels to high-Z, watched by captures (EXT pins to input). | `la` | | `expansion` | Attach an I2C/SPI GPIO expander board (chips: `tca9555`, `pca9555`, `mcp23017`, `pcf8574`, `pcf8574a`, `pcf8575`, `tca6416a`, `tca6424a`, `mcp23s17`, `74hc595`, `74hc165`), report it, or detach it. Its pins become `EXT1`..`EXTn`, which `gpio_mode`, `gpio_write`, `gpio_read`, `gpio_wait` and `gpio_release` take next to LA channels; `gpio_pulse`, triggers and `la_dir` refuse them. | `chip` (omit for the status), `detach=false`, `addr`, `sda`, `scl`, `spi` (`[sck, mosi, miso, cs]`), `load` (74hc165), `count` (chains), `hz`, `pullups`, `names` | | `la_dir` | Which way each pin's DUT signal goes (`dut_input`, `dut_output`, `bidir`, `unknown`); on a DUT output the pod refuses push-pull drivers. `connect` and `set_wiring` already send the wiring profile's; `from_wiring` sends them again; no arguments lists every pin. | `la`, `dir`, `from_wiring=false` | @@ -341,9 +341,9 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | Tool | Purpose | Parameters | | --- | --- | --- | -| `capture_adc` | Capture the ADC: calibrated statistics, dominant frequency and a min/max envelope; `clipped_samples` counts samples past the range's full scale. `oversample` converts at 400 kS/s and averages down to `sample_rate_hz` for lower noise, about 5 s at most. | `samples=4096`, `sample_rate_hz`, `source`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout=10`, `range`, `oversample` | -| `capture_la` | Capture all 14 LA channels: levels, edge count, first edge and frequency per channel. Up to 48 MS/s on gateware v50+. `send` (gateware v55+) runs one transaction right after the capture arms: `{"bus":"i2c","addr":118,"write_hex":"d0","read":1}` (the `i2c_open` session, else one from the wiring), `{"bus":"spi","tx_hex":"9f00"}` (SPI pins from the wiring) or `{"bus":"gpio","la":6,"level":0}` (a GPIO output); without `trigger_la` it triggers on SDA or CS falling or the pin's edge, and the result's `send` has the reply. | `samples=4096`, `sample_rate_hz`, `stop_dac_after`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout=10`, `trigger_pre_samples=0`, `send` | -| `capture_correlated` | ADC and LA from one hardware trigger, on one timebase. | `adc_samples=4096`, `adc_sample_rate_hz`, `la_samples=4096`, `la_sample_rate_hz`, `stop_dac_after`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout=10`, `source` | +| `capture_adc` | Capture the ADC: calibrated statistics, dominant frequency and a min/max envelope; `clipped_samples` counts samples past the range's full scale. `oversample` converts at 400 kS/s and averages down to `sample_rate_hz` for lower noise, about 5 s at most. | `samples=4096`, `sample_rate_hz`, `source`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `range`, `oversample` | +| `capture_la` | Capture all 14 LA channels: levels, edge count, first edge and frequency per channel. Up to 48 MS/s on gateware v50+. `send` (gateware v55+) runs one transaction right after the capture arms: `{"bus":"i2c","addr":118,"write_hex":"d0","read":1}` (the `i2c_open` session, else one from the wiring), `{"bus":"spi","tx_hex":"9f00"}` (SPI pins from the wiring) or `{"bus":"gpio","la":6,"level":0}` (a GPIO output); without `trigger_la` it triggers on SDA or CS falling or the pin's edge, and the result's `send` has the reply. | `samples=4096`, `sample_rate_hz`, `stop_dac_after_s`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `trigger_pre_samples=0`, `send` | +| `capture_correlated` | ADC and LA from one hardware trigger, on one timebase. | `adc_samples=4096`, `adc_sample_rate_hz`, `la_samples=4096`, `la_sample_rate_hz`, `stop_dac_after_s`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `source` | | `decode_la` | Decode I2C, UART or SPI from the last LA capture (or a new one). | **`protocol`**, `sda`, `scl`, `rx`, `baud`, `sclk`, `mosi`, `miso`, `cs`, `mode=0`, `capture=last`, `samples=16384`, `sample_rate_hz=1000000`, `max_items=200` | | `la_timing` | Edge timestamps, pulse widths, frequency, duty cycle and channel-to-channel delay from the last capture. | **`la`**, `edge=rising`, `to_la`, `to_edge=rising`, `after=0`, `max_edges=100` | @@ -351,11 +351,10 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | Tool | Purpose | Parameters | | --- | --- | --- | -| `generate` | Drive a sine, square or sawtooth on a DAC output (volts, or amps on `current_out`). | **`waveform`**, **`freq_hz`**, **`amplitude`**, `offset`, `dac_path=3v3`, `duration`, `sample_rate_hz`, `on_capture=false`, `route=true` | +| `generate` | Drive a sine, square or sawtooth on a DAC output (volts, or amps on `current_out`). | **`waveform`**, **`freq_hz`**, **`amplitude`**, `offset`, `dac_path=3v3`, `duration_s`, `sample_rate_hz`, `on_capture=false`, `route=true` | | `dac_stop` | Stop any DAC output: generator, replay or control loop. | none | -| `replay` | Loop your own samples, or the last ADC capture, out of the DAC. | `volts`, `from_last_capture=false`, `dac_path=3v3`, `mapping=faithful`, `sample_rate_hz`, `fault`, `on_capture=false`, `route=true`, `switch_image=true` | +| `replay` | Loop your own samples, the last ADC capture, or a cloud-library waveform out of the DAC. | `volts`, `from_last_capture=false`, `waveform_id`, `dac_path=3v3`, `mapping=faithful`, `sample_rate_hz`, `window_start=0`, `window_len=0`, `target_samples=0` (with `waveform_id`), `fault`, `on_capture=false`, `route=true`, `switch_image=true` | | `list_waveforms` | The organization's cloud waveform library. | none | -| `replay_waveform` | Loop a cloud-library waveform out of the DAC. | **`waveform_id`**, `dac_path`, `mapping=faithful`, `sample_rate_hz`, `window_start=0`, `window_len=0`, `target_samples=0`, `fault`, `on_capture=false`, `switch_image=true` | | `save_capture_as_recording` | Save the last ADC capture to the cloud waveform library. | **`name`**, `full_scale_v` | ### Control loop @@ -373,7 +372,7 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | --- | --- | --- | | `can_open` | Bring up the pod's CAN interface (normal, loopback or listen-only): classic CAN, or CAN FD with `data_bitrate` (firmware 3.10.2+, up to 8 Mbit/s, 64-byte frames). | `bitrate=500000`, `mode=normal`, `term=false`, `data_bitrate` | | `can_write` | Queue one CAN frame: up to 8 bytes, or 64 on a CAN FD bus (FD with bit-rate switching unless `fd=false` / `brs=false`). | **`can_id`**, `data`, `ext=false`, `rtr=false`, `fd`, `brs` | -| `can_read` | Read received frames, or wait for one id. | `timeout=0`, `can_id`, `max_frames=32` | +| `can_read` | Read received frames, or wait for one id. | `timeout_s=0`, `can_id`, `max_frames=32` | | `can_respond` | Answer a CAN id from the pod firmware (ECU simulation), or clear all rules. | `match_id`, `reply_id`, `reply_data`, `match_ext=false`, `reply_ext=false`, `reply_fd`, `reply_brs`, `clear=false` | | `can_status` | Link state: mode, bitrate, error counters, bus-off. | none | | `can_close` | Clear responder rules, stop CAN and switch the 120 Ω termination off. | none | @@ -382,7 +381,7 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | Tool | Purpose | Parameters | | --- | --- | --- | -| `la_step` | Step pulses for step/dir motor drivers: `delay` is half the step period (4 us to 65.535 ms), `steps` up to 65535. | **`la`**, **`steps`**, **`delay`**, `dir_la`, `direction=0` | +| `la_step` | Step pulses for step/dir motor drivers: `delay_s` is half the step period (4 us to 65.535 ms), `steps` up to 65535. | **`la`**, **`steps`**, **`delay_s`**, `dir_la`, `direction=0` | | `command` | Raw firmware JSON command, for anything no tool covers. | **`request`** | ### AI Vision board @@ -523,8 +522,8 @@ capture tools' summaries, `la_timing` and `decode_la` instead. - **Sessions.** `uart_open` buffers the DUT's console in the background (open it before `power_on`, then `uart_read` / `uart_write`); `can_open` keeps a CAN bus open across calls. - **Gateware images.** The pod's FPGA runs either the `loop` image (`control_loop`) or the - `deep_replay` image (replays longer than 2048 samples). `control_loop`, `replay` and - `replay_waveform` switch automatically (~3 s) and report it as `switched_image`; + `deep_replay` image (replays longer than 2048 samples). `control_loop` and `replay` + switch automatically (~3 s) and report it as `switched_image`; `switch_image: false` fails instead. A switch resets the FPGA — a running DAC output, UART session or sensor emulation stops — and the server instructions tell the agent to start those after it. `fpga_image` switches explicitly. I2C, SPI and UART sensors run on a third, emulation image that diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index fca1f19..455490e 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -23,13 +23,13 @@ Typical flows: - Flash and boot: flash(file) then power_cycle_and_capture(until_regex) — with a wiring profile that is all; otherwise pass swclk, swdio, target, nreset and rx, tx. - SPI flash (a 25-series chip on four LA pins, wiring spi_sclk/spi_mosi/spi_miso/spi_cs): spi_flash_info to see it answers, then spi_flash_program(file, addr); hold_reset=true keeps the DUT off the bus. spi_transfer talks to any other SPI device. -- I2C master (gateware v55+): set_pull([sda, scl], pull="up"), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions, so this is on by default. +- I2C master (gateware v55+): set_pull(la=[sda, scl], pull="up"), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions, so this is on by default. - Interactive console: uart_open, power_on, uart_read(until_regex), uart_write, uart_close. -- Emulate sensors (I2C, SPI, UART, analog; firmware with the 'sensors' capability): the pod plays a sensor from a definition. sensor_library lists ready ones (bme280, bmp280, sht4x, mpu6050, gps_nmea, ...) and sensor_show gives one's YAML and params. For I2C, set_pull([sda, scl], pull="up") on LA1-LA6 (LA7/LA8 pull down only) first. sensor_start(definition=, pins={sda, scl} | {tx} | ...), then sensor_set(instance, values) changes readings, sensor_stimulus_load + sensor_stimulus_start play values over time, sensor_fault injects a fault, sensor_status shows bus activity, sensor_capture waits for the DUT's next transaction on an I2C sensor's bus and decodes it, sensor_stop ends it. A part the library lacks: read sensor_format, write a definition from the datasheet, check it with sensor_validate, then sensor_start it. A GPS module is gps_nmea on pins={tx: }. +- Emulate sensors (I2C, SPI, UART, analog; firmware with the 'sensors' capability): the pod plays a sensor from a definition. sensor_library lists ready ones (bme280, bmp280, sht4x, mpu6050, gps_nmea, ...) and sensor_show gives one's YAML and params. For I2C, set_pull(la=[sda, scl], pull="up") on LA1-LA6 (LA7/LA8 pull down only) first. sensor_start(definition=, pins={sda, scl} | {tx} | ...), then sensor_set(instance, values) changes readings, sensor_stimulus_load + sensor_stimulus_start play values over time, sensor_fault injects a fault, sensor_status shows bus activity, sensor_capture waits for the DUT's next transaction on an I2C sensor's bus and decodes it, sensor_stop ends it. A part the library lacks: read sensor_format, write a definition from the datasheet, check it with sensor_validate, then sensor_start it. A GPS module is gps_nmea on pins={tx: }. - Analog: dac_output (DC), generate (sine/square/sawtooth) and replay drive the DAC and route its path; adc_read gives one calibrated value, capture_adc a waveform summary; dac_stop ends any DAC output. - 4-20 mA input: adc_read(source='current_in') reads terminal J8 and returns current in amps (0.004 to 0.020 for a live loop) next to the voltage across the sense resistor (249 ohm; from analog module v3r5 100 ohm behind a 30 mA limiter, read in the low range by default, so a reading stuck near 28.5 to 31.5 mA is the limiter). calibration shows whether the pod has calibrated its ADC offset there. If not, analog readings can be off by up to about 50 mV: ask the user to disconnect J8, then calibrate (once per pod, stored on the pod; it corrects every ADC source). -- 4-20 mA output: current_out(current) holds a loop current on terminal J9, in amps (0.012 is 12 mA), and returns the current actually held and the range. It needs an external floating loop supply on J9 and cannot go below about 4 mA or above about 20 mA. It shares the DAC with the voltage outputs and switches them off; dac_stop does not return the loop to 4 mA, current_out(0.004) does. The loop must float: nothing in it may touch pod ground, also not through a target that shares a ground with the pod (SWD, UART). Ask the user how J9 is wired first, and never suggest wiring J9 straight into J8. generate, replay and replay_waveform take dac_path='current_out' to play a waveform as a current (levels in amps); capture_adc(source='current_in') summarises the loop current in amps. -- Gateware images: the FPGA runs either the 'loop' image (control_loop) or the 'deep_replay' image (replays longer than 2048 samples). control_loop, replay and replay_waveform switch automatically (~3 s; switched_image in the result says so). A switch resets the FPGA and stops any DAC output, UART session or sensor emulation, so start those after it. fpga_image switches explicitly. I2C/SPI/UART sensors run on a third, emulation image that sensor_start loads by itself (control_loop and deep replays are unavailable while it runs). +- 4-20 mA output: current_out(current) holds a loop current on terminal J9, in amps (0.012 is 12 mA), and returns the current actually held and the range. It needs an external floating loop supply on J9 and cannot go below about 4 mA or above about 20 mA. It shares the DAC with the voltage outputs and switches them off; dac_stop does not return the loop to 4 mA, current_out(0.004) does. The loop must float: nothing in it may touch pod ground, also not through a target that shares a ground with the pod (SWD, UART). Ask the user how J9 is wired first, and never suggest wiring J9 straight into J8. generate and replay take dac_path='current_out' to play a waveform as a current (levels in amps); capture_adc(source='current_in') summarises the loop current in amps. +- Gateware images: the FPGA runs either the 'loop' image (control_loop) or the 'deep_replay' image (replays longer than 2048 samples). control_loop and replay switch automatically (~3 s; switched_image in the result says so). A switch resets the FPGA and stops any DAC output, UART session or sensor emulation, so start those after it. fpga_image switches explicitly. I2C/SPI/UART sensors run on a third, emulation image that sensor_start loads by itself (control_loop and deep replays are unavailable while it runs). - Logic: capture_la, then decode_la (i2c/uart/spi) re-decodes that capture without re-capturing, and la_timing measures edge times, pulse widths, frequency and the delay between two channels (e.g. trigger pin to result pin). - Triggers: capture_adc, capture_la and capture_correlated take trigger_la (+ trigger_edge rising/falling/high/low, trigger_timeout seconds) to start on an event rather than immediately, so t = 0 is that edge. Without the trigger firing the tool fails with "TriggerTimeout: ...". - Power profiles: measure_power(duration) reports the DUT's average/minimum/peak current, voltage, energy and charge over a window, with an optional trace (points). To profile across other tool calls, bracket them with power_profile_start and power_profile_stop. @@ -63,7 +63,7 @@ ALARM (DUT output) LA5 signal "ALARM" Target power internal 5 V (efuse 1) efuse=1 (external: efuse=2) -Pull resistors: set_pull(las, pull="up"|"down"|"off"); the pod picks the value. Today's boards +Pull resistors: set_pull(la=[...], pull="up"|"down"|"off"); the pod picks the value. Today's boards (pull_status shows each channel's supported directions; they pull to the LA voltage, 1.8 V or 3.3 V): LA1, LA2 4.7k up LA3, LA4 2.2k up LA5, LA6 10k up LA7, LA8 10k down only LA9-LA14 none diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py index 1b944e8..94c60b4 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py @@ -989,6 +989,6 @@ class LogLevelResult(BaseModel): class UsbNetworkResult(BaseModel): - """The pod's USB network setting (firmware 3.9.0+).""" - setting: str = Field(description='"on" or "off": whether the pod\'s USB port is also a network adapter.') + """The pod's USB network setting.""" + enabled: bool = Field(description="Whether the pod's USB port is also a network adapter.") note: str = Field("", description="What happens next, after a change.") diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index b981635..bc2e706 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -484,7 +484,7 @@ async def connect( la_voltage: Annotated[Optional[Literal[1.8, 3.3, 5.0]], Field(description=( "Select the LA I/O-bank voltage right after connecting (the DUT's I/O voltage; 5.0 needs the " "digital board v3r4)."))] = None, - lease_wait: Annotated[float, Field(ge=0, le=3600, description=( + lease_wait_s: Annotated[float, Field(ge=0, le=3600, description=( "Seconds to wait when someone else holds the pod's lease (the cloud device's, or the " "pod's own on the LAN and USB network)."))] = 30.0, wiring_profile: Annotated[Optional[str], Field(description=( @@ -498,7 +498,7 @@ 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_s, wiring_profile=wiring_profile) try: return _status() @@ -531,7 +531,7 @@ def _pin21(state: Any) -> Optional[m.Pin21Result]: @mcp.tool(annotations=_ann("Set LA I/O voltage", idempotent=True)) -async def set_la_voltage(voltage: Annotated[Optional[Literal[1.8, 3.3, 5.0]], Field(description=( +async def set_la_voltage(la_voltage: Annotated[Optional[Literal[1.8, 3.3, 5.0]], Field(description=( "The DUT's I/O voltage. 5.0 needs a pod with the digital board v3r4 (status capabilities " "vref_out). Omit it to read the current voltage and pin 21 without changing anything."))] = None, ) -> m.LaVoltageResult: @@ -547,10 +547,10 @@ async def set_la_voltage(voltage: Annotated[Optional[Literal[1.8, 3.3, 5.0]], Fi v3r4 the result has pin21; when its state is high, tell the user a DUT signal is above the I/O voltage (select 5.0 or remove the signal). """ - if voltage is None: + if la_voltage is None: state = await _call(lambda: SESSION.require().get_la_voltage()) else: - state = await _call(lambda: SESSION.require().set_la_voltage(voltage)) + state = await _call(lambda: SESSION.require().set_la_voltage(la_voltage)) return m.LaVoltageResult(voltage=state.voltage, readback=state.readback, pin21=_pin21(state)) @@ -752,7 +752,7 @@ def _switch_power(efuse: Optional[int], on: bool, delay: Optional[float], @mcp.tool(annotations=_ann("Power target on", destructive=True, idempotent=True)) async def power_on( efuse: WiredEfuse = None, - delay: Annotated[Optional[float], Field(description=( + delay_s: 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); " @@ -763,21 +763,21 @@ async def power_on( 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)) + return await _call(lambda: _switch_power(efuse, True, delay_s, wiring_profile)) @mcp.tool(annotations=_ann("Power target off", destructive=True, idempotent=True)) async def power_off( efuse: WiredEfuse = None, - delay: Annotated[Optional[float], Field(description="Seconds: schedule the power-off pod-side.")] = None, + delay_s: Annotated[Optional[float], Field(description="Seconds: schedule the power-off pod-side.")] = None, ) -> m.PowerResult: """Switch the target's power rail off. The result says which rail was used.""" - return await _call(lambda: _switch_power(efuse, False, delay)) + return await _call(lambda: _switch_power(efuse, False, delay_s)) @mcp.tool(annotations=_ann("Profile the target's power")) async def measure_power( - duration: Annotated[float, Field(gt=0, le=600, description="Seconds to sample (blocking).")], + duration_s: Annotated[float, Field(gt=0, le=600, description="Seconds to sample (blocking).")], efuse: WiredEfuse = None, rate_hz: Annotated[float, Field(ge=100, le=500, description=( "Samples per second. Accurate to ~200 Hz; above that the pod delivers what its sampling " @@ -794,7 +794,7 @@ async def measure_power( calls, bracket them with power_profile_start / power_profile_stop. """ return await _call_reporting(ctx, "profiling power", lambda: power_summary( - SESSION.require().measure_power(duration, efuse=efuse, rate_hz=rate_hz, + SESSION.require().measure_power(duration_s, efuse=efuse, rate_hz=rate_hz, keep_samples=points), points)) @@ -803,7 +803,7 @@ async def power_profile_start( efuse: WiredEfuse = None, rate_hz: Annotated[float, Field(ge=100, le=500, description=( "Samples per second; accurate to ~200 Hz, flattening near 365 Hz above that."))] = 500.0, - max_duration: Annotated[float, Field(gt=0, le=600, description=( + max_duration_s: Annotated[float, Field(gt=0, le=600, description=( "Seconds after which the pod stops sampling by itself (the result is then truncated)."))] = 60.0, ) -> m.PowerProfileStartResult: """Start sampling the target-power rail in the background, then run the steps you want to @@ -812,8 +812,8 @@ def op() -> m.PowerProfileStartResult: pod = SESSION.require() rail = pod.wiring.efuse if efuse is None else efuse SESSION.power_profile = pod.power_profile(efuse=rail, rate_hz=rate_hz, - max_duration=max_duration).start() - return m.PowerProfileStartResult(efuse=rail, rate_hz=rate_hz, max_duration=max_duration) + max_duration=max_duration_s).start() + return m.PowerProfileStartResult(efuse=rail, rate_hz=rate_hz, max_duration=max_duration_s) return await _call(op) @@ -859,13 +859,13 @@ def rail(n: int) -> m.RailResult: async def reset_target( action: Annotated[Literal["pulse", "hold", "release", "status"], Field(description=( "pulse = reset once; hold = keep the target in reset; release = let it run; status = read only."))] = "pulse", - pulse: Annotated[float, Field(gt=0, le=1, description="Pulse length in seconds (at most 1).")] = 0.1, + pulse_s: Annotated[float, Field(gt=0, le=1, description="Pulse length in seconds (at most 1).")] = 0.1, ) -> m.ResetResult: """Drive the DUT's reset line from the pod's reset pin (rev3 pods, DUT header J1 pin 22).""" def op() -> m.ResetResult: pod = SESSION.require() if action == "pulse": - state = pod.reset_target(pulse=pulse) + state = pod.reset_target(pulse=pulse_s) elif action == "status": state = pod.reset_state() else: @@ -1006,7 +1006,7 @@ async def i2c_open( scl: Annotated[Optional[LaRef], Field(description="SCL channel; omit for the profile's i2c_scl.")] = None, hz: Annotated[int, Field(ge=10_000, le=1_000_000, description="SCL rate.")] = 100_000, pullups: Annotated[Literal["pod", "external"], Field(description=( - "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today; at 1.8 V firmware newer than 3.10.12); " + "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today); " "external: the board has its own."))] = "pod", ) -> m.I2cSessionResult: """Make the pod an I2C master on two LA pins (gateware v55+), replacing any open session. @@ -1091,7 +1091,7 @@ async def flash( connect_under_reset: Optional[bool] = None, extra_configs: Optional[List[str]] = None, extra_args: Optional[List[str]] = None, - timeout: Annotated[float, Field(gt=0, le=3600)] = 300.0, + timeout_s: Annotated[float, Field(gt=0, le=3600)] = 300.0, connect_attempts: Annotated[int, Field(ge=1, le=20)] = 5, build: Annotated[str, Field(description=( "Flash a build uploaded to embeddedci.com instead of a file: its build id (the upload's " @@ -1162,7 +1162,7 @@ def op() -> m.FlashResult: target=target or pod.wiring.swd_target, file=file, load_address=load_address, target_power=target_power, verify=verify, reset=reset, connect_under_reset=connect_under_reset, extra_configs=tuple(extra_configs or ()), - extra_args=tuple(extra_args or ()), timeout=timeout, + extra_args=tuple(extra_args or ()), timeout=timeout_s, connect_attempts=connect_attempts, check=False, **from_build, ) @@ -1263,7 +1263,7 @@ def _uart_line(pod: Any, method: str, half_duplex: bool, entry: Optional[UartEnt @mcp.tool(annotations=_ann("Capture UART output")) async def capture_uart( - duration: Annotated[float, Field(gt=0, le=600, description="Capture window in seconds.")], + duration_s: Annotated[float, Field(gt=0, le=600, description="Capture window in seconds.")], rx: UartRx = None, tx: UartTx = None, baud: WiredBaud = None, @@ -1288,7 +1288,7 @@ async def capture_uart( def op() -> m.UartCaptureResult: pod = SESSION.require() - return _uart_result(pod.capture_uart(rx=rx, tx=tx, baud=baud, duration=duration, until=pattern, + return _uart_result(pod.capture_uart(rx=rx, tx=tx, baud=baud, duration=duration_s, until=pattern, **_uart_frame(pod, "capture_uart", parity, stop_bits), **_uart_line(pod, "capture_uart", half_duplex, entry), **_uart_de(pod, "capture_uart", de, de_active_low))) @@ -1301,11 +1301,11 @@ async def power_cycle_and_capture( rx: UartRx = None, tx: UartTx = None, efuse: WiredEfuse = None, - delay: Annotated[float, Field(ge=0, le=60, description="Seconds into the capture the power comes back.")] = 1.0, - duration: Annotated[float, Field(gt=0, le=600, description="Capture window in seconds; must exceed delay.")] = 4.0, + delay_s: Annotated[float, Field(ge=0, le=60, description="Seconds into the capture the power comes back.")] = 1.0, + duration_s: Annotated[float, Field(gt=0, le=600, description="Capture window in seconds; must exceed delay_s.")] = 4.0, baud: WiredBaud = None, until_regex: Regex = None, - off_settle: Annotated[float, Field(ge=0, le=10)] = 0.3, + off_settle_s: Annotated[float, Field(ge=0, le=10)] = 0.3, parity: UartParity = None, stop_bits: UartStopBits = None, ctx: Context = None, # type: ignore[assignment] @@ -1320,8 +1320,8 @@ async def power_cycle_and_capture( def op() -> m.UartCaptureResult: pod = SESSION.require() return _uart_result(pod.power_cycle_and_capture( - rx=rx, tx=tx, efuse=efuse, delay=delay, duration=duration, baud=baud, until=pattern, - off_settle=off_settle, **_uart_frame(pod, "power_cycle_and_capture", parity, stop_bits))) + rx=rx, tx=tx, efuse=efuse, delay=delay_s, duration=duration_s, baud=baud, until=pattern, + off_settle=off_settle_s, **_uart_frame(pod, "power_cycle_and_capture", parity, stop_bits))) return await _call_reporting(ctx, "power-cycling", op) @@ -1388,7 +1388,7 @@ def op() -> m.UartWriteResult: @mcp.tool(annotations=_ann("Read the DUT console", read_only=True)) async def uart_read( until_regex: Regex = None, - timeout: Annotated[float, Field(ge=0, le=600, description=( + timeout_s: Annotated[float, Field(ge=0, le=600, description=( "Seconds to wait for until_regex (or, without one, for any new output)."))] = 2.0, ) -> m.UartReadResult: """Return the UART output received since the previous uart_read, optionally waiting for a match.""" @@ -1398,11 +1398,11 @@ def op() -> m.UartReadResult: uart = SESSION.require_uart() matched: Optional[bool] = None if pattern is not None: - through_match = uart.read_until(pattern, timeout=timeout) # searches unread text + through_match = uart.read_until(pattern, timeout=timeout_s) # searches unread text matched = through_match is not None new = (through_match or "") + uart.read() else: - new = uart.read(timeout=timeout) + new = uart.read(timeout=timeout_s) return m.UartReadResult(text=clip(new, MAX_TEXT), matched=matched, closed=uart.closed, overflowed=uart.overflowed, truncated=len(new) > MAX_TEXT) @@ -1540,7 +1540,7 @@ async def sensor_start( ) -> m.SensorStarted: """Make the pod play a sensor for the DUT: upload the definition (library name or your own YAML/JSON) and start it on pins. - Set the LA voltage first, and the pull-ups for I2C (set_pull([sda, scl], pull="up"), LA1-LA6). + Set the LA voltage first, and the pull-ups for I2C (set_pull(la=[sda, scl], pull="up"), LA1-LA6). Starting an instance name that runs replaces it. Up to 4 I2C sensors (several may share one bus at different addresses), 1 SPI, 1 UART and 2 analog sensors (one per output) run at once. I2C/SPI/UART sensors load the pod's emulation FPGA image if another runs (image_loaded in the @@ -1672,72 +1672,42 @@ def _pull(state: Any) -> m.PullChannel: held=getattr(state, "held", None)) -def _sdk_pulls_by_direction(pod: Any) -> bool: - """The SDK takes set_pull(la, "up" | "down" | "off") (embeddedci 3.0.3+).""" - return "pull" in inspect.signature(type(pod).set_pull).parameters - - -def _set_pull_old_sdk(pod: Any, la: int, want: Any) -> Any: - """set_pull on embeddedci before 3.0.3, which only knows on/off: a direction is checked here, - so "up" never engages LA7's pull-down.""" - from embeddedci.benchpod.constants import PULLDOWN_CHANNELS, PULLUP_CHANNELS - - if want in ("up", "down"): - ok = PULLUP_CHANNELS if want == "up" else PULLDOWN_CHANNELS - if la not in ok: - raise ValueError(f"LA{la} can't pull {want} on this board; upgrade embeddedci for the full " - "message (pull_status shows each channel's direction)") - want = True - elif want == "off": - want = False - return pod.set_pull(la, bool(want)) - - @mcp.tool(annotations=_ann("Set pull resistors", idempotent=True)) async def set_pull( - las: Annotated[List[PullPin], Field(min_length=1, max_length=14, description="LA channels (1-14).")], - pull: Annotated[Optional[Literal["up", "down", "off"]], Field(description=( + la: Annotated[List[PullPin], Field(min_length=1, max_length=14, description="LA channels (1-14).")], + pull: Annotated[Literal["up", "down", "off"], Field(description=( "The direction: up, down or off. The pod picks the resistor from the pin's function (ohms and " "strength in the result). A channel pulls only the ways its resistor allows (pull_status: " "supported): on the digital board v3r4 every channel pulls up or down; on older boards LA1-LA6 " - "pull up, LA7/LA8 down, LA9-LA14 have none, and the pod refuses the rest (BP0024, BP0023)."))] = None, - enabled: Annotated[Optional[bool], Field(description=( - "Older form, use pull: true engages each channel's own direction, false is off."))] = None, + "pull up, LA7/LA8 down, LA9-LA14 have none, and the pod refuses the rest (BP0024, BP0023)."))], ) -> m.PullStatusResult: """Pull LA channels up or down, or switch their pull resistor off. For an I2C bus pull SDA and - SCL up. The pull-ups pull to the LA voltage, at 1.8 V too on firmware newer than 3.10.12 (older - firmware refuses them with the LA bank at 1.8 V).""" - if pull is None and enabled is None: - raise ValueError('set_pull needs pull: "up", "down" or "off"') - want: Any = pull if pull is not None else bool(enabled) - + SCL up. The pull-ups pull to the LA voltage (1.8 V or 3.3 V).""" def op() -> m.PullStatusResult: pod = SESSION.require() - if _sdk_pulls_by_direction(pod): - return m.PullStatusResult(channels=[_pull(pod.set_pull(la, want)) for la in las]) - return m.PullStatusResult(channels=[_pull(_set_pull_old_sdk(pod, la, want)) for la in las]) + return m.PullStatusResult(channels=[_pull(pod.set_pull(ch, pull)) for ch in la]) return await _call(op) @mcp.tool(annotations=_ann("USB network setting", destructive=True)) async def usb_network( - set: Annotated[Optional[Literal["off"]], Field(description=( - 'Omit to read the setting. "off" turns the pod\'s USB network adapter off (only over the ' + enabled: Annotated[Optional[Literal[False]], Field(description=( + "Omit to read the setting. false turns the pod's USB network adapter off (only over the " "pod's USB network link: connection 'usb'); the pod then re-enumerates as its USB console " "only and this connection ends. Turning it back on needs the USB console: the user runs " "`benchpod usb-network on`."))] = None, ) -> m.UsbNetworkResult: - """Read the pod's USB network setting (firmware 3.9.0+), or turn the adapter off. Only the device - changes it: Ethernet, Wi-Fi and the cloud may only read it.""" + """Read the pod's USB network setting, or turn the adapter off. Only the device changes it: + Ethernet, Wi-Fi and the cloud may only read it.""" def op() -> m.UsbNetworkResult: pod = SESSION.require() - on = pod.usb_network(None if set is None else False) + on = pod.usb_network(None if enabled is None else False) note = "" - if set == "off": + if enabled is False: note = ("The pod re-enumerates as its USB console only; this connection ends. Ask the user to run " "`benchpod usb-network on` over the USB console to turn it back on.") - return m.UsbNetworkResult(setting="on" if on else "off", note=note) + return m.UsbNetworkResult(enabled=on, note=note) return await _call(op) @@ -1794,8 +1764,7 @@ async def pull_status() -> m.PullStatusResult: (empty without a resistor) and its value.""" def op() -> m.PullStatusResult: pod = SESSION.require() - las = range(1, 15) if _sdk_pulls_by_direction(pod) else range(1, 9) - return m.PullStatusResult(channels=[_pull(pod.pull_state(la)) for la in las]) + return m.PullStatusResult(channels=[_pull(pod.pull_state(la)) for la in range(1, 15)]) return await _call(op) @@ -1933,10 +1902,10 @@ def op() -> m.GpioReadResult: async def gpio_wait( la: LaRef, level: GpioLevel = 1, - timeout: Annotated[float, Field(ge=0, le=600, description="Seconds to wait.")] = 5.0, + timeout_s: Annotated[float, Field(ge=0, le=600, description="Seconds to wait.")] = 5.0, ctx: Context = None, # type: ignore[assignment] ) -> m.GpioWaitResult: - """Wait until an LA channel or EXT pin reads `level` (reached=false when the timeout passes + """Wait until an LA channel or EXT pin reads `level` (reached=false when timeout_s passes first). Polled from this host, so it resolves to a few milliseconds plus the round trip — for precise @@ -1946,7 +1915,7 @@ def op() -> m.GpioWaitResult: pod = SESSION.require() ch = _gpio_ref(pod, la) start = time.monotonic() - reached = pod.wait_for_level(ch, level, timeout=timeout) + reached = pod.wait_for_level(ch, level, timeout=timeout_s) return m.GpioWaitResult(la=ch, level=level, reached=reached, waited=round(time.monotonic() - start, 4)) @@ -1956,7 +1925,7 @@ def op() -> m.GpioWaitResult: @mcp.tool(annotations=_ann("Pulse a GPIO channel", destructive=True)) async def gpio_pulse( la: LaRef, - width: Annotated[float, Field(ge=4e-6, le=0.065535, + width_s: Annotated[float, Field(ge=4e-6, le=0.065535, description="Seconds the pulse is high (and low between pulses), " "4 us to 65.535 ms.")], count: Annotated[int, Field(ge=1, le=65535, description="Number of pulses (at most 65535).")] = 1, @@ -1969,8 +1938,8 @@ async def gpio_pulse( def op() -> m.GpioPulseResult: pod = SESSION.require() ch = _gpio_ref(pod, la) # an EXT pin: la_step refuses it, saying why - pod.la_step(ch, steps=count, delay=width) - return m.GpioPulseResult(la=ch, count=count, width=width) + pod.la_step(ch, steps=count, delay=width_s) + return m.GpioPulseResult(la=ch, count=count, width=width_s) return await _call(op) @@ -2250,7 +2219,7 @@ async def capture_adc( points: EnvelopePoints = 200, trigger_la: TriggerLa = None, trigger_edge: Annotated[TriggerEdge, Field(description="What starts the capture on trigger_la.")] = "rising", - trigger_timeout: TriggerTimeoutS = 10.0, + trigger_timeout_s: TriggerTimeoutS = 10.0, range: AdcRangeArg = None, oversample: Annotated[bool, Field(description=( "Convert at 400 kS/s and average down to sample_rate_hz: lower noise and a smaller step at 0 V, " @@ -2272,7 +2241,7 @@ async def capture_adc( def op() -> m.AdcCaptureResult: cap = SESSION.require().capture_adc(samples, sample_rate_hz=sample_rate_hz, source=source, trigger=_trigger(trigger_la, trigger_edge), - trigger_timeout=trigger_timeout, range=range, + trigger_timeout=trigger_timeout_s, range=range, oversample=oversample) SESSION.last_adc = cap return adc_summary(cap, points) @@ -2284,11 +2253,11 @@ def op() -> m.AdcCaptureResult: async def capture_la( samples: Samples = 4096, sample_rate_hz: RateHz = None, - stop_dac_after: Annotated[Optional[float], Field(description=( + stop_dac_after_s: Annotated[Optional[float], Field(description=( "Seconds into the capture to cut a running DAC output (see the DUT react)."))] = None, trigger_la: TriggerLa = None, trigger_edge: Annotated[TriggerEdge, Field(description="What starts the capture on trigger_la.")] = "rising", - trigger_timeout: TriggerTimeoutS = 10.0, + trigger_timeout_s: TriggerTimeoutS = 10.0, trigger_pre_samples: Annotated[int, Field(ge=0, le=16_777_215, description=( "With trigger_la: also return up to this many samples from before the trigger " "(gateware v50+)."))] = 0, @@ -2309,13 +2278,13 @@ async def capture_la( def op() -> m.LaCaptureResult: pod = SESSION.require() if send is not None: - la = _capture_with_send(pod, send, samples, sample_rate_hz, stop_dac_after, trigger_la, - trigger_edge, trigger_timeout, trigger_pre_samples) + la = _capture_with_send(pod, send, samples, sample_rate_hz, stop_dac_after_s, trigger_la, + trigger_edge, trigger_timeout_s, trigger_pre_samples) else: la = pod.capture_la(samples, sample_rate_hz=sample_rate_hz, - stop_dac_after=stop_dac_after, + stop_dac_after=stop_dac_after_s, trigger=_trigger(trigger_la, trigger_edge, trigger_pre_samples), - trigger_timeout=trigger_timeout) + trigger_timeout=trigger_timeout_s) SESSION.last_la = la return la_summary(la) @@ -2356,11 +2325,11 @@ async def capture_correlated( adc_sample_rate_hz: RateHz = None, la_samples: Annotated[int, Field(ge=0, le=8_000_000)] = 4096, la_sample_rate_hz: RateHz = None, - stop_dac_after: Annotated[Optional[float], Field(description="Seconds into the capture to cut a running DAC.")] = None, + stop_dac_after_s: Annotated[Optional[float], Field(description="Seconds into the capture to cut a running DAC.")] = None, points: EnvelopePoints = 200, trigger_la: TriggerLa = None, trigger_edge: Annotated[TriggerEdge, Field(description="What starts both streams on trigger_la.")] = "rising", - trigger_timeout: TriggerTimeoutS = 10.0, + trigger_timeout_s: TriggerTimeoutS = 10.0, source: Annotated[Optional[AdcSource], Field(description=( "Route this ADC source first for the analog half; omit to keep routing. current_in captures " "the 4-20 mA input (J8) and the analog stats are then amps."))] = None, @@ -2374,8 +2343,8 @@ async def capture_correlated( def op() -> m.CorrelatedCaptureResult: cc = SESSION.require().capture_correlated( adc_samples=adc_samples, adc_sample_rate_hz=adc_sample_rate_hz, la_samples=la_samples, - la_sample_rate_hz=la_sample_rate_hz, stop_dac_after=stop_dac_after, - trigger=_trigger(trigger_la, trigger_edge), trigger_timeout=trigger_timeout, source=source) + la_sample_rate_hz=la_sample_rate_hz, stop_dac_after=stop_dac_after_s, + trigger=_trigger(trigger_la, trigger_edge), trigger_timeout=trigger_timeout_s, source=source) if adc_samples: SESSION.last_adc = cc.adc if la_samples: @@ -2504,7 +2473,7 @@ async def generate( dac_path: Annotated[Optional[DacPath], Field(description=( "DAC output. Omitted: 3v3, the lowest voltage output (with route false: the output last routed, " "cal1 = 5v). Pick the one the DUT pin tolerates: 5v and 12v can damage a 3.3 V pin."))] = None, - duration: Annotated[Optional[float], Field(description="Seconds; omit to run until dac_stop.")] = None, + duration_s: Annotated[Optional[float], Field(description="Seconds; omit to run until dac_stop.")] = None, sample_rate_hz: RateHz = None, on_capture: Annotated[bool, Field(description="Start on the next capture's hardware t0 (phase-locked).")] = False, route: Annotated[bool, Field(description=( @@ -2523,7 +2492,7 @@ async def generate( """ handle = await _call(lambda: SESSION.require().generate( waveform, freq_hz=freq_hz, amplitude=amplitude, offset=offset, **_dac_path_arg(dac_path, route), - duration=duration, sample_rate_hz=sample_rate_hz, on_capture=on_capture, route=route)) + duration=duration_s, sample_rate_hz=sample_rate_hz, on_capture=on_capture, route=route)) return m.GenerateResult(waveform=waveform, freq_hz=freq_hz, dac_path=handle.dac_path, cotrig=handle.cotrig) @@ -2557,26 +2526,42 @@ async def replay( volts: Annotated[Optional[List[float]], Field(description=( "Waveform in volts, one value per sample. On dac_path current_out the values are AMPS (0.004 to 0.020)."))] = None, from_last_capture: Annotated[bool, Field(description="Replay the last capture_adc instead of volts.")] = False, + waveform_id: Annotated[Optional[str], Field(description=( + "Instead of volts: a waveform from the cloud library (list_waveforms; needs server access)."))] = None, dac_path: Annotated[Optional[DacPath], Field(description=( "DAC output. Omitted: 3v3, the lowest voltage output (with route false: the output last routed, " - "cal1 = 5v). Pick the one the DUT pin tolerates: 5v and 12v can damage a 3.3 V pin."))] = None, + "cal1 = 5v; for waveform_id: the waveform's own, else 3v3). Pick the one the DUT pin " + "tolerates: 5v and 12v can damage a 3.3 V pin."))] = None, mapping: Annotated[ReplayMapping, Field(description="faithful = reproduce volts (clip); fit = auto-scale.")] = "faithful", sample_rate_hz: Annotated[Optional[float], Field(description="Replay rate; defaults to the capture's own rate.")] = None, + window_start: Annotated[int, Field(ge=0, description="waveform_id: first recording sample to replay.")] = 0, + window_len: Annotated[int, Field(ge=0, description="waveform_id: samples to replay; 0 = to the end.")] = 0, + target_samples: Annotated[int, Field(ge=0, description=( + "waveform_id: downsample a shallow replay to this many samples."))] = 0, fault: Optional[m.FaultSpec] = None, on_capture: bool = False, route: Annotated[bool, Field(description="Route dac_path first (false = keep the current analog path).")] = True, switch_image: SwitchImage = True, ctx: Context = None, # type: ignore[assignment] ) -> m.ReplayResult: - """Loop a waveform out of the DAC until dac_stop — agent-provided volts or the last ADC capture. - - More than 2048 samples need the deep_replay gateware image, switched to automatically. - dac_path current_out replays on the 4-20 mA output (J9) in amps. A last capture of current_in - replays as the same current; a capture of a voltage source there needs mapping fit. See - current_out for the wiring. After dac_stop, call current_out(0.004) to go back to 4 mA. + """Loop a waveform out of the DAC until dac_stop: agent-provided volts, the last ADC capture, + or a waveform from the cloud library (waveform_id). + + More than 2048 samples need the deep_replay gateware image, switched to automatically (a + library waveform with target_samples is downsampled instead). dac_path current_out replays on + the 4-20 mA output (J9) in amps. A last capture of current_in, or a library recording with unit + mA, replays as the same current; a voltage recording there needs mapping fit. See current_out + for the wiring. After dac_stop, call current_out(0.004) to go back to 4 mA. """ - if (volts is None) == (not from_last_capture): - raise ToolError("invalid argument: pass exactly one of volts or from_last_capture=true") + given = sum((volts is not None, from_last_capture, waveform_id is not None)) + if given != 1: + raise ToolError("invalid argument: pass exactly one of volts, from_last_capture=true or waveform_id") + if waveform_id is not None: + return await _call_reporting(ctx, "arming replay", lambda: _replay_result( + SESSION.require().replay_waveform( + waveform_id, dac_path=dac_path, mapping=mapping, sample_rate_hz=sample_rate_hz, + window_start=window_start, window_len=window_len, target_samples=target_samples, + fault=_fault(fault), on_capture=on_capture, switch_image=switch_image))) def op() -> m.ReplayResult: pod = SESSION.require() @@ -2737,35 +2722,6 @@ def op() -> m.CloudRunTrace: return await _call(_lookup(op), lock=False) -@mcp.tool(annotations=_ann("Replay a library waveform", destructive=True, cloud=True)) -async def replay_waveform( - waveform_id: str, - dac_path: Annotated[Optional[DacPath], Field(description="Output path; default the waveform's own, else 3v3.")] = None, - mapping: ReplayMapping = "faithful", - sample_rate_hz: RateHz = None, - window_start: Annotated[int, Field(ge=0, description="First recording sample to replay.")] = 0, - window_len: Annotated[int, Field(ge=0, description="Samples to replay; 0 = to the end.")] = 0, - target_samples: Annotated[int, Field(ge=0, description="Downsample a shallow replay to this many samples.")] = 0, - fault: Optional[m.FaultSpec] = None, - on_capture: bool = False, - switch_image: SwitchImage = True, - ctx: Context = None, # type: ignore[assignment] -) -> m.ReplayResult: - """Loop a cloud-library waveform out of the DAC until dac_stop (needs server access). - - A recording too long for a shallow replay switches the pod to the deep_replay gateware image - (unless target_samples asks for a downsampled replay). - dac_path current_out replays on the 4-20 mA output (J9). A recording with unit mA replays there - as the same current; a recording in V there, or a mA recording on a voltage output, needs - mapping fit. After dac_stop, call current_out(0.004) to go back to 4 mA. - """ - return await _call_reporting(ctx, "arming replay", lambda: _replay_result( - SESSION.require().replay_waveform( - waveform_id, dac_path=dac_path, mapping=mapping, sample_rate_hz=sample_rate_hz, - window_start=window_start, window_len=window_len, target_samples=target_samples, - fault=_fault(fault), on_capture=on_capture, switch_image=switch_image))) - - @mcp.tool(annotations=_ann("Save capture to the library", cloud=True)) async def save_capture_as_recording( name: Annotated[str, Field(min_length=1)], @@ -2856,7 +2812,7 @@ async def fpga_image( ) -> m.FpgaImageResult: """Reprogram the pod's FPGA with another stored gateware image (~2-3 s). - Rarely needed: control_loop, replay and replay_waveform switch automatically (also back from + Rarely needed: control_loop and replay switch automatically (also back from the emulation image once no I2C/SPI/UART sensor runs). The pod never switches back by itself, and refuses to leave the emulation image while I2C/SPI/UART sensors run (sensor_stop first). The switch resets the FPGA (any DAC output or UART session stops). @@ -2919,7 +2875,7 @@ async def can_write( @mcp.tool(annotations=_ann("Read CAN frames", read_only=True)) async def can_read( - timeout: Annotated[float, Field(ge=0, le=120, description=( + timeout_s: Annotated[float, Field(ge=0, le=120, description=( "With can_id: wait up to this long for it. Without: collect frames for this long (0 = what is buffered)."))] = 0.0, can_id: Optional[Annotated[int, Field(ge=0, le=0x1FFFFFFF)]] = None, max_frames: Annotated[int, Field(ge=1, le=1000)] = 32, @@ -2929,9 +2885,9 @@ def op() -> m.CanReadResult: SESSION.require() bus = SESSION.require_can() if can_id is not None: - f = bus.read_until(can_id, timeout=timeout) + f = bus.read_until(can_id, timeout=timeout_s) return m.CanReadResult(frames=[_frame(f)] if f else [], matched=f is not None) - frames = bus.collect(timeout) if timeout > 0 else bus.read(max_frames) + frames = bus.collect(timeout_s) if timeout_s > 0 else bus.read(max_frames) return m.CanReadResult(frames=[_frame(f) for f in frames[:max_frames]]) return await _call(op) @@ -2986,21 +2942,21 @@ async def can_close() -> m.CanOpenResult: async def la_step( la: LaPin, steps: Annotated[int, Field(ge=1, le=65535, description="Number of step pulses (at most 65535).")], - delay: Annotated[float, Field(ge=4e-6, le=0.065535, + delay_s: Annotated[float, Field(ge=4e-6, le=0.065535, description="HALF the step period in seconds: each pulse is high for " - "delay, then low for delay, so pulses are 2 x delay apart. " + "delay_s, then low for delay_s, so pulses are 2 x delay_s apart. " "4 us to 65.535 ms.")], dir_la: Optional[LaPin] = None, direction: Literal[0, 1] = 0, ) -> m.StepResult: """Emit step pulses on an LA channel (step/dir motor drivers); with dir_la, set direction first. - The step rate is 1 / (2 x delay). The FPGA runs the train by itself; this returns as soon as it + The step rate is 1 / (2 x delay_s). The FPGA runs the train by itself; this returns as soon as it starts. More than 65535 steps: send several trains (wait for the pod between them). """ - reply = await _call(lambda: SESSION.require().la_step(la, steps=steps, delay=delay, dir_la=dir_la, + reply = await _call(lambda: SESSION.require().la_step(la, steps=steps, delay=delay_s, dir_la=dir_la, direction=direction)) - return m.StepResult(la=la, steps=steps, delay=delay, status=str(reply.get("status", "started"))) + return m.StepResult(la=la, steps=steps, delay=delay_s, status=str(reply.get("status", "started"))) @mcp.tool(annotations=_ann("Raw firmware command", destructive=True)) diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py index 3519b6a..a59d253 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py @@ -10,7 +10,7 @@ from typing import Any, List, Optional, Sequence, Tuple from embeddedci.benchpod import Capture, LaCapture, PowerProfile, Trigger, Wiring -from embeddedci.benchpod.constants import PULL_OHMS, PULLDOWN_CHANNELS +from embeddedci.benchpod.constants import PULL_TABLE try: # embeddedci 3.0.3+: the board's pull table (directions per channel) from embeddedci.benchpod.constants import PULL_TABLE @@ -121,8 +121,8 @@ def _bias(la: int) -> Optional[str]: hw = PULL_TABLE.get(la) if hw: return f"{hw.ohms} {'/'.join(hw.dirs)}" - ohms = PULL_OHMS.get(la) - return None if not ohms else f"{ohms} {'down' if la in PULLDOWN_CHANNELS else 'up'}" + hw = PULL_TABLE.get(la) + return None if not hw else f"{hw.ohms} {hw.default}" def wiring_summary(wiring: Wiring, *, saved: bool = False) -> m.WiringResult: diff --git a/packages/embeddedci-mcp/tests/test_e2e_mcp.py b/packages/embeddedci-mcp/tests/test_e2e_mcp.py index 4e01cb8..787af07 100644 --- a/packages/embeddedci-mcp/tests/test_e2e_mcp.py +++ b/packages/embeddedci-mcp/tests/test_e2e_mcp.py @@ -203,7 +203,7 @@ def test_sensor_and_can(connected): if connected["capabilities"]["board"] == "stm32h563": call("can_open", mode="internal") call("can_write", can_id=0x321, data=[7, 8]) - frames = call("can_read", can_id=0x321, timeout=1.0) + frames = call("can_read", can_id=0x321, timeout_s=1.0) assert frames["matched"] and frames["frames"][0]["data"] == [7, 8] call("can_close") @@ -256,7 +256,7 @@ def test_firmware_refusals_are_tool_errors(connected): with pytest.raises(ToolError, match="FirmwareError"): call("reset_target") with pytest.raises(ToolError, match="FirmwareError"): - call("set_la_voltage", voltage=1.8) + call("set_la_voltage", la_voltage=1.8) def test_rev3_tools(connected): @@ -269,20 +269,20 @@ def test_rev3_tools(connected): caps = connected["capabilities"] assert caps["board_rev"] in ("v3", "v3r2", "v3r4") and caps["nrst_pin"] and caps["usb_cc"], caps try: - r = call("set_la_voltage", voltage=1.8) + r = call("set_la_voltage", la_voltage=1.8) assert (r["voltage"], r["readback"]) == (1.8, 1.8), r # pin 21 only on digital v3r4, where it follows the bank to 1.8 V assert (r.get("pin21") is None) == (not caps.get("vref_out")), r finally: - assert call("set_la_voltage", voltage=3.3)["readback"] == 3.3 + assert call("set_la_voltage", la_voltage=3.3)["readback"] == 3.3 try: assert call("reset_target", action="hold")["asserted"] is True assert call("reset_target", action="status")["asserted"] is True finally: assert call("reset_target", action="release")["asserted"] is False - assert call("reset_target", action="pulse", pulse=0.05)["asserted"] is False + assert call("reset_target", action="pulse", pulse_s=0.05)["asserted"] is False with pytest.raises(ToolError): - call("reset_target", pulse=5) # longer than the pod can hold + call("reset_target", pulse_s=5) # longer than the pod can hold cc = call("command", request={"cmd": "usb_cc"})["reply"] # the raw firmware reply assert cc["supported"] is True and cc["orientation"] in ("none", "cc1", "cc2"), cc @@ -313,16 +313,16 @@ def test_dut_flash_boot_and_console(connected, pytestconfig): target="target/stm32f4x.cfg", file=os.path.abspath(firmware), target_power=1) assert flash["ok"], flash try: - boot = call("power_cycle_and_capture", rx=rx, tx=tx, delay=0.5, duration=25, until_regex="APP_OK") + boot = call("power_cycle_and_capture", rx=rx, tx=tx, delay_s=0.5, duration_s=25, until_regex="APP_OK") assert boot["matched"], boot["text"][-1000:] call("power_off") call("uart_open", rx=rx, tx=tx) call("power_on") - assert call("uart_read", until_regex="APP_OK", timeout=25)["matched"] - call("uart_read", until_regex="> ", timeout=5) + assert call("uart_read", until_regex="APP_OK", timeout_s=25)["matched"] + call("uart_read", until_regex="> ", timeout_s=5) call("uart_write", text="help", line_ending="none") call("uart_write", text="\r", line_ending="none") - assert call("uart_read", until_regex="commands:", timeout=5)["matched"] + assert call("uart_read", until_regex="commands:", timeout_s=5)["matched"] call("uart_close") finally: call("power_off") diff --git a/packages/embeddedci-mcp/tests/test_expansion_tools.py b/packages/embeddedci-mcp/tests/test_expansion_tools.py index 38d1831..85bde17 100644 --- a/packages/embeddedci-mcp/tests/test_expansion_tools.py +++ b/packages/embeddedci-mcp/tests/test_expansion_tools.py @@ -26,7 +26,7 @@ def test_attach_drive_read_and_detach(connected): assert levels == [{"la": "EXT1", "level": 1}, {"la": 3, "level": 0}] everything = call("gpio_read")["levels"] assert len(everything) == 14 + 16 and everything[14] == {"la": "EXT1", "level": 1} - assert call("gpio_wait", la="EXT1", level=1, timeout=0.1)["reached"] is True + assert call("gpio_wait", la="EXT1", level=1, timeout_s=0.1)["reached"] is True assert call("gpio_release", la=["EXT1"])["released"] == ["EXT1"] assert call("expansion", detach=True)["attached"] is False assert connected.tca[6:8] == [0xFF, 0xFF] @@ -41,6 +41,6 @@ def test_refusals(connected): call("expansion", chip="tca9555", addr=0x21) call("expansion", chip="tca9555") with pytest.raises(ToolError, match="pulses are timed by the FPGA"): - call("gpio_pulse", la="EXT1", width=0.001) + call("gpio_pulse", la="EXT1", width_s=0.001) with pytest.raises(ToolError, match="not both"): call("expansion", chip="tca9555", detach=True) diff --git a/packages/embeddedci-mcp/tests/test_gpio_tools.py b/packages/embeddedci-mcp/tests/test_gpio_tools.py index 01250c9..bda0664 100644 --- a/packages/embeddedci-mcp/tests/test_gpio_tools.py +++ b/packages/embeddedci-mcp/tests/test_gpio_tools.py @@ -88,17 +88,17 @@ def test_gpio_release_frees_channels(connected): def test_gpio_wait_returns_as_soon_as_the_level_is_there(connected): connected.inputs = 1 << 8 # LA9 is already high - result = call("gpio_wait", la=9, level=1, timeout=1.0) + result = call("gpio_wait", la=9, level=1, timeout_s=1.0) assert result["reached"] is True and result["la"] == 9 and result["waited"] < 1.0 def test_gpio_wait_times_out_without_failing(connected): - result = call("gpio_wait", la=9, level=1, timeout=0.05) + result = call("gpio_wait", la=9, level=1, timeout_s=0.05) assert result["reached"] is False and result["waited"] >= 0.05 def test_gpio_pulse_runs_a_step_train(connected): - assert call("gpio_pulse", la=3, width=0.001, count=5) == {"la": 3, "count": 5, "width": 0.001} + assert call("gpio_pulse", la=3, width_s=0.001, count=5) == {"la": 3, "count": 5, "width": 0.001} assert connected.requests[-1] == {"cmd": "la_step", "la": 3, "steps": 5, "delay_us": 1000} @@ -122,7 +122,7 @@ def test_a_gpio_channel_blocks_the_uart_until_it_is_released(connected): def test_pull_conflict_reaches_the_agent(connected): - call("set_pull", las=[7], pull="down") + call("set_pull", la=[7], pull="down") with pytest.raises(ToolError, match="PullConflictError: .*BP0032: LA7 has its 10k pull-down on"): call("gpio_mode", la=[7], mode="open_drain") diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index e65a62c..7c92b8d 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -29,7 +29,7 @@ def command(req): def _pulse_error() -> str: with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) + call("gpio_pulse", la=3, width_s=0.001, count=5) return str(info.value) @@ -198,7 +198,7 @@ def command(req): connected.command = command with pytest.raises(ToolError) as info: - call("gpio_pulse", la=3, width=0.001, count=5) + call("gpio_pulse", la=3, width_s=0.001, count=5) msg = str(info.value) assert "ClientTooOldError: la_step: this BenchPod MCP server" in msg assert "needs client API 2 or newer, this server sent 1" in msg diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index 8858889..6bcfec9 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -33,7 +33,7 @@ "set_pull", "pull_status", "usb_network", "log_level", "lan_tls", "analog_path", "dac_output", "current_out", "adc_read", "adc_range", "calibration", "calibrate", "calibrate_dac", "calibrate_adc_gain", "capture_adc", "capture_la", "capture_correlated", "decode_la", "la_timing", - "generate", "dac_stop", "replay", "list_waveforms", "replay_waveform", + "generate", "dac_stop", "replay", "list_waveforms", "save_capture_as_recording", "control_loop", "loop_input", "loop_probe", "fpga_image", "can_open", "can_write", "can_read", "can_respond", "can_status", "can_close", @@ -87,7 +87,7 @@ def test_enums_reach_the_schema(): tools = {t.name: t for t in anyio.run(mcp.list_tools)} assert tools["analog_path"].inputSchema["properties"]["path"]["enum"][0] == "off" # optional since digital v3r4 (omitted = read); 5.0 is the v3r4 5 V mode - assert tools["set_la_voltage"].inputSchema["properties"]["voltage"]["anyOf"][0]["enum"] == [1.8, 3.3, 5.0] + assert tools["set_la_voltage"].inputSchema["properties"]["la_voltage"]["anyOf"][0]["enum"] == [1.8, 3.3, 5.0] # -- errors + connection --------------------------------------------------------------- @@ -286,7 +286,7 @@ def missing(timeout=None): def test_schema_rejects_bad_arguments(connected): with pytest.raises(ToolError): - call("set_la_voltage", voltage=5.0) + call("set_la_voltage", la_voltage=5.0) with pytest.raises(ToolError): call("power_on", efuse=3) @@ -305,7 +305,7 @@ 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_s=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") @@ -402,17 +402,17 @@ def fake_flash(**kwargs): # -- UART ------------------------------------------------------------------------------ def test_capture_uart(connected): - result = call("capture_uart", rx=5, tx=4, duration=1.0, until_regex="APP_OK") + result = call("capture_uart", rx=5, tx=4, duration_s=1.0, until_regex="APP_OK") assert result["matched"] is True and "boot" in result["text"] and result["truncated"] is False def test_bad_regex_is_a_tool_error(connected): with pytest.raises(ToolError, match="until_regex"): - call("capture_uart", rx=5, tx=4, duration=1.0, until_regex="(") + call("capture_uart", rx=5, tx=4, duration_s=1.0, until_regex="(") def test_power_cycle_and_capture(connected): - result = call("power_cycle_and_capture", rx=5, tx=4, delay=0.2, duration=1.0, off_settle=0) + result = call("power_cycle_and_capture", rx=5, tx=4, delay_s=0.2, duration_s=1.0, off_settle_s=0) assert "APP_OK" in result["text"] assert [c for c in connected.calls if c[0] == "target_power"] == [ ("target_power", 1, False, 0), ("target_power", 1, True, 200)] @@ -440,7 +440,7 @@ def test_uart_frame_format(connected): SESSION.require().refresh_capabilities() r = call("uart_open", rx=5, tx=4, baud=19200, parity="even") assert (r["parity"], r["stop_bits"], r["baud"]) == ("even", 1, 19200) - call("capture_uart", rx=5, tx=4, duration=0.2, stop_bits=2) + call("capture_uart", rx=5, tx=4, duration_s=0.2, stop_bits=2) assert connected.uart_frames[-2:] == [("even", 1), ("none", 2)] with pytest.raises(ToolError): call("uart_open", rx=5, tx=4, parity="mark") @@ -465,7 +465,7 @@ def test_uart_half_duplex_and_entry(connected): entry={"reset_ms": 5, "hold_ms": 3, "idle_ms": 2, "data_hex": "00"}) e = connected.uart_lines[-1][3] assert e.to_request() == {"reset_ms": 5, "tx_low": True, "hold_ms": 3, "idle_ms": 2, "hex": "00"} - call("capture_uart", rx=1, tx=2, duration=0.2, entry={}) + call("capture_uart", rx=1, tx=2, duration_s=0.2, entry={}) assert connected.uart_lines[-1][2] is False and connected.uart_lines[-1][3] is not None with pytest.raises(ToolError): call("uart_open", rx=3, half_duplex=True, entry={"data_hex": "0"}) @@ -487,7 +487,7 @@ def test_uart_de(connected): SESSION.require().refresh_capabilities() call("uart_open", rx=5, tx=4, de=9) assert connected.uart_des[-1] == (9, False) - call("capture_uart", rx=5, tx=4, duration=0.2, de=9, de_active_low=True) + call("capture_uart", rx=5, tx=4, duration_s=0.2, de=9, de_active_low=True) assert connected.uart_des[-1] == (9, True) call("uart_open", rx=5, tx=4) assert connected.uart_des[-1] == (None, False) @@ -527,7 +527,7 @@ def test_sensor_library_tools_need_no_pod(): def test_sensor_flow_from_a_library_name_and_inline_yaml(connected): - call("set_pull", las=[1, 2], enabled=True) + call("set_pull", la=[1, 2], pull="up") started = call("sensor_start", definition="bme280", instance="env", pins={"sda": 2, "scl": 1}, address="0x77", values={"temperature_c": 22.5}) assert started["instance"] == "env" and started["kind"] == "i2c" and started["name"] == "bme280" @@ -578,29 +578,23 @@ def test_sensor_stimulus_tools(connected): def test_pulls(connected): - res = call("set_pull", las=[7], enabled=True) # the older form still works + res = call("set_pull", la=[7], pull="down") assert res["channels"][0]["direction"] == "down" and res["channels"][0]["state"] == "down" - res = call("set_pull", las=[1, 2], pull="up") + res = call("set_pull", la=[1, 2], pull="up") assert [c["state"] for c in res["channels"]] == ["up", "up"] assert res["channels"][0]["supported"] == ["up"] and res["channels"][0]["ohms"] == "4.7k" - assert call("set_pull", las=[7], pull="off")["channels"][0]["state"] == "off" + assert call("set_pull", la=[7], pull="off")["channels"][0]["state"] == "off" status = call("pull_status") - new_sdk = "pull" in inspect.signature(BenchPod.set_pull).parameters - if not new_sdk: # embeddedci before 3.0.3 (the mcp-min-sdk job): LA1-LA8, checked here - assert [c["la"] for c in status["channels"]] == list(range(1, 9)) - with pytest.raises(ToolError, match="LA7 can't pull up"): - call("set_pull", las=[7], pull="up") - return assert [c["la"] for c in status["channels"]] == list(range(1, 15)) assert status["channels"][8] == {"la": 9, "state": "off", "supported": [], "enabled": False, "direction": None, "ohms": "", "available": True, "strength": None, "held": None} with pytest.raises(ToolError, match="BP0023"): - call("set_pull", las=[9], pull="up") + call("set_pull", la=[9], pull="up") with pytest.raises(ToolError, match="LA7 supports pull-down only on this board"): - call("set_pull", las=[7], pull="up") - with pytest.raises(ToolError, match="needs pull"): - call("set_pull", las=[1]) + call("set_pull", la=[7], pull="up") + with pytest.raises(ToolError, match="pull"): + call("set_pull", la=[1]) # -- analog + captures ----------------------------------------------------------------- @@ -833,7 +827,7 @@ def test_can_tools(connected): call("can_write", can_id=0x123, data=[1]) assert call("can_open", mode="internal")["open"] is True call("can_write", can_id=0x123, data=[0xDE, 0xAD]) - frames = call("can_read", can_id=0x123, timeout=0.5) + frames = call("can_read", can_id=0x123, timeout_s=0.5) assert frames["matched"] is True and frames["frames"][0]["data"] == [0xDE, 0xAD] assert frames["frames"][0]["id_hex"] == "0x123" assert call("can_respond", match_id=0x7DF, reply_id=0x7E8, reply_data=[0x50])["rules"] == 1 @@ -857,7 +851,7 @@ def test_can_fd_tools(connected): call("can_write", can_id=0x123, data=list(range(64)), brs=False) req = [r for r in connected.requests if r["cmd"] == "can_write"][-1] assert len(req["data"]) == 64 and req["brs"] is False and "fd" not in req - frames = call("can_read", can_id=0x123, timeout=0.5) + frames = call("can_read", can_id=0x123, timeout_s=0.5) assert frames["frames"][0]["fd"] is True and len(frames["frames"][0]["data"]) == 64 call("can_respond", match_id=0x7DF, reply_id=0x7E8, reply_data=list(range(12)), reply_fd=False) rr = [r for r in connected.requests if r["cmd"] == "can_respond"][-1] @@ -870,16 +864,16 @@ def test_can_fd_tools(connected): # -- stepper + escape hatch -------------------------------------------------------------- def test_la_step_and_command(connected): - assert call("la_step", la=3, steps=100, delay=0.001) == {"la": 3, "steps": 100, "delay": 0.001, + assert call("la_step", la=3, steps=100, delay_s=0.001) == {"la": 3, "steps": 100, "delay": 0.001, "status": "started"} assert connected.requests[-1]["delay_us"] == 1000 sent = len(connected.requests) with pytest.raises(ToolError): - call("la_step", la=3, steps=70000, delay=0.001) # the pod counts 16 bits + call("la_step", la=3, steps=70000, delay_s=0.001) # the pod counts 16 bits with pytest.raises(ToolError): - call("la_step", la=3, steps=10, delay=0.1) # half-period above 65.535 ms + call("la_step", la=3, steps=10, delay_s=0.1) # half-period above 65.535 ms with pytest.raises(ToolError): - call("gpio_pulse", la=3, width=0.001, count=70000) + call("gpio_pulse", la=3, width_s=0.001, count=70000) assert len(connected.requests) == sent assert call("command", request={"cmd": "adc_read", "source": "cal1"})["reply"]["source"] == "cal1" with pytest.raises(ToolError): @@ -907,9 +901,9 @@ def test_usb_network_reads_and_turns_off(fake_open, fake_transport, monkeypatch) pod = SESSION.require() seen = [] monkeypatch.setattr(pod, "usb_network", lambda on=None: seen.append(on) or (on is not False), raising=False) - assert call("usb_network")["setting"] == "on" - res = call("usb_network", set="off") - assert res["setting"] == "off" and "usb-network on" in res["note"] and seen == [None, False] + assert call("usb_network")["enabled"] is True + res = call("usb_network", enabled=False) + assert res["enabled"] is False and "usb-network on" in res["note"] and seen == [None, False] def test_log_level_reads_and_sets(fake_open, fake_transport, monkeypatch): diff --git a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py index 7ad82b0..21ba6c2 100644 --- a/packages/embeddedci-mcp/tests/test_trigger_power_tools.py +++ b/packages/embeddedci-mcp/tests/test_trigger_power_tools.py @@ -14,7 +14,7 @@ def test_capture_la_sends_the_trigger_and_reports_it(connected): result = call("capture_la", samples=500, sample_rate_hz=1e6, trigger_la=9, - trigger_edge="falling", trigger_timeout=2.5) + trigger_edge="falling", trigger_timeout_s=2.5) req = [r for r in connected.requests if r["cmd"] == "la_capture"][-1] assert req["trigger"] == {"la": 9, "edge": "falling"} and req["trigger_timeout_ms"] == 2500 assert result["trigger"] == "LA9 falling" @@ -60,13 +60,13 @@ def test_the_schema_bounds_the_trigger_arguments(connected): with pytest.raises(ToolError): call("capture_la", samples=100, trigger_la=9, trigger_edge="sideways") with pytest.raises(ToolError): - call("capture_la", samples=100, trigger_la=9, trigger_timeout=601) + call("capture_la", samples=100, trigger_la=9, trigger_timeout_s=601) # -- power profiles ------------------------------------------------------------------------- def test_measure_power_reports_statistics_in_si_units(connected): - result = call("measure_power", duration=1.0) + result = call("measure_power", duration_s=1.0) assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 0, "duration_ms": 1000} assert result["efuse"] == 1 and result["n"] == 950 @@ -83,7 +83,7 @@ def test_measure_power_reports_statistics_in_si_units(connected): def test_measure_power_returns_a_trace_when_points_are_asked_for(connected): - result = call("measure_power", duration=1.0, points=4, efuse=2, rate_hz=500) + result = call("measure_power", duration_s=1.0, points=4, efuse=2, rate_hz=500) assert connected.requests[-1]["keep_samples"] == 4 and connected.requests[-1]["efuse"] == 2 assert connected.requests[-1]["sample_rate_hz"] == 500 assert result["trace_current"] == [0.04, 0.18, 0.05, 0.048] @@ -93,13 +93,13 @@ def test_measure_power_returns_a_trace_when_points_are_asked_for(connected): def test_measure_power_downsamples_a_long_trace(connected): - result = call("measure_power", duration=1.0, points=2) + result = call("measure_power", duration_s=1.0, points=2) assert result["trace_current"] == [0.11, 0.049] # two bins, averaged assert result["trace_step"] == pytest.approx(0.5) def test_power_profile_session_brackets_other_calls(connected): - started = call("power_profile_start", rate_hz=500, max_duration=5) + started = call("power_profile_start", rate_hz=500, max_duration_s=5) assert started == {"running": True, "efuse": 1, "rate_hz": 500.0, "max_duration": 5.0} assert connected.requests[-1] == {"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 4096, "max_duration_ms": 5000, @@ -126,10 +126,10 @@ def test_disconnect_forgets_the_running_profile(connected): def test_the_schema_bounds_the_power_arguments(connected): with pytest.raises(ToolError): - call("measure_power", duration=1.0, rate_hz=5000) + call("measure_power", duration_s=1.0, rate_hz=5000) with pytest.raises(ToolError): - call("measure_power", duration=0) + call("measure_power", duration_s=0) with pytest.raises(ToolError): - call("measure_power", duration=1.0, points=501) + call("measure_power", duration_s=1.0, points=501) with pytest.raises(ToolError): - call("power_profile_start", max_duration=601) + call("power_profile_start", max_duration_s=601) diff --git a/packages/embeddedci-mcp/tests/test_wiring_tools.py b/packages/embeddedci-mcp/tests/test_wiring_tools.py index 86727b2..c1a7656 100644 --- a/packages/embeddedci-mcp/tests/test_wiring_tools.py +++ b/packages/embeddedci-mcp/tests/test_wiring_tools.py @@ -112,9 +112,9 @@ def test_uart_tools_take_channels_and_baud_from_the_profile(connected): assert result == {"open": True, "rx": 7, "tx": 8, "baud": 9600, "parity": "none", "stop_bits": 1, "half_duplex": False} call("uart_close") - call("capture_uart", duration=0.2) + call("capture_uart", duration_s=0.2) assert connected.uart_links[-1] is not None - call("power_cycle_and_capture", delay=0.1, duration=0.3, off_settle=0) + call("power_cycle_and_capture", delay_s=0.1, duration_s=0.3, off_settle_s=0) assert [c for c in connected.calls if c[0] == "target_power"][-2:] == [ ("target_power", 2, False, 0), ("target_power", 2, True, 100)] # the profile's rail diff --git a/packages/embeddedci-mcp/tests/tools_surface.json b/packages/embeddedci-mcp/tests/tools_surface.json index 3573dcf..3e8dee8 100644 --- a/packages/embeddedci-mcp/tests/tools_surface.json +++ b/packages/embeddedci-mcp/tests/tools_surface.json @@ -381,12 +381,12 @@ "title": "Max Frames", "type": "integer" }, - "timeout": { + "timeout_s": { "default": 0.0, "description": "With can_id: wait up to this long for it. Without: collect frames for this long (0 = what is buffered).", "maximum": 120, "minimum": 0, - "title": "Timeout", + "title": "Timeout S", "type": "number" } }, @@ -697,12 +697,12 @@ "description": "Wait for an edge or level on this LA channel (a number, or a wiring-profile name) before sampling, so t = 0 is that moment. Omit for a free-running capture. Needs the capture_trigger capability.", "title": "Trigger La" }, - "trigger_timeout": { + "trigger_timeout_s": { "default": 10.0, "description": "Seconds to wait for the trigger before the capture is abandoned with a TriggerTimeout.", "exclusiveMinimum": 0, "maximum": 600, - "title": "Trigger Timeout", + "title": "Trigger Timeout S", "type": "number" } }, @@ -787,7 +787,7 @@ "description": "Route this ADC source first for the analog half; omit to keep routing. current_in captures the 4-20 mA input (J8) and the analog stats are then amps.", "title": "Source" }, - "stop_dac_after": { + "stop_dac_after_s": { "anyOf": [ { "type": "number" @@ -798,7 +798,7 @@ ], "default": null, "description": "Seconds into the capture to cut a running DAC.", - "title": "Stop Dac After" + "title": "Stop Dac After S" }, "trigger_edge": { "default": "rising", @@ -830,12 +830,12 @@ "description": "Wait for an edge or level on this LA channel (a number, or a wiring-profile name) before sampling, so t = 0 is that moment. Omit for a free-running capture. Needs the capture_trigger capability.", "title": "Trigger La" }, - "trigger_timeout": { + "trigger_timeout_s": { "default": 10.0, "description": "Seconds to wait for the trigger before the capture is abandoned with a TriggerTimeout.", "exclusiveMinimum": 0, "maximum": 600, - "title": "Trigger Timeout", + "title": "Trigger Timeout S", "type": "number" } }, @@ -990,7 +990,7 @@ "default": null, "description": "Run one transaction right after the capture arms (gateware v55+): i2c (the i2c_open session, else one from the wiring), spi (SPI pins from the wiring) or gpio (a GPIO output). Without trigger_la it triggers on SDA / CS falling or the gpio pin's edge." }, - "stop_dac_after": { + "stop_dac_after_s": { "anyOf": [ { "type": "number" @@ -1001,7 +1001,7 @@ ], "default": null, "description": "Seconds into the capture to cut a running DAC output (see the DUT react).", - "title": "Stop Dac After" + "title": "Stop Dac After S" }, "trigger_edge": { "default": "rising", @@ -1041,12 +1041,12 @@ "title": "Trigger Pre Samples", "type": "integer" }, - "trigger_timeout": { + "trigger_timeout_s": { "default": 10.0, "description": "Seconds to wait for the trigger before the capture is abandoned with a TriggerTimeout.", "exclusiveMinimum": 0, "maximum": 600, - "title": "Trigger Timeout", + "title": "Trigger Timeout S", "type": "number" } }, @@ -1154,11 +1154,11 @@ "title": "De Active Low", "type": "boolean" }, - "duration": { + "duration_s": { "description": "Capture window in seconds.", "exclusiveMinimum": 0, "maximum": 600, - "title": "Duration", + "title": "Duration S", "type": "number" }, "entry": { @@ -1275,7 +1275,7 @@ } }, "required": [ - "duration" + "duration_s" ], "title": "capture_uartArguments", "type": "object" @@ -1554,12 +1554,12 @@ "description": "Select the LA I/O-bank voltage right after connecting (the DUT's I/O voltage; 5.0 needs the digital board v3r4).", "title": "La Voltage" }, - "lease_wait": { + "lease_wait_s": { "default": 30.0, "description": "Seconds to wait when someone else holds the pod's lease (the cloud device's, or the pod's own on the LAN and USB network).", "maximum": 3600, "minimum": 0, - "title": "Lease Wait", + "title": "Lease Wait S", "type": "number" }, "wiring_profile": { @@ -2530,11 +2530,11 @@ "description": "Power this rail on before flashing: internal 5 V (efuse 1) or external (efuse 2).", "title": "Target Power" }, - "timeout": { + "timeout_s": { "default": 300.0, "exclusiveMinimum": 0, "maximum": 3600, - "title": "Timeout", + "title": "Timeout S", "type": "number" }, "tx": { @@ -2633,7 +2633,7 @@ "description": "DAC output. Omitted: 3v3, the lowest voltage output (with route false: the output last routed, cal1 = 5v). Pick the one the DUT pin tolerates: 5v and 12v can damage a 3.3 V pin.", "title": "Dac Path" }, - "duration": { + "duration_s": { "anyOf": [ { "type": "number" @@ -2644,7 +2644,7 @@ ], "default": null, "description": "Seconds; omit to run until dac_stop.", - "title": "Duration" + "title": "Duration S" }, "freq_hz": { "exclusiveMinimum": 0, @@ -2806,17 +2806,17 @@ "description": "LA channel 1-14, or a name from the wiring profile \u2014 a signal ('READY') or a role ('uart_rx', 'i2c_sda', 'swd_swclk'). Call `wiring` to see the names. The gpio_* tools also take expander pins ('EXT1') once one is attached (expansion).", "title": "La" }, - "width": { + "width_s": { "description": "Seconds the pulse is high (and low between pulses), 4 us to 65.535 ms.", "maximum": 0.065535, "minimum": 4e-06, - "title": "Width", + "title": "Width S", "type": "number" } }, "required": [ "la", - "width" + "width_s" ], "title": "gpio_pulseArguments", "type": "object" @@ -2938,12 +2938,12 @@ "title": "Level", "type": "integer" }, - "timeout": { + "timeout_s": { "default": 5.0, "description": "Seconds to wait.", "maximum": 600, "minimum": 0, - "title": "Timeout", + "title": "Timeout S", "type": "number" } }, @@ -3050,7 +3050,7 @@ }, "pullups": { "default": "pod", - "description": "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today; at 1.8 V firmware newer than 3.10.12); external: the board has its own.", + "description": "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today); external: the board has its own.", "enum": [ "pod", "external" @@ -3269,11 +3269,11 @@ }, "input": { "properties": { - "delay": { - "description": "HALF the step period in seconds: each pulse is high for delay, then low for delay, so pulses are 2 x delay apart. 4 us to 65.535 ms.", + "delay_s": { + "description": "HALF the step period in seconds: each pulse is high for delay_s, then low for delay_s, so pulses are 2 x delay_s apart. 4 us to 65.535 ms.", "maximum": 0.065535, "minimum": 4e-06, - "title": "Delay", + "title": "Delay S", "type": "number" }, "dir_la": { @@ -3318,7 +3318,7 @@ "required": [ "la", "steps", - "delay" + "delay_s" ], "title": "la_stepArguments", "type": "object" @@ -3591,11 +3591,11 @@ }, "input": { "properties": { - "duration": { + "duration_s": { "description": "Seconds to sample (blocking).", "exclusiveMinimum": 0, "maximum": 600, - "title": "Duration", + "title": "Duration S", "type": "number" }, "efuse": { @@ -3633,7 +3633,7 @@ } }, "required": [ - "duration" + "duration_s" ], "title": "measure_powerArguments", "type": "object" @@ -3664,20 +3664,20 @@ "description": "UART baud rate; omit for the wiring profile's uart_baud.", "title": "Baud" }, - "delay": { + "delay_s": { "default": 1.0, "description": "Seconds into the capture the power comes back.", "maximum": 60, "minimum": 0, - "title": "Delay", + "title": "Delay S", "type": "number" }, - "duration": { + "duration_s": { "default": 4.0, - "description": "Capture window in seconds; must exceed delay.", + "description": "Capture window in seconds; must exceed delay_s.", "exclusiveMinimum": 0, "maximum": 600, - "title": "Duration", + "title": "Duration S", "type": "number" }, "efuse": { @@ -3697,11 +3697,11 @@ "description": "Target-power rail: internal 5 V (efuse 1) or external (efuse 2). Omit for the wiring profile's rail.", "title": "Efuse" }, - "off_settle": { + "off_settle_s": { "default": 0.3, "maximum": 10, "minimum": 0, - "title": "Off Settle", + "title": "Off Settle S", "type": "number" }, "parity": { @@ -3813,7 +3813,7 @@ }, "input": { "properties": { - "delay": { + "delay_s": { "anyOf": [ { "type": "number" @@ -3824,7 +3824,7 @@ ], "default": null, "description": "Seconds: schedule the power-off pod-side.", - "title": "Delay" + "title": "Delay S" }, "efuse": { "anyOf": [ @@ -3858,7 +3858,7 @@ }, "input": { "properties": { - "delay": { + "delay_s": { "anyOf": [ { "type": "number" @@ -3869,7 +3869,7 @@ ], "default": null, "description": "Seconds: schedule the power-on pod-side and return at once (e.g. to power on during a capture).", - "title": "Delay" + "title": "Delay S" }, "efuse": { "anyOf": [ @@ -3933,12 +3933,12 @@ "description": "Target-power rail: internal 5 V (efuse 1) or external (efuse 2). Omit for the wiring profile's rail.", "title": "Efuse" }, - "max_duration": { + "max_duration_s": { "default": 60.0, "description": "Seconds after which the pod stops sampling by itself (the result is then truncated).", "exclusiveMinimum": 0, "maximum": 600, - "title": "Max Duration", + "title": "Max Duration S", "type": "number" }, "rate_hz": { @@ -4079,7 +4079,7 @@ } ], "default": null, - "description": "DAC output. Omitted: 3v3, the lowest voltage output (with route false: the output last routed, cal1 = 5v). Pick the one the DUT pin tolerates: 5v and 12v can damage a 3.3 V pin.", + "description": "DAC output. Omitted: 3v3, the lowest voltage output (with route false: the output last routed, cal1 = 5v; for waveform_id: the waveform's own, else 3v3). Pick the one the DUT pin tolerates: 5v and 12v can damage a 3.3 V pin.", "title": "Dac Path" }, "fault": { @@ -4139,6 +4139,13 @@ "title": "Switch Image", "type": "boolean" }, + "target_samples": { + "default": 0, + "description": "waveform_id: downsample a shallow replay to this many samples.", + "minimum": 0, + "title": "Target Samples", + "type": "integer" + }, "volts": { "anyOf": [ { @@ -4154,165 +4161,36 @@ "default": null, "description": "Waveform in volts, one value per sample. On dac_path current_out the values are AMPS (0.004 to 0.020).", "title": "Volts" - } - }, - "title": "replayArguments", - "type": "object" - } - }, - "replay_waveform": { - "annotations": { - "destructiveHint": true, - "idempotentHint": false, - "openWorldHint": true, - "readOnlyHint": false, - "title": "Replay a library waveform" - }, - "input": { - "$defs": { - "FaultSpec": { - "description": "A fault spliced into a replayed waveform.", - "properties": { - "level": { - "anyOf": [ - { - "maximum": 65535, - "minimum": 0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Raw DAC code to hold (default per fault type).", - "title": "Level" - }, - "start": { - "default": 0, - "description": "First replay sample the fault covers.", - "minimum": 0, - "title": "Start", - "type": "integer" - }, - "type": { - "enum": [ - "flatline", - "spike", - "stuck" - ], - "title": "Type", - "type": "string" - }, - "width": { - "default": 0, - "description": "Samples covered; 0 = to the end.", - "minimum": 0, - "title": "Width", - "type": "integer" - } - }, - "required": [ - "type" - ], - "title": "FaultSpec", - "type": "object" - } - }, - "properties": { - "dac_path": { - "anyOf": [ - { - "enum": [ - "3v3", - "5v", - "12v", - "current_out" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Output path; default the waveform's own, else 3v3.", - "title": "Dac Path" - }, - "fault": { - "anyOf": [ - { - "$ref": "#/$defs/FaultSpec" - }, - { - "type": "null" - } - ], - "default": null }, - "mapping": { - "default": "faithful", - "enum": [ - "faithful", - "fit" - ], - "title": "Mapping", - "type": "string" - }, - "on_capture": { - "default": false, - "title": "On Capture", - "type": "boolean" - }, - "sample_rate_hz": { + "waveform_id": { "anyOf": [ { - "type": "number" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Sample rate in Hz; omit for the device maximum.", - "title": "Sample Rate Hz" - }, - "switch_image": { - "default": true, - "description": "If the pod is on the other gateware image, switch it first (~3 s). The switch resets the FPGA, stopping any DAC output, UART session or sensor emulation. false = fail instead.", - "title": "Switch Image", - "type": "boolean" - }, - "target_samples": { - "default": 0, - "description": "Downsample a shallow replay to this many samples.", - "minimum": 0, - "title": "Target Samples", - "type": "integer" - }, - "waveform_id": { - "title": "Waveform Id", - "type": "string" + "description": "Instead of volts: a waveform from the cloud library (list_waveforms; needs server access).", + "title": "Waveform Id" }, "window_len": { "default": 0, - "description": "Samples to replay; 0 = to the end.", + "description": "waveform_id: samples to replay; 0 = to the end.", "minimum": 0, "title": "Window Len", "type": "integer" }, "window_start": { "default": 0, - "description": "First recording sample to replay.", + "description": "waveform_id: first recording sample to replay.", "minimum": 0, "title": "Window Start", "type": "integer" } }, - "required": [ - "waveform_id" - ], - "title": "replay_waveformArguments", + "title": "replayArguments", "type": "object" } }, @@ -4338,12 +4216,12 @@ "title": "Action", "type": "string" }, - "pulse": { + "pulse_s": { "default": 0.1, "description": "Pulse length in seconds (at most 1).", "exclusiveMinimum": 0, "maximum": 1, - "title": "Pulse", + "title": "Pulse S", "type": "number" } }, @@ -5101,7 +4979,7 @@ }, "input": { "properties": { - "voltage": { + "la_voltage": { "anyOf": [ { "enum": [ @@ -5117,7 +4995,7 @@ ], "default": null, "description": "The DUT's I/O voltage. 5.0 needs a pod with the digital board v3r4 (status capabilities vref_out). Omit it to read the current voltage and pin 21 without changing anything.", - "title": "Voltage" + "title": "La Voltage" } }, "title": "set_la_voltageArguments", @@ -5134,20 +5012,7 @@ }, "input": { "properties": { - "enabled": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Older form, use pull: true engages each channel's own direction, false is off.", - "title": "Enabled" - }, - "las": { + "la": { "description": "LA channels (1-14).", "items": { "maximum": 14, @@ -5156,30 +5021,23 @@ }, "maxItems": 14, "minItems": 1, - "title": "Las", + "title": "La", "type": "array" }, "pull": { - "anyOf": [ - { - "enum": [ - "up", - "down", - "off" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, "description": "The direction: up, down or off. The pod picks the resistor from the pin's function (ohms and strength in the result). A channel pulls only the ways its resistor allows (pull_status: supported): on the digital board v3r4 every channel pulls up or down; on older boards LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none, and the pod refuses the rest (BP0024, BP0023).", - "title": "Pull" + "enum": [ + "up", + "down", + "off" + ], + "title": "Pull", + "type": "string" } }, "required": [ - "las" + "la", + "pull" ], "title": "set_pullArguments", "type": "object" @@ -6022,12 +5880,12 @@ }, "input": { "properties": { - "timeout": { + "timeout_s": { "default": 2.0, "description": "Seconds to wait for until_regex (or, without one, for any new output).", "maximum": 600, "minimum": 0, - "title": "Timeout", + "title": "Timeout S", "type": "number" }, "until_regex": { @@ -6091,19 +5949,19 @@ }, "input": { "properties": { - "set": { + "enabled": { "anyOf": [ { - "const": "off", - "type": "string" + "const": false, + "type": "boolean" }, { "type": "null" } ], "default": null, - "description": "Omit to read the setting. \"off\" turns the pod's USB network adapter off (only over the pod's USB network link: connection 'usb'); the pod then re-enumerates as its USB console only and this connection ends. Turning it back on needs the USB console: the user runs `benchpod usb-network on`.", - "title": "Set" + "description": "Omit to read the setting. false turns the pod's USB network adapter off (only over the pod's USB network link: connection 'usb'); the pod then re-enumerates as its USB console only and this connection ends. Turning it back on needs the USB console: the user runs `benchpod usb-network on`.", + "title": "Enabled" } }, "title": "usb_networkArguments", diff --git a/packages/embeddedci-openhtf/README.md b/packages/embeddedci-openhtf/README.md index 553341a..4724db9 100644 --- a/packages/embeddedci-openhtf/README.md +++ b/packages/embeddedci-openhtf/README.md @@ -95,7 +95,7 @@ unset for analog-only tests that don't touch the LA bank. | Key | Default | Meaning | | --- | --- | --- | -| `benchpod_connection` | `None` → `BENCHPOD_CONNECTION` | `host[:port]`, a serial device path, `usb`, or `serial` | +| `benchpod_connection` | `None` → `BENCHPOD_CONNECTION` | `host[:port]`, a serial device path, or `usb` | | `benchpod_timeout` | `30.0` | Transport timeout in seconds | | `benchpod_la_voltage` | `None` → `BENCHPOD_LA_VOLTAGE` | LA I/O-bank voltage in volts (`1.8` or `3.3`) | diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 64e24e0..224bb24 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -53,6 +53,14 @@ Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: `code16` in the loop probe and input replies, `can_start`/`can_stop`, CAN `ts_ms`, `target_power` `enabled` (booleans in `target_status` too), `usb_network` `enabled` (a boolean in and out; `status.usb.enabled` and `status.usb.net` are booleans). +- **Removed** (approved for 4.0): `set_pull(la, True|False)` and `set_pull(..., enabled=)` (pass + `"up"`, `"down"` or `"off"`; the four shortcuts `enable_pullup`, `disable_pullup`, + `enable_pulldown`, `disable_pulldown` stay); `wiring.REFERENCE_BENCH` (use `DEFAULT_PINS`), + `wiring.PRESET_ALIASES` and the preset name `"embeddedci-reference"`, `Wiring.defaults()` (use + `Wiring.preset()`); `constants.PULL_OHMS`, `PULLUP_CHANNELS`, `PULLDOWN_CHANNELS` (use + `PULL_TABLE`); `transport.serial.RP_VID`; the `serial` connection keyword (use `usb`); the + CLI config's legacy `bench_pod_addr`; an LA channel number as `upload_build`'s reset input (a + flag only); `CanBus.expect(can_id=)` and `read_until(can_id=)` (pass the id as `match`). - `ModuleInfo.dac_pinout_ok`: `False` when the digital board and the analog module use different flat-cable DAC pinouts (the DAC is off). - Error catalog synced (`BP0031` to `BP0080`); features table revision 11. diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index bc803b5..f8d1086 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -218,7 +218,7 @@ explicitly. The pytest plugin does **not** fall back to it (see [pytest plugin]( | `192.168.1.213`, `benchpod-baea06.local`, `[fe80::1]` | network: JSON over TLS on port 8443 (see [TLS on the LAN](#tls-on-the-lan)); an address on the pod's USB network adapter (`10.237.x.y`) is plaintext 8080 | | `host:8080`, `host:8443` | network on that port: `:8080` is plaintext (refused on Ethernet and Wi-Fi unless the pod's HTTPS-only is off), `:8443` TLS | | `/dev/ttyACM0`, `COM3`, `\\.\COM10` | USB console, explicit device path | -| `usb` | USB pod, auto-detected by probing the serial ports (`serial` also accepted): its USB network adapter on firmware 3.9.0 and later (full API), else its USB console | +| `usb` | USB pod, auto-detected by probing the serial ports: its USB network adapter (full API), else its USB console (status only) | | `usb:` | the USB pod with that name when several are plugged into one computer: `usb:baea06`, `usb:benchpod-baea06` (any case, optional `.local`); otherwise as `usb` | | `discover` (or `mdns`, `auto`) | find exactly one pod on the LAN via mDNS (needs `[discovery]`); errors on zero or several | | `embeddedci:` | a named device through embeddedci.com (needs `[cloud]`; the `benchpod login` session or an API key anywhere, or GitHub Actions OIDC) | @@ -783,7 +783,7 @@ not set is never driven, and a call that needs it says which one to pass: `bp.fl `swclk`/`swdio` in the profile raises `ValueError: swd_swclk was not given and the wiring profile has no swd_swclk`. The default pins, what profiles used to default to (UART RX on LA5 and TX on LA4, I2C SDA on LA1 and SCL on LA2, SWD on LA11/LA12, 3.3 V, internal 5 V), are a preset: -`Wiring.preset("embeddedci-default")` (the old name `"embeddedci-reference"` still works). They are +`Wiring.preset("embeddedci-default")`. They are not the wiring of any particular bench: load your board's own profile by name (`BenchPod(conn, wiring_profile="process-node-stm32")`, `bp.load_wiring("process-node-stm32")`), as the [process-node example](https://github.com/embeddedci-com/examples/tree/main/process-node-stm32) @@ -1288,11 +1288,9 @@ bp.disable_pullup(PIN1, PIN2) # off, on a channel that pulls up A direction the channel can't pull raises `PullDirectionError` (a `FirmwareError` and a `ValueError`) with code `BP0024`, "LA7 supports pull-down only on this board", and `"up"` or `"down"` on a channel without a resistor raises it with `BP0023`. `.la`, `.want` and `.have` name the channel -and the directions. `set_pull(la, True)` / `set_pull(la, False)` (or `enabled=`) still work but are -deprecated: True pulls the channel's own direction. - -Firmware before the `la_pull_dir` feature (`bp.supports("la_pull_dir")`) only takes on/off; the SDK -then sends that and checks the direction itself, so the calls above work on every pod. +and the directions. The boolean form (`set_pull(la, True)`, `enabled=`) is gone in 4.0: pass the +direction. The shortcuts `enable_pullup`, `disable_pullup`, `enable_pulldown` and +`disable_pulldown` stay. An open-drain bus such as I2C must sit on LA1–LA6. @@ -2269,7 +2267,7 @@ switches the 120 Ω termination off on exit. ```python with bp.open_can(bitrate=500_000, mode="internal") as can: can.write(0x123, [0xDE, 0xAD]) - frame = can.expect(can_id=0x123, timeout=1.0) # raises CanTimeout (.frames) on timeout + frame = can.expect(0x123, timeout=1.0) # raises CanTimeout (.frames) on timeout assert frame.data == b"\xde\xad" with bp.open_can(bitrate=500_000, term=True) as can: # on a real bus, 120 Ω termination in @@ -2288,7 +2286,7 @@ padded with zeros to the next one. ```python with bp.open_can(bitrate=500_000, data_bitrate=2_000_000, mode="internal") as can: can.write(0x123, bytes(range(64))) - frame = can.expect(can_id=0x123, timeout=1.0) + frame = can.expect(0x123, timeout=1.0) assert frame.fd and frame.brs and frame.data == bytes(range(64)) ``` @@ -2666,7 +2664,7 @@ few built from other shapes); `to_dict()` goes the other way where a type is sen | `MotorEmulator` (class) | `open_motor_emulator` | `configure()`, `boards()`, `probe()`, `read()`, `read_signed(reg)`, `write()`, `status()`, `trips()`, `clear_trips()`, `arm()`, `set_control()`, `set_pwm()`, `set_duties(a, b, c)`, `set_shape(shape)`, `set_protection()`, `set_battery()`, `battery_state()`, `set_pv_calibration(offset, gain)`, `sample()`, `time()`, `start_log()`, `stop_log()`, `read_log()`, `eeprom_read(addr, length)`, `eeprom_write(addr, data)`, `close()` | | `BatteryModel` | `MotorEmulator.set_battery` | `capacity_ah`, `ocv`, `r0_ohm`, `r1_ohm`, `tau_s`, `soc`, `v_min`, `v_max`, `invert_current` | | `EmulatorCalibration` | `open_motor_emulator(calibration=...)` | `codes_per_amp`, `codes_per_volt`, `offsets`, `sample_rate_hz`, `amps()`, `volts()`, `current_code()`, `bus_code()`, `resistance_code()` | -| `Wiring` | `wiring`, `save_wiring` | see [Wiring profile](#wiring-profile); also `defaults()`, `load(path)`, `coerce(value)` (a `Wiring`, dict or file path), `from_dict(data, *, strict=True)` (`strict=False` keeps unknown keys in `extra`), `to_dict()`, `with_changes(**changes)`, `assignments()`, `pins()`, `la(name)`, `signal(name)`, `dut_dir(name)`, `pin_dut_dirs()`, `describe()`, `warnings()`, `la_voltage`, `i2c_address`, `dut_dirs` | +| `Wiring` | `wiring`, `save_wiring` | see [Wiring profile](#wiring-profile); also `load(path)`, `coerce(value)` (a `Wiring`, dict or file path), `from_dict(data, *, strict=True)` (`strict=False` keeps unknown keys in `extra`), `to_dict()`, `with_changes(**changes)`, `assignments()`, `pins()`, `la(name)`, `signal(name)`, `dut_dir(name)`, `pin_dut_dirs()`, `describe()`, `warnings()`, `la_voltage`, `i2c_address`, `dut_dirs` | | `Signal` | `Wiring.signals` | `name`, `la`, `direction`, `active_low`, `description`, `to_dict()` | | `Waveform` | `WaveformLibrary` | `id`, `name`, `kind`, `sample_count`, `sample_rate_hz`, `bits`, `full_scale_v`, `recording_size_bytes`, `created_at`, `dac_path`, `segments`, `unit`, `is_recording` | | `WaveformLibrary` (class) | `waveforms` | `list()`, `get()`, `find()`, `save_recording()`, `save_waveform()`, `save_segments()`, `rename()`, `delete()`, `preview()`, `download_recording()`, `samples_b64(waveform_id)` | diff --git a/packages/embeddedci/src/embeddedci/benchpod/can.py b/packages/embeddedci/src/embeddedci/benchpod/can.py index 85730c6..b821119 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/can.py +++ b/packages/embeddedci/src/embeddedci/benchpod/can.py @@ -14,7 +14,7 @@ with bp.open_can(bitrate=500_000, mode="internal") as can: can.write(0x123, [0xDE, 0xAD]) - frame = can.expect(can_id=0x123, timeout=1.0) + frame = can.expect(0x123, timeout=1.0) assert frame.data == b"\\xde\\xad" CAN FD (firmware 3.10.2+): pass ``data_bitrate``. Frames then carry up to 64 @@ -22,7 +22,7 @@ with bp.open_can(bitrate=500_000, data_bitrate=2_000_000, mode="internal") as can: can.write(0x123, bytes(range(64))) - frame = can.expect(can_id=0x123, timeout=1.0) + frame = can.expect(0x123, timeout=1.0) assert frame.fd and frame.brs and len(frame.data) == 64 """ @@ -171,18 +171,14 @@ def read(self, max_frames: int = 8) -> List[CanFrame]: out, self._pending = self._pending[:max_frames], self._pending[max_frames:] return out - def read_until(self, match: Optional[Match] = None, *, - can_id: Optional[int] = None, timeout: float, + def read_until(self, match: Optional[Match] = None, *, timeout: float, poll: float = 0.02) -> Optional[CanFrame]: """Poll until a frame matches ``match`` (an id or a predicate) or ``timeout`` elapses. Returns the matching :class:`CanFrame` or ``None``. Non-matching frames drained in the process are kept buffered, so a later - :meth:`read`/:meth:`read_until` still sees them. ``can_id`` is a - convenience alias for matching a specific identifier. + :meth:`read`/:meth:`read_until` still sees them. """ - if can_id is not None and match is None: - match = can_id pred = _matcher(match) deadline = time.monotonic() + timeout while True: @@ -196,13 +192,9 @@ def read_until(self, match: Optional[Match] = None, *, if not self._pending: time.sleep(poll) - def expect(self, match: Optional[Match] = None, *, can_id: Optional[int] = None, - timeout: float = 1.0) -> CanFrame: - """Like :meth:`read_until` but raises :class:`CanTimeout` on timeout. - - ``can_id`` is a convenience alias for matching a specific identifier. - """ - f = self.read_until(match, can_id=can_id, timeout=timeout) + def expect(self, match: Optional[Match] = None, *, timeout: float = 1.0) -> CanFrame: + """Like :meth:`read_until` but raises :class:`CanTimeout` on timeout.""" + f = self.read_until(match, timeout=timeout) if f is None: raise CanTimeout( f"no matching CAN frame within {timeout:g}s", diff --git a/packages/embeddedci/src/embeddedci/benchpod/cli_config.py b/packages/embeddedci/src/embeddedci/benchpod/cli_config.py index a4674d0..bfc8daa 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/cli_config.py +++ b/packages/embeddedci/src/embeddedci/benchpod/cli_config.py @@ -3,8 +3,7 @@ ``benchpod-cli`` keeps its configuration in ``~/.config/benchpod-cli/config.json`` (or under ``$XDG_CONFIG_HOME``; see its ``internal/benchpodconfig``). ``benchpod set-connection `` -and ``benchpod discover --save`` store the default connection there as ``connection``; older CLI -versions wrote a TCP address as ``bench_pod_addr``, which is read the same way. The SDK never +and ``benchpod discover --save`` store the default connection there as ``connection``. The SDK never writes this file. A missing, unreadable or malformed file means "nothing saved". """ @@ -36,8 +35,8 @@ def config_path() -> Path: def saved_connection(path: Optional[Path] = None) -> Optional[str]: - """The default connection ``benchpod-cli`` saved (``connection``, else the legacy - ``bench_pod_addr``), or None when there is none or the file cannot be read.""" + """The default connection ``benchpod-cli`` saved (``connection``), or None when there is none + or the file cannot be read.""" path = path or config_path() try: data = json.loads(path.read_text(encoding="utf-8")) @@ -49,7 +48,7 @@ def saved_connection(path: Optional[Path] = None) -> Optional[str]: if not isinstance(data, dict): _log.warning("ignoring the benchpod-cli config %s: not a JSON object", path) return None - for key in ("connection", "bench_pod_addr"): + for key in ("connection",): value = data.get(key) if isinstance(value, str) and value.strip(): conn = value.strip() diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index aaba825..5c65e0b 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -264,16 +264,6 @@ def _check_level(level: Any) -> int: } -class _NoPull: - """set_pull's "pull not given" (``enabled=`` is the older keyword); a stable repr for the docs.""" - - def __repr__(self) -> str: - return "" - - -_NO_PULL = _NoPull() - - def _one_or_many(las: List[int]) -> Any: return las[0] if len(las) == 1 else las @@ -1664,13 +1654,13 @@ def _pulls_at(self, volts: Optional[float]) -> bool: return False @staticmethod - def _pull_want(la: int, pull: Union[str, bool, None]) -> str: - """``pull`` as "up" / "down" / "off". True (deprecated) is the channel's own direction.""" - if pull is None or pull is False: + def _pull_want(la: int, pull: Optional[str]) -> str: + """``pull`` as "up" / "down" / "off" (``None`` and ``"none"`` are off).""" + if pull is None: return "off" - if pull is True: - hw = PULL_TABLE.get(la) - return hw.default if hw else "up" + if isinstance(pull, bool): + raise TypeError(f'set_pull() takes "up", "down" or "off", not {pull!r} (the boolean form ' + "is gone in embeddedci 4.0)") want = str(pull).strip().lower() if want == "none": want = "off" @@ -1687,8 +1677,7 @@ def _pull_refusal(la: int, want: str, supported: Tuple[str, ...]) -> PullDirecti return firmware_error(f"LA{la} supports pull-{have} only on this board", cmd="la_pull", code="BP0024", values={"la": la, "want": want, "have": have}) # type: ignore[return-value] - def set_pull(self, la: Union[Pin, int], pull: Union[PullDirection, bool, None, object] = _NO_PULL, *, - enabled: Optional[bool] = None) -> PullState: + def set_pull(self, la: Union[Pin, int], pull: Optional[PullDirection]) -> PullState: """Pull LA ``la`` ``"up"``, ``"down"`` or ``"off"`` (``None`` is off too) and return its :class:`PullState`. @@ -1696,15 +1685,7 @@ def set_pull(self, la: Union[Pin, int], pull: Union[PullDirection, bool, None, o resistor can't pull raises :class:`~embeddedci.benchpod.errors.PullDirectionError` (BP0024, "LA7 supports pull-down only on this board"), and ``"up"``/``"down"`` on a channel without one too (BP0023). ``"off"`` is fine on every channel. - - ``set_pull(la, True)`` / ``set_pull(la, False)`` (and ``enabled=``) still work - (deprecated): True engages the channel's own direction (up on LA1-LA6, down on LA7/LA8), - False is off. """ - if pull is _NO_PULL: - if enabled is None: - raise TypeError('set_pull() needs pull: "up", "down" or "off"') - pull = bool(enabled) la_i = coerce_pin(la, "la") want = self._pull_want(la_i, pull) # type: ignore[arg-type] with _classified_errors(): @@ -2224,7 +2205,7 @@ def open_can(self, *, bitrate: int = 500_000, mode: CanMode = "normal", with bp.open_can(bitrate=500_000, mode="internal") as can: can.write(0x123, [1, 2, 3]) - frame = can.expect(can_id=0x123, timeout=1.0) + frame = can.expect(0x123, timeout=1.0) ``data_bitrate`` makes it a CAN FD bus (see :meth:`can_config`):: diff --git a/packages/embeddedci/src/embeddedci/benchpod/connection.py b/packages/embeddedci/src/embeddedci/benchpod/connection.py index eebd113..b4d3851 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/connection.py +++ b/packages/embeddedci/src/embeddedci/benchpod/connection.py @@ -6,10 +6,9 @@ USB network adapter, 10.237.0.0/16, or when ``:8080`` is given) * ``/dev/tty*`` / ``COM3`` / ``\\\\.\\COM3`` -> serial device path -* ``usb`` -> USB pod, auto-detected by probing the ports - (``serial`` is accepted as a legacy spelling); on - firmware 3.9.0+ the transport is the pod's USB network - adapter when it answers, else the console (see +* ``usb`` -> USB pod, auto-detected by probing the ports; the + transport is the pod's USB network adapter when it + answers, else the console (see :func:`~embeddedci.benchpod.transport.open_transport`) * ``usb:`` -> the USB pod with that name, when several are plugged in (``usb:baea06``, ``usb:benchpod-baea06``) @@ -120,8 +119,6 @@ def parse_connection(raw: str) -> ConnSpec: "embeddedci destination requires a device name, e.g. 'embeddedci:my-bench'" ) return ConnSpec(kind="embeddedci", device_name=name) - # "usb" is the documented spelling; "serial" is the older one, still accepted - # so connection strings written before the rename keep working. if s.lower() == SAVED_KEYWORD: saved = saved_connection() if not saved: @@ -130,7 +127,7 @@ def parse_connection(raw: str) -> ConnSpec: "holds none; save one with `benchpod set-connection `" ) return parse_connection(saved) - if s.lower() in ("usb", "serial"): + if s.lower() == "usb": return ConnSpec(kind="serial", device="") if s.lower().startswith(USB_PREFIX): pod = normalize_pod_name(s[len(USB_PREFIX):]) diff --git a/packages/embeddedci/src/embeddedci/benchpod/constants.py b/packages/embeddedci/src/embeddedci/benchpod/constants.py index 02ccfe5..d8fc5d1 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/constants.py +++ b/packages/embeddedci/src/embeddedci/benchpod/constants.py @@ -168,7 +168,7 @@ class Pin(IntEnum): class PullHw(NamedTuple): """One LA channel's pull resistor on a board: the directions it can pull, the one - ``set_pull(la, True)`` (and firmware's older ``pullup:on``) engages, and its value.""" + the channel pulls by default, and its value.""" dirs: Tuple[str, ...] default: str @@ -187,10 +187,6 @@ class PullHw(NamedTuple): } PULL_TABLE: Dict[int, PullHw] = PULL_TABLE_V3 -#: Derived from :data:`PULL_TABLE`, kept for existing callers. -PULL_OHMS: Dict[int, str] = {la: hw.ohms for la, hw in PULL_TABLE.items()} -PULLUP_CHANNELS: Tuple[int, ...] = tuple(la for la, hw in PULL_TABLE.items() if "up" in hw.dirs) -PULLDOWN_CHANNELS: Tuple[int, ...] = tuple(la for la, hw in PULL_TABLE.items() if "down" in hw.dirs) # LA step trains (``la_step``, ``GpioPin.pulse``): the gateware counts steps and the half-period in # 16-bit counters, so the pod refuses more steps or a longer half-period. diff --git a/packages/embeddedci/src/embeddedci/benchpod/header.py b/packages/embeddedci/src/embeddedci/benchpod/header.py index 60cc6fe..24843eb 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/header.py +++ b/packages/embeddedci/src/embeddedci/benchpod/header.py @@ -15,7 +15,7 @@ from typing import Any, Dict, List, Mapping, Optional, Tuple -from .constants import PULL_OHMS +from .constants import PULL_TABLE from .wiring import ROLE_KEYS, Wiring HEADERS: Tuple[str, ...] = ("j1", "front") @@ -75,7 +75,7 @@ def _uses(w: Wiring, la: int) -> List[Tuple[str, str]]: def _pull(w: Wiring, la: int) -> Optional[str]: - ohms = PULL_OHMS.get(la) + ohms = PULL_TABLE[la].ohms if la in PULL_TABLE else None d = w.pull_directions().get(la) if not ohms or not d: return None diff --git a/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py b/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py index 8bb05f6..f635132 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py +++ b/packages/embeddedci/src/embeddedci/benchpod/pytest_plugin.py @@ -24,13 +24,13 @@ from .cli_config import SAVED_KEYWORD, config_path, saved_connection from .connection import ENV_VAR from .wiring import Wiring -from .constants import PULL_OHMS as _PULL_OHMS -from .constants import PULLDOWN_CHANNELS +from .constants import PULL_TABLE from .runs import pytest_runs as _runs from .runs.pytest_runs import measure # noqa: F401 -- a fixture of this plugin #: The channels whose network pulls DOWN rather than up. -_PULLDOWN_CHANNELS = frozenset(PULLDOWN_CHANNELS) +_PULL_OHMS = {la: hw.ohms for la, hw in PULL_TABLE.items()} +_PULLDOWN_CHANNELS = frozenset(la for la, hw in PULL_TABLE.items() if "down" in hw.dirs) class BenchPodPins: diff --git a/packages/embeddedci/src/embeddedci/benchpod/wiring.py b/packages/embeddedci/src/embeddedci/benchpod/wiring.py index 5e413b1..3240c7e 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/wiring.py +++ b/packages/embeddedci/src/embeddedci/benchpod/wiring.py @@ -24,9 +24,9 @@ from pathlib import Path from typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple, Union -from .constants import PULL_TABLE, PULLDOWN_CHANNELS, PULLUP_CHANNELS +from .constants import PULL_TABLE -PULL_CHANNELS = PULLUP_CHANNELS + PULLDOWN_CHANNELS +PULL_CHANNELS = tuple(PULL_TABLE) WIRING_VERSION = 2 #: The schema versions :meth:`Wiring.from_dict` reads: 1 (missing keys = the default pins) and 2. @@ -37,12 +37,8 @@ "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, } -#: The old name of :data:`DEFAULT_PINS`, kept for older code. -REFERENCE_BENCH = DEFAULT_PINS #: Presets: complete profiles to start a new one from (:meth:`Wiring.preset`). Copied, never linked. PRESETS: Mapping[str, Mapping[str, Any]] = {"embeddedci-default": DEFAULT_PINS} -#: Old preset names that still work: name -> the preset it is now. -PRESET_ALIASES: Mapping[str, str] = {"embeddedci-reference": "embeddedci-default"} #: 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", @@ -198,20 +194,13 @@ def preset(cls, name: str = "embeddedci-default") -> "Wiring": pod assumed before version 2 (UART RX on LA5 and TX on LA4, I2C SDA on LA1 and SCL on LA2, SWD on LA11/LA12, 3.3 V, internal 5 V). It is not the wiring of any particular bench: check it against yours, then save a copy under your board's name: - ``bp.save_wiring(Wiring.preset().with_changes(uart_rx=3), name="nucleo")``. The old name - ``"embeddedci-reference"`` still works.""" + ``bp.save_wiring(Wiring.preset().with_changes(uart_rx=3), name="nucleo")``.""" try: - values = PRESETS[PRESET_ALIASES.get(name, name)] + 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 pins, what a profile was before version 2 left nothing undefined. Kept for - older code: use :meth:`preset` (or :meth:`undefined`).""" - return cls.preset("embeddedci-default") - @classmethod def from_dict(cls, data: Mapping[str, Any], *, source: str = "dict", strict: bool = True) -> "Wiring": @@ -226,7 +215,7 @@ def from_dict(cls, data: Mapping[str, Any], *, source: str = "dict", 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} + data = {**DEFAULT_PINS, **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] = {} diff --git a/packages/embeddedci/src/embeddedci/upload_build.py b/packages/embeddedci/src/embeddedci/upload_build.py index 3592a25..9587e07 100644 --- a/packages/embeddedci/src/embeddedci/upload_build.py +++ b/packages/embeddedci/src/embeddedci/upload_build.py @@ -51,10 +51,8 @@ def _optional_flag(value: Optional[str]) -> Optional[bool]: """Parse a yes/no input. Empty means "not specified" (leave the field out), which is different from an explicit false. - Pods drive NRST from a dedicated pin now, so this is a flag — but the GitHub - action passes whatever the workflow put in the input, and old workflows put - an LA channel number there. A bare number still parses: any channel meant - "reset is wired".""" + Pods drive NRST from a dedicated pin, so this is a flag; an LA channel number + (what old workflows put there) raises ``ValueError``.""" if value is None: return None value = value.strip().lower() @@ -64,8 +62,7 @@ def _optional_flag(value: Optional[str]) -> Optional[bool]: return True if value in ("false", "0", "no", "n", "off"): return False - # Legacy: an LA channel number. - return int(value) > 0 + raise ValueError(f"reset must be true or false, got {value!r}") def _optional_pin(value: Optional[str]) -> Optional[int]: diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 0761d67..49311ef 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -183,7 +183,7 @@ "set_lan_tls_https_only": "(self, on: 'bool') -> \"'LanTls'\"", "set_log_level": "(self, level: 'str') -> 'str'", "set_module_id": "(self, serial: 'str', rev: 'str', module_type: 'str' = 'analog', *, replace: 'bool' = False) -> 'ModuleInfo'", - "set_pull": "(self, la: 'Union[Pin, int]', pull: 'Union[PullDirection, bool, None, object]' = , *, enabled: 'Optional[bool]' = None) -> 'PullState'", + "set_pull": "(self, la: 'Union[Pin, int]', pull: 'Optional[PullDirection]') -> 'PullState'", "set_reset": "(self, asserted: 'bool') -> 'ResetState'", "signal": "(self, name: 'str') -> 'GpioPin'", "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'", @@ -247,10 +247,10 @@ "clear_responders": "(self) -> 'dict'", "close": "(self) -> 'None'", "collect": "(self, duration: 'float', *, match: 'Optional[Match]' = None, poll: 'float' = 0.02) -> 'List[CanFrame]'", - "expect": "(self, match: 'Optional[Match]' = None, *, can_id: 'Optional[int]' = None, timeout: 'float' = 1.0) -> 'CanFrame'", + "expect": "(self, match: 'Optional[Match]' = None, *, timeout: 'float' = 1.0) -> 'CanFrame'", "fd": "property", "read": "(self, max_frames: 'int' = 8) -> 'List[CanFrame]'", - "read_until": "(self, match: 'Optional[Match]' = None, *, can_id: 'Optional[int]' = None, timeout: 'float', poll: 'float' = 0.02) -> 'Optional[CanFrame]'", + "read_until": "(self, match: 'Optional[Match]' = None, *, timeout: 'float', poll: 'float' = 0.02) -> 'Optional[CanFrame]'", "set_term": "(self, on: 'bool') -> 'dict'", "simulate_ecu": "(self, rules: 'dict') -> 'None'", "status": "(self) -> 'dict'", @@ -1324,7 +1324,6 @@ ], "assignments": "(self) -> 'Iterator[Tuple[str, int]]'", "coerce": "(cls, value: \"Union['Wiring', Mapping[str, Any], str, Path]\") -> \"'Wiring'\"", - "defaults": "(cls) -> \"'Wiring'\"", "describe": "(self) -> 'str'", "dut_dir": "(self, name: 'str') -> 'str'", "from_dict": "(cls, data: 'Mapping[str, Any]', *, source: 'str' = 'dict', strict: 'bool' = True) -> \"'Wiring'\"", diff --git a/packages/embeddedci/tests/e2e/test_e2e_pod.py b/packages/embeddedci/tests/e2e/test_e2e_pod.py index d6bf437..3c6a8b6 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_pod.py +++ b/packages/embeddedci/tests/e2e/test_e2e_pod.py @@ -1192,10 +1192,10 @@ def test_can_loopback_responder_and_typed_reads(pod): pytest.skip("CAN is on the STM32H563 pod") with pod.open_can(bitrate=500_000, mode="internal") as can: can.write(0x123, [1, 2, 3]) - assert can.expect(can_id=0x123, timeout=1.0).data == bytes([1, 2, 3]) + assert can.expect(0x123, timeout=1.0).data == bytes([1, 2, 3]) can.add_responder(0x7DF, 0x7E8, [0x41, 0x0C]) can.write(0x7DF, [0x02, 0x01, 0x0C]) - assert can.expect(can_id=0x7E8, timeout=1.0).data == bytes([0x41, 0x0C]) + assert can.expect(0x7E8, timeout=1.0).data == bytes([0x41, 0x0C]) pod.can_write(0x55, [9]) time.sleep(0.05) result = pod.can_read(max_frames=8) @@ -1217,17 +1217,17 @@ def test_can_fd_loopback(pod, mode, data_bitrate): reply = can.write(0x100 + n, payload, ext=n == 33) want = {33: 48}.get(n, n) assert reply["fd"] is True and reply["brs"] is True and reply["dlc"] == want - f = can.expect(can_id=0x100 + n, timeout=1.0) + f = can.expect(0x100 + n, timeout=1.0) assert f.fd and f.brs and f.data == payload + bytes(want - n) can.write(0x50, [1, 2], fd=False) # classic frame on the FD bus - f = can.expect(can_id=0x50, timeout=1.0) + f = can.expect(0x50, timeout=1.0) assert not f.fd and f.data == b"\x01\x02" can.write(0x51, bytes(20), brs=False) # FD at the nominal rate - f = can.expect(can_id=0x51, timeout=1.0) + f = can.expect(0x51, timeout=1.0) assert f.fd and not f.brs and len(f.data) == 20 can.add_responder(0x7DF, 0x7E8, bytes(range(64))) can.write(0x7DF, [2, 1, 0x0C]) - f = can.expect(can_id=0x7E8, timeout=1.0) + f = can.expect(0x7E8, timeout=1.0) assert f.fd and f.data == bytes(range(64)) for i in range(12): # more than one can_read reply holds can.write(0x300 + i, bytes([i]) * 64) diff --git a/packages/embeddedci/tests/examples/test_can_ecu_demo.py b/packages/embeddedci/tests/examples/test_can_ecu_demo.py index 78a475a..ef25922 100644 --- a/packages/embeddedci/tests/examples/test_can_ecu_demo.py +++ b/packages/embeddedci/tests/examples/test_can_ecu_demo.py @@ -71,11 +71,11 @@ def test_pod_simulates_an_ecu(benchpod: BenchPod): # Stand in for the DUT issuing the request (in loopback this echoes to RX, # which triggers the responder). On a real bus the DUT sends this. can.write(0x7DF, [0x03, 0x22, 0x01, 0x00]) - reply = can.expect(can_id=0x7E8, timeout=1.0) + reply = can.expect(0x7E8, timeout=1.0) assert reply.data == b"\x62\x01\x00\x2a" can.write(0x123, [0x01]) - assert can.expect(can_id=0x124, timeout=1.0).data == b"\xaa\xbb" + assert can.expect(0x124, timeout=1.0).data == b"\xaa\xbb" # The firmware counts how many auto-replies it emitted. assert can.status()["responder_hits"] >= 2 @@ -101,7 +101,7 @@ def test_frame_timestamps_track_elapsed_time(benchpod: BenchPod): with benchpod.open_can(bitrate=500_000, mode="internal") as can: def stamp(): can.write(0x100, [0x01]) - return can.expect(can_id=0x100, timeout=1.0).ts + return can.expect(0x100, timeout=1.0).ts a, b, c = stamp(), stamp(), stamp() # back-to-back (overhead only) time.sleep(0.3) @@ -130,7 +130,7 @@ def test_observe_real_dut(benchpod: BenchPod): # 2. Request/response: stimulate the DUT and assert its reply. can.write(0x7DF, [0x02, 0x10, 0x03]) - reply = can.expect(can_id=0x7E8, timeout=0.5) + reply = can.expect(0x7E8, timeout=0.5) assert reply.data[0] == 0x50 # 3. The link should be healthy (a lone/ miswired node goes bus-off). diff --git a/packages/embeddedci/tests/examples/test_can_loopback_hil.py b/packages/embeddedci/tests/examples/test_can_loopback_hil.py index efeb1c0..751ebfa 100644 --- a/packages/embeddedci/tests/examples/test_can_loopback_hil.py +++ b/packages/embeddedci/tests/examples/test_can_loopback_hil.py @@ -38,9 +38,9 @@ def test_can_internal_loopback_roundtrip(benchpod: BenchPod): can.write(0x123, [0xDE, 0xAD, 0xBE, 0xEF]) can.write(0x7A5, [0x01], ext=False) - f1 = can.expect(can_id=0x123, timeout=1.0) + f1 = can.expect(0x123, timeout=1.0) assert f1.data == b"\xde\xad\xbe\xef" - f2 = can.expect(can_id=0x7A5, timeout=1.0) + f2 = can.expect(0x7A5, timeout=1.0) assert f2.data == b"\x01" st = can.status() @@ -53,7 +53,7 @@ def test_can_extended_id_loopback(benchpod: BenchPod): _requires_can(benchpod) with benchpod.open_can(mode="internal") as can: can.write(0x18FF50E5, [0x11, 0x22], ext=True) - f = can.expect(can_id=0x18FF50E5, timeout=1.0) + f = can.expect(0x18FF50E5, timeout=1.0) assert f.ext and f.data == b"\x11\x22" @@ -63,7 +63,7 @@ def test_can_external_loopback_roundtrip(benchpod: BenchPod): _requires_can(benchpod) with benchpod.open_can(bitrate=500_000, mode="external", term=True) as can: can.write(0x2AB, [0xC0, 0xFF, 0xEE]) - f = can.read_until(can_id=0x2AB, timeout=1.0) + f = can.read_until(0x2AB, timeout=1.0) if f is None: st = can.status() pytest.skip(f"external loopback did not echo (tec={st['tec']} " diff --git a/packages/embeddedci/tests/test_can.py b/packages/embeddedci/tests/test_can.py index 6782e65..aa12086 100644 --- a/packages/embeddedci/tests/test_can.py +++ b/packages/embeddedci/tests/test_can.py @@ -205,7 +205,7 @@ def test_can_term_toggle(bp, pod): def test_open_can_loopback_roundtrip(bp): with bp.open_can(bitrate=500_000, mode="internal") as can: can.write(0x123, [0xDE, 0xAD]) - frame = can.expect(can_id=0x123, timeout=1.0) + frame = can.expect(0x123, timeout=1.0) assert frame.data == b"\xde\xad" assert frame.id == 0x123 @@ -221,7 +221,7 @@ def test_open_can_expect_predicate(bp): def test_open_can_expect_times_out(bp): with bp.open_can(mode="internal") as can: with pytest.raises(CanTimeout): - can.expect(can_id=0x7FF, timeout=0.1) + can.expect(0x7FF, timeout=0.1) def test_open_can_disables_on_exit(bp, pod): @@ -253,8 +253,8 @@ def test_read_until_does_not_drop_other_frames(bp): can.write(0x111, [1]) can.write(0x222, [2]) # Ask for the SECOND id first; the first must not be lost. - assert can.expect(can_id=0x222, timeout=1.0).id == 0x222 - assert can.expect(can_id=0x111, timeout=1.0).id == 0x111 + assert can.expect(0x222, timeout=1.0).id == 0x222 + assert can.expect(0x111, timeout=1.0).id == 0x111 # -- autonomous responder (ECU simulation) ---------------------------------- @@ -263,7 +263,7 @@ def test_responder_roundtrip(bp, pod): with bp.open_can(mode="internal") as can: can.add_responder(0x7DF, 0x7E8, [0x50, 0x03]) can.write(0x7DF, [0x02, 0x10, 0x03]) # request - reply = can.expect(can_id=0x7E8, timeout=1.0) # firmware auto-reply + reply = can.expect(0x7E8, timeout=1.0) # firmware auto-reply assert reply.data == b"\x50\x03" assert pod._resp_hits == 1 assert can.status()["responder_rules"] == 1 @@ -274,8 +274,8 @@ def test_simulate_ecu_table(bp): can.simulate_ecu({0x100: (0x200, [0xAB]), 0x300: [0xCD]}) # 0x300 -> 0x301 can.write(0x100, [0]) can.write(0x300, [0]) - assert can.expect(can_id=0x200, timeout=1.0).data == b"\xab" - assert can.expect(can_id=0x301, timeout=1.0).data == b"\xcd" + assert can.expect(0x200, timeout=1.0).data == b"\xab" + assert can.expect(0x301, timeout=1.0).data == b"\xcd" def test_clear_responders(bp, pod): @@ -285,7 +285,7 @@ def test_clear_responders(bp, pod): assert pod._rules == [] can.write(0x1, [0]) with pytest.raises(CanTimeout): - can.expect(can_id=0x2, timeout=0.1) + can.expect(0x2, timeout=0.1) # -- timing helpers --------------------------------------------------------- @@ -373,11 +373,11 @@ def test_open_can_fd_loopback_64_bytes(bp): with bp.open_can(bitrate=500_000, data_bitrate=2_000_000, mode="internal") as can: assert can.fd and can.data_bitrate == 2_000_000 can.write(0x123, bytes(range(64))) - f = can.expect(can_id=0x123, timeout=1.0) + f = can.expect(0x123, timeout=1.0) assert f.fd and f.brs and f.data == bytes(range(64)) assert "FD+BRS" in str(f) can.write(0x124, [1, 2], fd=False) - g = can.expect(can_id=0x124, timeout=1.0) + g = can.expect(0x124, timeout=1.0) assert not g.fd and g.data == b"\x01\x02" diff --git a/packages/embeddedci/tests/test_connection.py b/packages/embeddedci/tests/test_connection.py index 20643df..fd9473b 100644 --- a/packages/embeddedci/tests/test_connection.py +++ b/packages/embeddedci/tests/test_connection.py @@ -17,7 +17,6 @@ ("[fe80::1]", "tcp", "[fe80::1]:8443", ""), ("/dev/ttyACM0", "serial", "", "/dev/ttyACM0"), ("COM3", "serial", "", "COM3"), - ("serial", "serial", "", ""), ("USB", "serial", "", ""), ], ) @@ -64,7 +63,7 @@ def test_resolve_prefers_explicit_over_env(monkeypatch): def test_resolve_falls_back_to_env(monkeypatch): - monkeypatch.setenv(ENV_VAR, "serial") + monkeypatch.setenv(ENV_VAR, "usb") spec = resolve_connection() assert spec.is_serial() @@ -149,3 +148,8 @@ def test_constant_coercion(): with pytest.raises(ValueError): constants.coerce_pin(15, "swdio") assert not issubclass(ValueError, BenchPodError) + + +def test_the_serial_alias_is_gone(): + """embeddedci 4.0: "usb" only; "serial" is a host name like any other.""" + assert parse_connection("serial").kind == "tcp" diff --git a/packages/embeddedci/tests/test_one_source.py b/packages/embeddedci/tests/test_one_source.py index 0c50c3f..0d0c9ef 100644 --- a/packages/embeddedci/tests/test_one_source.py +++ b/packages/embeddedci/tests/test_one_source.py @@ -63,8 +63,8 @@ def test_saved_connection_reads_the_cli_config(tmp_path): _save_config(tmp_path, {"connection": " 192.168.1.220 ", "last_serial": "/dev/x"}) assert cli_config.saved_connection() == "192.168.1.220" assert cli_config.config_path() == tmp_path / "xdg" / "benchpod-cli" / "config.json" - _save_config(tmp_path, {"bench_pod_addr": "10.0.0.5:8080"}) # the legacy field - assert cli_config.saved_connection() == "10.0.0.5:8080" + _save_config(tmp_path, {"bench_pod_addr": "10.0.0.5:8080"}) # the legacy field: gone in 4.0 + assert cli_config.saved_connection() is None _save_config(tmp_path, {"connection": "usb", "bench_pod_addr": "10.0.0.5"}) assert cli_config.saved_connection() == "usb" diff --git a/packages/embeddedci/tests/test_pull_direction.py b/packages/embeddedci/tests/test_pull_direction.py index 2f548fa..99271ca 100644 --- a/packages/embeddedci/tests/test_pull_direction.py +++ b/packages/embeddedci/tests/test_pull_direction.py @@ -1,6 +1,5 @@ -"""Pull resistors by direction (``set_pull(la, "up"|"down"|"off")``, firmware feature -``la_pull_dir``): what the SDK sends to new firmware, the ``pullup`` fallback for older firmware, -the refusals (BP0023 / BP0024) and the wiring profile's ``pulls`` map (firmware +"""Pull resistors by direction (``set_pull(la, "up"|"down"|"off")``, the ``la_pull`` command): +what the SDK sends, the refusals (BP0023 / BP0024) and the wiring profile's ``pulls`` map (firmware command_handler_pins.c handle_la, la_pins.c s_pulls_v3).""" from __future__ import annotations @@ -72,7 +71,7 @@ def test_new_firmware_gets_the_direction(): assert st.ohms == "4.7k" st = bp.set_pull(7, "down") assert pod.sent[-1] == {"cmd": "la_pull", "la": 7, "pull": "down"} and st.state == "down" - for off in ("off", None, False): + for off in ("off", None): st = bp.set_pull(7, off) assert pod.sent[-1] == {"cmd": "la_pull", "la": 7, "pull": "off"} and st.state == "off" assert not st.enabled and st.direction == "down" @@ -95,14 +94,17 @@ def test_new_firmware_refusals_carry_the_code(): assert st.direction is None and st.ohms == "" and st.state == "off" -def test_true_false_and_enabled_still_work(): +def test_the_boolean_form_is_gone(): + """embeddedci 4.0: set_pull takes a direction only (no True/False, no enabled=).""" bp, pod = _bp(3) - assert bp.set_pull(8, True).state == "down" # True = the channel's own direction - assert pod.sent[-1] == {"cmd": "la_pull", "la": 8, "pull": "down"} - assert bp.set_pull(2, enabled=True).state == "up" - assert bp.set_pull(2, enabled=False).state == "off" - with pytest.raises(TypeError, match="needs pull"): - bp.set_pull(2) + for bad in (True, False): + with pytest.raises(TypeError, match="boolean form is gone"): + bp.set_pull(8, bad) # type: ignore[arg-type] + with pytest.raises(TypeError): + bp.set_pull(2, enabled=True) # type: ignore[call-arg] + with pytest.raises(TypeError): + bp.set_pull(2) # type: ignore[call-arg] + assert pod.sent == [] with pytest.raises(ValueError, match="pull"): bp.set_pull(2, "sideways") # type: ignore[arg-type] diff --git a/packages/embeddedci/tests/test_upload_build.py b/packages/embeddedci/tests/test_upload_build.py index 8d0d8f7..5d15dd0 100644 --- a/packages/embeddedci/tests/test_upload_build.py +++ b/packages/embeddedci/tests/test_upload_build.py @@ -183,3 +183,13 @@ def test_main_allow_missing_token_succeeds_without_a_session(tmp_path, monkeypat class _NoopReporter: active = False build_id = None + + +def test_reset_is_a_flag_only(): + """embeddedci 4.0: the old LA channel number for reset is refused.""" + import pytest + + assert upload_build._optional_flag("true") is True and upload_build._optional_flag("") is None + assert upload_build._optional_flag("0") is False + with pytest.raises(ValueError, match="true or false"): + upload_build._optional_flag("7") diff --git a/packages/embeddedci/tests/test_usb_net.py b/packages/embeddedci/tests/test_usb_net.py index 7d32cb0..709f497 100644 --- a/packages/embeddedci/tests/test_usb_net.py +++ b/packages/embeddedci/tests/test_usb_net.py @@ -138,12 +138,6 @@ def test_usb_name_selects_the_pod_and_upgrades(usb): assert FakeConsole.instances[0].pod == "baea06" # the console was auto-detected by name -def test_serial_keyword_also_upgrades(usb): - usb["status"] = {"device": "benchpod", - "usb": {"net": True, "link": True, "ip": "10.237.8.85", "host_ip": "10.237.8.86"}} - assert isinstance(open_transport(parse_connection("serial")), TcpTransport) - - @pytest.mark.parametrize("line", [USB_WIFI, USB_DOWN]) def test_usb_falls_back_to_the_pods_network_address(usb, line, caplog): """USB networking off or down: the console answers status only, so the way in is the pod's diff --git a/packages/embeddedci/tests/test_wiring.py b/packages/embeddedci/tests/test_wiring.py index 2cdbfad..0755877 100644 --- a/packages/embeddedci/tests/test_wiring.py +++ b/packages/embeddedci/tests/test_wiring.py @@ -10,7 +10,7 @@ import pytest from embeddedci.benchpod import BenchPod, Signal, Wiring -from embeddedci.benchpod.wiring import DEFAULT_PINS, REFERENCE_BENCH, ROLE_KEYS +from embeddedci.benchpod.wiring import DEFAULT_PINS, ROLE_KEYS def test_nothing_is_wired_by_default(): @@ -25,9 +25,10 @@ def test_the_default_preset_is_the_old_default_pins(): w = Wiring.preset("embeddedci-default") 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 == "preset" and w.warnings() == [] and Wiring.defaults() == w - assert Wiring.preset() == w and Wiring.preset("embeddedci-reference") == w # the old name - assert DEFAULT_PINS is REFERENCE_BENCH + assert w.source == "preset" and w.warnings() == [] + assert Wiring.preset() == w and not hasattr(Wiring, "defaults") + with pytest.raises(ValueError, match="no wiring preset"): + Wiring.preset("embeddedci-reference") # the old name is gone in 4.0 with pytest.raises(ValueError, match="no wiring preset"): Wiring.preset("nope") From 0d5560b6bf0f98d1ef1687973b560435a79d51c5 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 06:51:17 -0600 Subject: [PATCH 06/10] openhtf and MCP need embeddedci 4.0; examples connect without :8080 Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/pyproject.toml | 2 +- packages/embeddedci-openhtf/CHANGELOG.md | 6 ++++++ packages/embeddedci-openhtf/README.md | 16 ++++++++-------- .../examples/analog_loopback.py | 2 +- .../examples/flash_and_boot.py | 2 +- packages/embeddedci-openhtf/examples/station.py | 2 +- packages/embeddedci-openhtf/pyproject.toml | 2 +- .../src/embeddedci_openhtf/__init__.py | 2 +- .../src/embeddedci_openhtf/analog.py | 2 +- .../src/embeddedci_openhtf/measurements.py | 2 +- .../src/embeddedci_openhtf/phases.py | 2 +- .../src/embeddedci_openhtf/plug.py | 6 +++--- 12 files changed, 26 insertions(+), 20 deletions(-) diff --git a/packages/embeddedci-mcp/pyproject.toml b/packages/embeddedci-mcp/pyproject.toml index ad8e81c..458b68e 100644 --- a/packages/embeddedci-mcp/pyproject.toml +++ b/packages/embeddedci-mcp/pyproject.toml @@ -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]>=3.0.5,<4", + "embeddedci[cloud,discovery,analysis,yaml]>=4.0.0,<5", "mcp>=1.12,<2", "anyio>=4", "pydantic>=2.7", diff --git a/packages/embeddedci-openhtf/CHANGELOG.md b/packages/embeddedci-openhtf/CHANGELOG.md index 1bfa7bd..289fcf6 100644 --- a/packages/embeddedci-openhtf/CHANGELOG.md +++ b/packages/embeddedci-openhtf/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog — `embeddedci-openhtf` +## Unreleased + +- Needs embeddedci 4.0 (`embeddedci>=4.0.0,<5`), so BenchPod firmware 4.0: a pod with firmware 3.x + fails the plug's setup with `FirmwareTooOldError`. The examples connect without `:8080` (TLS on + 8443 by default). + ## 2.4.0 - Needs embeddedci 3.0: wiring profiles live on the pod and nothing is wired by default. A plug diff --git a/packages/embeddedci-openhtf/README.md b/packages/embeddedci-openhtf/README.md index 4724db9..1e5a4dc 100644 --- a/packages/embeddedci-openhtf/README.md +++ b/packages/embeddedci-openhtf/README.md @@ -39,7 +39,7 @@ from embeddedci_openhtf import benchpod_plug # TCP — or benchpod_plug("/dev/ttyACM0"). Bind it once per station; la_voltage is the DUT's # I/O voltage — change it to 1.8 for a 1V8 board. -bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3) +bench = benchpod_plug("192.168.1.50", la_voltage=3.3) @htf.plug(bench=bench) def power_up(test, bench): @@ -52,7 +52,7 @@ Connection forms (all **direct**, never cloud): | Form | Example | | --- | --- | -| TCP `host[:port]` | `benchpod_plug("192.168.1.50:8080")` | +| TCP `host[:port]` | `benchpod_plug("192.168.1.50")` | | USB, auto-detected | `benchpod_plug("usb")` (the pod's USB network adapter on firmware 3.9.0+, else its console) | | Serial device path | `benchpod_plug("/dev/ttyACM0")` / `benchpod_plug("COM5")` (the console only) | | `BENCHPOD_CONNECTION` env | `benchpod_plug()` (unbound) | @@ -68,7 +68,7 @@ on which LA channel. Pass it to the plug — a dict, a path to a `.json` / `.tom `Wiring` — and it reaches `BenchPod(wiring=...)`: ```python -bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3, wiring="bench.json") +bench = benchpod_plug("192.168.1.50", la_voltage=3.3, wiring="bench.json") ``` Every channel, baud, power rail and SWD argument a helper or phase leaves out then comes from the @@ -120,7 +120,7 @@ Ready-made, fully-decorated phases for the common steps: import openhtf as htf from embeddedci_openhtf import benchpod_plug, boot_banner_phase, flash_phase, power_phase -bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3) +bench = benchpod_plug("192.168.1.50", la_voltage=3.3) test = htf.Test( power_phase(bench, on=True), @@ -188,7 +188,7 @@ from embeddedci_openhtf import ( loopback_measure_phase, signal_generate_phase, ) -bench = benchpod_plug("192.168.1.50:8080") +bench = benchpod_plug("192.168.1.50") test = htf.Test( # drive a 1 V-peak sine centered on 2.5 V (5V DAC path), capture the front ADC SMA @@ -258,7 +258,7 @@ the seconds between an edge on one channel and the next edge on another. import openhtf as htf from embeddedci_openhtf import benchpod_plug, gpio_phase, la_delay_phase, release_gpio -bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3, wiring="bench.json") +bench = benchpod_plug("192.168.1.50", la_voltage=3.3, wiring="bench.json") test = htf.Test( gpio_phase(bench, la="TRIGGER", mode="output", level=0), @@ -302,7 +302,7 @@ import openhtf as htf from embeddedci_openhtf import adc_capture, benchpod_plug, signal_generate @htf.measures(htf.Measurement("ripple_v").in_range(0.0, 0.05).with_units("V")) -@htf.plug(bench=benchpod_plug("192.168.1.50:8080")) +@htf.plug(bench=benchpod_plug("192.168.1.50")) def ripple_under_load(test, bench): with signal_generate(bench, waveform="square", freq_hz=10, amplitude=2.0, dac_path="5v"): cap = adc_capture(bench, 8192, sample_rate_hz=20_000, source="ext") @@ -326,7 +326,7 @@ from embeddedci_openhtf import ( benchpod_plug, boot_banner_phase, close_persistent_benchpods, power_phase, ) -bench = benchpod_plug("192.168.1.50:8080", persistent=True, la_voltage=3.3) +bench = benchpod_plug("192.168.1.50", persistent=True, la_voltage=3.3) test = htf.Test(power_phase(bench, on=True), boot_banner_phase(bench, rx=1, tx=2, expect="APP_OK")) try: diff --git a/packages/embeddedci-openhtf/examples/analog_loopback.py b/packages/embeddedci-openhtf/examples/analog_loopback.py index e8be07c..73532f2 100644 --- a/packages/embeddedci-openhtf/examples/analog_loopback.py +++ b/packages/embeddedci-openhtf/examples/analog_loopback.py @@ -9,7 +9,7 @@ filter/amplifier whose response you want to check). pip install embeddedci-openhtf - python analog_loopback.py --pod 192.168.1.50:8080 + python analog_loopback.py --pod 192.168.1.50 Units follow the embeddedci SDK: amplitude/offset/limits in volts, durations in seconds, frequencies and sample rates in hertz. diff --git a/packages/embeddedci-openhtf/examples/flash_and_boot.py b/packages/embeddedci-openhtf/examples/flash_and_boot.py index 65d2685..2d94906 100644 --- a/packages/embeddedci-openhtf/examples/flash_and_boot.py +++ b/packages/embeddedci-openhtf/examples/flash_and_boot.py @@ -5,7 +5,7 @@ Run it against a pod on your LAN:: pip install embeddedci-openhtf - python flash_and_boot.py --pod 192.168.1.50:8080 --firmware fw.elf + python flash_and_boot.py --pod 192.168.1.50 --firmware fw.elf Needs `openocd` on PATH (the pod is the CMSIS-DAP probe; OpenOCD drives the flash algorithm). The bench wiring below — which LA channel carries SWCLK/SWDIO and the diff --git a/packages/embeddedci-openhtf/examples/station.py b/packages/embeddedci-openhtf/examples/station.py index 564c20f..3102c4f 100644 --- a/packages/embeddedci-openhtf/examples/station.py +++ b/packages/embeddedci-openhtf/examples/station.py @@ -9,7 +9,7 @@ with ``close_persistent_benchpods()``. pip install embeddedci-openhtf - python station.py --pod 192.168.1.50:8080 + python station.py --pod 192.168.1.50 # enter each board's serial number when prompted; Ctrl-C to stop The pod connection stays up for the whole session; only the per-DUT test phases diff --git a/packages/embeddedci-openhtf/pyproject.toml b/packages/embeddedci-openhtf/pyproject.toml index 6460d1a..f07104b 100644 --- a/packages/embeddedci-openhtf/pyproject.toml +++ b/packages/embeddedci-openhtf/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ "Topic :: Software Development :: Testing", ] dependencies = [ - "embeddedci>=3.0.0,<4", + "embeddedci>=4.0.0,<5", "openhtf>=1.6", ] diff --git a/packages/embeddedci-openhtf/src/embeddedci_openhtf/__init__.py b/packages/embeddedci-openhtf/src/embeddedci_openhtf/__init__.py index 9e7e192..8f9cc47 100644 --- a/packages/embeddedci-openhtf/src/embeddedci_openhtf/__init__.py +++ b/packages/embeddedci-openhtf/src/embeddedci_openhtf/__init__.py @@ -8,7 +8,7 @@ import openhtf as htf from embeddedci_openhtf import benchpod_plug, flash_phase, boot_banner_phase - bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3) # or "/dev/ttyACM0" + bench = benchpod_plug("192.168.1.50", la_voltage=3.3) # or "/dev/ttyACM0" test = htf.Test( flash_phase(bench, file="fw.elf", target="target/stm32f4x.cfg", diff --git a/packages/embeddedci-openhtf/src/embeddedci_openhtf/analog.py b/packages/embeddedci-openhtf/src/embeddedci_openhtf/analog.py index 6c3e92a..840702b 100644 --- a/packages/embeddedci-openhtf/src/embeddedci_openhtf/analog.py +++ b/packages/embeddedci-openhtf/src/embeddedci_openhtf/analog.py @@ -15,7 +15,7 @@ *or* a :class:`~embeddedci_openhtf.BenchPodPlug` (the plug proxies the SDK methods), so inside a phase you can pass the injected ``bench`` straight through:: - @htf.plug(bench=benchpod_plug("192.168.1.50:8080")) + @htf.plug(bench=benchpod_plug("192.168.1.50")) def stim(test, bench): signal_generate(bench, waveform="sine", freq_hz=1000, amplitude=1.0) # 1 V peak on 5V path diff --git a/packages/embeddedci-openhtf/src/embeddedci_openhtf/measurements.py b/packages/embeddedci-openhtf/src/embeddedci_openhtf/measurements.py index b8fad6d..6062e7b 100644 --- a/packages/embeddedci-openhtf/src/embeddedci_openhtf/measurements.py +++ b/packages/embeddedci-openhtf/src/embeddedci_openhtf/measurements.py @@ -7,7 +7,7 @@ hand-roll the boilerplate: @htf.measures(flash_ok_measurement()) - @htf.plug(bench=benchpod_plug("192.168.1.50:8080")) + @htf.plug(bench=benchpod_plug("192.168.1.50")) def flash(test, bench): result = bench.flash(file="fw.elf", target="target/stm32f4x.cfg", swclk=11, swdio=12, nreset=True, check=False) diff --git a/packages/embeddedci-openhtf/src/embeddedci_openhtf/phases.py b/packages/embeddedci-openhtf/src/embeddedci_openhtf/phases.py index 4c18437..45fbdc1 100644 --- a/packages/embeddedci-openhtf/src/embeddedci_openhtf/phases.py +++ b/packages/embeddedci-openhtf/src/embeddedci_openhtf/phases.py @@ -7,7 +7,7 @@ from embeddedci_openhtf import benchpod_plug, flash_phase, boot_banner_phase # direct TCP, no cloud; the LA bank voltage must be set before flashing / UART - bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3) + bench = benchpod_plug("192.168.1.50", la_voltage=3.3) test = htf.Test( flash_phase(bench, file="fw.elf", target="target/stm32f4x.cfg", diff --git a/packages/embeddedci-openhtf/src/embeddedci_openhtf/plug.py b/packages/embeddedci-openhtf/src/embeddedci_openhtf/plug.py index 2368be2..ab14457 100644 --- a/packages/embeddedci-openhtf/src/embeddedci_openhtf/plug.py +++ b/packages/embeddedci-openhtf/src/embeddedci_openhtf/plug.py @@ -13,7 +13,7 @@ import openhtf as htf from embeddedci_openhtf import benchpod_plug - @htf.plug(bench=benchpod_plug("192.168.1.50:8080", la_voltage=3.3)) + @htf.plug(bench=benchpod_plug("192.168.1.50", la_voltage=3.3)) def power_up(test, bench): bench.power_on() # methods proxy to the BenchPod SDK status = bench.pod.target_status() # or reach the full client via .pod @@ -35,7 +35,7 @@ def power_up(test, bench): channels, baud, power rail and SWD target every helper and phase leaves out, and names work wherever a channel does:: - bench = benchpod_plug("192.168.1.50:8080", la_voltage=3.3, wiring="bench.json") + bench = benchpod_plug("192.168.1.50", la_voltage=3.3, wiring="bench.json") @htf.plug(bench=bench) def run(test, bench): @@ -277,7 +277,7 @@ def benchpod_plug(connection: Optional[str] = None, *, persistent: bool = False, Ergonomic for direct bench use — put the pod's address right in the test:: - @htf.plug(bench=benchpod_plug("192.168.1.50:8080", la_voltage=3.3)) + @htf.plug(bench=benchpod_plug("192.168.1.50", la_voltage=3.3)) def phase(test, bench): ... @htf.plug(bench=benchpod_plug("/dev/ttyACM0")) From 9572761b9d50dc9c3bff54f1c6e2572a421b0538 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 06:53:56 -0600 Subject: [PATCH 07/10] Error catalog from benchpod-firmware 4.0 (MCP hints: set_pull(la=...)) Co-Authored-By: Claude Opus 5.5 --- .../embeddedci/src/embeddedci/benchpod/error_catalog.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json index 68567af..5067f29 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json +++ b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "ceaaf830950d2109f3322d4045471f1677c40d668f98ffa875c9343780b49769", + "catalog_sha256": "8f18331e99506bc37019f0613a1361febb68316d985bbcb04e1ab7343071dc83", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -377,7 +377,7 @@ "fix": { "sdk": "use bp.set_pull({la}, \"{have}\"), or pick a channel that pulls {want} (bp.la_pins() shows them)", "cli": "use `benchpod la pull {la} {have}`, or pick a channel that pulls {want} (`benchpod la pins` shows them)", - "mcp": "call set_pull(las=[{la}], pull=\"{have}\"), or pick a channel that pulls {want} (pull_status shows them)", + "mcp": "call set_pull(la=[{la}], pull=\"{have}\"), or pick a channel that pulls {want} (pull_status shows them)", "web": "LA{la} can only pull {have} on this board. Pick a pin that pulls {want}." } }, @@ -515,7 +515,7 @@ "fix": { "sdk": "switch the pull-down off with bp.set_pull({la}, \"off\"), or use another channel", "cli": "switch the pull-down off with `benchpod la pull {la} off`, or use another channel", - "mcp": "call set_pull(las=[{la}], pull=\"off\"), or use another channel", + "mcp": "call set_pull(la=[{la}], pull=\"off\"), or use another channel", "web": "Switch off LA{la}'s pull-down in the Pins pane, or pick another pin." } }, @@ -986,7 +986,7 @@ "fix": { "sdk": "switch the pull-up on (bp.enable_pullup({la})), or pass pullups=\"external\" when the board has its own", "cli": "pull LA{la} up with `benchpod la pull {la} up`, or pass --pullups external when the board has its own", - "mcp": "call set_pull(las=[{la}], pull=\"up\"), or pass pullups=\"external\" when the board has its own", + "mcp": "call set_pull(la=[{la}], pull=\"up\"), or pass pullups=\"external\" when the board has its own", "web": "Switch on LA{la}'s pull-up, or say the board has its own." } }, From 6f953b5d2fb8b943c1355bb2c0d47cd2320d6df9 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 06:55:11 -0600 Subject: [PATCH 08/10] MCP: the pull-conflict hint and README name set_pull(la=...) Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/README.md | 2 +- packages/embeddedci-mcp/tests/test_refusals.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index 39d38ce..43f6f59 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -455,7 +455,7 @@ capture tools' summaries, `la_timing` and `decode_la` instead. the user for the board's (1.8 or 3.3, 5.0 on a digital v3r4 pod), set it in the profile (set_wiring with la_mv 1800 or 3300, then save_wiring) or call set_la_voltage` and `PinConflictError: uart_proxy_start: pin conflict: LA4 is in use by gpio; release it with gpio_release(la=[4])`. The other pin owners point to `uart_close` and - `sensor_stop`; a pull conflict to `set_pull(las=[7], pull="off")`. + `sensor_stop`; a pull conflict to `set_pull(la=[7], pull="off")`. - **Error codes.** Firmware 3.10.8 and later sends a stable code with a refusal (`BP0009` ...): the error then reads `: : BP0009: ; (docs: https://embeddedci.com/docs/errors#BP0009)`. The code is the stable part to act on, and it also diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index 7c92b8d..7366334 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -86,7 +86,7 @@ def test_pull_conflict_names_set_pull(connected): reason="a released line would read low") msg = _pulse_error() assert "PullConflictError: la_step: BP0032: LA7 has its 10k pull-down on" in msg - assert 'set_pull(las=[7], pull="off")' in msg + assert 'set_pull(la=[7], pull="off")' in msg def test_dac_pinout_mismatch(connected): From a21fd73f2793f3e8323cb91d2baa2a855fc5060f Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 07:39:06 -0600 Subject: [PATCH 09/10] e2e tests follow firmware 4.0; the console checks the version on connect The hardware run of #130 against the 4.0 candidate failed only in e2e tests written for 3.x: set_pull booleans, a refusal text assert (now BP0031 code and fields), the raw measure command (freq_hz, enc dec), the BP0039 trigger edge (the SDK names it start, documented), and the console tier (status and ping only). The USB console now runs the firmware version check on connect like the other transports, and its network-only refusals all say it is a network command. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci/CHANGELOG.md | 3 + .../src/embeddedci/benchpod/client.py | 2 + .../embeddedci/benchpod/transport/serial.py | 8 +-- .../embeddedci/tests/e2e/test_e2e_gpio.py | 6 +- packages/embeddedci/tests/e2e/test_e2e_pod.py | 16 +++--- .../embeddedci/tests/e2e/test_e2e_rev3.py | 14 ++--- packages/embeddedci/tests/e2e/test_e2e_usb.py | 55 ++++++------------- 7 files changed, 43 insertions(+), 61 deletions(-) diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 224bb24..99c5100 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -61,6 +61,9 @@ Pairs with BenchPod firmware 4.0.0 (client API 2). Breaking changes: `PULL_TABLE`); `transport.serial.RP_VID`; the `serial` connection keyword (use `usb`); the CLI config's legacy `bench_pod_addr`; an LA channel number as `upload_build`'s reset input (a flag only); `CanBus.expect(can_id=)` and `read_until(can_id=)` (pass the id as `match`). +- `TriggerTimeout.edge` is `"start"` for an emulated sensor's bus capture (`BP0039`, an I2C START); + it was `"falling"` from the 3.x text. Over the USB console the firmware version is checked on + connect, and a network-only call says it is a network command. - `ModuleInfo.dac_pinout_ok`: `False` when the digital board and the analog module use different flat-cable DAC pinouts (the DAC is off). - Error catalog synced (`BP0031` to `BP0080`); features table revision 11. diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 5c65e0b..4c432d2 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -3568,6 +3568,8 @@ def _auto_pin_directions(self) -> None: try: if type(self._transport).__name__ == "SerialTransport": self.pin_directions_status = "not sent: the USB console has no la_dir" + # connect's client API check: the console announces no level, its version decides + self._check_client_api(Capabilities.from_status(_dict(self._caps_status()))) return # The cached capabilities when there are some; else one status read that is not cached # (the first real use of capabilities reads and caches them as before). It is also diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py index 1399474..d1c3af0 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py @@ -388,10 +388,10 @@ def _send_command(self, line: str) -> str: @staticmethod def _unsupported(what: str) -> str: - return (f"{what!r} is not available over this pod's USB console, which only answers " - "status and ping; connect over the network (host[:port]) or the cloud " - "(embeddedci:) for it. Connection 'usb' reaches the full API over the " - "pod's USB network adapter (off while Wi-Fi is configured on the pod)") + return (f"{what!r} is not on this pod's USB console, which answers status and ping " + "only: it is a network command. Connection 'usb' reaches the full API over the " + "pod's USB network adapter (off while Wi-Fi is configured on the pod); a network " + "address (host[:port]) or the cloud (embeddedci:) works too") def command(self, req: dict) -> Any: """Answer a JSON command through its text-console equivalent: the commands in diff --git a/packages/embeddedci/tests/e2e/test_e2e_gpio.py b/packages/embeddedci/tests/e2e/test_e2e_gpio.py index c15e128..91fcd64 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_gpio.py +++ b/packages/embeddedci/tests/e2e/test_e2e_gpio.py @@ -131,8 +131,6 @@ def test_pull_by_direction(gpio_pod, bench): assert gpio_pod.set_pull(bare, "off").supported == () assert gpio_pod.pull_state(bare).state == "off" assert sorted(gpio_pod.enabled_pulls()) == sorted([up, down]) - assert gpio_pod.set_pull(down, True).state == "down" # the deprecated on/off form - assert gpio_pod.set_pull(down, False).state == "off" finally: gpio_pod.release_gpio(up, down) gpio_pod.set_pull(up, "off") @@ -146,8 +144,8 @@ def test_uart_is_refused_on_a_gpio_pin_until_released(gpio_pod, bench): gpio_pod.gpio(tx) with pytest.raises(PinConflictError) as ei: gpio_pod.open_uart(rx=rx, tx=tx) - assert (ei.value.la, ei.value.function) == (tx, "gpio") - assert f"release it with bp.release_gpio({tx})" in str(ei.value) # the SDK's own hint + assert (ei.value.code, ei.value.la, ei.value.function) == ("BP0031", tx, "gpio") + assert ei.value.owner == "gpio" gpio_pod.release_gpio(tx) with gpio_pod.open_uart(rx=rx, tx=tx): assert {_function(gpio_pod, rx).function, _function(gpio_pod, tx).function} == {"uart_rx", "uart_tx"} diff --git a/packages/embeddedci/tests/e2e/test_e2e_pod.py b/packages/embeddedci/tests/e2e/test_e2e_pod.py index 3c6a8b6..dc7cd79 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_pod.py +++ b/packages/embeddedci/tests/e2e/test_e2e_pod.py @@ -569,8 +569,8 @@ def _measure(pod, waveform: str, samples: int): """Volts of one firmware ``measure``: one DAC period of ``samples`` points, captured by the ADC phase-locked to it. The SDK does not wrap it, so this goes through the raw command.""" np = pytest.importorskip("numpy") - counts = pod.command({"cmd": "measure", "waveform": waveform, "freq": 1000, - "samples": samples}) + counts = pod.command({"cmd": "measure", "waveform": waveform, "freq_hz": 1000, + "samples": samples, "enc": "dec"}) # decimal: the default is base64 assert len(counts) == samples, (waveform, samples, len(counts)) return np.array([pod.capabilities.counts_to_volts(c) for c in counts]) @@ -995,12 +995,13 @@ def test_bias_resistors_report_their_direction(pod): @FREE_PULL_LA def test_bias_resistors_are_direction_aware(pod, bench): ch = bench.free_pull_la - before = pod.pull_state(ch).enabled + before = pod.pull_state(ch) + flip = "off" if before.enabled else before.supported[0] try: - assert pod.set_pull(ch, not before).enabled == (not before) - assert (ch in pod.enabled_pulls()) == (not before) + assert pod.set_pull(ch, flip).enabled == (not before.enabled) + assert (ch in pod.enabled_pulls()) == (not before.enabled) finally: - pod.set_pull(ch, before) + pod.set_pull(ch, before.state) @pytest.fixture @@ -1042,7 +1043,8 @@ def test_sensor_emulation(pod, sensors, bench): try: txns = s.i2c_transactions(1024, timeout_s=0.5) except TriggerTimeout as exc: - assert exc.la == bench.i2c_sda and exc.edge == "falling", exc + # BP0039: the SDK names the trigger "start" (an I2C START), not an edge. + assert exc.code == "BP0039" and exc.la == bench.i2c_sda and exc.edge == "start", exc assert time.monotonic() - t0 >= 0.4, "the pod gave up before the timeout" else: assert txns, "a triggered sensor capture holds no transaction" diff --git a/packages/embeddedci/tests/e2e/test_e2e_rev3.py b/packages/embeddedci/tests/e2e/test_e2e_rev3.py index c308655..c1f95a1 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_rev3.py +++ b/packages/embeddedci/tests/e2e/test_e2e_rev3.py @@ -48,12 +48,12 @@ def nrst_la(v3, bench): ch = bench.nrst_la if v3.capabilities.la_pins: v3.release_gpio(ch) - before = v3.pull_state(ch).enabled if ch <= 8 else None - if before: - v3.set_pull(ch, False) # the pod's own 10 k pull-up must be what sets the level + before = v3.pull_state(ch).state if ch <= 8 else "off" + if before != "off": + v3.set_pull(ch, "off") # the pod's own 10 k pull-up must be what sets the level yield ch - if before: - v3.set_pull(ch, True) + if before != "off": + v3.set_pull(ch, before) def _level(pod, ch: int) -> int: @@ -112,7 +112,7 @@ def test_pulls_at_1v8(v3, bench): it on the switch and refuses it at 1.8 V.""" ch = bench.free_pull_la v3.set_la_voltage(3.3) - before = v3.pull_state(ch).enabled + before = v3.pull_state(ch).state try: v3.enable_pullup(ch) v3.set_la_voltage(1.8) @@ -138,7 +138,7 @@ def test_pull_down_at_1v8(v3, bench): if not v3.supports("la_pull_1v8"): pytest.skip("the pod firmware has no pulls at 1.8 V (feature la_pull_1v8)") ch = bench.free_pulldown_la - before = v3.pull_state(ch).enabled + before = v3.pull_state(ch).state try: v3.set_la_voltage(1.8) v3.set_pull(ch, "down") diff --git a/packages/embeddedci/tests/e2e/test_e2e_usb.py b/packages/embeddedci/tests/e2e/test_e2e_usb.py index 42c43d8..2af339b 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_usb.py +++ b/packages/embeddedci/tests/e2e/test_e2e_usb.py @@ -2,9 +2,11 @@ BENCHPOD_E2E_USB=/dev/cu.usbmodem… pytest packages/embeddedci/tests/e2e/test_e2e_usb.py -On the STM32 pod the USB console is a text shell: status and ping work everywhere; LA voltage and -power work on firmware before 3.9.0 and, from 3.9.0 (which moved them to the JSON API), fail with -the hint to use the network; every other operation fails at once with that hint too. +On firmware 4.0 the USB console is a text shell that answers status and ping (and identity); +every other operation, the LA voltage and target power included, fails at once with the hint to +use the network or connection 'usb' (the USB network adapter). The console announces no client API +level, so the SDK checks the firmware version there: firmware 3.x raises FirmwareTooOldError on +connect. """ from __future__ import annotations @@ -14,64 +16,39 @@ import pytest -from embeddedci.benchpod import BenchPod, FirmwareError, TransportError +from embeddedci.benchpod import BenchPod, TransportError # Not marked `hardware`: that gate wants --benchpod-connection, and this tier opens its own # connection from BENCHPOD_E2E_USB (the `usb` fixture skips without it). @pytest.fixture(scope="module") -def usb(benchpod_la_voltage): +def usb(): device = os.environ.get("BENCHPOD_E2E_USB") if not device: pytest.skip("set BENCHPOD_E2E_USB to the pod's USB console (a device path or 'usb')") with BenchPod(device, la_voltage=None, timeout=10) as pod: if type(pod.transport).__name__ != "SerialTransport": - pytest.skip("'usb' reached the pod's USB network adapter (firmware 3.9.0+), not the " - "console; set BENCHPOD_E2E_USB to the console's device path") - if not _moved(pod): - pod.set_la_voltage(benchpod_la_voltage) + pytest.skip("'usb' reached the pod's USB network adapter, not the console; set " + "BENCHPOD_E2E_USB to the console's device path") yield pod -def _moved(pod) -> bool: - """Firmware 3.9.0+ (its console status has a usb line): LA voltage and power are JSON-only.""" - return isinstance(pod.status().get("usb"), dict) - - def test_status_is_a_dict(usb): status = usb.status() assert status["device"] == "benchpod" and status["board"] and status["version"] assert usb.capabilities.board == status["board"] -def test_ping_and_la_voltage(usb): +def test_ping_works_and_the_la_voltage_is_a_network_command(usb): assert usb.ping() - if _moved(usb): - with pytest.raises(TransportError, match="network command"): - usb.get_la_voltage() - return - assert usb.get_la_voltage().voltage == 3.3 - - -def test_1v8_on_a_v2_board(usb): - if _moved(usb) or usb.status().get("board_rev") != "v2": - pytest.skip("rev3 pods accept 1.8 V") - try: - with pytest.raises(FirmwareError, match="v3"): - usb.set_la_voltage(1.8) - finally: - usb.set_la_voltage(3.3) + with pytest.raises(TransportError, match="network command"): + usb.get_la_voltage() -def test_power_off(usb): - if _moved(usb): - with pytest.raises(TransportError, match="network command"): - usb.power_off(1) - return - usb.power_off(1) - with pytest.raises(TransportError, match="delayed"): - usb.power_on(1, delay=0.5) +def test_power_is_a_network_command(usb): + with pytest.raises(TransportError, match="network command"): + usb.power_off(1) @pytest.mark.parametrize("call", [ @@ -83,7 +60,7 @@ def test_power_off(usb): ], ids=["adc_read", "capture_la", "power_status", "dap_start", "uart_proxy"]) def test_network_only_features_fail_fast(usb, call): start = time.monotonic() - with pytest.raises(TransportError, match="network"): + with pytest.raises(TransportError, match="network command"): call(usb) assert time.monotonic() - start < 5 assert usb.status()["device"] == "benchpod" # the console is still healthy From 12a9e14fe1e4ba47626196f83921766a92b818b4 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 07:54:50 -0600 Subject: [PATCH 10/10] embeddedci 4.0.0.dev0 on main until the release; MCP and OpenHTF accept it The MCP and OpenHTF need SDK 4.0, and CI installs them next to the SDK from this tree: a dev version lets that install work before 4.0.0 is published. The release PR sets 4.0.0 and the pins to >=4.0.0. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/pyproject.toml | 2 +- packages/embeddedci-openhtf/pyproject.toml | 2 +- packages/embeddedci/pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/embeddedci-mcp/pyproject.toml b/packages/embeddedci-mcp/pyproject.toml index 458b68e..152127c 100644 --- a/packages/embeddedci-mcp/pyproject.toml +++ b/packages/embeddedci-mcp/pyproject.toml @@ -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]>=4.0.0,<5", + "embeddedci[cloud,discovery,analysis,yaml]>=4.0.0.dev0,<5", "mcp>=1.12,<2", "anyio>=4", "pydantic>=2.7", diff --git a/packages/embeddedci-openhtf/pyproject.toml b/packages/embeddedci-openhtf/pyproject.toml index f07104b..6ee131b 100644 --- a/packages/embeddedci-openhtf/pyproject.toml +++ b/packages/embeddedci-openhtf/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ "Topic :: Software Development :: Testing", ] dependencies = [ - "embeddedci>=4.0.0,<5", + "embeddedci>=4.0.0.dev0,<5", "openhtf>=1.6", ] diff --git a/packages/embeddedci/pyproject.toml b/packages/embeddedci/pyproject.toml index db54568..336505b 100644 --- a/packages/embeddedci/pyproject.toml +++ b/packages/embeddedci/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "embeddedci" -version = "3.0.5" +version = "4.0.0.dev0" description = "BenchPod SDK and pytest plugin for EmbeddedCI hardware-in-the-loop testing" readme = "README.md" requires-python = ">=3.10"