From 06d476aab86bd255d4cce275b06015a3ba97ed82 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 16:50:34 -0600 Subject: [PATCH 1/4] Sync the features table and error catalog (api, min_client_api, BP0030) From benchpod-firmware#191 (client-api-level): features.json gets api 1 and min_client_api 0, the catalog gets BP0030 client_too_old. Co-Authored-By: Claude Opus 5.5 --- .../embeddedci/benchpod/error_catalog.json | 78 ++++++++++++------- .../src/embeddedci/benchpod/feature_map.json | 78 ++++++++++--------- 2 files changed, 91 insertions(+), 65 deletions(-) diff --git a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json index 80fe3a0..9549d8d 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json +++ b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json @@ -1,13 +1,13 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "ef614af22c086dc10994ecb05d7148b8f27cf1483a34bc3309a39e5ef9768550", + "catalog_sha256": "1fdf57bcda663e4e263d034fc81e30b23d565347daafb03b09b5cd7d7e63a332", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { "name": "la_voltage_not_set", "area": "io", - "since": "next", + "since": "3.10.8", "message": "The I/O voltage is not set", "cause": "The pod starts with its I/O voltage unset and never picks one on its own, so it cannot drive a board at a voltage the board does not take. Anything that uses the LA pins (UART, flashing, captures, GPIO, I2C, SPI, sensor emulation) needs it first.", "args": {}, @@ -21,7 +21,7 @@ "BP0002": { "name": "unknown_command", "area": "protocol", - "since": "next", + "since": "3.10.8", "message": "The pod does not know the command {cmd}", "cause": "The firmware on the pod is older than the tool that sent the command, or the command name is wrong. Newer SDK, CLI and MCP versions check the pod's capabilities first and say which firmware a feature needs.", "args": { @@ -37,7 +37,7 @@ "BP0003": { "name": "i2c_session_open", "area": "i2c", - "since": "next", + "since": "3.10.8", "message": "An I2C session is already open", "cause": "The pod runs one I2C master session at a time.", "args": {}, @@ -51,7 +51,7 @@ "BP0004": { "name": "spi_session_open", "area": "spi", - "since": "next", + "since": "3.10.8", "message": "An SPI session is already open", "cause": "The pod runs one SPI master session at a time.", "args": {}, @@ -65,7 +65,7 @@ "BP0005": { "name": "bus_engine_busy", "area": "spi", - "since": "next", + "since": "3.10.8", "message": "The engine that runs SWD, SPI and I2C is in use, so {want} cannot start", "cause": "Flashing (SWD), the SPI master and the I2C master share one engine on the pod. While one of them runs, the other two wait.", "args": { @@ -81,7 +81,7 @@ "BP0006": { "name": "missing_argument", "area": "protocol", - "since": "next", + "since": "3.10.8", "message": "The request is missing {arg}", "cause": "A required value was not sent. The SDK, CLI and MCP always send it, so this usually means a hand-written protocol request or a tool older than the firmware.", "args": { @@ -97,7 +97,7 @@ "BP0007": { "name": "wiring_profile_not_found", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The pod has no wiring profile named {name}", "cause": "Wiring profiles live on the pod. This one was never saved there, was deleted, or was saved on another pod.", "args": { @@ -113,7 +113,7 @@ "BP0008": { "name": "wiring_bad_name", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "{name} is not a valid wiring profile name", "cause": "Profile names are 1 to 40 characters: lowercase letters, digits and dashes, not starting with a dash.", "args": { @@ -129,7 +129,7 @@ "BP0009": { "name": "wiring_revision_conflict", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The wiring profile {name} changed since it was loaded (it is now at revision {rev})", "cause": "Someone saved {name} from another connection (the web app, another script or agent) after this one loaded it. Saving now would overwrite their change, so the pod refuses.", "args": { @@ -146,7 +146,7 @@ "BP0010": { "name": "wiring_store_full", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The pod cannot hold another wiring profile (at most {max}, and 16 KB in all)", "cause": "Wiring profiles live on the pod, in a fixed amount of storage.", "args": { @@ -162,7 +162,7 @@ "BP0011": { "name": "wiring_profile_too_large", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The wiring profile is {bytes} bytes; the pod takes at most {max}", "cause": "One wiring profile fits in {max} bytes of JSON. Long signal descriptions or many signals add up.", "args": { @@ -179,7 +179,7 @@ "BP0012": { "name": "wiring_not_json_object", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The wiring profile is not one JSON object", "cause": "The pod stores a profile as the JSON object the tools send. This one is cut off or not an object, which points at a damaged upload or a hand-written request.", "args": {}, @@ -193,7 +193,7 @@ "BP0013": { "name": "wiring_delete_default", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "{name} is the pod's default wiring profile and cannot be deleted", "cause": "A connection that names no profile uses the default, so the pod always keeps one.", "args": { @@ -209,7 +209,7 @@ "BP0014": { "name": "wiring_upload_out_of_order", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The wiring profile upload skipped ahead (the pod expected offset {expected})", "cause": "Profiles are sent to the pod in pieces, in order, starting at offset 0. A piece went missing or another upload started in between.", "args": { @@ -225,7 +225,7 @@ "BP0015": { "name": "wiring_storage_failed", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The pod could not read or write its wiring profiles", "cause": "The flash chip that holds the profiles did not answer or a write did not verify. Profiles saved before are kept: a write never replaces them until it has been read back.", "args": {}, @@ -239,7 +239,7 @@ "BP0016": { "name": "storage_busy", "area": "wiring", - "since": "next", + "since": "3.10.8", "message": "The pod cannot save now: the DAC or a capture is using the bus the storage shares", "cause": "The flash chip that holds the wiring profiles shares a bus with the DAC replay and the captures. Saving would stop a running waveform, so the pod refuses instead. Reading profiles always works.", "args": {}, @@ -253,7 +253,7 @@ "BP0017": { "name": "gateware_too_old", "area": "firmware", - "since": "next", + "since": "3.10.11", "message": "{feature} needs gateware v{min} or later", "cause": "The pod's FPGA image is older than the feature. Firmware updates bring the matching gateware with them.", "args": { @@ -270,7 +270,7 @@ "BP0018": { "name": "uart_same_pin", "area": "uart", - "since": "next", + "since": "3.10.11", "message": "UART rx and tx are both LA{la}; a one-wire UART needs half_duplex", "cause": "A normal UART drives its TX pin all the time, so it cannot share the pin with RX. In half duplex the pod only pulls the line low and lets the pull-up hold it high, so both sides can talk on one wire.", "args": { @@ -286,7 +286,7 @@ "BP0019": { "name": "uart_half_duplex_two_pins", "area": "uart", - "since": "next", + "since": "3.10.11", "message": "half_duplex runs on one pin, but rx is LA{rx} and tx is LA{tx}", "cause": "In half duplex the pod sends and receives on the same wire, so rx and tx name the same LA channel.", "args": { @@ -303,7 +303,7 @@ "BP0020": { "name": "uart_entry_no_reset_pin", "area": "uart", - "since": "next", + "since": "3.10.11", "message": "The UART entry sequence needs the pod's reset pin, which this board does not have", "cause": "The entry sequence holds the target in reset with the pod's own reset pin while it holds TX low. Pods before v3 have no reset pin.", "args": {}, @@ -317,7 +317,7 @@ "BP0021": { "name": "uart_entry_invalid", "area": "uart", - "since": "next", + "since": "3.10.11", "message": "The UART entry option {arg} is out of range (0 to {max})", "cause": "The entry sequence times are milliseconds, each up to a limit, and the first bytes are at most a few dozen hex bytes.", "args": { @@ -334,7 +334,7 @@ "BP0022": { "name": "uart_de_pin", "area": "uart", - "since": "next", + "since": "3.10.11", "message": "The UART's DE pin LA{la} is also its rx or tx", "cause": "DE switches an RS-485 transceiver between sending and listening, so it is a wire of its own, from an LA channel to the transceiver's DE and /RE pins.", "args": { @@ -350,7 +350,7 @@ "BP0023": { "name": "la_no_pull", "area": "io", - "since": "next", + "since": "3.10.12", "message": "LA{la} has no pull resistor on this board", "cause": "Only some LA channels have a pull resistor the pod can switch, and which ones depends on the board. la_pins lists each channel's pull and the directions it supports.", "args": { @@ -366,7 +366,7 @@ "BP0024": { "name": "la_pull_direction", "area": "io", - "since": "next", + "since": "3.10.12", "message": "LA{la} supports pull-{have} only on this board", "cause": "The pull resistor on LA{la} is wired one way on this board, so it cannot pull {want}. Which way each channel pulls depends on the board; la_pins lists it.", "args": { @@ -384,7 +384,7 @@ "BP0025": { "name": "lease_busy", "area": "lease", - "since": "next", + "since": "3.10.13", "message": "{holder} holds this pod ({purpose}, {left_s} s left)", "cause": "Someone took the pod's lease (a CI run, an SDK or CLI session, or a cloud job). While it is held, only its owners may drive the pod; everyone else may still read status and other light reads. The lease ends when its owner releases it, when it is not renewed in time, or when the pod restarts.", "args": { @@ -402,7 +402,7 @@ "BP0026": { "name": "lease_lost", "area": "lease", - "since": "next", + "since": "3.10.13", "message": "The pod's lease was stopped by {by}", "cause": "This connection or this lease id owned the pod's lease, and {by} stopped it from the web app or the cloud. The command was not run. A connection that owned it hears this once. A command, lease_acquire or lease_renew that carries the stopped lease's id keeps getting it for 30 minutes, so a run that was stopped does not take the pod back; a new id gets a new lease.", "args": { @@ -418,7 +418,7 @@ "BP0027": { "name": "lease_not_held", "area": "lease", - "since": "next", + "since": "3.10.13", "message": "The pod holds no lease with id {id}", "cause": "lease_renew found no lease: it ran out (it was not renewed before its deadline), it was released, or the pod restarted, which clears it. A lease that was stopped answers BP0026 instead.", "args": { @@ -434,7 +434,7 @@ "BP0028": { "name": "vref_5v_missing", "area": "io", - "since": "next", + "since": "3.10.13", "message": "5 V did not come up on pin 21 ({mv} mV)", "cause": "In 5 V mode the pod switches pin 21, the rail every pull-up pulls to, to its USB supply. The pod measures pin 21 and found it below 4.3 V, so it went back to the previous I/O voltage. A weak USB supply, a hub without power, or a load on pin 21 causes it.", "args": { @@ -450,7 +450,7 @@ "BP0029": { "name": "pull_rail_down", "area": "io", - "since": "next", + "since": "3.10.13", "message": "pin 21 is down ({mv} mV): the pull resistors are off until it is back", "cause": "The pull resistors pull up to J1 pin 21. The pod measures pin 21 and found it down, so it holds both pull expanders off (with pin 21 down they would answer on the same address). Pin 21 is shorted, overloaded, or a DUT holds it down.", "args": { @@ -462,6 +462,24 @@ "mcp": "ask the user to check what is wired to J1 pin 21 (set_la_voltage with no voltage shows its state), then set the pull again", "web": "Pin 21 is down, so the pull resistors are off. Check what is wired to pin 21." } + }, + "BP0030": { + "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.", + "args": { + "client_api": "int", + "min_client_api": "int", + "api": "int" + }, + "fix": { + "sdk": "update the SDK (pip install -U embeddedci), then run again", + "cli": "update the CLI (`brew upgrade --cask benchpod`, or the latest release from GitHub), then run the command again", + "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." + } } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json index 7d42158..bbc5dbd 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json +++ b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json @@ -1,8 +1,10 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 7, - "table_sha256": "a6a88ef88c0925212fcfa41f87409572bc0210a9fd02f2f418fc2a50b86eba64", + "revision": 8, + "api": 1, + "min_client_api": 0, + "table_sha256": "02f6411c240dcbc0cedda72648ba8713eb498a9a878ecca7f9fc817a3da586b2", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -140,35 +142,35 @@ "firmware": "3.9.2", "board": "any", "legacy_caps": "gpio", - "docs": "API.md#gpio" + "docs": "API.md#gpio--use-la-pins-as-gpio" }, "power": { "rev": 1, "firmware": "3.9.2", "board": "any", "legacy_caps": "power", - "docs": "API.md#power" + "docs": "API.md#target_power--enabledisable-a-target-power-efuse" }, "swd": { "rev": 1, "firmware": "3.9.2", "board": "any", "legacy_caps": "swd", - "docs": "API.md#swd" + "docs": "dap-over-tunnel.md" }, "uart": { "rev": 1, "firmware": "3.9.2", "board": "any", "legacy_caps": "uart", - "docs": "API.md#uart_proxy_start" + "docs": "API.md#uart_proxy_start--transparent-uart-bridge" }, "la": { "rev": 1, "firmware": "3.9.2", "board": "any", "legacy_caps": "la", - "docs": "API.md#la_capture" + "docs": "API.md#la_capture--deep-raw-logic-analyzer-capture" }, "analyzer": { "rev": 1, @@ -197,7 +199,7 @@ "board": "any", "legacy_caps": "ota", "legacy_frame": "ota", - "docs": "API.md#ota_begin" + "docs": "API.md#firmware-and-blob-updates-ota" }, "la_pins": { "rev": 1, @@ -205,7 +207,7 @@ "board": "any", "legacy_caps": "la_pins", "legacy_frame": "la_pins", - "docs": "API.md#la_pins" + "docs": "API.md#la_pins--report-every-la-pin" }, "power_profile": { "rev": 1, @@ -213,7 +215,7 @@ "board": "any", "legacy_caps": "power_profile", "legacy_frame": "power_profile", - "docs": "API.md#power_profile" + "docs": "API.md#power_profile--record-a-rail-current-profile" }, "capture_b64": { "rev": 1, @@ -221,7 +223,7 @@ "board": "any", "legacy_caps": "capture_b64", "legacy_frame": "capture_b64", - "docs": "API.md#capture" + "docs": "API.md#base64-samples-encb64" }, "blob_slots": { "rev": 1, @@ -235,7 +237,7 @@ "board": "any", "legacy_caps": "can", "legacy_frame": "can", - "docs": "API.md#can_config" + "docs": "API.md#can_config--bring-can-up" }, "ota_sig": { "rev": 1, @@ -290,14 +292,14 @@ "firmware": "3.9.2", "board": "any", "legacy_caps": "usb_net", - "docs": "API.md#usb_network" + "docs": "API.md#usb_network--the-usb-network-adapter-on-or-off" }, "usb_net_setting": { "rev": 1, "firmware": "3.9.2", "board": "any", "legacy_caps": "usb_net_setting", - "docs": "API.md#usb_network" + "docs": "API.md#usb_network--the-usb-network-adapter-on-or-off" }, "lan_tls": { "rev": 1, @@ -324,7 +326,7 @@ "board": "any", "legacy_caps": "sensors", "legacy_frame": "sensors", - "docs": "API.md#sensor_define" + "docs": "API.md#emulated-sensors" }, "sensors_format_1": { "rev": 1, @@ -337,7 +339,7 @@ "firmware": "3.10.4", "board": "any", "legacy_caps": "sensor_la_trigger", - "docs": "API.md#sensor_la" + "docs": "API.md#sensor_la--raw-i2c-bus-capture" }, "can_fd": { "rev": 1, @@ -345,20 +347,20 @@ "board": "any", "legacy_caps": "can_fd", "legacy_frame": "can_fd", - "docs": "API.md#can_config" + "docs": "API.md#can_config--bring-can-up" }, "la_dir": { "rev": 1, "firmware": "3.10.4", "board": "any", - "docs": "API.md#la_dir" + "docs": "API.md#la_dir--which-way-each-pins-dut-signal-goes" }, "wiring_store": { "rev": 1, "firmware": "3.10.8", "board": "any", "legacy_frame": "wiring_store", - "docs": "API.md#wiring_list" + "docs": "API.md#wiring-profiles-wiring_list-wiring_get-wiring_put-wiring_delete-wiring_default" }, "error_codes": { "rev": 1, @@ -390,7 +392,7 @@ "board": "any", "legacy_caps": "gpio_read", "legacy_frame": "gpio_read", - "docs": "API.md#gpio_get" + "docs": "API.md#3-read-the-live-levels" }, "capture_trigger": { "rev": 1, @@ -399,7 +401,7 @@ "board": "any", "legacy_caps": "capture_trigger", "legacy_frame": "capture_trigger", - "docs": "API.md#capture" + "docs": "API.md#capture-triggers" }, "spi_master": { "rev": 1, @@ -408,7 +410,7 @@ "board": "any", "legacy_caps": "spi_master", "legacy_frame": "spi_master", - "docs": "API.md#spi_xfer" + "docs": "API.md#spi-master-flash-an-spi-device" }, "spi_stream": { "rev": 1, @@ -417,7 +419,7 @@ "board": "any", "legacy_caps": "spi_stream", "legacy_frame": "spi_stream", - "docs": "API.md#spi_stream" + "docs": "API.md#spi_stream--send-a-staged-upload-in-one-cs-frame" }, "la_rate_48mhz": { "rev": 1, @@ -439,14 +441,14 @@ "firmware": "3.10.4", "gateware": 55, "board": "any", - "docs": "API.md#i2c_start" + "docs": "API.md#i2c-master" }, "spi_modes_1_2": { "rev": 1, "firmware": "3.10.4", "gateware": 55, "board": "any", - "docs": "API.md#spi_xfer" + "docs": "API.md#spi_xfer--raw-full-duplex-transfer" }, "uart_frame": { "rev": 1, @@ -455,7 +457,7 @@ "board": "any", "legacy_caps": "uart_frame", "legacy_frame": "uart_frame", - "docs": "API.md#uart_proxy_start" + "docs": "API.md#uart_proxy_start--transparent-uart-bridge" }, "uart_hd": { "rev": 1, @@ -473,7 +475,7 @@ "emu_image" ], "legacy_frame": "sensors_digital", - "docs": "API.md#sensor_start" + "docs": "API.md#sensor_start--start-an-instance" }, "scope": { "rev": 1, @@ -481,7 +483,7 @@ "board": "analog", "legacy_caps": "scope", "legacy_frame": "scope", - "docs": "API.md#capture" + "docs": "API.md#capture--adc-snapshot" }, "dac": { "rev": 1, @@ -489,7 +491,7 @@ "board": "analog", "legacy_caps": "dac", "legacy_frame": "dac", - "docs": "API.md#generate" + "docs": "API.md#generate--dac-waveform-output" }, "dac_dc": { "rev": 1, @@ -497,7 +499,7 @@ "board": "analog", "legacy_caps": "dac_dc", "legacy_frame": "dac_dc", - "docs": "API.md#dac_out" + "docs": "API.md#dac_out--route-an-output-path-and-set-a-calibrated-voltage" }, "dac_replay": { "rev": 1, @@ -505,7 +507,7 @@ "board": "analog", "legacy_caps": "dac_replay", "legacy_frame": "dac_replay", - "docs": "API.md#replay" + "docs": "API.md#replay--play-a-recorded-trace-out-the-dac" }, "signal_alias": { "rev": 1, @@ -529,7 +531,7 @@ ], "legacy_caps": "dac_deep_replay", "legacy_frame": "dac_deep_replay", - "docs": "API.md#replay" + "docs": "API.md#replay--play-a-recorded-trace-out-the-dac" }, "dac_control_loop": { "rev": 1, @@ -541,7 +543,7 @@ ], "legacy_caps": "dac_control_loop", "legacy_frame": "dac_control_loop", - "docs": "API.md#dac_loop" + "docs": "API.md#dac_control_loop--arm-the-closed-loop-dac" }, "dac_cotrig": { "rev": 1, @@ -573,7 +575,7 @@ "board": "analog", "legacy_caps": "dac_limits", "legacy_frame": "dac_limits", - "docs": "API.md#dac_limits" + "docs": "API.md#dac_limits--dac-output-limits-for-an-external-output-stage" }, "calibrate": { "rev": 1, @@ -581,7 +583,7 @@ "board": "analog", "legacy_caps": "calibrate", "legacy_frame": "calibrate", - "docs": "API.md#calibrate" + "docs": "API.md#calibrate--calibrate-the-adc-offset-on-the-current_in-input-j8" }, "current_out": { "rev": 1, @@ -696,6 +698,12 @@ "vref_out" ], "docs": "API.md#pull-resistors-on-digital-v3r4" + }, + "client_api": { + "rev": 8, + "firmware": "next", + "board": "any", + "docs": "API.md#client-compatibility" } } } From cba609bcea293e76e4afcfa96f6d4121d766ecd1 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 16:58:59 -0600 Subject: [PATCH 2/4] SDK: classify pod refusals by their error code One table (errors._BY_CODE) maps every catalog code, BP0001 to BP0030, to its exception class and fills the class's fields from the code's args. The text patterns stay as the fallback for a reply without a code the SDK knows (older firmware, a code newer than this SDK), each marked with what replaces it. New WiringError (BP0007-BP0015) and ClientTooOldError (BP0030); BP0003-BP0005 and BP0016 are PodBusyError, BP0017 UnsupportedFeatureError with the feature from its args. BP0001 keeps the SDK's own la voltage text. open_i2c's busy rewrite keys on BP0003. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci/README.md | 6 +- .../src/embeddedci/benchpod/__init__.py | 4 + .../src/embeddedci/benchpod/client.py | 5 +- .../src/embeddedci/benchpod/errors.py | 200 +++++++++++++++--- .../embeddedci/benchpod/sensors/emulation.py | 1 + packages/embeddedci/tests/api_surface.json | 8 + packages/embeddedci/tests/test_error_codes.py | 134 ++++++++++++ packages/embeddedci/tests/test_i2c_master.py | 23 +- .../embeddedci/tests/test_wiring_profiles.py | 5 +- 9 files changed, 345 insertions(+), 41 deletions(-) create mode 100644 packages/embeddedci/tests/test_error_codes.py diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 4d95137..695a988 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -2478,11 +2478,13 @@ Invalid arguments raise `ValueError` before anything is sent. Everything else ra | `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 | `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` | | `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`, or the digital-only board has no analog front end | `feature`, `firmware_version`, `firmware_message`, `cmd` | +| `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` | | `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` | diff --git a/packages/embeddedci/src/embeddedci/benchpod/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/__init__.py index cc03666..6a37884 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/__init__.py @@ -97,6 +97,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin from .errors import ( BenchPodError, CanTimeout, + ClientTooOldError, CloudAuthError, ConnectionClosedError, ConnectionConfigError, @@ -120,6 +121,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin UartLinkError, UartTimeout, UnsupportedFeatureError, + WiringError, ) from .flash import FlashResult from .expansion import ( @@ -357,6 +359,8 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin "PodBusyError", "PodLeasedError", "PodLeaseLostError", + "WiringError", + "ClientTooOldError", "PermissionDeniedError", "UartTimeout", "UartLinkError", diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index bf84b9a..d99ceb4 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -2057,6 +2057,7 @@ def board_header(self) -> Optional[str]: 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 if header is None: try: @@ -2514,7 +2515,8 @@ 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: - if exc.firmware_message.startswith("i2c busy"): + # BP0003; the text for firmware without codes. + if exc.code == "BP0003" or (not exc.code and exc.firmware_message.startswith("i2c busy")): exc.args = (self._i2c_busy_text(exc),) raise return _i2c_master.I2CMaster(self._classified_command, info) @@ -3521,6 +3523,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): raise first = self._la_pins_query(list(range(1, 8))) diff --git a/packages/embeddedci/src/embeddedci/benchpod/errors.py b/packages/embeddedci/src/embeddedci/benchpod/errors.py index 8ceff63..e60bbd5 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/errors.py +++ b/packages/embeddedci/src/embeddedci/benchpod/errors.py @@ -5,7 +5,7 @@ import json import re from importlib import resources -from typing import Any, Dict, Mapping, Optional +from typing import Any, Callable, Dict, Mapping, Optional, Tuple class BenchPodError(Exception): @@ -238,7 +238,10 @@ class PodLockedError(FirmwareError): 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`).""" + 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``).""" class PodLeasedError(PodBusyError, DeviceBusyError, TransportError): @@ -274,6 +277,42 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, by: str = "") -> self.by = by +class WiringError(FirmwareError): + """The pod refused a wiring-profile operation (``BP0007`` to ``BP0015``): no profile with that + name, a bad name, a revision conflict, the store is full, the profile is too large or not one + JSON object, the default cannot be deleted, an upload out of order, or the storage failed. + :attr:`name` is the profile's name when the pod sent one (``""`` otherwise); :attr:`code` says + which of these it is and :attr:`values` has the rest (``rev``, ``max``, ``bytes``).""" + + def __init__(self, message: str, *, cmd: Optional[str] = None, name: str = "") -> None: + super().__init__(message, cmd=cmd) + self.name = name + + +class ClientTooOldError(FirmwareError): + """This SDK is too old for the pod's firmware: the firmware changed a reply or a message in a + way this SDK would misread, so it is not used with it. + + Raised on connect when the pod announces a client API level (``api``) above + :data:`~embeddedci.benchpod.feature_map.CLIENT_API`, the highest this SDK handles, and for the + pod's own refusal ``BP0030`` (the SDK's level is below the firmware's ``min_client_api``). + :attr:`client_api` is this SDK's level, :attr:`api` the pod's (0 when unknown), + :attr:`min_client_api` the lowest the pod takes (0 when unknown) and :attr:`firmware_version` + the pod's firmware when known. The fix is to update the SDK: ``pip install -U embeddedci``. + + Not an :class:`UnsupportedFeatureError`: the pod can do it, this client cannot talk to it. A + :class:`FirmwareError` (and so a :class:`BenchPodError`). + """ + + def __init__(self, message: str, *, cmd: Optional[str] = None, client_api: int = 0, + api: int = 0, min_client_api: int = 0, firmware_version: str = "") -> None: + super().__init__(message, cmd=cmd) + self.client_api = client_api + self.api = api + self.min_client_api = min_client_api + self.firmware_version = firmware_version + + 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 @@ -289,34 +328,56 @@ 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+". +#: "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). +#: 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). +#: 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). +#: 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. +#: (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. +#: 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" @@ -329,8 +390,10 @@ def status_too_large(message: str, cmd: Optional[str] = "status") -> bool: 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.""" + 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)") @@ -390,9 +453,18 @@ def _sdk_refusal_text(message: str) -> str: def classify_firmware_error(exc: FirmwareError) -> FirmwareError: - """The specific :class:`FirmwareError` subclass for a pod refusal, or ``exc`` itself.""" - if type(exc) is not FirmwareError: + """The specific :class:`FirmwareError` subclass for a pod refusal, or ``exc`` itself. + + 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: @@ -413,9 +485,9 @@ def classify_firmware_error(exc: FirmwareError) -> FirmwareError: 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:"): + if msg.startswith(_BUSY): return PodBusyError(msg, cmd=exc.cmd) - if msg.startswith("forbidden:"): + 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 "") @@ -472,7 +544,10 @@ def _attach_code(exc: FirmwareError, code: str, values: Optional[Mapping[str, An exc.values = dict(values or {}) exc.docs_url = error_docs_url(code) if code else "" entry = error_catalog().get("codes", {}).get(code) if code else None - if entry: + 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: @@ -480,24 +555,89 @@ def _attach_code(exc: FirmwareError, code: str, values: Optional[Mapping[str, An return exc +def _int(v: Any) -> int: + """An int arg, 0 when it is missing or not a number.""" + if isinstance(v, bool): + return 0 + if isinstance(v, (int, float)): + return int(v) + return int(v) if isinstance(v, str) and v.strip().isdigit() else 0 + + +def _str(v: Any) -> str: + return "" if v is None else str(v) + + +def _leased(v: Mapping[str, Any], cmd: Optional[str]) -> Dict[str, Any]: + left = v.get("left_s") + return {"holder": _str(v.get("holder")), "purpose": _str(v.get("purpose")), + "left_s": int(left) if isinstance(left, (int, float)) and not isinstance(left, bool) else None} + + +_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]] + +#: 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. +_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 ""}), + "BP0003": (PodBusyError, _NO_FIELDS), # i2c_session_open + "BP0004": (PodBusyError, _NO_FIELDS), # spi_session_open + "BP0005": (PodBusyError, _NO_FIELDS), # bus_engine_busy {want} + "BP0006": (FirmwareError, _NO_FIELDS), # missing_argument {arg} + "BP0007": (WiringError, _WIRING), # wiring_profile_not_found + "BP0008": (WiringError, _WIRING), # wiring_bad_name + "BP0009": (WiringError, _WIRING), # wiring_revision_conflict {rev} + "BP0010": (WiringError, _WIRING), # wiring_store_full {max} + "BP0011": (WiringError, _WIRING), # wiring_profile_too_large + "BP0012": (WiringError, _WIRING), # wiring_not_json_object + "BP0013": (WiringError, _WIRING), # wiring_delete_default + "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 ""}), + "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"))}), + "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} + "BP0028": (FirmwareError, _NO_FIELDS), # vref_5v_missing {mv} + "BP0029": (FirmwareError, _NO_FIELDS), # pull_rail_down {mv} + "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"))}), +} + +#: Codes whose message is the SDK's own text rather than the catalog's message and fix. +_SDK_TEXT = {"BP0001": _LA_VOLTAGE_SDK} + + def firmware_error(message: str, *, cmd: Optional[str] = None, code: str = "", values: Optional[Mapping[str, Any]] = None) -> FirmwareError: """The :class:`FirmwareError` (its specific subclass when there is one) for a pod refusal. - ``code`` / ``values``: the pod's stable error code and its args, when the firmware sends them.""" - exc = FirmwareError(message, cmd=cmd) + ``code`` / ``values``: the pod's stable error code and its args, when the firmware sends them. + + 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.""" v = dict(values or {}) - if code == "BP0025": # the pod's lease: someone else holds it - left = v.get("left_s") - exc = PodLeasedError(message, cmd=cmd, holder=str(v.get("holder") or ""), - purpose=str(v.get("purpose") or ""), - left_s=int(left) if isinstance(left, (int, float)) and not isinstance(left, bool) else None) - elif code == "BP0026": # the lease was stopped from the web app or the cloud - exc = PodLeaseLostError(message, cmd=cmd, by=str(v.get("by") or "")) - elif code == "BP0002": # unknown command: the firmware lacks the feature - exc = UnsupportedFeatureError(message, cmd=cmd, feature=cmd or "") - elif code in ("BP0023", "BP0024"): # no pull resistor / the other direction only - la = v.get("la", 0) - exc = PullDirectionError(message, cmd=cmd, la=int(la) if str(la).isdigit() else 0, - want=str(v.get("want", "")), have=str(v.get("have", ""))) - exc = classify_firmware_error(exc) + 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)) return _attach_code(exc, code or "", values) diff --git a/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py index d96e764..67479e8 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py +++ b/packages/embeddedci/src/embeddedci/benchpod/sensors/emulation.py @@ -220,6 +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): return {} raise diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index de22ca2..def41e1 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -401,6 +401,9 @@ "rms_ac": "(self) -> 'float'", "times": "(self) -> 'List[float]'" }, + "ClientTooOldError": { + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, client_api: 'int' = 0, api: 'int' = 0, min_client_api: 'int' = 0, firmware_version: 'str' = '') -> 'None'" + }, "CloudAuthError": {}, "ConnSpec": { "__fields__": [ @@ -1329,6 +1332,9 @@ "warnings": "(self) -> 'List[str]'", "with_changes": "(self, **changes: 'Any') -> \"'Wiring'\"" }, + "WiringError": { + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, name: 'str' = '') -> 'None'" + }, "__all__": [ "AdcCompensation", "AdcGainSource", @@ -1356,6 +1362,7 @@ "CanTimeout", "Capabilities", "Capture", + "ClientTooOldError", "CloudAuthError", "ConnSpec", "ConnectionClosedError", @@ -1486,6 +1493,7 @@ "WaveformLibrary", "Waveshape", "Wiring", + "WiringError", "build_constant_curve", "build_linear_curve", "build_panel_curve", diff --git a/packages/embeddedci/tests/test_error_codes.py b/packages/embeddedci/tests/test_error_codes.py new file mode 100644 index 0000000..4041cfb --- /dev/null +++ b/packages/embeddedci/tests/test_error_codes.py @@ -0,0 +1,134 @@ +"""Pod refusals are classified by their stable error code; the text only decides without one. + +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.""" + +from __future__ import annotations + +import pytest + +from embeddedci.benchpod import errors +from embeddedci.benchpod.errors import ( + ClientTooOldError, + DirectionConflictError, + FirmwareError, + PermissionDeniedError, + PinConflictError, + PodBusyError, + PodLeasedError, + PodLeaseLostError, + PodLockedError, + PullConflictError, + PullDirectionError, + TriggerTimeout, + UnsupportedFeatureError, + WiringError, + classify_firmware_error, + 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}), +} + + +def test_every_catalog_code_has_a_class(): + """A sync that adds a code fails here until the code is in the table.""" + 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) + assert type(err) is cls + assert err.code == code and err.values == args and err.docs_url.endswith("#" + code) + 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}: ") + + +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_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): + 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 diff --git a/packages/embeddedci/tests/test_i2c_master.py b/packages/embeddedci/tests/test_i2c_master.py index ad4f990..fe5016d 100644 --- a/packages/embeddedci/tests/test_i2c_master.py +++ b/packages/embeddedci/tests/test_i2c_master.py @@ -16,11 +16,13 @@ I2CNackError, I2CSend, PinConflictError, + PodBusyError, SpiSend, Trigger, UnsupportedFeatureError, Wiring, ) +from embeddedci.benchpod.errors import firmware_error from embeddedci.benchpod.wiring import Signal @@ -38,8 +40,10 @@ class BusPod: TARGET = 0x42 - def __init__(self, *, gateware: Optional[int] = 55) -> None: + def __init__(self, *, gateware: Optional[int] = 55, coded: bool = False) -> 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,6 +93,8 @@ def command(self, req: dict) -> Any: 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) self.session = req self.driven[req["sda"]] = "i2cm_sda" @@ -192,22 +198,27 @@ def test_open_i2c_accepts_wiring_names_and_validates(): bp.open_i2c(1, 1) -def test_busy_names_another_connection_as_the_holder(): +@pytest.mark.parametrize("coded", [True, False]) +def test_busy_names_another_connection_as_the_holder(coded): """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() + bp, fake = pod(coded=coded) 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 - assert e.value.firmware_message == "i2c busy: send i2c_stop first" + 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 fake.session["hz"] == 100_000 # nothing was stopped -def test_busy_names_this_benchpods_own_open_session(): - bp, fake = pod() +@pytest.mark.parametrize("coded", [True, False]) +def test_busy_names_this_benchpods_own_open_session(coded): + bp, fake = pod(coded=coded) 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() diff --git a/packages/embeddedci/tests/test_wiring_profiles.py b/packages/embeddedci/tests/test_wiring_profiles.py index 5688401..bd6bb09 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, firmware_error +from embeddedci.benchpod.errors import FirmwareError, UnsupportedFeatureError, WiringError, firmware_error class ProfilePod: @@ -152,6 +152,7 @@ def test_saving_the_loaded_profile_checks_its_revision(): bp.save_wiring(bp.wiring.with_changes(uart_baud=19200)) err = exc.value assert err.code == "BP0009" and err.values == {"name": "k66", "rev": 2} + assert isinstance(err, WiringError) and err.name == "k66" assert "load it again" in str(err) and err.docs_url.endswith("#BP0009") bp.load_wiring("k66") assert bp.save_wiring(bp.wiring.with_changes(uart_baud=19200)).profile_rev == 3 @@ -171,7 +172,7 @@ def test_deleting_the_default_is_refused_with_its_code(): bp = BenchPod(transport=pod, lease=False) with pytest.raises(FirmwareError) as exc: bp.delete_wiring("k66") - assert exc.value.code == "BP0013" + assert exc.value.code == "BP0013" and isinstance(exc.value, WiringError) bp.delete_wiring("nrf") assert "nrf" not in pod.profiles From d6601608bb0478b9b547f8196aa4bbd8b64dfe70 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 17:08:44 -0600 Subject: [PATCH 3/4] SDK: client API level (client_api, client, ClientTooOldError) feature_map.CLIENT_API = 1 is the highest pod api the SDK handles; a test ties it to the bundled table's api. protocol.encode_request (TCP, USB network, the cloud tunnel, the pod lease, discovery probes) and the cloud command channel add "client_api" and "client": "sdk " to every JSON command; the USB console's text protocol gets nothing. Capabilities reads api and min_client_api (status, cloud frame). A pod above CLIENT_API fails the connect with ClientTooOldError (the pin-direction read on connect does the check, so no extra request), and so does BP0030. README and CHANGELOG (3.0.6) describe the error codes and the client API level. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci/CHANGELOG.md | 18 ++ packages/embeddedci/README.md | 43 ++++- .../src/embeddedci/benchpod/capabilities.py | 21 +++ .../src/embeddedci/benchpod/client.py | 45 ++++- .../src/embeddedci/benchpod/feature_map.py | 15 ++ .../src/embeddedci/benchpod/protocol.py | 45 ++++- .../embeddedci/benchpod/transport/__init__.py | 3 +- .../embeddedci/benchpod/transport/cloud.py | 3 +- .../embeddedci/benchpod/transport/usblink.py | 4 +- packages/embeddedci/tests/api_surface.json | 3 + packages/embeddedci/tests/test_can.py | 4 +- packages/embeddedci/tests/test_client_api.py | 178 ++++++++++++++++++ packages/embeddedci/tests/test_cloud.py | 4 +- packages/embeddedci/tests/test_protocol.py | 3 +- .../embeddedci/tests/test_tcp_transport.py | 6 +- packages/embeddedci/tests/test_timed_power.py | 4 +- packages/embeddedci/tests/test_uart_frame.py | 4 +- packages/embeddedci/tests/wire.py | 15 ++ 18 files changed, 395 insertions(+), 23 deletions(-) create mode 100644 packages/embeddedci/tests/test_client_api.py create mode 100644 packages/embeddedci/tests/wire.py diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index a06e90b..dfbb9c0 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog — `embeddedci` +## 3.0.6 + +- **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` + (`BP0007` to `BP0015`, with `name`). `BP0003` and `BP0004` (an I2C or SPI session is open), + `BP0005` (the SWD/SPI/I2C engine is busy) and `BP0016` (storage busy) raise `PodBusyError`; + `BP0017` (gateware too old) raises `UnsupportedFeatureError` with the feature from the code. + Match on `exc.code` or the class, not the text. README: [Error codes](README.md#error-codes). +- **Client API level.** Every JSON command carries `"client_api": 1` and `"client": "sdk + "` (firmware 3.10.13 and older ignores them). `feature_map.CLIENT_API` is the level this + SDK handles; `Capabilities.api`, `min_client_api` and `client_api_level` are the pod's (firmware + after 3.10.13; a pod that does not say counts as 1). Connecting to a pod above the SDK's level, + or the pod's refusal `BP0030`, raises the new `ClientTooOldError`: update the SDK with + `pip install -U embeddedci`. +- Error catalog: `BP0030` (client too old). Features table revision 8, with `api` and + `min_client_api`. + ## 3.0.5 - `la_pins(la=...)` lists only those channels (firmware after 3.10.12 sends only them; older diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 695a988..23acbd1 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -371,10 +371,28 @@ load it again (bp.load_wiring("k66")), redo your change and save, or save under (https://embeddedci.com/docs/errors#BP0009) ``` -A code never changes meaning and is never reused, so match on `exc.code` in tests and scripts, not -on the text. `embeddedci.benchpod.errors.explain("BP0009")` prints a code's entry offline. -[embeddedci.com/docs/errors](https://embeddedci.com/docs/errors) lists every code. Older firmware -sends no code (`.code == ""`). +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. + +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` | | +| `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. ## API conventions and stability @@ -420,6 +438,19 @@ flag of their own (`"la_dir"`, `"i2c_master"`, `"diag"`, `"wiring_store"`, ...). 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. +**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. + ```python import pytest @@ -2461,7 +2492,9 @@ without a session unless `--allow-missing-token` is passed. ## Errors Invalid arguments raise `ValueError` before anything is sent. Everything else raises a -`BenchPodError` subclass, all importable from `embeddedci.benchpod`: +`BenchPodError` subclass, all importable from `embeddedci.benchpod`. + +Match a pod refusal on its code or class, not its text: see [Error codes](#error-codes). | Exception | Raised when | Extra attributes | |---|---|---| diff --git a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py index 014c7f2..c821228 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py +++ b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py @@ -217,6 +217,13 @@ class Capabilities: #: ``"caps":false``, firmware after 3.10.10); 0 for older firmware, which sends a ``caps`` #: list instead. features_rev: int = 0 + #: The client API level the pod's firmware speaks (``status`` with ``"caps":false``, the + #: cloud capabilities frame; firmware after 3.10.13); 0 when it does not say, which counts as + #: 1 (:attr:`client_api_level`). Above :data:`~embeddedci.benchpod.feature_map.CLIENT_API` + #: this SDK is too old for the pod (:class:`~embeddedci.benchpod.errors.ClientTooOldError`). + api: int = 0 + #: The lowest ``client_api`` the pod's firmware takes; 0 when it does not say. + min_client_api: int = 0 #: With :attr:`features_rev`: every feature the table gives this pod #: (:mod:`~embeddedci.benchpod.feature_map`), including ones with no flag here (``la_dir``, #: ``i2c_master``, ``diag``, ...). Empty for older firmware. @@ -411,6 +418,10 @@ def from_status(cls, status: Mapping[str, Any]) -> "Capabilities": facts = _feature_map.facts_from_status(status) c.features = _feature_map.resolve(rev, c.gateware, facts) c._apply_features(facts) + if (v := _as_int(status, "api")) is not None and v > 0: + c.api = v + if (v := _as_int(status, "min_client_api")) is not None and v > 0: + c.min_client_api = v c.safe_mode = _as_bool(status, "safe_mode") is True c.safe_reason = str(status.get("safe_reason", "") or "") if c.safe_mode else "" c.last_crash = _crash_text(status.get("last_crash", status.get("crash"))) @@ -513,6 +524,10 @@ def from_parameters(cls, params: Mapping[str, Any]) -> "Capabilities": 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: + c.min_client_api = v if (v := _as_int(params, "cap.sig_keys")) is not None and v > 0: c.sig_keys = v c.sig_policy = str(params.get("cap.sig_policy", "") or "") @@ -609,6 +624,12 @@ def counts_to_volts(self, count: float) -> float: fs = (self.adc_fullscale_mv / 1000.0) if self.adc_fullscale_mv > 0 else 3.3 return (float(count) - self.adc_offset_counts) * (fs / mc) + @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).""" + return self.api or 1 + def merge(self, other: "Capabilities") -> "Capabilities": """Overlay the non-default fields of ``other`` onto a copy of ``self`` (other wins). diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index d99ceb4..ba65066 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -101,8 +101,9 @@ coerce_pin, ) from .connection import resolve_connection -from .errors import (BenchPodError, FirmwareError, PullDirectionError, UnsupportedFeatureError, - classify_firmware_error, firmware_error, status_too_large) +from .errors import (BenchPodError, ClientTooOldError, FirmwareError, PullDirectionError, + UnsupportedFeatureError, classify_firmware_error, firmware_error, + status_too_large) from .flash import FlashResult from .gpio import LA_DIRS, ExtPin, GpioPin, LaPinState from .lease import DEFAULT_LEASE_TTL, DEFAULT_LEASE_WAIT, DeviceLease @@ -209,6 +210,14 @@ def _mac_text(v: Any) -> Optional[str]: return v.strip().lower() if isinstance(v, str) and v.strip() else None +def _sdk_version() -> str: + try: + from importlib.metadata import version + return version("embeddedci") + except Exception: # a source tree without install + return "unknown" + + def _dict(data: Any) -> Dict[str, Any]: return data if isinstance(data, dict) else {} @@ -639,10 +648,26 @@ def capabilities(self) -> Capabilities: except BenchPodError: pass if not status_ok: + 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 + fw = caps.firmware_version or "unknown" + 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, + min_client_api=caps.min_client_api, firmware_version=caps.firmware_version) + 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 @@ -3615,7 +3640,8 @@ 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``. Never raises: the outcome goes to :attr:`pin_directions_status`.""" + 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`.""" if getattr(self, "_transport", None) is None: return try: @@ -3623,9 +3649,13 @@ def _auto_pin_directions(self) -> None: self.pin_directions_status = "not sent: the USB console has no la_dir" 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). - caps = self._caps if self._caps is not None else Capabilities.from_status( - _dict(self.status())) + # (the first real use of capabilities reads and caches them as before). It is also + # connect's client API check: the one error raised from here. + if self._caps is not None: + caps = self.capabilities + else: + caps = Capabilities.from_status(_dict(self._caps_status())) + 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 " @@ -3633,6 +3663,9 @@ def _auto_pin_directions(self) -> None: 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 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) diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.py b/packages/embeddedci/src/embeddedci/benchpod/feature_map.py index ed974fd..64dc0d7 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/feature_map.py +++ b/packages/embeddedci/src/embeddedci/benchpod/feature_map.py @@ -20,6 +20,16 @@ from typing import Any, Dict, FrozenSet, Mapping, Optional, Tuple +#: 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 +#: (: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 + + @lru_cache(maxsize=1) def feature_map() -> Dict[str, Any]: """The bundled table (``schema``, ``revision``, ``facts``, ``releases``, ``features``).""" @@ -33,6 +43,11 @@ def feature_map() -> Dict[str, Any]: return data +def table_api() -> int: + """The client API level of the bundled table (its ``api``; 1 for a table without one).""" + return int(feature_map().get("api", 1) or 1) + + def revision() -> int: """The highest revision this SDK's table knows.""" return int(feature_map().get("revision", 0) or 0) diff --git a/packages/embeddedci/src/embeddedci/benchpod/protocol.py b/packages/embeddedci/src/embeddedci/benchpod/protocol.py index 10ce319..857cd07 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/protocol.py +++ b/packages/embeddedci/src/embeddedci/benchpod/protocol.py @@ -28,9 +28,50 @@ class Reply: args: Any = None +#: The pod takes a ``client`` of at most this many printable characters (and drops a longer one). +CLIENT_NAME_MAX = 32 +_client_name: Optional[str] = None + + +def client_name() -> str: + """The ``client`` every request carries: ``"sdk "`` unless :func:`set_client_name` + set another (the MCP server sends ``"mcp "``).""" + global _client_name + if _client_name is None: + try: + from importlib.metadata import version + _client_name = f"sdk {version('embeddedci')}" + except Exception: # a source tree without install + _client_name = "sdk" + return _client_name + + +def set_client_name(name: str) -> None: + """Name this process's requests (``"mcp 3.0.6"``): the pod puts it in a refusal's text. A name + longer than :data:`CLIENT_NAME_MAX` or with other than printable ASCII is not sent.""" + global _client_name + _client_name = str(name) + + +def stamp_request(req: dict) -> dict: + """``req`` with this client's ``client_api`` (:data:`~embeddedci.benchpod.feature_map.CLIENT_API`) + and ``client`` name, the two fields every JSON command carries. Firmware 3.10.13 and older + ignores them; later firmware refuses a ``client_api`` below its ``min_client_api`` (BP0030). + A request that already has them keeps its own.""" + from .feature_map import CLIENT_API + + out = dict(req) + out.setdefault("client_api", CLIENT_API) + name = client_name() + if name and len(name) <= CLIENT_NAME_MAX and all(" " <= c <= "~" for c in name): + out.setdefault("client", name) + return out + + def encode_request(req: dict) -> bytes: - """Encode a request dict as a single newline-terminated JSON line.""" - return (json.dumps(req, separators=(",", ":")) + "\n").encode("utf-8") + """Encode a request dict as a single newline-terminated JSON line, with this client's + ``client_api`` and ``client`` (:func:`stamp_request`).""" + return (json.dumps(stamp_request(req), separators=(",", ":")) + "\n").encode("utf-8") def parse_reply(line: bytes) -> Reply: diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py index 24d1816..3ec6a6a 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/__init__.py @@ -21,6 +21,7 @@ from ..connection import DEFAULT_PORT, ConnSpec from ..errors import ConnectionConfigError +from ..protocol import encode_request from .base import RawLink, Transport __all__ = [ @@ -120,7 +121,7 @@ def _api_answers(host: str, port: int, timeout: float = USB_NET_PROBE_TIMEOUT) - try: with socket.create_connection((host, port), timeout=timeout) as s: s.settimeout(timeout) - s.sendall(b'{"cmd":"ping"}\n') + s.sendall(encode_request({"cmd": "ping"})) buf = b"" while b"\n" not in buf: chunk = s.recv(256) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py index c5affd0..0e0ef7b 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/cloud.py @@ -34,6 +34,7 @@ TransportTimeout, firmware_error, ) +from ..protocol import stamp_request from .base import request_timeout from .tcp import DEFAULT_DIAL_TIMEOUT, TcpTransport @@ -423,7 +424,7 @@ def command(self, req: dict) -> Any: # type: ignore[override] f"?device={quote(self.device_name, safe='')}") timeout = min(request_timeout(req, self.timeout), _SERVER_COMMAND_MAX_TIMEOUT) body = json.dumps( - {"command": req, "timeout_ms": int(timeout * 1000)} + {"command": stamp_request(req), "timeout_ms": int(timeout * 1000)} ).encode("utf-8") cmd = req.get("cmd") busy_until = time.monotonic() + _BUSY_RETRY_BUDGET diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/usblink.py b/packages/embeddedci/src/embeddedci/benchpod/transport/usblink.py index 4676c12..881857c 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/usblink.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/usblink.py @@ -17,6 +17,8 @@ import sys from typing import List, Optional, Tuple +from ..protocol import encode_request + _USB_NET = ipaddress.ip_network("10.237.0.0/16") _MASK_30 = ipaddress.ip_address("255.255.255.252") @@ -81,7 +83,7 @@ def _short_id(host: str, port: int, timeout: float) -> str: try: with socket.create_connection((host, port), timeout=timeout) as s: s.settimeout(timeout) - s.sendall(b'{"cmd":"identity_public"}\n') + s.sendall(encode_request({"cmd": "identity_public"})) buf = b"" while b"\n" not in buf: chunk = s.recv(1024) diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index def41e1..651cc16 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -329,6 +329,8 @@ "uart_de", "gateware", "features_rev", + "api", + "min_client_api", "features", "fpga_image", "calibrate", @@ -366,6 +368,7 @@ "adc_max_count": "property", "boot_warning": "(self) -> 'Optional[str]'", "bus_master": "property", + "client_api_level": "property", "counts_to_volts": "(self, count: 'float') -> 'float'", "from_parameters": "(cls, params: 'Mapping[str, Any]') -> \"'Capabilities'\"", "from_status": "(cls, status: 'Mapping[str, Any]') -> \"'Capabilities'\"", diff --git a/packages/embeddedci/tests/test_can.py b/packages/embeddedci/tests/test_can.py index f087159..7480c18 100644 --- a/packages/embeddedci/tests/test_can.py +++ b/packages/embeddedci/tests/test_can.py @@ -17,6 +17,8 @@ from embeddedci.benchpod.errors import CanTimeout, FirmwareError from embeddedci.benchpod.transport.tcp import TcpTransport +import wire + class FakeCanPod: """Minimal CAN pod: one connection per command (matches the firmware).""" @@ -138,7 +140,7 @@ def _serve(self): buf += c if not buf: continue - req = json.loads(buf.split(b"\n", 1)[0]) + req = wire.request(buf.split(b"\n", 1)[0]) self.requests.append(req) conn.sendall(json.dumps(self._reply(req)).encode() + b"\n") diff --git a/packages/embeddedci/tests/test_client_api.py b/packages/embeddedci/tests/test_client_api.py new file mode 100644 index 0000000..546ace9 --- /dev/null +++ b/packages/embeddedci/tests/test_client_api.py @@ -0,0 +1,178 @@ +"""The client API level: every JSON request carries ``client_api`` and ``client``; a pod that +announces a higher ``api`` than :data:`CLIENT_API`, or refuses with ``BP0030``, raises +:class:`ClientTooOldError`.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from embeddedci.benchpod import BenchPod, ClientTooOldError, 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 +from embeddedci.benchpod.transport.cloud import CloudTransport +from embeddedci.benchpod.transport.tcp import TcpTransport + +from test_cloud import _scripted_urlopen +from test_tcp_transport import FakePod + + +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 bundled["min_client_api"] <= bundled["api"] + + +# -- every transport's request encoding --------------------------------------------------------- + +def test_encode_request_carries_the_level_and_the_name(): + req = json.loads(protocol.encode_request({"cmd": "gpio", "la": 4})) + assert req["cmd"] == "gpio" and req["la"] == 4 + assert req["client_api"] == CLIENT_API + assert req["client"].startswith("sdk ") and len(req["client"]) <= protocol.CLIENT_NAME_MAX + + +def test_a_request_keeps_its_own_fields(): + req = json.loads(protocol.encode_request({"cmd": "x", "client_api": 0, "client": "mine"})) + assert req["client_api"] == 0 and req["client"] == "mine" + + +def test_a_name_the_pod_would_drop_is_not_sent(monkeypatch): + monkeypatch.setattr(protocol, "_client_name", "x" * 33) + assert "client" not in json.loads(protocol.encode_request({"cmd": "x"})) + monkeypatch.setattr(protocol, "_client_name", "mcp 3.0.6\n") + assert "client" not in json.loads(protocol.encode_request({"cmd": "x"})) + protocol.set_client_name("mcp 3.0.6") # monkeypatch puts the name back afterwards + assert json.loads(protocol.encode_request({"cmd": "x"}))["client"] == "mcp 3.0.6" + + +def test_tcp_requests_carry_it(): + seen: List[Dict[str, Any]] = [] + + def handler(conn, line): + seen.append(json.loads(line)) + conn.sendall(b'{"status":"ok","data":null}\n') + + pod = FakePod(handler) + try: + t = TcpTransport(pod.addr, timeout=2) + t.command({"cmd": "gpio", "la": 4, "mode": "off"}) + t.command_sequence([{"cmd": "ping"}]) + finally: + pod.close() + assert len(seen) == 2 + assert all(r["client_api"] == CLIENT_API and r["client"].startswith("sdk ") for r in seen) + + +def test_cloud_command_channel_carries_it(monkeypatch): + t = CloudTransport("dev-a", api_base="https://example.test", token="x") + calls = _scripted_urlopen(monkeypatch, [None]) + t.command({"cmd": "status"}) + sent = json.loads(calls[0].data)["command"] + assert sent["cmd"] == "status" and sent["client_api"] == CLIENT_API + assert sent["client"].startswith("sdk ") + + +def test_cloud_tunnel_carries_it(): + """The byte tunnel sends the TCP transport's lines.""" + t = CloudTransport("dev-a", api_base="https://example.test", token="x") + req = json.loads(t._encode({"cmd": "uart_proxy_start"})) + assert req["client_api"] == CLIENT_API and req["client"].startswith("sdk ") + + +def test_the_usb_console_text_protocol_gets_nothing(): + from embeddedci.benchpod.transport.serial import SerialTransport + + lines: List[str] = [] + t = SerialTransport.__new__(SerialTransport) + t.timeout = 1.0 + t._write_line = lines.append # type: ignore[method-assign] + t._read_until_prompt = lambda deadline: "PING ok\n>" # type: ignore[method-assign] + assert t.command({"cmd": "ping"}) == "pong" + assert lines == ["ping"] + + +# -- the pod's level on connect ----------------------------------------------------------------- + +class _Pod: + """A pod whose caps-less status announces ``api`` (or nothing, like firmware 3.10.13).""" + + def __init__(self, status_extra: Dict[str, Any]) -> None: + self.extra = status_extra + self.requests: List[dict] = [] + self.timeout = 30.0 + self.refuse_with: Dict[str, Any] = {} + + 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} + if self.refuse_with: + raise firmware_error("update the BenchPod SDK, MCP or CLI", cmd=req["cmd"], + code="BP0030", values=self.refuse_with) + return {} + + def ping(self) -> Any: + return "pong" + + 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_above_this_level_refuses_the_connect(): + pod = _Pod({"api": 2, "min_client_api": 1}) + 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" + msg = str(err) + assert "3.11.0" in msg and "client API 2" in msg and f"client API {CLIENT_API}" in msg + assert "pip install -U embeddedci" in msg + + +def test_capabilities_after_an_update_check_again(): + pod = _Pod({"api": 1}) + bp = BenchPod(transport=pod, lease=False, api_key="", api_base="") + pod.extra = {"api": 2} # the pod was updated meanwhile + with pytest.raises(ClientTooOldError): + bp.refresh_capabilities() + + +def test_bp0030_raises_client_too_old(): + pod = _Pod({"api": 1, "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} + 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 "pip install -U embeddedci" in str(e.value) + + +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 + assert Capabilities.from_parameters({}).client_api_level == 1 + diff --git a/packages/embeddedci/tests/test_cloud.py b/packages/embeddedci/tests/test_cloud.py index b763f66..128db9b 100644 --- a/packages/embeddedci/tests/test_cloud.py +++ b/packages/embeddedci/tests/test_cloud.py @@ -13,6 +13,8 @@ from embeddedci.benchpod.transport.cloud import CloudTransport, _WsTunnelSocket from embeddedci import _http +import wire + # -- connection parsing ----------------------------------------------------- @@ -456,7 +458,7 @@ def test_cloud_load_replay_skips_the_tunnel_ack_lines(monkeypatch): frames = sock._ws.frames import json assert json.loads(frames[0])["cmd"] == "load_bin" - assert json.loads(frames[-1]) == {"cmd": "replay"} + assert wire.request(frames[-1]) == {"cmd": "replay"} assert b"".join(frames[1:-1]) == b"\x00" * 20000 diff --git a/packages/embeddedci/tests/test_protocol.py b/packages/embeddedci/tests/test_protocol.py index ab3d6d3..c278fbc 100644 --- a/packages/embeddedci/tests/test_protocol.py +++ b/packages/embeddedci/tests/test_protocol.py @@ -10,7 +10,8 @@ def test_encode_request_is_one_json_line(): raw = protocol.encode_request({"cmd": "ping"}) assert raw.endswith(b"\n") assert raw.count(b"\n") == 1 - assert json.loads(raw) == {"cmd": "ping"} + req = json.loads(raw) + assert req["cmd"] == "ping" and set(req) == {"cmd", "client_api", "client"} def test_parse_ok_reply(): diff --git a/packages/embeddedci/tests/test_tcp_transport.py b/packages/embeddedci/tests/test_tcp_transport.py index 02fc6d5..1020662 100644 --- a/packages/embeddedci/tests/test_tcp_transport.py +++ b/packages/embeddedci/tests/test_tcp_transport.py @@ -8,6 +8,8 @@ from embeddedci.benchpod.errors import FirmwareError from embeddedci.benchpod.transport.tcp import TcpTransport +import wire + class FakePod: """A minimal JSON/TCP server that mimics the pod, one connection at a time.""" @@ -67,7 +69,7 @@ def test_target_power_request_shape(): def handler(conn, line): import json - seen.update(json.loads(line)) + seen.update(wire.request(line)) conn.sendall(b'{"status":"ok","data":null}\n') pod = FakePod(handler) @@ -148,7 +150,7 @@ def test_stage_psram_uploads_raw_bytes_on_one_connection(): got = {} def handler(conn, line): - got["begin"] = json.loads(line) + got["begin"] = wire.request(line) conn.sendall(b'{"status":"ok","data":{"ready":%d}}\n' % len(payload)) data = b"" while len(data) < len(payload): diff --git a/packages/embeddedci/tests/test_timed_power.py b/packages/embeddedci/tests/test_timed_power.py index 5fec5b9..eebe427 100644 --- a/packages/embeddedci/tests/test_timed_power.py +++ b/packages/embeddedci/tests/test_timed_power.py @@ -8,6 +8,8 @@ from embeddedci.benchpod.client import BenchPod from embeddedci.benchpod.transport.tcp import TcpTransport +import wire + class FakePod: def __init__(self): @@ -34,7 +36,7 @@ def _serve(self): break buf += c if buf: - self.requests.append(json.loads(buf.split(b"\n", 1)[0])) + self.requests.append(wire.request(buf.split(b"\n", 1)[0])) conn.sendall(b'{"status":"ok","data":{"efuse":1,"enabled":1,"delay_ms":0}}\n') def close(self): diff --git a/packages/embeddedci/tests/test_uart_frame.py b/packages/embeddedci/tests/test_uart_frame.py index a0de340..83d3ea2 100644 --- a/packages/embeddedci/tests/test_uart_frame.py +++ b/packages/embeddedci/tests/test_uart_frame.py @@ -14,6 +14,8 @@ from embeddedci.benchpod import BenchPod, UnsupportedFeatureError from embeddedci.benchpod.transport.tcp import TcpTransport +import wire + class UartPod: """Answers status with the given caps and records uart_proxy_start calls.""" @@ -128,7 +130,7 @@ def run(): if not chunk: break buf += chunk - seen.append(json.loads(buf.partition(b"\n")[0])) + seen.append(wire.request(buf.partition(b"\n")[0])) conn.sendall(b'{"status":"ok","data":"uart ready"}\n') threading.Thread(target=run, daemon=True).start() diff --git a/packages/embeddedci/tests/wire.py b/packages/embeddedci/tests/wire.py new file mode 100644 index 0000000..fc80be7 --- /dev/null +++ b/packages/embeddedci/tests/wire.py @@ -0,0 +1,15 @@ +"""Requests as the fake pods in these tests see them, without the two fields every request +carries (``client_api``, ``client``: test_client_api.py checks those).""" + +from __future__ import annotations + +import json +from typing import Any, Dict, Union + +CLIENT_FIELDS = ("client_api", "client") + + +def request(line: Union[bytes, str]) -> Dict[str, Any]: + """One JSON request line, without ``client_api`` and ``client``.""" + req = json.loads(line) + return {k: v for k, v in req.items() if k not in CLIENT_FIELDS} if isinstance(req, dict) else req From dc8cef853e28185c9f3e9b9b29ca33796b782736 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 17:12:15 -0600 Subject: [PATCH 4/4] MCP: name the server in requests, ClientTooOldError says to update it Requests carry "client": "mcp " (embeddedci after 3.0.5). A pod above this server's client API level (on connect) or its BP0030 refusal reaches the agent as ClientTooOldError telling the user to update embeddedci-mcp (uvx embeddedci-mcp@latest, pip install -U embeddedci-mcp, or the benchpod plugin). A coded BP0001 keeps this server's la voltage text. README, guide and CHANGELOG (3.0.6). Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/CHANGELOG.md | 13 +++++ packages/embeddedci-mcp/README.md | 11 ++++ .../src/embeddedci_mcp/guide.py | 2 +- .../src/embeddedci_mcp/server.py | 50 +++++++++++++++++ .../embeddedci-mcp/tests/test_refusals.py | 53 +++++++++++++++++++ 5 files changed, 128 insertions(+), 1 deletion(-) diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index f130c34..e15cf46 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog — `embeddedci-mcp` +## 3.0.6 + +- 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 + higher client API level, or refuses with `BP0030`) fails `connect` and every tool with + `ClientTooOldError`, saying to update the server (`uvx embeddedci-mcp@latest`, + `pip install -U embeddedci-mcp`, or the benchpod plugin) and reconnect. Needs embeddedci after + 3.0.5; with 3.0.5 nothing changes. +- Refusals take their kind from the error code (embeddedci after 3.0.5): `PodBusyError` for an + open I2C or SPI session, `WiringError` for the wiring profiles, and so on. `BP0001` (I/O voltage + not set) keeps this server's text, which names `set_wiring` and `set_la_voltage`. + ## 3.0.5 - Needs embeddedci 3.0.5. diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index dea44bf..395c868 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -456,6 +456,17 @@ capture tools' summaries, `la_timing` and `decode_la` instead. 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")`. +- **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 + picks the kind (`PodBusyError` for an open I2C or SPI session, `WiringError` for the wiring + profiles, ...); the text may change between releases. +- **Client too old.** Every command carries the server's client API level (`client_api`) and + `"client": "mcp "`. When the pod's firmware is newer than this server can talk to (it + announces a higher client API level on `connect`, or refuses a command with `BP0030`), the tool + fails with `ClientTooOldError` and says to update the server: `uvx embeddedci-mcp@latest`, or + `pip install -U embeddedci-mcp`, or update the benchpod plugin, then reconnect. Retrying does + not help. Firmware 3.10.13 and older does not announce a level and works as before. - **Capabilities.** `connect` and `status` report what the pod can do as flags, so an agent can check before it calls a tool: for example `la_pins`, `capture_trigger`, `power_profile`, `nrst_pin`, `can`, `calibrate`, `cal_dmm`, `current_out`, `pod_current`, `sensors` and `analog` (false on the diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index 35217d1..eb04efa 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -14,7 +14,7 @@ Cloud pods: cloud_list_devices lists the pods registered on embeddedci.com (name, online) without connecting to any; connect to one with its `connection` ('embeddedci:'). Tools named cloud_* talk to embeddedci.com, not to a pod. Test runs (benchpod ci, pytest --embeddedci-upload, build_report): cloud_runs_list finds them, cloud_run_get shows the failed cases and measurements outside their limits, cloud_run_trace the pod calls of a failed case, cloud_run_compare what changed since an earlier run. Cloud access (cloud_* and connect to 'embeddedci:') authenticates with BENCHPOD_API_KEY, else the user's `benchpod login` session; if neither exists, ask the user to run `benchpod login`. -Wiring: the pod has 14 generic LA channels (LA1-LA14) and nothing is fixed. Call `wiring` first: it is the bench's profile, normally one of the named profiles stored on the pod itself (the same ones the web app shows; `profile_name`, the pod's default unless connect(wiring_profile=...) named another): which DUT signal is on which channel, the I/O voltage, the target-power rail, the UART baud, the SWD target. Every channel, baud, rail or SWD argument you omit comes from it, and channel arguments also accept its names ("READY", "uart_rx"). What the profile does not set is undefined: when a tool says a pin is missing, ask the user which LA channel it is on, never guess. Confirm the wiring with the user if it looks wrong. `set_wiring` changes it for this connection only: nothing is stored until save_wiring (or the server's --wiring-autosave). Once the wiring works on the board, ask the user whether to save it, and under which name when it is a different board (save_wiring(name='nrf52840')). `unsaved_changes` in the result lists what is not stored; it is lost on disconnect. load_wiring switches to another stored profile, set_default_wiring changes the pod's default (ask first). power_on applies the profile first (its I/O voltage, then the rail) and records it on the pod. Refusals carry a stable code (BP0009 ...) with the fix; follow it. Target power is internal 5 V (efuse 1) or external (efuse 2). The DUT's reset line goes to the pod's own reset pin: flash(nreset=true), reset_target. +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. diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index 8f1b264..842392b 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -71,6 +71,7 @@ from embeddedci.benchpod.cloud_auth import DEFAULT_API_BASE 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 BenchPodError from embeddedci.benchpod.server_api import ServerApi @@ -224,6 +225,49 @@ def _error_text(exc: BenchPodError) -> str: 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") + + +def _mcp_version() -> str: + try: + from importlib.metadata import version + return version("embeddedci-mcp") + except Exception: # a source tree without install + return "unknown" + + +def _name_this_client() -> None: + """Requests from this server carry ``"client": "mcp "`` (embeddedci after 3.0.5).""" + set_name = getattr(_protocol, "set_client_name", None) + if callable(set_name): + set_name(f"mcp {_mcp_version()}") + + +_name_this_client() + + +def _client_too_old_text(exc: BenchPodError) -> Optional[str]: + """The ClientTooOldError of embeddedci after 3.0.5 (a pod above this server's client API + level on connect, or the pod's BP0030), told as what to update: this server, not the SDK.""" + cls = getattr(_errors, "ClientTooOldError", None) + if cls is None or not isinstance(exc, cls): + return None + fw = getattr(exc, "firmware_version", "") or "" + pod = f"the pod's firmware {fw}" if fw else "the pod's firmware" + have, api, need = (getattr(exc, "client_api", 0), getattr(exc, "api", 0), + getattr(exc, "min_client_api", 0)) + if getattr(exc, "code", "") == "BP0030": + why = f"{pod} needs client API {need or '?'} or newer, this server sent {have}" + else: + why = f"{pod} speaks client API {api or '?'}, this server handles {have}" + cmd = getattr(exc, "cmd", None) + text = (f"this BenchPod MCP server (embeddedci-mcp {_mcp_version()}) is too old for this pod: " + f"{why}. Tell the user to {_MCP_UPDATE}") + return f"{cmd}: {text}" if cmd else text + + def _coded_text(exc: BenchPodError) -> Optional[str]: """A refusal with a stable error code, rendered with the catalog's fix for an agent.""" from embeddedci.benchpod.errors import error_catalog @@ -234,11 +278,17 @@ 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 def _tool_error(exc: BenchPodError) -> ToolError: + too_old = _client_too_old_text(exc) + if too_old: + return ToolError(f"{type(exc).__name__}: {too_old}") coded = _coded_text(exc) if coded: return ToolError(f"{type(exc).__name__}: {coded}") diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index 8e5c8e2..ca17b53 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -172,3 +172,56 @@ def test_status_reports_the_macs(connected): connected.status = lambda: dict(real(), eth_mac="02:35:c7:76:b7:9b", wifi_mac="7c:e8:b1:c5:ca:6c") result = call("status") assert result["eth_mac"] == "02:35:c7:76:b7:9b" and result["wifi_mac"] == "7c:e8:b1:c5:ca:6c" + + +# -- the client API level (embeddedci after 3.0.5) --------------------------------------------- + +needs_client_api = pytest.mark.skipif(not hasattr(errors, "ClientTooOldError"), + reason="needs ClientTooOldError (embeddedci after 3.0.5)") + + +@needs_client_api +def test_requests_name_this_server(): + from embeddedci.benchpod import protocol + + assert protocol.client_name().startswith("mcp ") + + +@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} + 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 "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 + + +@needs_client_api +def test_bp0030_on_a_tool_says_to_update_this_server(connected): + def command(req): + raise firmware_error("update the BenchPod SDK, MCP or CLI", cmd=req["cmd"], code="BP0030", + values={"client_api": 1, "min_client_api": 2, "api": 2}) + + connected.command = command + 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 "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: BP0001: la voltage not set; the wiring profile sets no I/O voltage" in msg + assert "call set_la_voltage" in msg