diff --git a/README.md b/README.md index 8e1b391..ab68a38 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # benchpod-cli `benchpod` is the EmbeddedCI **BenchPod** command-line tool. It talks to a -pod over its network TCP/JSON API (port 8080), over its USB console (CDC-ACM), or -through embeddedci.com (`--connection embeddedci:`), and drives the pod's hardware: signal generation, ADC capture, +pod over its network JSON API (TLS on port 8443), over USB (the pod's USB network adapter, +and its console for recovery), or through embeddedci.com (`--connection embeddedci:`), and drives the pod's hardware: signal generation, ADC capture, logic-analyzer pins, Wi-Fi configuration, firmware flashing over SWD, SPI NOR flash programming, and the pod's own firmware, policies and cloud link. Every command and flag is listed in the [command reference](#command-reference). @@ -13,6 +13,44 @@ for you: it finds the pod, gets it on the network, sets the board I/O voltage, registers it with embeddedci.com and saves the connection, skipping whatever is already done. +## Breaking changes in 0.10 + +CLI 0.10 drives BenchPod firmware 4.0 (client API 2). Keep CLI 0.9 for pods you do not update. + +- **Firmware 4.0 only.** Against firmware 3.x only `status`, `flash-self`, `install-blobs`, + `dfu`, `bootsel`, `discover` and `identity` run; every other command exits with the new code + `7` and `this pod needs firmware 4.0: benchpod flash-self`. A newer pod still exits `6`. + `discover` marks such pods from their mDNS `api`. +- **Error codes only.** The CLI classifies and words every refusal by its code (`BP0001` and + up) from the catalog it ships with, never by its text. `BP0002`, `BP0017` and `BP0060` exit + `7`; the busy codes `4`; the others `3`. A refusal without a code is shown as the pod wrote it. +- **TLS on the LAN.** Firmware 4.0 answers its JSON API on Ethernet and Wi-Fi on 8443 (TLS) + only; the CLI uses it and pins the certificate on first use. `--tls off` only works after + `benchpod lan-tls https-only off`. New: `benchpod lan-tls scpi on|off`. The `lan-tls` + switches only work over USB or embeddedci.com. +- **JSON over USB.** `set-wifi`, `show-network`, `scan-wifi`, `clear-wifi`, `identity wipe`, + `sig-policy`, `cloud ca`, `cloud proxy`, `install-blobs`, `usb-reattach`, `la voltage` and + `flash` over USB send JSON over the pod's USB network adapter; the console is only for + `status`, `dfu`, `identity`, `lan-policy`, `usb-network`, `log` and the new `net-reset`. + With USB networking off: `benchpod usb-network on --connection usb`. The console blob + upload for firmware before 3.9.0 is gone. +- **Signatures.** `sig-policy set` is gone: firmware 4.0 always requires signatures (`BP0074`). +- **Removed commands and flags.** `stream`, `la pullup`, `set-bench-pod` (use + `set-connection`), `--connection serial` (use `usb`), `generate --amplitude/--offset` (8-bit + levels; use `--path` with `--amplitude-v`/`--offset-v`, or `--amplitude-ma`/`--offset-ma`), + `--sample-rate-mhz`, `--duration-ms`, `--delay-us`. `la voltage 3300` (bare millivolts) is + refused: a bare number is volts. +- **Renamed flags.** `--output-filename` is `--out` (`BENCHPOD_OUT`); `capture`, `measure` and + `test` take `--format` (was `--output`); `sensor export` writes to `--out`/`-o`; + `flash-self` and `sensor start` take `--addr` (was `--address`). +- **Exit codes.** Usage mistakes the commands find exit `2` (some exited `1`). `benchpod ci` + results moved to `10` (failed), `11` (drift regression) and `12` (invalid), so they never + clash with the codes 0 to 7 of [Exit codes](#exit-codes); a ci usage error is `2`, an + unreachable pod `5`, update the CLI `6`, update the pod `7`. +- **Wiring profiles** come from the pod only (firmware 3.10.8 moved them there); the + embeddedci.com profile fallback and `la voltage` saving to it are gone. +- The `--json` output is unchanged. + ## Installation Pre-built binaries for **macOS, Linux and Windows** (amd64 + arm64) are attached @@ -147,10 +185,11 @@ reach the pod; the transport is inferred from its value: | `embeddedci:` | Through embeddedci.com to the pod with that name on your account (see below). | | *(omitted)* | the default saved by `benchpod discover --save`, `benchpod setup` or `benchpod set-connection`. | -**TLS.** Pods with firmware 3.9.3 or later also serve the API on port 8443 with -TLS. For a network address on the default port (`192.168.1.5`, `:8080`, a pod -name) `benchpod` connects to 8443 first and falls back to plaintext 8080 only when -the pod has no TLS port and has never been pinned. The pod's certificate is +**TLS.** Firmware 4.0 serves the API on Ethernet and Wi-Fi on port 8443 with TLS only +(plaintext 8080 answers on its USB network adapter). For a network address on the default +port (`192.168.1.5`, `:8080`, a pod name) `benchpod` connects to 8443 first, with nothing to +set up, and falls back to plaintext 8080 only when the pod has no TLS port (firmware before +3.9.3, for `flash-self`) and has never been pinned. The pod's certificate is pinned the first time (trust on first use) in `known_pods.json` next to the config; a different certificate later stops the command with both fingerprints. `:8443` means TLS only, any other port and the USB network adapter mean @@ -166,20 +205,22 @@ system resolver as before. The global flags are also settable via a `BENCHPOD_*` environment variable (`BENCHPOD_CONNECTION=usb`, `BENCHPOD_TIMEOUT=2m`, `BENCHPOD_CONFIG_FILE`, -`BENCHPOD_OUTPUT_FILENAME`), with precedence flag > env > default. Command flags +`BENCHPOD_OUT`), with precedence flag > env > default. Command flags are flags only. The firmware itself is unauthenticated; `benchpod login` is independent of the device path and authenticates with `embeddedci-server` (device-login flow) for cloud features. Direct firmware commands on the network or USB do not send tokens. -**USB networking (firmware 3.9.0+).** The pod's USB device is also a network -adapter that carries the full network API on a fixed address (`10.237.x.y`, its own -point-to-point link: the computer keeps its default route and DNS). With a USB -connection (`usb` or a device path), a command that needs the network uses that -adapter, so the whole CLI works over one USB cable; the console is still used for -the commands it runs (below) and as the fallback. USB networking is off while Wi-Fi -is configured on the pod (`set-wifi` turns it off, `clear-wifi` back on). If a +**USB networking.** The pod's USB device is also a network adapter that carries the +full network API on a fixed address (`10.237.x.y`, its own point-to-point link: the +computer keeps its default route and DNS, and the link is plaintext 8080). With a USB +connection (`usb` or a device path) every pod command sends its JSON over that adapter, +so the whole CLI works over one USB cable. The USB console is only used for what firmware +4.0 keeps there: `status`, `dfu`, `identity`, `lan-policy`, `usb-network` and +`net-reset`. USB networking is off while Wi-Fi is configured on the pod (`set-wifi` turns +it off; `clear-wifi` over the pod's network address, or `net-reset` over USB, back on) or +when its `usb-network` setting is off (`benchpod usb-network on --connection usb`). If a command says the adapter is not up, unlock the screen (macOS ignores a new adapter while it is locked) and run `benchpod usb-reattach`. `benchpod usb-bridge` carries the pod's cloud link over the same cable. @@ -198,22 +239,20 @@ WSL2 and Docker on Windows are not tested: Windows routes the pod's `10.237.x.y` itself, so a WSL2 distribution or a container on the host network should reach it with `--connection `, but USB auto-detect and mDNS may not work from inside them. -**Compatibility with older firmware and older CLIs.** The CLI decides per pod, from what -the pod reports (the `usb` line of its console `status`), never from its own version: - -| | Pod firmware before 3.9.0 | Pod firmware 3.9.0 and later | -|---|---|---| -| **This CLI (0.6.0+)** | Works as before: the USB console for `status`, `la voltage`, `install-blobs`, `flash-self`, `set-wifi`, the policies, `cloud ca`/`proxy` and `identity`; the network commands need the pod's network address, as before, and say so. The serial auto-detect still finds `0483:5740` and `2E8A` consoles. | Over `usb`, every command uses the pod's USB network adapter when it is up (including `flash`, which the STM32 pod's console never ran), and the console for the commands that stay there. When USB networking is off (Wi-Fi configured) or not up, the network commands use the pod's Ethernet or Wi-Fi address from its console `status` if this computer reaches it, say so, and are subject to the pod's external LAN policy there (`benchpod clear-wifi` turns USB networking back on). | -| **An older CLI (0.5.x)** | Unchanged. | The kept console commands keep their names and replies (`status`, `dfu`, `identity`, `identity wipe`, `lan-policy`, `sig-policy`, `set-wifi`, `show-network`, `clear-wifi`, `cloud ca show`/`clear`, `cloud proxy`), so those still work, and `flash-self` still flashes over DFU. What 3.9.0 moved to the network API (`la voltage` over USB, and every upload: `install-blobs`, the blob step of `flash-self` and `set-wifi`, `cloud ca set`) prints the pod's "moved to the network API ... update the benchpod CLI to 0.6.0 or later" line: update the CLI with the firmware. Over a network address everything works. | +**Firmware 3.x.** This CLI drives firmware 4.0. Against a pod with firmware 3.x it runs only +what upgrades or inspects the pod: `status`, `flash-self`, `install-blobs` (firmware 3.9.0 +and later), `dfu`, `bootsel`, `discover` and `identity`; every other command stops with exit +code `7` and `this pod needs firmware 4.0: benchpod flash-self`. See +[Firmware and CLI levels](#firmware-and-cli-levels). CLI 0.9 keeps working with firmware 3.x. Which command works over which connection: | Connection | Commands | |---------------------|----------| -| Network address | Every pod command except the USB-only ones below. | -| USB | With firmware 3.9.0+ and no Wi-Fi configured, every network command over the pod's USB network adapter, including `status`, `la voltage`, `flash` (SWD), `install-blobs`, `cloud ca` and `cloud proxy`; without it the pod's Ethernet or Wi-Fi address, and the console where it still has the command. Firmware before 3.9.0: the console, as before. `lan-policy`, `sig-policy` and `identity` always use the console (physical presence). | -| `embeddedci:` | `flash-self`, `status`, `ping`, `la voltage`, `la pull`, `la pullup`, `la status`, `la step`, `la pins`, `la dir`, `i2c`, `generate`, `lan-policy`, `sig-policy`, `cloud ca show`, `cloud ca clear`, `cloud proxy` (show, set, clear), `deregister`. | -| USB only | `set-wifi`, `show-network`, `scan-wifi`, `clear-wifi`, `identity`, `install-blobs`, `bootsel`, `dfu`, `usb-bridge`, `usb-reattach`; `flash-self` uses USB DFU (or, with `--connection embeddedci:`, embeddedci.com). These always use the USB console: a saved address or `embeddedci:` default falls through to USB auto-detection, a device path still selects the port, and an explicit `--connection embeddedci:` is refused. | +| Network address | Every pod command except the USB console ones below. Settings the pod changes only over USB or the cloud (`lan-tls` switches, `cloud ca`/`proxy` changes, `identity wipe`, `usb-network`) are refused there with their code. | +| USB | Every pod command, as JSON over the pod's USB network adapter. With USB networking off (Wi-Fi configured), the pod's Ethernet or Wi-Fi address from its console `status` when this computer reaches it (its external LAN policy applies there), and the command says so. | +| `embeddedci:` | `flash-self`, `status`, `ping`, `la voltage`, `la pull`, `la status`, `la step`, `la pins`, `la dir`, `i2c`, `generate`, `lan-policy`, `sig-policy`, `cloud ca show`, `cloud ca clear`, `cloud proxy` (show, set, clear), `set-wifi`, `show-network`, `scan-wifi`, `clear-wifi`, `deregister`. | +| USB console only | `dfu`, `bootsel`, `net-reset`, `usb-network`, `usb-bridge`, `lan-policy set` over USB; `flash-self` uses USB DFU (or, with `--connection embeddedci:`, embeddedci.com). A saved address or `embeddedci:` default falls through to USB auto-detection, a device path still selects the port, and an explicit `--connection embeddedci:` is refused. | A command that cannot use the connection it is given says so and names what to use instead. @@ -255,7 +294,7 @@ when the pod is in another of your organizations, the `--org` that reaches it. A key belongs to the organization it was created in. Commands that stream data or need a direct link to the pod do not go through -embeddedci.com: `capture`, `stream`, `measure`, `test`, `flash --file`, `spi-flash`, +embeddedci.com: `capture`, `measure`, `test`, `flash --file`, `spi-flash`, `cloud ca set`, `register`, the USB-only commands and `discover`. Over a cloud connection they refuse with a message pointing to the web app, the Python SDK or pytest plugin (which take `embeddedci:` for those too), or a network/USB @@ -264,9 +303,10 @@ cloud connection: embeddedci.com runs OpenOCD. The CLI has no UART command; use ### One wiring profile -The pod's wiring profile on embeddedci.com (the web app's Wiring tab; the SDK and -MCP read the same one) says which LA channel carries which signal. `flash` and -`spi-flash` take the pins you leave out from it: +The pod keeps its wiring profiles itself (the web app's Pins pane, the SDK and MCP read the +same ones; `benchpod wiring` lists and saves them): which LA channel carries which signal. +Commands that take pins (`flash`, `spi-flash`, `i2c`, `sensor start`, ...) take the ones you +leave out from the profile named by `--wiring-profile`, else the pod's default: | Command | Flag | Profile field | |-------------|--------------|---------------| @@ -276,16 +316,9 @@ MCP read the same one) says which LA channel carries which signal. `flash` and | `flash` | `--target` | `swd_target` | | `spi-flash` | `--sck`, `--mosi`, `--miso`, `--cs` | `spi_sclk`, `spi_mosi`, `spi_miso`, `spi_cs` | -That happens when the connection is the pod's network address (or, for `flash --build`, -`embeddedci:`), this machine is -signed in (`benchpod login` or `BENCHPOD_API_KEY`) and the pod is on that account -(its `cloud_status` device id is in the account's pod list, as `status` and -`discover` check). Flags always win. The log says which values came from the -profile (`[benchpod] flash: SWCLK LA11, SWDIO LA12 from the pod's wiring profile on -embeddedci.com; ...`) or that the flags were used. Without a profile (over USB, not -signed in, another account) the command behaves as before: the pin flags are -required. If the lookup fails (it gives up after a few seconds), the CLI prints one -warning line and goes on with the flags. +Flags always win. The log says which values came from the profile (`[benchpod] flash: SWCLK +LA11, SWDIO LA12 from the pod's wiring profile; ...`) or that the flags were used. Firmware +before 3.10.8 kept one profile on embeddedci.com instead; CLI 0.10 reads only the pod's. ### Shared config @@ -338,10 +371,9 @@ benchpod status --json # the pod's raw status reply # Hardware (network): benchpod la voltage 3.3V # the DUT's I/O voltage for now (it normally comes from the wiring profile) benchpod la voltage 5V # digital board v3r4: 5 V I/O (see the 5 V page linked under la voltage) -benchpod generate --waveform sine --freq 1kHz --duration 2s # DAC waveform +benchpod generate --waveform sine --freq 1kHz --path 3v3 --amplitude-v 1 --offset-v 1.65 --duration 2s # DAC waveform benchpod measure --waveform sine --samples 1024 # DAC + ADC loopback -benchpod capture --samples 1024 --output csv # ADC snapshot -benchpod stream ... +benchpod capture --samples 1024 --format csv # ADC snapshot benchpod test ... benchpod la pull 3 up # LA pin pull resistor: up, down or off (digital v3r4: every pin, strength picked by the pod) benchpod la status @@ -352,13 +384,14 @@ benchpod la dir 9,10 dut_output # the pod refuses push-pull dr benchpod i2c start --sda 1 --scl 2 --hz 400000 # the pod as an I2C master (gateware v55+) benchpod i2c xfer 0x48 --write 0d --read 2 # hex in, hex out -# Network (always over the USB console): +# Network (over the pod's USB network adapter): benchpod set-wifi benchpod show-network # the pod's IP (wired lease included), SSID, state, RSSI -benchpod scan-wifi # networks the pod's Wi-Fi sees (firmware 3.9.4+) +benchpod scan-wifi # networks the pod's Wi-Fi sees benchpod clear-wifi +benchpod net-reset # no network reaches the pod: forget Wi-Fi, reset Ethernet (USB console) -# One USB cable (firmware 3.9.0+, no Wi-Fi configured): +# One USB cable (no Wi-Fi configured): benchpod capture --connection usb ... # network commands use the pod's USB network adapter benchpod usb-bridge # the pod's cloud link through this computer (Ctrl-C stops it) benchpod usb-reattach # re-enumerate on USB (macOS: after unlocking the screen) @@ -383,10 +416,9 @@ benchpod logout # Pod policies (cloud with --device-name, or USB): benchpod lan-policy --device-name benchpod-baea06 # show benchpod lan-policy set locked --device-name benchpod-baea06 -benchpod sig-policy --connection usb # show -benchpod sig-policy set permissive --connection usb +benchpod sig-policy --connection usb # show (always required) -# Device identity (USB console only): +# Device identity (USB only): benchpod identity --connection usb # show benchpod identity wipe --connection usb # erase the key, make a new one @@ -399,8 +431,8 @@ benchpod cloud proxy clear Flags that take a physical quantity accept it with its unit: `--freq 2kHz`, `--sample-rate 10MHz`, `--duration 2s`, `--delay 50us`, and `benchpod la voltage 3.3V`. -The older flags with the unit in their name (`--sample-rate-mhz`, `--duration-ms`, -`--delay-us`) keep working; pass one or the other, not both. +CLI 0.10 dropped the older flags with the unit in their name (`--sample-rate-mhz`, +`--duration-ms`, `--delay-us`). `deregister` is the inverse of `register`: it detaches the pod from the logged-in account and clears the pod's cloud configuration so it stops @@ -437,16 +469,16 @@ Two settings the pod keeps in its config flash: | `locked` | read and instrument control only; config and firmware need cloud or USB | | `off` | nothing: no LAN listener, no mDNS. The cloud and USB keep working | -| `sig-policy` | How firmware and blob signatures are treated | -|--------------|---------------------------------------------------------------------------| -| `audit` | every image is accepted; signatures are only reported | -| `permissive` | unsigned images are accepted, a bad signature is refused | -| `required` | unsigned images are refused | +`sig-policy` (how firmware and blob signatures are treated) is always `required` from +firmware 4.0: the pod installs only signed images on every path, and the policy cannot be +loosened (`BP0074`). Install firmware you built yourself over USB DFU (`benchpod flash-self +./fw.bin`). -`benchpod lan-policy` and `benchpod sig-policy` show the policy; `... set ` -changes it. Pick the pod with `--device-name` / `--device-id` (through -embeddedci.com, like `deregister`) or with `--connection usb`. Over the LAN the -commands can only show the policy: the pod refuses changes from the LAN. +`benchpod lan-policy` and `benchpod sig-policy` show the policy; `lan-policy set ` +changes the LAN policy. Pick the pod with `--device-name` / `--device-id` (through +embeddedci.com, like `deregister`) or with `--connection usb` (`sig-policy` over the pod's +USB network adapter, `lan-policy set` over its console). Over the LAN the commands can only +show the policy: the pod refuses changes from the LAN. ``` $ benchpod lan-policy --device-name benchpod-baea06 @@ -455,9 +487,6 @@ LAN policy of benchpod-baea06: locked (read and instrument control only on the L - Over the cloud a change needs an organization owner or admin (an API key needs the `benchpod:admin` scope). -- The cloud can only make `sig-policy` stricter. Only the USB console can loosen - it (`benchpod sig-policy set permissive --connection usb`); the CLI says so when - the pod refuses. - With `lan-policy off`, LAN tools stop working until it is set back: SCPI/VISA, hwe2e `TestHW` and LAN `discover`. Set it back over the cloud or USB. - Firmware without these commands gets "this firmware has no LAN policy; update @@ -465,15 +494,18 @@ LAN policy of benchpod-baea06: locked (read and instrument control only on the L #### LAN TLS: encrypted LAN API -The pod's API on port 8443 is the same as on 8080, over TLS (firmware 3.9.3+). The -pod makes its own key and self-signed certificate on first boot; `benchpod` -pins it on first use. `benchpod lan-tls` shows it: +The pod's API on port 8443 is the same as on 8080, over TLS. From firmware 4.0 it is the only +port the JSON API answers on over Ethernet and Wi-Fi (HTTPS-only is on by default), and SCPI is +off until you switch it on. The pod makes its own key and self-signed certificate on first boot +and keeps it across updates; `benchpod` pins it on first use, so this needs no action from you. +`benchpod lan-tls` shows it: ``` $ benchpod lan-tls --connection 192.168.1.220 LAN TLS of 192.168.1.220:8080 (connected over TLS) port 8443 - https-only off + https-only on + scpi off sessions 1 certificate CN=benchpod-baea06 (generated, EC P-256), valid to 9999-12-31 names benchpod-baea06, benchpod-baea06.local @@ -481,9 +513,11 @@ LAN TLS of 192.168.1.220:8080 (connected over TLS) pinned yes, for 192.168.1.220:8443 ``` -- `benchpod lan-tls https-only on` turns plaintext 8080 off on Ethernet and Wi-Fi - (the pod keeps it on its USB link). Use it when the LAN path is shared, for - example through a Wi-Fi bridge. +- `benchpod lan-tls https-only off` turns plaintext 8080 back on for Ethernet and + Wi-Fi (for older tools); `on`, the default, takes only TLS there. The pod keeps + 8080 on its USB link either way. +- `benchpod lan-tls scpi on` turns SCPI on: it then answers on 8443 and on 8080 (on + the LAN, 8080 takes SCPI only while HTTPS-only is on); `off` turns it off again. - `benchpod lan-tls set-cert --cert pod.pem --key pod.key` installs your own certificate (with its chain) and unencrypted key; `regenerate` makes a new self-signed one. Both update this computer's pin. @@ -494,9 +528,11 @@ LAN TLS of 192.168.1.220:8080 (connected over TLS) - A TLS handshake costs the pod about 0.5 s; `benchpod` keeps the pod's session ticket for an hour in `tls_sessions.json` (mode 0600, next to the pins), so later runs resume in about 40 ms. -- The pod refuses `https-only off`, `regenerate` and `set-cert` over plaintext - Ethernet or Wi-Fi: use TLS (the default), `--connection usb` or - `--connection embeddedci:`. +- `https-only`, `scpi`, `regenerate` and `set-cert` only work over USB + (`--connection usb`, the pod's USB network adapter) or through embeddedci.com + (`--connection embeddedci:`): the pod refuses them from Ethernet and Wi-Fi, + TLS or not (`BP0042`). The pod's USB console has the same switches + (`lan-tls https-only on|off`, `lan-tls scpi on|off`). - `benchpod lan-tls show --pem > pod.pem` saves the certificate, for curl or socat (VISA raw sockets have no TLS; see the firmware API docs, LAN TLS). @@ -516,8 +552,10 @@ The pod stays offline without an identity. Recover it with: benchpod identity wi ``` `benchpod identity wipe` erases the key and makes a new one. It works only over -the pod's USB console (`--connection usb` or a serial device path): the pod -refuses it over the LAN and the cloud, so it needs someone at the pod. The CLI +USB (`--connection usb` or a serial device path): the CLI reads the identity on the +pod's console and sends the wipe (`identity_wipe`) over its USB network adapter; the +pod refuses it over the LAN and the cloud (`BP0043`), so it needs someone at the pod. +With USB networking off, `benchpod usb-network on --connection usb` turns it on. The CLI shows the current identity and asks before it wipes (`--yes` skips the question for scripts); the pod also checks a confirmation token (the current short id, or `unknown`), so a stray command cannot wipe a key. @@ -540,26 +578,26 @@ belongs to the old record. On a network whose proxy inspects TLS, the pod's cloud link fails: the proxy re-signs embeddedci.com with a company root the pod does not trust. Some networks also only reach the internet through an HTTP proxy. `benchpod cloud` sets both -over the USB console (`--connection usb`) or through embeddedci.com +over the pod's USB network adapter (`--connection usb`) or through embeddedci.com (`--connection embeddedci:`: `cloud proxy` show, set and clear, `cloud ca` show and clear; the CA upload needs USB, and a change needs an organization owner or -admin). The LAN (`--connection
`) can show them; current firmware refuses -changes from the LAN: +admin). The LAN (`--connection
`) can show them; the pod refuses changes +from the LAN. With USB networking off, `benchpod usb-network on --connection usb` +turns it back on: ``` $ benchpod cloud ca set acme-root.pem --connection usb acme-root.pem: 1 certificate CN=Acme Root CA,O=Acme Corp SHA-256 3b1f...c2d9 -Uploading 652 bytes to the pod on /dev/cu.usbmodem1101 ... -Company CA of the pod on /dev/cu.usbmodem1101 is now 1 certificate +Company CA of 10.237.8.85:8080 is now 1 certificate CN=Acme Root CA,O=Acme Corp SHA-256 3b1f...c2d9 The pod reconnects to the cloud, trusting this CA in addition to its built-in roots. $ benchpod cloud proxy set proxy.corp:3128 --user alice --connection usb Proxy password: -HTTP proxy of the pod on /dev/cu.usbmodem1101 is now proxy.corp:3128 (with a user and password) +HTTP proxy of 10.237.8.85:8080 is now proxy.corp:3128 (with a user and password) The pod reconnects to the cloud through proxy.corp:3128. ``` @@ -576,20 +614,15 @@ The pod reconnects to the cloud through proxy.corp:3128. TCP and the password would cross the network unencrypted. - `show` (the default) reports what the pod holds. The pod reconnects to the cloud after every change. -- Current firmware refuses `set` and `clear` from the LAN, whatever its LAN - policy: only USB or the cloud link may change the company CA or the proxy. The - CLI then prints the pod's reason and a hint to rerun with `--connection usb`: +- The pod refuses `set` and `clear` from the LAN, whatever its LAN policy: only + USB or the cloud link may change the company CA or the proxy (`BP0042`). The + CLI shows the code, the reason and to rerun with `--connection usb`: ``` $ benchpod cloud proxy clear --connection 192.168.1.50 - [benchpod] cloud proxy clear: the pod refused: cloud_proxy: change it from the cloud or over USB (the pod only takes this change over USB or from the cloud, never from Ethernet or Wi-Fi; run it with --connection usb) + [benchpod] cloud proxy clear: the pod refused: BP0042: cloud_proxy cannot be changed over the LAN: change it from the cloud or over USB; run this over USB with --connection usb, or from the cloud (https://embeddedci.com/docs/errors#BP0042) ``` - Older firmware with its LAN policy `locked` refuses the same way, with its own - message. -- Firmware without them gets "this firmware has no company CA support; update the - pod's firmware" (or the same for the HTTP proxy). - Run `benchpod -h` for the flags of any subcommand. #### Flashing: CMSIS-DAP @@ -599,8 +632,8 @@ intelligence and OpenOCD's exit code is the verdict. The pod runs a CMSIS-DAP processor locally and OpenOCD's `cmsis-dap` **TCP backend** ships whole DAP transfers (`DAP_Transfer`/`DAP_TransferBlock`), so a flash is one round-trip per DAP command instead of thousands of per-bit round-trips — fast even over the -network. Works on **TCP** (`dap_start`) and **USB** (the console `dap-start` -command). It needs a **recent OpenOCD with the `cmsis_dap_tcp` backend** +network. Works on **TCP** (`dap_start`), over the network or over USB on the pod's +USB network adapter (firmware 4.0 has no probe on its console). It needs a **recent OpenOCD with the `cmsis_dap_tcp` backend** (post-0.12.0; e.g. `brew install --HEAD open-ocd`); the CLI checks for the backend up front and fails with clear advice if it is missing. @@ -611,9 +644,9 @@ speaks it. `spi-flash` reads, erases and programs a 25-series SPI NOR flash (W25Q, MX25, GD25, IS25, ...) wired to four LA pins, through the pod's SPI master. It needs -gateware v45 or newer (`spi_master` in the `status` caps; the CLI checks first) +gateware v45 or newer (`spi_master` in the features table; the CLI checks first) and the LA voltage set. Network (TCP) connection only for now. Pins you leave out -come from the pod's wiring profile on embeddedci.com when you are signed in (see +come from the pod's wiring profile (see [One wiring profile](#one-wiring-profile)). ```bash @@ -776,10 +809,10 @@ dies it expires on its own after 5 minutes. Every command the run sends to the p the lease's id, and so do the commands of its pytest and run steps (the SDK reads `BENCHPOD_LEASE`). -A pod that is in use when the run starts ends it at once with exit code 4 and who holds it; +A pod that is in use when the run starts ends it at once with exit code 12 and who holds it; `--wait 10m` waits for it instead. A pod whose firmware has no lease gets one warning and the run goes on without one. A lease lost during the run (someone stopped the run from the web -app, the pod rebooted) makes the run invalid (exit code 4). The step that is running stops +app, the pod rebooted) makes the run invalid (exit code 12). The step that is running stops at once (a pytest or run step is stopped like at its timeout, and the cases it recorded so far are kept), the steps left are skipped, and cleanup still runs, without the lease (if another session took the pod meanwhile, the pod refuses it, and `logs/cleanup.log` says so). @@ -855,7 +888,7 @@ suite: process-node-hil # required: the name runs are stored and compar dut: process-node # required: the board on the pod; "none" for a pod-only suite wiring: process-node # the pod's stored wiring profile (default: the pod's default) require: - pod_firmware: ">=3.10.12" # not met: the run is invalid (exit 4) and nothing is driven + pod_firmware: ">=3.10.12" # not met: the run is invalid (exit 12) and nothing is driven firmware: build: make -C firmware # optional; runs in this file's directory before flashing file: firmware/build/app.elf # the image to flash (relative to this file) @@ -868,7 +901,7 @@ keep: {traces: failed} # all | failed | none cleanup: default # or none, or a list: [dac_stop, power_off, sensors_off, pulls_off] upload: auto # auto (when signed in) | true | false baseline: main # after the upload, compare with the last valid run on this branch -gate: drift # optional: every drift allowance gates (exit 3); default: per metric +gate: drift # optional: every drift allowance gates (exit 11); default: per metric steps: - id: boot # stable id: the case id across runs (default: from name) power_cycle: {until: "APP_OK", timeout: 10s, off_ms: 500} @@ -940,10 +973,10 @@ Baseline main (run 3f9c...): 0 newly failing, 1 fixed, 2 drifted, 1 beyond a gat ``` A measurement whose change against the baseline is beyond its `drift` allowance fails the run -with exit code 3 when the metric says `fail_on_drift: true`, or the file says `gate: drift` +with exit code 11 when the metric says `fail_on_drift: true`, or the file says `gate: drift` (every measurement with a drift allowance gates, including the ones a test records with -`measure()`; `fail_on_drift: false` on a metric opts it out). Exit code 3 only replaces a -passing run's 0: a failed or invalid run keeps its 2 or 4. Without a baseline run on the +`measure()`; `fail_on_drift: false` on a metric opts it out). Exit code 11 only replaces a +passing run's 0: a failed or invalid run keeps its 10 or 12. Without a baseline run on the branch yet, or when the run was not uploaded, the compare is skipped with a note and gates nothing. @@ -974,13 +1007,21 @@ from a repository the organization trusts. ### Exit codes of `benchpod ci` +Codes 0 to 7 mean what they mean for every other command ([Exit codes](#exit-codes)); a run's +results are 10 and up, so a script never mistakes one for the other (CLI 0.10 moved them from 2, +3 and 4). + | Code | Meaning | |---|---| | `0` | Every case passed (skipped and expected failures included). | -| `1` | A file, usage or setup error: the YAML, the firmware build, no pod, a missing wiring profile, `upload: true` without a sign-in. | -| `2` | A test failed or errored, or a required step failed. | -| `3` | The run passed, but a gated measurement drifted beyond its allowance against the baseline (see [Baseline gating](#baseline-gating)). | -| `4` | The run is not valid: the pod was in use, `require` was not met, the pod rebooted or stopped answering, the lease was lost, a capture lost samples, or the run was interrupted. | +| `1` | A file or setup error: the YAML, the firmware build, a missing wiring profile, `upload: true` without a sign-in. | +| `2` | Usage: a bad flag or argument. | +| `5` | The pod did not answer, or no pod was found. | +| `6` | The pod's firmware needs a newer benchpod CLI. | +| `7` | The pod's firmware is too old for this CLI (firmware before 4.0: `benchpod flash-self`). | +| `10` | A test failed or errored, or a required step failed. | +| `11` | The run passed, but a gated measurement drifted beyond its allowance against the baseline (see [Baseline gating](#baseline-gating)). | +| `12` | The run is not valid: the pod was in use, `require` was not met, the pod rebooted or stopped answering, the lease was lost, a capture lost samples, or the run was interrupted. | ## Command reference @@ -1001,9 +1042,9 @@ and `token.json` for the embeddedci.com session. |---------------------|----------------------------------|-------------------------------------------------------------------| | `--connection` | (saved `set-connection` target) | Network address, pod name (`benchpod-a1b2c3`), device path, `usb`, or `embeddedci:` (through embeddedci.com); see [Connection](#connection). | | `--config-file` | `~/.config/benchpod-cli/config.json` | The CLI's config file, where `set-connection` saves the default. | -| `--output-filename` | (stdout) | Write command output to this file instead of stdout. | +| `--out` | (stdout) | Write command output to this file instead of stdout (`benchpod ci` takes `--out` as its run folder). Also `BENCHPOD_OUT`. | | `--timeout` | `0` (per-command default) | Overall command deadline; `0` uses each command's own default. | -| `--tls` | `auto` | TLS to the pod's LAN API: `auto` (8443 when the pod has it, pinned on first use), `on` (TLS only) or `off` (plaintext 8080). Also `BENCHPOD_TLS`. See [Connection](#connection). | +| `--tls` | `auto` | TLS to the pod's LAN API: `auto` (8443 when the pod has it, pinned on first use), `on` (TLS only) or `off` (plaintext 8080; firmware 4.0 answers it on the LAN only after `benchpod lan-tls https-only off`). Also `BENCHPOD_TLS`. See [Connection](#connection). | | `--tls-ca` | (none) | PEM file of CA certificates: verify the pod's certificate and name against them instead of pinning. Also `BENCHPOD_TLS_CA`. | | `--org` | (the active organization) | The embeddedci.com organization cloud calls act in: its id, slug or name. Also `BENCHPOD_ORG`. See [Organizations](#organizations). | | `--wiring-profile` | (the pod's default profile) | The wiring profile stored on the pod that fills in the pins a command leaves out (`flash`, `i2c`, `spi-flash`, ...). Also `BENCHPOD_WIRING_PROFILE`. See [`benchpod wiring`](#benchpod-wiring). | @@ -1038,25 +1079,33 @@ stderr with a `[benchpod]` prefix. | `3` | Refused: the pod refused the command (a locked LAN, a missing role, a bad request). | | `4` | Busy: the pod or one of its engines is in use (a cloud job's lease, another session). | | `5` | Unreachable: nothing answered on the pod's address, no pod was found on USB, or the pod is offline on embeddedci.com. | -| `6` | Update the CLI: the pod's firmware needs a newer benchpod CLI (see [Firmware newer than the CLI](#firmware-newer-than-the-cli)). | +| `6` | Update the CLI: the pod's firmware needs a newer benchpod CLI (see [Firmware and CLI levels](#firmware-and-cli-levels)). | +| `7` | Update the pod: its firmware is older than this CLI drives (firmware before 4.0: run `benchpod flash-self`), or it lacks what the command needs (`BP0002`, `BP0017`, `BP0060`). | `benchpod ci` has its own exit codes (a CI result, not a command's): see [Exit codes of `benchpod ci`](#exit-codes-of-benchpod-ci). -#### Firmware newer than the CLI +#### Firmware and CLI levels Every JSON command the CLI sends to the pod (on the LAN, over USB networking and through -embeddedci.com) carries `"client_api"`, the pod API level this CLI was built for, and -`"client"`, its name and version (`"cli 0.9.5"`). Firmware 3.10.13 and older ignores both. -Newer firmware announces its own level in `status`; it goes up only when the firmware changes -a reply in a way an older CLI would misread. When the pod's level is above this CLI's (a pod -without one counts as level 1), a command that reads the pod's status stops with exit code -`6` and says so. `status`, `flash-self`, `install-blobs`, `dfu`, `bootsel`, `discover` and -`identity` still run: `status` prints the same line as a warning, and the firmware commands are -how such a pod is updated or rolled back. +embeddedci.com) carries `"client_api"`, the pod API level this CLI was built for (2), and +`"client"`, its name and version (`"cli 0.10.0"`). The pod announces its own level in `status`; +it goes up only when the firmware changes a reply in a way an older CLI would misread. + +This CLI drives firmware 4.0 (level 2) only. Before a pod's first command it reads the pod's +status once and stops when the level does not match: + +- A pod above level 2 needs a newer CLI: exit code `6`. +- A pod below level 2 (firmware 3.x announces no level, which counts as 1) needs firmware 4.0: + exit code `7`, with `this pod needs firmware 4.0: benchpod flash-self`. + +`status`, `flash-self`, `install-blobs`, `dfu`, `bootsel`, `discover` and `identity` still run +against a pod of any level: `status` prints the same line as a warning, and the firmware commands +are how such a pod is updated or rolled back. Against firmware 3.x they send what 3.x takes. ```text -[benchpod] la voltage: this pod's firmware 3.11.0 needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod, or download the latest release from https://github.com/embeddedci-com/benchpod-cli/releases/latest +[benchpod] la voltage: this pod's firmware 3.10.13 is too old for this benchpod CLI (pod API 1, this CLI needs 2): this pod needs firmware 4.0: benchpod flash-self +[benchpod] la voltage: this pod's firmware 5.0.0 needs a newer benchpod CLI (pod API 3, this CLI handles 2): brew upgrade --cask benchpod, or download the latest release from https://github.com/embeddedci-com/benchpod-cli/releases/latest ``` A pod that no longer takes commands from a CLI this old refuses them with `BP0030`, which @@ -1064,19 +1113,21 @@ the CLI reports the same way. Update the CLI as you installed it (see [Installation](#installation)). Commands that only talk to embeddedci.com or work locally are not affected, and neither is the USB console. -Firmware 3.10.8 and later sends more and more refusals with a stable error code (`BP0001` and up). -The CLI then shows the code, what went wrong and what to run, from the error catalog it ships -with, plus a link to the code's page; `benchpod explain ` prints the whole entry. The -exit code follows the code: a session, the bus engine, the storage or a lease in use -(`BP0003`, `BP0004`, `BP0005`, `BP0016`, `BP0025`) is `4`, every other code `3`. +#### Error codes + +Every refusal a script or user acts on has a stable error code (`BP0001` and up), and firmware +4.0 sends only the code and its values. The CLI shows the code, what went wrong and what to run, +from the error catalog it ships with, plus a link to the code's page; `benchpod explain ` +prints the whole entry. The exit code follows the code: -A refusal without a code (older firmware, or one that has no code yet) is printed word for -word as the pod sent it. For a `locked:` (LAN policy), -`busy:` (cloud lease) or `forbidden:` (missing role) refusal the CLI adds what to do next. -So it does for `la voltage not set` (run `benchpod la voltage 3.3V` or 1.8V, or set it on -the web app's Wiring tab) and for a `pin conflict: LA4 is in use by ...`, where the raw -JSON command the firmware suggests is replaced by where to free the pin (the web app, -the SDK or the MCP session that holds it). +- `4` (busy): a session, the bus engine, the storage, a lease or the pod in use (`BP0003`, + `BP0004`, `BP0005`, `BP0016`, `BP0025`, `BP0047` to `BP0052`, `BP0066`). +- `7` (update the pod): `BP0002`, `BP0017`, `BP0060`. +- `6` (update the CLI): `BP0030`. +- `3` (refused): every other code. + +A refusal without a code (a bad argument, a failure only a person reads) is printed word for +word as the pod sent it, with exit code `3`. The CLI never reads a refusal's text. ### `benchpod setup` @@ -1170,6 +1221,11 @@ LAN address when the pod has one, and `usb` when it was only heard on its USB li `10.237.x.y` address only works while the pod is plugged into this computer, so it is never saved; `usb` finds the pod again on any port. +The API level a pod advertises over mDNS (`api` in its TXT record, firmware 4.0 and later; none +is level 1) marks a pod this CLI does not drive: `needs firmware update` for firmware before 4.0 +(update it with `benchpod flash-self`), `needs a newer CLI` for a pod above level 2. See +[Firmware and CLI levels](#firmware-and-cli-levels). + Each pod on USB also gets a `MAC` line: its Ethernet MAC and, on firmware after 3.10.7 with Wi-Fi, the MAC it uses on Wi-Fi (`not known yet` until a `benchpod scan-wifi` or a join). Give them to your network admin when the network hands out addresses only to registered devices. @@ -1198,9 +1254,11 @@ the network address and link, the cloud registration (and, when this machine is signed in, whether the pod is on your account), and a cloud job's lease when one holds the pod. With firmware 3.9.0+ a `USB` line shows the pod's USB network address and warns when the USB port powering the pod offers only default USB power (500 mA), -which may not carry the pod plus a DUT on the internal 5 V rail. Over USB it asks over -the pod's USB network adapter when that is up, else it prints the console's `status` -text. +which may not carry the pod plus a DUT on the internal 5 V rail. On a two-board pod whose +digital board and analog module use different flat-cable pinouts, a `DAC` line says +`off: board/module pinout mismatch` (the pod keeps the DAC off and refuses DAC commands with +`BP0080`). Over USB it asks over the pod's USB network adapter when that is up, else it prints +the console's `status` text. ```text BenchPod at 192.168.1.220:8080 @@ -1227,11 +1285,10 @@ shows them. Start DAC waveform output (network or embeddedci.com). -Give the waveform in volts with `--path`, `--amplitude-v` and `--offset-v` (or in mA on the 4-20 mA -output with `--amplitude-ma` and `--offset-ma`): firmware 3.9.1 and later calibrates it and plays it -at the DAC's full 16 bits, about 50 µV a step on the 3.3 V output. The CLI checks the pod has it -first and refuses on older firmware. `--amplitude` and `--offset` are the older 8-bit levels: 256 -steps over the output, no calibration. +Give the waveform in volts with `--path`, `--amplitude-v` and `--offset-v`, or in mA on the 4-20 mA +output with `--amplitude-ma` and `--offset-ma`: the pod calibrates it and plays it at the DAC's +full 16 bits, about 50 µV a step on the 3.3 V output. One of the two is required: firmware 4.0 +has no 8-bit levels for `generate` (CLI 0.10 dropped `--amplitude` and `--offset` here). ```bash benchpod generate --waveform sine --freq 1kHz --path 3v3 --amplitude-v 1.48 --offset-v 1.65 @@ -1241,17 +1298,13 @@ benchpod generate --waveform sine --freq 1kHz --path 3v3 --amplitude-v 1.48 --of |---------------------|---------|-----------------------------------------------------------| | `--waveform` | (required) | `sine`, `square` or `sawtooth`. | | `--freq` | `1kHz` | Output frequency with its unit, e.g. `2kHz`; a bare number is Hz. | -| `--path` | | DAC output for the volts: `3v3`, `5v` or `12v` (firmware 3.9.1+). | -| `--amplitude-v` | | Peak in volts on `--path`, 16-bit and calibrated (firmware 3.9.1+). | +| `--path` | | DAC output for the volts: `3v3`, `5v` or `12v`. | +| `--amplitude-v` | | Peak in volts on `--path`, 16-bit and calibrated. | | `--offset-v` | | Center in volts on `--path`, with `--amplitude-v`. | -| `--amplitude-ma` | | Peak in mA on the 4-20 mA output (J9), 16-bit (firmware 3.9.1+). | +| `--amplitude-ma` | | Peak in mA on the 4-20 mA output (J9), 16-bit. | | `--offset-ma` | | Center in mA on the 4-20 mA output, with `--amplitude-ma`. | -| `--amplitude` | `127` | Half-scale amplitude in 8-bit levels, 0-127. | -| `--offset` | `128` | DC offset in 8-bit levels, 0-255. | | `--duration` | `0` | How long to play, e.g. `2s` or `500ms`; `0` runs until the next command. | -| `--duration-ms` | `0` | The same in ms (older form of `--duration`). | | `--sample-rate` | auto | FPGA sample-clock rate, e.g. `10MHz`; leave it out to auto-pick. | -| `--sample-rate-mhz` | auto | The same in MHz (older form of `--sample-rate`). | ### `benchpod capture` @@ -1260,24 +1313,13 @@ Blocking ADC snapshot (network). Prints the samples. | Flag | Default | Purpose | |---------------------|---------|------------------------------------------------------| | `--samples` | `256` | Number of ADC samples, 1-4096. | -| `--output` | `json` | Output format: `json`, `csv` or `ndjson`. | +| `--format` | `json` | Output format: `json`, `csv` or `ndjson`. | | `--sample-rate` | max | ADC sample rate, e.g. `100kHz`; leave it out for the maximum (400 kSPS). | -| `--sample-rate-mhz` | max | The same in MHz (older form of `--sample-rate`). | - -### `benchpod stream` - -Asynchronous ADC capture (network). Same flags and output as `capture`. - -| Flag | Default | Purpose | -|---------------------|---------|------------------------------------------------------| -| `--samples` | `256` | Number of ADC samples, 1-4096. | -| `--output` | `json` | Output format: `json`, `csv` or `ndjson`. | -| `--sample-rate` | max | ADC sample rate, e.g. `100kHz`; leave it out for the maximum (400 kSPS). | -| `--sample-rate-mhz` | max | The same in MHz (older form of `--sample-rate`). | ### `benchpod measure` -DAC plus ADC loopback capture (network): play a waveform and capture the ADC. +DAC plus ADC loopback capture (network): play a waveform and capture the ADC. It keeps the +8-bit `--amplitude` and `--offset` codes (the pod builds the waveform at 8 bits for it). | Flag | Default | Purpose | |---------------------|---------|------------------------------------------------------| @@ -1286,9 +1328,8 @@ DAC plus ADC loopback capture (network): play a waveform and capture the ADC. | `--amplitude` | `127` | Half-scale amplitude code, 0-127. | | `--offset` | `128` | DC offset code, 0-255. | | `--samples` | `256` | Number of ADC samples, 1-4096. | -| `--output` | `json` | Output format: `json`, `csv` or `ndjson`. | +| `--format` | `json` | Output format: `json`, `csv` or `ndjson`. | | `--sample-rate` | auto | Sample-clock rate, e.g. `10MHz`; leave it out to auto-pick. | -| `--sample-rate-mhz` | auto | The same in MHz (older form of `--sample-rate`). | ### `benchpod test` @@ -1299,7 +1340,7 @@ A diagnostic sample pattern made by the pod's MCU, without the FPGA (network). | `--pattern` | `sine` | `sine`, `counter`, `ramp` or `const` (`const` when only `--value` is set). | | `--value` | `255` | Constant byte value, 0-255, for the `const` pattern. | | `--samples` | `256` | Number of samples, 1-4096. | -| `--output` | `json` | Output format: `json`, `csv` or `ndjson`. | +| `--format` | `json` | Output format: `json`, `csv` or `ndjson`. | ### `benchpod adc-range [show|normal|low|test]` @@ -1384,7 +1425,7 @@ your own part. | Flag | Default | Purpose | |-------------------|---------|---------------------------------------------------------------| -| `--output`, `-o` | (stdout) | Write to this file. | +| `--out`, `-o` | (stdout) | Write to this file. | | `--version` | (none) | Library version (default: the pinned one, or the saved one). | | `--format-doc` | `false` | Write the library's format reference (`docs/format.md`) instead. | @@ -1414,16 +1455,16 @@ replaces it. It prints the params `sensor set` takes. | Flag | Default | Purpose | |--------------|---------|---------| -| `--pin` | (none) | `role=channel`, repeatable. I2C `sda`, `scl` (default: the wiring profile's `i2c_sda`/`i2c_scl` on embeddedci.com) and `drdy`; SPI `sclk`, `mosi`, `miso`, `cs` (default: the profile's `spi_*`; the emulated SPI target has no data-ready pin); UART `tx` (pod to DUT RX) and `rx`; analog `output=dac` (default) or `output=current`. A channel is `1`-`14` or `la1`-`la14`; another word is a name in the wiring profile on embeddedci.com (a role such as `i2c_sda` or a signal such as `DRDY`), resolved to its channel here. | +| `--pin` | (none) | `role=channel`, repeatable. I2C `sda`, `scl` (default: the wiring profile's `i2c_sda`/`i2c_scl`) and `drdy`; SPI `sclk`, `mosi`, `miso`, `cs` (default: the profile's `spi_*`; the emulated SPI target has no data-ready pin); UART `tx` (pod to DUT RX) and `rx`; analog `output=dac` (default) or `output=current`. A channel is `1`-`14` or `la1`-`la14`; another word is a name in the pod's wiring profile (a role such as `i2c_sda` or a signal such as `DRDY`), resolved to its channel here. | | `--instance` | (the definition's name) | Instance name, 1 to 16 characters of `a-z`, `0-9` and `_`. | -| `--address` | (none) | I2C: the definition's address or one of its `alt_addresses` (`0x77`). | +| `--addr` | (none) | I2C: the definition's address or one of its `alt_addresses` (`0x77`). | | `--set` | (none) | Initial value as `key=number`, repeatable. | | `--baud` | `0` (the definition's) | UART: override the baud rate. | | `--version` | (none) | Library version for a library name. | ```bash benchpod sensor start gps_nmea --instance gps --pin tx=9 --set lat_deg=50.85 --set lon_deg=4.35 -benchpod sensor start sensors/my_adc.yaml --pin sda=2 --pin scl=1 --address 0x49 +benchpod sensor start sensors/my_adc.yaml --pin sda=2 --pin scl=1 --addr 0x49 ``` ### `benchpod sensor set ...` @@ -1507,7 +1548,7 @@ embeddedci.com; `la voltage` also works over USB. ### `benchpod la voltage [VOLTAGE]` Show or set the LA bank's I/O voltage, which must match the DUT's: `1.8V` or `3.3V` -(also `1800mV`, `3.3` or `3300`), or `5V` on a pod with the digital board v3r4 +(also `1800mV` or `3.3`: a bare number is volts), or `5V` on a pod with the digital board v3r4 ([5 V I/O](https://embeddedci.com/docs/benchpod-targets/5v-rs485#5v-io): pin 21 goes to 5 V, and the output then shows pin 21). Leave it out to show the setting. The pod refuses LA capture, UART, SWD flash, pull-ups and sensor emulation until it is set; @@ -1539,12 +1580,6 @@ benchpod la pull 7 down benchpod la pull 7 off ``` -### `benchpod la pullup PIN STATE` - -The older form of `la pull`: `STATE` `on` engages the pin's resistor in its own -direction (up on LA1-LA6, down on LA7/LA8), `off` switches it off. Still accepted; -use `la pull`. No flags. - ### `benchpod la status [PIN]` Report the pull state of one pin, or the bitmask of the engaged ones. No flags. @@ -1557,8 +1592,7 @@ Pulse an LA pin N times, for step/dir stepper drivers. The FPGA times the train. |---------------|---------|--------------------------------------------------------------| | `--la` | (required) | LA pin to pulse, e.g. `6` or `la6`. | | `--steps` | (required) | Number of pulses, positive. | -| `--delay` | (required) | High and low half-period, e.g. `50us` or `1ms` (this or `--delay-us`). | -| `--delay-us` | (required) | The same in microseconds (older form of `--delay`). | +| `--delay` | (required) | High and low half-period, e.g. `50us` or `1ms`. | | `--dir-la` | (none) | Direction pin, driven before stepping. | | `--direction` | `0` | Level for `--dir-la`: `0` or `1`. | @@ -1827,7 +1861,7 @@ embeddedci.com. See [Flashing the pod itself](#flashing-the-pod-itself-stm32-usb | `--firmware-version` | (latest) | Fetch this release tag instead of the latest. | | `--firmware-url` | (latest) | Download the firmware from this URL instead (https only). | | `--allow-unsigned` | off | Flash a downloaded image whose signature is missing or fails (a local file is never refused). | -| `--address` | `0x08000000` | Flash base address (STM32 main flash). | +| `--addr` | `0x08000000` | Flash base address (STM32 main flash). | | `--dfu-util` | (`PATH`) | Path to the `dfu-util` binary. | | `--no-leave` | off | Stay in DFU after flashing instead of starting the firmware. | | `--skip-blobs` | off | Do not install the gateware and ESP32-C3 images afterwards. | @@ -1843,7 +1877,10 @@ download's checksum does not match, or dfu-util fails. A local file's signature ### `benchpod install-blobs` Install the gateware and ESP32-C3 images the pod's firmware goes with (USB: over the -pod's USB network adapter when it is up, firmware 3.9.0+, else its console). By +pod's USB network adapter when it is up, else the pod's network address; firmware 3.9.0 +and later). Firmware before 3.9.0 took blobs over its console, which this CLI no longer +uses: update such a pod with `benchpod flash-self` (USB DFU). With USB networking off, +`benchpod usb-network on --connection usb` turns it back on. By default they come from the release that matches the firmware the pod runs. Each blob's signature is reported; for now a missing or failing one never stops it. When the pod does not list its blob slots (its `blob_status` command fails), it installs @@ -1887,14 +1924,19 @@ Reboot a (retired) RP2350 pod into its UF2 bootloader (USB). ### `benchpod set-wifi` -Save Wi-Fi credentials and join (USB). With firmware 3.9.0+ this turns the pod's USB networking off (Wi-Fi and USB networking are one or the other; `clear-wifi` turns it back on). Installs the ESP32-C3 image first when the -pod lacks it; if the pod's image slots cannot be read, it stops and says so -(`--skip-blobs` sets Wi-Fi without the check). +Save Wi-Fi credentials and join. The CLI sends them as JSON (`wifi_set`) over the pod's USB +network adapter (or the `--connection` given: a network address or `embeddedci:`). +Wi-Fi and USB networking are one or the other: once the credentials are stored, USB networking +turns off, and set-wifi follows the join on the address the pod's console reports. `clear-wifi` +over the pod's network address, or `net-reset` over USB, turns it back on. Installs the +ESP32-C3 image first when the pod lacks it; if the pod's image slots cannot be read, it stops +and says so (`--skip-blobs` sets Wi-Fi without the check). With USB networking off, +`benchpod usb-network on --connection usb` turns it back on. -With a Wi-Fi bridge on the pod's Ethernet port (firmware with bridge support), the -credentials go to the bridge instead (the pod sends the password sealed), no ESP32-C3 -image is needed, and set-wifi waits up to 45 s for the bridge to join: it reports a -wrong password or a network the bridge cannot see. The pod keeps its Ethernet address. +With a Wi-Fi bridge on the pod's Ethernet port, the credentials go to the bridge instead (the +pod sends the password sealed), no ESP32-C3 image is needed, USB networking stays on, and +set-wifi waits up to 45 s for the bridge to join: it reports a wrong password or a network the +bridge cannot see. The pod keeps its Ethernet address. | Flag | Default | Purpose | |--------------------|------------|-----------------------------------------------------------| @@ -1905,26 +1947,38 @@ wrong password or a network the bridge cannot see. The pod keeps its Ethernet ad ### `benchpod show-network` -The pod's IP (the wired lease first) plus the stored Wi-Fi SSID, state and RSSI -(USB). With a Wi-Fi bridge, `Via:` names it (MAC, firmware, paired or not), State is -the bridge's (`joining`, `connected`, `auth-failed`, `no-ap`, ...) and `Problem:` says -what the pod sees wrong with it. No flags. +The pod's IP (the wired lease first) plus the stored Wi-Fi SSID, state and RSSI (`status` and +`wifi_status` over the pod's USB network adapter, or the `--connection` given). With a Wi-Fi +bridge, `Via: wifi-bridge`, State is the bridge's (`joining`, `connected`, `auth-failed`, +`no-ap`, ...) and `Problem:` says what the pod sees wrong with it. No flags. ### `benchpod scan-wifi` -List the Wi-Fi networks the pod sees, strongest first: RSSI, channel, security and SSID, -to pick one for `set-wifi` (USB). The pod scans with its built-in Wi-Fi (firmware 3.9.4 or -later), or with a Wi-Fi bridge on its Ethernet port when one is plugged in. A scan takes a few -seconds; a pod that is joined to a network stays joined, and a pod that is joining finishes -that first (up to 30 seconds). No flags. - -On older firmware the pod cannot scan, but it can still join a network: the command says so, -suggests `benchpod flash-self` and `benchpod set-wifi --ssid `, and exits 0. -It fails only on a pod with no Wi-Fi at all. +List the Wi-Fi networks the pod sees, strongest first: RSSI, channel, security and SSID, to pick +one for `set-wifi` (`wifi_scan` over the pod's USB network adapter, or the `--connection` +given). The pod scans with its built-in Wi-Fi, or with a Wi-Fi bridge on its Ethernet port when +one is plugged in. A scan takes a few seconds; a pod that is joined to a network stays joined, +and a pod that is joining finishes that first (up to 30 seconds). No flags. ### `benchpod clear-wifi` -Erase the stored Wi-Fi credentials (USB). Wi-Fi goes down at once, no reboot needed, and USB networking (firmware 3.9.0+) comes back on. Firmware after 3.7.0 also erases the copy older firmware left on the ESP32-C3 Wi-Fi chip, which takes a few seconds more. No flags. +Erase the stored Wi-Fi credentials (`wifi_clear`). Wi-Fi goes down at once, no reboot needed, +and USB networking comes back on. The pod also erases the copy older firmware left on the +ESP32-C3 Wi-Fi chip, which takes a few seconds more. Over USB the CLI uses the pod's USB network +adapter, else (it is off while Wi-Fi is set) the pod's network address from its console. When no +network reaches the pod, use `benchpod net-reset`. No flags. + +### `benchpod net-reset` + +The way back to a pod that no network reaches (firmware 4.0, over the USB console): the pod +forgets its Wi-Fi credentials (its own flash and the ESP32-C3's, or the Wi-Fi bridge's), which +turns USB networking back on, and puts Ethernet back to autonegotiation with a PHY reset and a +new DHCP lease. The LAN and signature policies, the cloud settings and the device key stay. It +prints the pod's `net-reset` lines. + +| Flag | Default | Purpose | +|---------|---------|--------------------------------| +| `--yes` | off | Skip the confirmation prompt. | ### `benchpod usb-bridge` @@ -1977,11 +2031,12 @@ Show whether the background service is installed and running. No flags. ### `benchpod usb-reattach` -Make the pod drop off the USB bus for half a second and connect again (USB). The -computer then sets up the console and the USB network adapter anew, as after -replugging the cable. macOS ignores a new network adapter while the screen is -locked: run this after unlocking when the pod was plugged in or rebooted meanwhile. -Needs firmware 3.9.0 or later. No flags. +Make the pod drop off the USB bus for half a second and connect again (`usb_reattach`). The +computer then sets up the console and the USB network adapter anew, as after replugging the +cable. macOS ignores a new network adapter while the screen is locked: run this after +unlocking when the pod was plugged in or rebooted meanwhile. The CLI sends it over the pod's +USB network adapter when that is up, else over the pod's network address from its console +`status` (or the `--connection` given); with neither, replug the cable. No flags. ### `benchpod login` @@ -2187,8 +2242,8 @@ Every code is also on [embeddedci.com/docs/errors](https://embeddedci.com/docs/e ### `benchpod lan-tls` -Show the pod's LAN TLS certificate, its SHA-256, the HTTPS-only setting and -whether this computer has it pinned (firmware 3.9.3+). See +Show the pod's LAN TLS certificate, its SHA-256, the HTTPS-only and SCPI settings +and whether this computer has it pinned. See [LAN TLS](#lan-tls-encrypted-lan-api). Over the network, USB or embeddedci.com. | Flag | Default | Purpose | @@ -2205,20 +2260,28 @@ Same as `benchpod lan-tls`. ### `benchpod lan-tls https-only ` -`on`: the pod refuses plaintext 8080 on Ethernet and Wi-Fi and answers only on -8443 there; its USB link keeps 8080. `off` needs a TLS, USB or embeddedci.com -connection. Stored on the pod. +`on` (the default from firmware 4.0): the pod refuses plaintext 8080 on Ethernet and +Wi-Fi and answers only on 8443 there; its USB link keeps 8080. `off`: plaintext 8080 +on the LAN too. Only over USB (`--connection usb`) or embeddedci.com. Stored on the pod. + +### `benchpod lan-tls scpi ` + +`on`: SCPI answers on the pod's TCP ports (8443, and 8080; on the LAN 8080 takes SCPI +only while HTTPS-only is on), and the pod advertises `_scpi-raw._tcp`. `off` (the +default from firmware 4.0) closes SCPI sessions. Only over USB (`--connection usb`) +or embeddedci.com. Stored on the pod. ### `benchpod lan-tls regenerate` A new key and self-signed certificate on the pod; this computer's pin follows. -Needs a TLS, USB or embeddedci.com connection. +Only over USB (`--connection usb`) or embeddedci.com. ### `benchpod lan-tls set-cert` Install your own certificate and key. Checks them here first (they must match, the key must not be encrypted, at most 7.6 KB together), uploads them over the -network (TLS or the USB network adapter), checks the pod reports the new +pod's USB network adapter (`--connection usb`; the pod refuses the upload from +Ethernet and Wi-Fi), checks the pod reports the new certificate and updates the pin. | Flag | Default | Purpose | @@ -2269,9 +2332,9 @@ benchpod log-level debug ### `benchpod sig-policy` -Show the pod's signature policy: `audit`, `permissive` or `required`. Same -transports as `lan-policy`; the cloud can only make it stricter. These flags apply -to `show` and `set` too. +Show the pod's signature policy (always `required` from firmware 4.0) and how many release +keys it trusts. Over embeddedci.com, the pod's USB network adapter or the LAN. There is no +`set`: CLI 0.10 dropped the loosening. These flags apply to `show` too. | Flag | Default | Purpose | |-----------------|------------------------------|----------------------------------------------------------| @@ -2284,10 +2347,6 @@ to `show` and `set` too. Same as `benchpod sig-policy`. -### `benchpod sig-policy set ` - -Set the signature policy. Loosening it needs the USB console. - ### `benchpod identity` Show the pod's device identity (USB). See @@ -2299,7 +2358,8 @@ Same as `benchpod identity`. ### `benchpod identity wipe` -Erase the pod's device key and make a new one (USB only). The pod then needs to be +Erase the pod's device key and make a new one (USB only: the console shows the +identity, the wipe goes over the pod's USB network adapter). The pod then needs to be registered again. | Flag | Default | Purpose | diff --git a/cmd/benchpod-cli/adcrange.go b/cmd/benchpod-cli/adcrange.go index b0a1c47..9553c7f 100644 --- a/cmd/benchpod-cli/adcrange.go +++ b/cmd/benchpod-cli/adcrange.go @@ -99,7 +99,7 @@ func adcRange(ctx context.Context, c podCommander, via, action, what string, out return errors.New(adcRangeMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/blobs.go b/cmd/benchpod-cli/blobs.go index ff85b97..a38e4dd 100644 --- a/cmd/benchpod-cli/blobs.go +++ b/cmd/benchpod-cli/blobs.go @@ -26,7 +26,7 @@ import ( const blobsManifestName = "blobs-manifest.json" -// blobsInstallTimeout bounds a whole install: ~1.3 MB over the USB console plus the slot writes. +// blobsInstallTimeout bounds a whole install: ~1.3 MB over USB plus the slot writes. const blobsInstallTimeout = 10 * time.Minute type blobEntry struct { @@ -267,19 +267,6 @@ func espLast(todo []blobEntry) []blobEntry { return append(out, esp...) } -// podFirmwareRelease is the release tag of the firmware a pod runs ("v3.4.0"), "" if unknown. -func podFirmwareRelease(ctx context.Context, console *serialconsole.Console) string { - raw, err := console.Status(ctx) - if err != nil { - return "" - } - v := serialconsole.FirmwareVersion(raw) - if v != "" && !strings.HasPrefix(v, "v") { - v = "v" + v - } - return v -} - func newInstallBlobsCmd(g *globalFlags) *cobra.Command { var dir, release, only string var force bool @@ -288,8 +275,9 @@ func newInstallBlobsCmd(g *globalFlags) *cobra.Command { Short: "Install the gateware and ESP32-C3 images the pod's firmware goes with (over USB)", Long: "The pod keeps its iCE40 gateware images and its ESP32-C3 Wi-Fi image in the\n" + "W25Q flash next to the FPGA, not in its firmware. This sends the ones it lacks\n" + - "over USB: the pod's USB network adapter when it is up (firmware 3.9.0+), else its\n" + - "USB console. By default they come from the GitHub release that matches\n" + + "over the pod's USB network adapter (firmware 3.9.0+), else its network address.\n" + + "USB networking off: `benchpod usb-network on --connection usb` (the console's\n" + + "`usb-network on`). By default they come from the GitHub release that matches\n" + "the firmware the pod runs; --dir takes them from a local build (stm32h563/build/blobs).\n\n" + "Each blob's signature (blob-*.bin.sig) is checked and reported, and handed to\n" + "firmware that checks it too; for now a missing or failing one never stops an install.", @@ -301,8 +289,8 @@ func newInstallBlobsCmd(g *globalFlags) *cobra.Command { } ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(blobsInstallTimeout)) defer cancel() - // This computer's end of the pod's USB network link (firmware 3.9.0+) needs no console; - // else the console names the way in: the USB network when it is up, else the console. + // This computer's end of the pod's USB network link needs no console; else the console + // names the way in: the USB network when it is up, else the pod's network address. target, closeTarget := g.localBlobTarget(ctx) path := "the USB network" if target == nil { diff --git a/cmd/benchpod-cli/blobs_target.go b/cmd/benchpod-cli/blobs_target.go index fd56abf..85242e3 100644 --- a/cmd/benchpod-cli/blobs_target.go +++ b/cmd/benchpod-cli/blobs_target.go @@ -16,8 +16,8 @@ import ( ) // blobTarget is where install-blobs reads the pod's W25Q slots and sends blobs: the pod's network -// API (over its USB network adapter, firmware 3.9.0+: blob_status and ota_* with a target) or its -// USB console (blobs and upload-*, older firmware). +// API (blob_status and ota_* with a target), over its USB network adapter or its network address +// (firmware 3.9.0 and later; older firmware had a console upload this CLI no longer sends). type blobTarget interface { Blobs(ctx context.Context) ([]serialconsole.BlobSlot, error) UploadSigned(ctx context.Context, target string, data []byte, version int, manifest []byte, @@ -33,24 +33,6 @@ type blobTarget interface { Method() string } -// consoleBlobs is the USB console. -type consoleBlobs struct { - *serialconsole.Console - path string -} - -func (c consoleBlobs) Release(ctx context.Context) string { return podFirmwareRelease(ctx, c.Console) } -func (c consoleBlobs) Via() string { return c.path } -func (c consoleBlobs) Method() string { return "usb_console" } - -func (c consoleBlobs) Identity(ctx context.Context) (string, string) { - id, err := c.Console.Identity(ctx) - if err != nil { - return "", "" - } - return id.PublicKey, id.ShortID -} - // lanBlobChunk is the raw bytes per ota_data line (as the LAN OTA in hwe2e sends). const lanBlobChunk = 768 @@ -244,7 +226,8 @@ func (l lanBlobs) waitApplied(ctx context.Context, target string) error { func blobTargetFor(ctx context.Context, console *serialconsole.Console, path string) (blobTarget, func(), error) { u, err := console.USBNetwork(ctx) if errors.Is(err, serialconsole.ErrNoUSBNet) { - return consoleBlobs{Console: console, path: path}, func() {}, nil // firmware before 3.9.0 + return nil, func() {}, errors.New("this pod's firmware is older than 3.9.0 and takes blobs only over its USB console, " + + "which this CLI no longer uses: update the pod with `benchpod flash-self` (USB DFU), which installs its blobs") } if err != nil { return nil, func() {}, fmt.Errorf("read the pod's status: %w", err) @@ -272,8 +255,8 @@ func blobTargetFor(ctx context.Context, console *serialconsole.Console, path str return t, c, nil } } - return nil, func() {}, errors.New("this pod's firmware (3.9.0 or later) takes blobs over the network, and neither its USB " + - "network adapter (Wi-Fi configured on the pod turns it off: `benchpod clear-wifi`) nor its network address answers") + return nil, func() {}, errors.New("the pod takes blobs over the network, and neither its USB network adapter " + + "nor its network address answers. " + usbNetworkOffHint) } // localBlobTarget is the pod's network API on this computer's end of its USB network link diff --git a/cmd/benchpod-cli/blobs_target_test.go b/cmd/benchpod-cli/blobs_target_test.go index f248661..1a7a469 100644 --- a/cmd/benchpod-cli/blobs_target_test.go +++ b/cmd/benchpod-cli/blobs_target_test.go @@ -42,23 +42,14 @@ func (c *textConsole) Close() error { return nil } var _ io.ReadWriteCloser = (*textConsole)(nil) -// New CLI + firmware without a usable USB network: install-blobs keeps today's console path. -func TestBlobTargetFallsBackToTheConsole(t *testing.T) { - cases := map[string]string{ - "firmware before 3.9.0": " device : benchpod\r\n ip : 192.168.1.220\r\n", - } - for name, status := range cases { - c := serialconsole.NewConsole(&textConsole{status: status}) - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - target, closeT, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1") - cancel() - if err != nil { - t.Fatalf("%s: %v", name, err) - } - closeT() - if _, ok := target.(consoleBlobs); !ok || target.Via() != "/dev/cu.usbmodem1" { - t.Fatalf("%s: target %T via %s, want the console", name, target, target.Via()) - } +// Firmware before 3.9.0 has no USB network adapter: its console upload is gone, so a clear error +// that names flash-self. +func TestBlobTargetBefore39IsAnError(t *testing.T) { + c := serialconsole.NewConsole(&textConsole{status: " device : benchpod\r\n ip : 192.168.1.220\r\n"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "benchpod flash-self") { + t.Fatalf("err = %v", err) } } @@ -72,7 +63,7 @@ func TestBlobTargetOn39WithoutANetworkIsAnError(t *testing.T) { " usb : net off (Wi-Fi configured) pod 10.237.8.85 host 10.237.8.86 link down rx 0 (drop 0) tx 0 (full 0)\r\n"}) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() - if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "clear-wifi") { + if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "usb-network on") { t.Fatalf("err = %v", err) } } diff --git a/cmd/benchpod-cli/busmaster.go b/cmd/benchpod-cli/busmaster.go index a20ac7c..15d6f3d 100644 --- a/cmd/benchpod-cli/busmaster.go +++ b/cmd/benchpod-cli/busmaster.go @@ -41,7 +41,7 @@ func busCommand(ctx context.Context, t *podTarget, what, feature string, req map if isUnknownCommand(err) { return &shownRefusal{msg: what + ": " + tooOldForBusMaster(feature), pe: pe} } - return refusedError(what, pe, !t.spec.IsCloud()) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } @@ -206,7 +206,7 @@ type i2cSession struct { Active *bool `json:"active"` SDA int `json:"sda"` SCL int `json:"scl"` - Hz int `json:"hz"` + Hz int `json:"clock_hz"` Pullups string `json:"pullups"` } @@ -272,7 +272,7 @@ func newI2CStartCmd(g *globalFlags) *cobra.Command { } defer cancel() var s i2cSession - req := map[string]any{"cmd": "i2c_start", "sda": sdaPin, "scl": sclPin, "hz": hz, "pullups": pullups} + req := map[string]any{"cmd": "i2c_start", "sda": sdaPin, "scl": sclPin, "clock_hz": hz, "pullups": pullups} if err := busCommand(ctx, t, "i2c start", "I2C master", req, &s); err != nil { return err } @@ -463,7 +463,7 @@ func newI2CStopCmd(g *globalFlags) *cobra.Command { } } -// writeLine prints one line to the command output (--output-filename or stdout). +// writeLine prints one line to the command output (--out or stdout). func writeLine(g *globalFlags, line string) error { out, closeOut, err := resolveOutput(g.outputFilename) if err != nil { @@ -567,74 +567,31 @@ type laPinsCommander interface { Command(ctx context.Context, req map[string]any) (json.RawMessage, error) } -// laPinsFetch reads la_pins: every pin (pins nil) or only those pins. Firmware after 3.10.12 sends -// only the pins asked for; older firmware sends all 14 and they are filtered here. A full listing -// the pod answers with "reply too large" (a long sensor instance name on every pin) is read in two -// parts, LA1-7 and LA8-14, and joined. +// laPinsFetch reads la_pins: every pin (pins nil) or only those pins (the pod sends only the pins +// asked for). A full listing the pod answers with BP0053 (reply_too_large: a long sensor instance +// name on every pin) is read in two parts, LA1-7 and LA8-14, and joined. func laPinsFetch(ctx context.Context, c laPinsCommander, pins []int) (json.RawMessage, error) { - if pins == nil { - raw, err := c.Command(ctx, map[string]any{"cmd": "la_pins"}) - if err == nil || !strings.Contains(err.Error(), "reply too large") { // no code yet - return raw, err + if pins != nil { + return c.Command(ctx, map[string]any{"cmd": "la_pins", "la": pins}) + } + raw, err := c.Command(ctx, map[string]any{"cmd": "la_pins"}) + if err == nil || !tcpclient.HasCode(err, "BP0053") { + return raw, err + } + var parts [2]map[string]any + for i, half := range [][]int{{1, 2, 3, 4, 5, 6, 7}, {8, 9, 10, 11, 12, 13, 14}} { + raw, err := c.Command(ctx, map[string]any{"cmd": "la_pins", "la": half}) + if err != nil { + return nil, err } - first, err1 := laPinsQuery(ctx, c, []int{1, 2, 3, 4, 5, 6, 7}) - if err1 != nil { - return nil, laPinsUpdateHint(err) + if err := json.Unmarshal(raw, &parts[i]); err != nil { + return nil, fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) } - if n, _ := first["pins"].([]any); len(n) > 7 { - return nil, laPinsUpdateHint(err) // firmware without the pin subset: it sent everything again - } - second, err2 := laPinsQuery(ctx, c, []int{8, 9, 10, 11, 12, 13, 14}) - if err2 != nil { - return nil, err2 - } - a, _ := first["pins"].([]any) - b, _ := second["pins"].([]any) - first["pins"] = append(a, b...) - return json.Marshal(first) - } - m, err := laPinsQuery(ctx, c, pins) - if err != nil { - return nil, err - } - return json.Marshal(m) -} - -// laPinsUpdateHint says what to do when older firmware (no pin subset) cannot send the whole list. -func laPinsUpdateHint(err error) error { - return fmt.Errorf("%w; firmware after 3.10.12 reads this list in parts: update the pod "+ - "(benchpod flash-self, or the firmware update in the web app), or ask for fewer pins "+ - "(benchpod la pins 1-7)", err) -} - -// laPinsQuery sends la_pins with "la" and keeps only the entries of those pins. -func laPinsQuery(ctx context.Context, c laPinsCommander, pins []int) (map[string]any, error) { - raw, err := c.Command(ctx, map[string]any{"cmd": "la_pins", "la": pins}) - if err != nil { - return nil, err - } - var m map[string]any - if err := json.Unmarshal(raw, &m); err != nil { - return nil, fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) - } - want := map[int]bool{} - for _, p := range pins { - want[p] = true - } - var keep []any - entries, _ := m["pins"].([]any) - for _, e := range entries { - if em, ok := e.(map[string]any); ok { - if la, ok := em["la"].(float64); ok && want[int(la)] { - keep = append(keep, e) - } - } - } - if keep == nil { - keep = []any{} } - m["pins"] = keep - return m, nil + a, _ := parts[0]["pins"].([]any) + b, _ := parts[1]["pins"].([]any) + parts[0]["pins"] = append(a, b...) + return json.Marshal(parts[0]) } func newLAPinsCmd(g *globalFlags) *cobra.Command { @@ -644,7 +601,7 @@ func newLAPinsCmd(g *globalFlags) *cobra.Command { Short: "List every LA pin: function, GPIO state, live level, pull-up, direction and warnings", Long: "List every LA pin, or only PINS (a pin, a list or a range: 9, 9,10, 9-12, la9, or a\n" + "name from the pod's wiring profile). A list too large for one cloud reply is read\n" + - "in two parts by itself (firmware after 3.10.12).", + "in two parts by itself.", Example: " benchpod la pins\n benchpod la pins 1-4\n benchpod la pins uart_rx --json", Args: cobra.MaximumNArgs(1), RunE: func(_ *cobra.Command, args []string) error { diff --git a/cmd/benchpod-cli/busmaster_test.go b/cmd/benchpod-cli/busmaster_test.go index 56ca21a..15cb380 100644 --- a/cmd/benchpod-cli/busmaster_test.go +++ b/cmd/benchpod-cli/busmaster_test.go @@ -33,7 +33,7 @@ func TestI2CStartSendsPinsAndPrintsTheRate(t *testing.T) { pod, g := newFakeSensorPod(t) pod.reply = func(req map[string]any) (any, string) { if req["cmd"] == "i2c_start" { - return map[string]any{"sda": 1, "scl": 2, "hz": 363636, "pullups": "pod"}, "" + return map[string]any{"sda": 1, "scl": 2, "clock_hz": 363636, "pullups": "pod"}, "" } return nil, "" } @@ -41,7 +41,7 @@ func TestI2CStartSendsPinsAndPrintsTheRate(t *testing.T) { if err != nil { t.Fatal(err) } - if got := reqJSON(pod.last("i2c_start")); got != `{"cmd":"i2c_start","hz":400000,"pullups":"pod","scl":2,"sda":1}` { + if got := reqJSON(pod.last("i2c_start")); got != `{"clock_hz":400000,"cmd":"i2c_start","pullups":"pod","scl":2,"sda":1}` { t.Fatalf("request %s", got) } if out != "i2c: SDA LA1, SCL LA2 at 363.636 kHz, the pod's pull-ups" { @@ -63,7 +63,7 @@ func TestI2CStartPinsFromTheWiringProfile(t *testing.T) { if _, err := runBus(t, g, newI2CCmd(g), "start", "--pullups", "external"); err != nil { t.Fatal(err) } - if got := reqJSON(pod.last("i2c_start")); got != `{"cmd":"i2c_start","hz":100000,"pullups":"external","scl":4,"sda":3}` { + if got := reqJSON(pod.last("i2c_start")); got != `{"clock_hz":100000,"cmd":"i2c_start","pullups":"external","scl":4,"sda":3}` { t.Fatalf("request %s", got) } // A wiring name for a pin. @@ -168,7 +168,7 @@ func TestI2CStatusAndStop(t *testing.T) { if !active { return map[string]any{"active": false}, "" } - return map[string]any{"active": true, "sda": 5, "scl": 6, "hz": 100000, "pullups": "external"}, "" + return map[string]any{"active": true, "sda": 5, "scl": 6, "clock_hz": 100000, "pullups": "external"}, "" case "i2c_stop": return "i2c stopped", "" } @@ -191,7 +191,7 @@ func TestBusMasterOnOldFirmwareNamesTheUpdate(t *testing.T) { pod, g := newFakeSensorPod(t) pod.reply = func(req map[string]any) (any, string) { if req["cmd"] != "status" { - return nil, "unknown cmd" + return nil, "BP0002" } return nil, "" } @@ -207,19 +207,20 @@ func TestBusMasterOnOldFirmwareNamesTheUpdate(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "gateware v55 or later") || !strings.Contains(err.Error(), "benchpod flash-self") { t.Fatalf("%v: err = %v", c.args, err) } - if exitCode(err) != exitRefused { + if exitCode(err) != exitUpdatePod { t.Fatalf("%v: exit %d", c.args, exitCode(err)) } } - // The new firmware on old gateware says it itself; the CLI adds the command. + // Firmware 4.0 on old gateware says so with BP0017; the catalog names the command. pod.reply = func(req map[string]any) (any, string) { if req["cmd"] == "i2c_start" { - return nil, "the I2C master needs gateware v55+: update the pod's firmware" + return nil, `BP0017 {"feature":"I2C master","min":55}` } return nil, "" } _, err := runBus(t, g, newI2CCmd(g), "start", "--sda", "1", "--scl", "2") - if err == nil || !strings.Contains(err.Error(), "needs gateware v55+") || !strings.Contains(err.Error(), "benchpod flash-self") { + if err == nil || !strings.Contains(err.Error(), "I2C master needs gateware v55 or later") || !strings.Contains(err.Error(), "benchpod flash-self") || + exitCode(err) != exitUpdatePod { t.Fatalf("err = %v", err) } } @@ -228,7 +229,7 @@ func TestI2CPullupRefusalNamesTheCLICommand(t *testing.T) { pod, g := newFakeSensorPod(t) pod.reply = func(req map[string]any) (any, string) { if req["cmd"] == "i2c_start" { - return nil, `I2C needs pull-ups: switch on LA1's with {"cmd":"la","la":1,"pullup":"on"}, or pass "pullups":"external"` + return nil, `BP0061 {"la":1}` } return nil, "" } @@ -237,24 +238,6 @@ func TestI2CPullupRefusalNamesTheCLICommand(t *testing.T) { strings.Contains(err.Error(), `{"cmd"`) { t.Fatalf("err = %v", err) } - // firmware with la_pull_dir names the pull form - pod.reply = func(req map[string]any) (any, string) { - if req["cmd"] == "i2c_start" { - return nil, `I2C needs pull-ups: switch on LA2's with {"cmd":"la","la":2,"pull":"up"}, or pass "pullups":"external"` - } - return nil, "" - } - _, err = runBus(t, g, newI2CCmd(g), "start", "--sda", "1", "--scl", "2") - if err == nil || !strings.Contains(err.Error(), "benchpod la pull 2 up") || strings.Contains(err.Error(), `{"cmd"`) { - t.Fatalf("err = %v", err) - } -} - -func TestPinConflictWithTheI2CMaster(t *testing.T) { - shown, hint := translateRefusal(`pin conflict: LA1 is in use by i2cm_sda; stop the I2C session first ({"cmd":"i2c_stop"})`) - if shown != "pin conflict: LA1 is in use by i2cm_sda" || !strings.Contains(hint, "benchpod i2c stop") { - t.Fatalf("%q, %q", shown, hint) - } } func TestLADirSendsPins(t *testing.T) { diff --git a/cmd/benchpod-cli/ci_cmd.go b/cmd/benchpod-cli/ci_cmd.go index c09dd72..db31d77 100644 --- a/cmd/benchpod-cli/ci_cmd.go +++ b/cmd/benchpod-cli/ci_cmd.go @@ -20,14 +20,18 @@ import ( // ── benchpod ci ───────────────────────────────────────────────────────────── -const ciExitCodesHelp = "Exit codes:\n" + - " 0 passed\n" + - " 1 a file, usage or setup error (the YAML, the firmware build, no pod)\n" + - " 2 a test failed (or errored)\n" + - " 3 the run passed, but a gated measurement drifted beyond its allowance against the\n" + - " baseline (baseline: with fail_on_drift, or gate: drift)\n" + - " 4 the run is not valid: the pod is in use, require is not met, the pod rebooted\n" + - " or was lost, the lease was lost, a capture lost data, or the run was interrupted" +const ciExitCodesHelp = "Exit codes (0 to 7 as for every benchpod command, a run's results 10 and up):\n" + + " 0 passed\n" + + " 1 a file or setup error (the YAML, the firmware build, a missing wiring profile)\n" + + " 2 usage: a bad flag or argument\n" + + " 5 the pod did not answer, or no pod was found\n" + + " 6 the pod's firmware needs a newer benchpod CLI\n" + + " 7 the pod's firmware is too old for this CLI (`benchpod flash-self`)\n" + + " 10 a test failed (or errored)\n" + + " 11 the run passed, but a gated measurement drifted beyond its allowance against the\n" + + " baseline (baseline: with fail_on_drift, or gate: drift)\n" + + " 12 the run is not valid: the pod is in use, require is not met, the pod rebooted\n" + + " or was lost, the lease was lost, a capture lost data, or the run was interrupted" func newCICmd(g *globalFlags) *cobra.Command { o := &ciOptions{} @@ -71,7 +75,7 @@ func addCIRunFlags(cmd *cobra.Command, o *ciOptions) { f.BoolVar(&o.keepGoing, "keep-going", false, "go on after a required step fails") f.IntVar(&o.repeat, "repeat", 1, "run the steps N times (the firmware is flashed once); each case records its attempt") f.BoolVar(&o.json, "json", false, "print run.json on stdout instead of the summary") - f.DurationVar(&o.wait, "wait", 0, "wait this long for a pod another session holds, e.g. 10m (default: fail at once with exit 4)") + f.DurationVar(&o.wait, "wait", 0, "wait this long for a pod another session holds, e.g. 10m (default: fail at once with exit 12)") } func runCICommand(g *globalFlags, o *ciOptions, cmd *cobra.Command) error { @@ -196,29 +200,24 @@ func takeCILease(ctx context.Context, c *ciConnected, join *tcpclient.LeaseJoin, type leaseHas int const ( - leaseUnknown leaseHas = iota // no features_rev (the caps-list form, or no status) + leaseUnknown leaseHas = iota // no features_rev, or no status leaseNo leaseYes ) -// leaseFeature decides the lease feature from a {"cmd":"status","caps":false} reply: with -// features_rev the embedded features table decides; without it (a pod that sent the frozen caps -// list) it is unknown. form says which reply it was, for the log. +// leaseFeature decides the lease feature from a status reply: the embedded features table +// decides from features_rev; without it, it is unknown. form says which reply it was, for the log. func leaseFeature(st json.RawMessage, err error) (leaseHas, string) { if err != nil { return leaseUnknown, "no status (" + err.Error() + ")" } var v struct { - FeaturesRev *int `json:"features_rev"` - Caps []string `json:"caps"` + FeaturesRev *int `json:"features_rev"` } if json.Unmarshal(st, &v) != nil { return leaseUnknown, "an unreadable status" } if v.FeaturesRev == nil { - if v.Caps != nil { - return leaseUnknown, `the caps list (no features_rev: the pod ignored "caps":false)` - } return leaseUnknown, "no features_rev" } form := fmt.Sprintf("features_rev %d", *v.FeaturesRev) @@ -394,13 +393,20 @@ func validatePod(g *globalFlags, cfg *ci.Config, podFlag string, res *ciValidate // ── benchpod ci diff ──────────────────────────────────────────────────────── // ciCommandExit maps the error of a `benchpod ci` command to its exit code: the ci codes, with a -// usage error as 1 (file/usage/setup) instead of the CLI's usual 2. +// setup failure that is an unreachable pod or a firmware or CLI level mismatch as the CLI's own +// code for it (5, 6, 7). func ciCommandExit(err error) (int, bool) { var ce *ciExit - if errors.As(err, &ce) { - return ce.code, true + if !errors.As(err, &ce) { + return 0, false + } + if ce.code == ci.ExitSetup && ce.err != nil { + switch c := exitCode(ce.err); c { + case exitUnreachable, exitUpdateCLI, exitUpdatePod: + return c, true + } } - return 0, false + return ce.code, true } // isCICommand says cmd is `benchpod ci` or one of its subcommands. diff --git a/cmd/benchpod-cli/ci_lease.go b/cmd/benchpod-cli/ci_lease.go index 5f95655..827dccc 100644 --- a/cmd/benchpod-cli/ci_lease.go +++ b/cmd/benchpod-cli/ci_lease.go @@ -54,7 +54,7 @@ type ciLease interface { Release(ctx context.Context) } -// ciBusyError is the pod held by someone else (exit 4). +// ciBusyError is the pod held by someone else (exit 12). type ciBusyError struct{ msg string } func (e *ciBusyError) Error() string { return e.msg } @@ -266,7 +266,7 @@ const ( ) func isLeaseBusy(pe *tcpclient.PodError) bool { - return pe.Code == codeLeaseBusy || pe.Kind() == tcpclient.Busy // Kind: the text fallback without a code + return pe.Code == codeLeaseBusy || pe.Kind() == tcpclient.Busy } // busyText is " holds this pod (, N s left)" from a lease_busy refusal. @@ -285,8 +285,7 @@ func busyText(pe *tcpclient.PodError) string { } return s } - // fallback: BP0025's holder/purpose/left_s args replace it (firmware without codes) - return strings.TrimPrefix(strings.TrimSpace(pe.Reason), "busy: ") + return strings.TrimSpace(pe.Reason) } // leaseLostText is why a lease_lost / lease_not_held refusal says the lease is gone. @@ -297,16 +296,12 @@ func leaseLostText(pe *tcpclient.PodError) string { } return "the pod lease was stopped during the run" } - return "the pod lease was lost (" + strings.TrimSpace(pe.Reason) + "): the pod rebooted, or the lease expired" + return "the pod lease was lost: the pod rebooted, or the lease expired" } // isLeaseLost is a command refused because the run's lease was stopped (BP0026) or expired (BP0027). func isLeaseLost(pe *tcpclient.PodError) bool { - if pe.Code == codeLeaseLost || pe.Code == codeLeaseNotHeld { - return true - } - // fallback: BP0026 / BP0027 replace it (firmware without codes) - return strings.HasPrefix(strings.TrimSpace(pe.Reason), "lease lost") + return pe.Code == codeLeaseLost || pe.Code == codeLeaseNotHeld } // ── the server's lease (embeddedci.com) ───────────────────────────────────── diff --git a/cmd/benchpod-cli/ci_phase4_test.go b/cmd/benchpod-cli/ci_phase4_test.go index b5f2e36..6c42a0f 100644 --- a/cmd/benchpod-cli/ci_phase4_test.go +++ b/cmd/benchpod-cli/ci_phase4_test.go @@ -28,8 +28,8 @@ func TestCIBaselineGating(t *testing.T) { name, extra, expect string code int }{ - {"fail_on_drift", "", "", 3}, - {"gate drift", "gate: drift\n", "", 3}, + {"fail_on_drift", "", "", ci.ExitRegression}, + {"gate drift", "gate: drift\n", "", ci.ExitRegression}, {"not gated", "", "", 0}, {"fail_on_drift false beats gate", "gate: drift\n", "", 0}, } @@ -59,7 +59,7 @@ func TestCIBaselineGating(t *testing.T) { if !strings.Contains(out, "Baseline main (run r-base): 0 newly failing, 0 fixed, 1 drifted") { t.Errorf("headline:\n%s", out) } - if c.code == 3 && !strings.Contains(out, "boot mean_ma drifted +30.0%") { + if c.code == ci.ExitRegression && !strings.Contains(out, "boot mean_ma drifted +30.0%") { t.Errorf("gated line:\n%s", out) } md, _ := os.ReadFile(summary) @@ -69,7 +69,7 @@ func TestCIBaselineGating(t *testing.T) { t.Errorf("summary lacks %q:\n%s", want, text) } } - if strings.Contains(text, "(fails the run)") != (c.code == 3) { + if strings.Contains(text, "(fails the run)") != (c.code == ci.ExitRegression) { t.Errorf("summary gating mark:\n%s", text) } }) @@ -130,7 +130,7 @@ func TestGitHubActionsSignIn(t *testing.T) { _, _ = w.Write([]byte(`{"access_token":"gha-token","token_type":"Bearer","expires_at":"` + time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + `","devices":["benchpod-a1b2c3"]}`)) case "/api/cloud/devices/command": g.cmdPath, g.cmdAuth = r.URL.RequestURI(), r.Header.Get("Authorization") - _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"3.10.13"}}`)) + _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"4.0.0","api":2,"min_client_api":2}}`)) case "/api/cloud/devices/lease": g.leaseAuth = r.Header.Get("Authorization") _, _ = w.Write([]byte(`{"lease_id":"L-1"}`)) @@ -157,7 +157,7 @@ func TestGitHubActionsSignIn(t *testing.T) { t.Fatalf("cloud pod %+v", cp) } data, err := cp.Command(ctx, map[string]any{"cmd": "status"}) - if err != nil || !strings.Contains(string(data), "3.10.13") { + if err != nil || !strings.Contains(string(data), "4.0.0") { t.Fatalf("command %s %v", data, err) } lease, err := acquireCloudLease(ctx, cp.API, cp.Credential, cp.Name, "L-1", 0, time.Hour, io.Discard) diff --git a/cmd/benchpod-cli/ci_runner.go b/cmd/benchpod-cli/ci_runner.go index 5eceaa4..0e7bdfb 100644 --- a/cmd/benchpod-cli/ci_runner.go +++ b/cmd/benchpod-cli/ci_runner.go @@ -94,6 +94,7 @@ func stoppedWhy(ctx context.Context, lease ciLease) string { type ciExit struct { code int msg string + err error // the error a setup failure came from, when there was one (its CLI exit code may apply) } func (e *ciExit) Error() string { @@ -104,7 +105,13 @@ func (e *ciExit) Error() string { } func setupErr(format string, args ...any) *ciExit { - return &ciExit{code: ci.ExitSetup, msg: fmt.Sprintf(format, args...)} + e := &ciExit{code: ci.ExitSetup, msg: fmt.Sprintf(format, args...)} + for _, a := range args { + if err, ok := a.(error); ok { + e.err = err + } + } + return e } // execute runs the whole run and returns its exit code. ctx ends on Ctrl-C. @@ -571,7 +578,7 @@ func (r *ciRunner) cleanup() { note(a, err) case ci.CleanupPowerOff: for _, efuse := range []int{1, 2} { - _, err := pod.Command(ctx, map[string]any{"cmd": "target_power", "efuse": efuse, "state": 0}) + _, err := pod.Command(ctx, map[string]any{"cmd": "target_power", "efuse": efuse, "enabled": false}) note(fmt.Sprintf("%s efuse %d", a, efuse), err) } case ci.CleanupSensorsOff: diff --git a/cmd/benchpod-cli/ci_status_test.go b/cmd/benchpod-cli/ci_status_test.go index b6cb02c..217074c 100644 --- a/cmd/benchpod-cli/ci_status_test.go +++ b/cmd/benchpod-cli/ci_status_test.go @@ -61,7 +61,7 @@ func (p *statusFormPod) reply(req map[string]any) []byte { ok := func(data any) []byte { b, _ := json.Marshal(map[string]any{"status": "ok", "data": data}); return b } switch req["cmd"] { case "status": - st := map[string]any{"version": "3.10.13", "board_rev": "v3", "gateware": 58, "analog": true, + st := map[string]any{"version": "4.0.0", "board_rev": "v3", "gateware": 58, "analog": true, "api": 2, "min_client_api": 2, "lease": map[string]any{"held": false, "holder": "", "left_s": 0}} if caps, set := req["caps"]; p.featuresRev > 0 && set && caps == false { st["features_rev"] = p.featuresRev @@ -121,7 +121,7 @@ func TestCILeaseFromFeaturesRev(t *testing.T) { }{ {5, true, true, ""}, {4, false, false, "features_rev 4; the lease needs features_rev 5"}, - {0, false, true, "the caps list"}, // older firmware: lease_acquire answers unknown command + {0, false, true, "no features_rev"}, // lease_acquire answers unknown command } for _, c := range cases { p := startStatusFormPod(t, c.rev) @@ -152,7 +152,7 @@ func TestCILeaseFromFeaturesRev(t *testing.T) { func TestStatusJSONHasLocalLease(t *testing.T) { p := startStatusFormPod(t, 5) out := filepath.Join(t.TempDir(), "status.json") - if code := run([]string{"--connection", p.addr, "--tls", "off", "status", "--json", "--output-filename", out}); code != 0 { + if code := run([]string{"--connection", p.addr, "--tls", "off", "status", "--json", "--out", out}); code != 0 { t.Fatalf("exit %d", code) } data, _ := os.ReadFile(out) diff --git a/cmd/benchpod-cli/ci_steps.go b/cmd/benchpod-cli/ci_steps.go index 7aac353..1a2beaf 100644 --- a/cmd/benchpod-cli/ci_steps.go +++ b/cmd/benchpod-cli/ci_steps.go @@ -216,7 +216,7 @@ func (r *ciRunner) powerOn(ctx context.Context, w io.Writer) error { fmt.Fprintf(w, "I/O voltage %d mV from the wiring profile\n", mv) } } - req := map[string]any{"cmd": "target_power", "efuse": rail, "state": 1} + req := map[string]any{"cmd": "target_power", "efuse": rail, "enabled": true} if r.wiring.Name != "" { req["profile"] = r.wiring.Name } @@ -229,7 +229,7 @@ func (r *ciRunner) powerOn(ctx context.Context, w io.Writer) error { func (r *ciRunner) powerOff(ctx context.Context, w io.Writer) error { rail := r.wiring.rail() - if _, err := r.pod.Command(ctx, map[string]any{"cmd": "target_power", "efuse": rail, "state": 0}); err != nil { + if _, err := r.pod.Command(ctx, map[string]any{"cmd": "target_power", "efuse": rail, "enabled": false}); err != nil { return fmt.Errorf("power off (eFuse %d): %w", rail, err) } fmt.Fprintf(w, "power off, eFuse %d\n", rail) @@ -246,9 +246,9 @@ func (r *ciRunner) railOn(ctx context.Context, rail int) bool { return false } if rail == 2 { - return tp.Efuse2.Enabled == 1 + return bool(tp.Efuse2.Enabled) } - return tp.Efuse1.Enabled == 1 + return bool(tp.Efuse1.Enabled) } // uartRequest is uart_proxy_start on the profile's UART. @@ -477,7 +477,7 @@ func (r *ciRunner) measurePower(ctx context.Context, m *ci.MeasurePower, w io.Wr var stats *powerStats if r.pod.Transport() == "cloud" { // The cloud command channel takes start/stop, not the one-shot (it waits on a stream). - start := map[string]any{"cmd": "power_profile", "action": "start", "efuse": rail, "rate_hz": 500, "keep_samples": 0, "max_duration_ms": ms + 10000} + start := map[string]any{"cmd": "power_profile", "action": "start", "efuse": rail, "sample_rate_hz": 500, "keep_samples": 0, "max_duration_ms": ms + 10000} if _, err := r.pod.Command(ctx, start); err != nil { return nil, fmt.Errorf("power_profile start: %w", err) } @@ -494,7 +494,7 @@ func (r *ciRunner) measurePower(ctx context.Context, m *ci.MeasurePower, w io.Wr } stats = st } else { - lines, err := r.pod.Chunks(ctx, map[string]any{"cmd": "power_profile", "efuse": rail, "duration_ms": ms, "rate_hz": 500, "keep_samples": 0}) + lines, err := r.pod.Chunks(ctx, map[string]any{"cmd": "power_profile", "efuse": rail, "duration_ms": ms, "sample_rate_hz": 500, "keep_samples": 0}) if err != nil { return nil, fmt.Errorf("power_profile: %w", err) } diff --git a/cmd/benchpod-cli/ci_test.go b/cmd/benchpod-cli/ci_test.go index 81e7d81..d4e44ec 100644 --- a/cmd/benchpod-cli/ci_test.go +++ b/cmd/benchpod-cli/ci_test.go @@ -49,7 +49,7 @@ func (p *fakeCIPod) cmds() []string { for _, r := range p.reqs { s := r["cmd"].(string) if s == "target_power" { - s += fmt.Sprintf(":%v:%v", r["efuse"], r["state"]) + s += fmt.Sprintf(":%v:%v", r["efuse"], map[any]int{true: 1, false: 0}[r["enabled"]]) } out = append(out, s) } @@ -69,7 +69,7 @@ func (p *fakeCIPod) Command(_ context.Context, req map[string]any) (json.RawMess if p.statusErr != nil { return nil, p.statusErr } - st := map[string]any{"version": p.version, "board_rev": "v3", "analog": true, "gateware": 58, "features_rev": 4, "la_vccio_mv": 3300} + st := map[string]any{"version": p.version, "board_rev": "v3", "analog": true, "gateware": 58, "features_rev": 4, "la_vccio_mv": 3300, "api": 2, "min_client_api": 2} p.mu.Lock() if len(p.uptimes) > 0 { st["uptime_ms"] = p.uptimes[0] @@ -87,7 +87,7 @@ func (p *fakeCIPod) Command(_ context.Context, req map[string]any) (json.RawMess case "calibrate": return json.RawMessage(`{"offset":{"current_in":12}}`), nil case "target_power": - if req["state"] == 1 { + if req["enabled"] == true { p.mu.Lock() w := p.uart p.mu.Unlock() @@ -98,9 +98,9 @@ func (p *fakeCIPod) Command(_ context.Context, req map[string]any) (json.RawMess }() } } - return json.RawMessage(`{"efuse":1,"enabled":1}`), nil + return json.RawMessage(`{"efuse":1,"enabled":true}`), nil case "target_status": - return json.RawMessage(`{"efuse1":{"enabled":0},"efuse2":{"enabled":0}}`), nil + return json.RawMessage(`{"efuse1":{"enabled":false},"efuse2":{"enabled":false}}`), nil } return json.RawMessage(`{}`), nil } @@ -653,7 +653,7 @@ func TestLocalLeaseRequests(t *testing.T) { renewErr = &tcpclient.PodError{Reason: "lease not held", Code: "BP0027"} mu.Unlock() time.Sleep(70 * time.Millisecond) - if !strings.Contains(l.Lost(), "lease not held") { + if !strings.Contains(l.Lost(), "lease was lost") { t.Errorf("lost %q", l.Lost()) } l.Release(context.Background()) @@ -750,7 +750,7 @@ func TestCICommandExitCodes(t *testing.T) { if code := run([]string{"ci", "run", "-f", bad}); code != 1 { t.Errorf("run bad: %d", code) } - if code := run([]string{"ci", "run", "--no-such-flag"}); code != 1 { + if code := run([]string{"ci", "run", "--no-such-flag"}); code != exitUsage { t.Errorf("usage error under ci: %d", code) } if code := run([]string{"ci", "-f", filepath.Join(dir, "nope.yaml")}); code != 1 { @@ -768,7 +768,7 @@ func TestCICommandExitCodes(t *testing.T) { } a, b := mk("a", ci.Passed), mk("b", ci.Failed) out := filepath.Join(dir, "diff.json") - if code := run([]string{"ci", "diff", a, filepath.Join(b, "run.json"), "--json", "--output-filename", out}); code != 0 { + if code := run([]string{"ci", "diff", a, filepath.Join(b, "run.json"), "--json", "--out", out}); code != 0 { t.Errorf("diff: %d", code) } if code := run([]string{"ci", "diff", a, filepath.Join(dir, "missing")}); code != 1 { diff --git a/cmd/benchpod-cli/cloudcfg.go b/cmd/benchpod-cli/cloudcfg.go index 2911a94..a3ec1c8 100644 --- a/cmd/benchpod-cli/cloudcfg.go +++ b/cmd/benchpod-cli/cloudcfg.go @@ -18,7 +18,6 @@ import ( "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -37,30 +36,11 @@ import ( // policy ("cloud_ca: change it from the cloud or over USB"); only reading works there. const ( - caMaxPEM = 16 * 1024 // the pod's limit on the stored PEM - caMaxFile = 1024 * 1024 // refuse to even read a larger file - caLANChunk = 768 // raw bytes per ota_data line (as the hwe2e LAN OTA sends) - caMissing = "this firmware has no company CA support; update the pod's firmware" - proxyMissing = "this firmware has no HTTP proxy support; update the pod's firmware" - lanGateHint = "the pod only takes this change over USB or from the cloud, never from Ethernet or Wi-Fi; run it with --connection usb" + caMaxPEM = 16 * 1024 // the pod's limit on the stored PEM + caMaxFile = 1024 * 1024 // refuse to even read a larger file + caLANChunk = 768 // raw bytes per ota_data line (as the hwe2e LAN OTA sends) ) -// lanGateRefusals are the tails of the firmware's refusal of a cloud link change from the LAN -// (pod_policy_cloud_link_gate): "cloud_ca: ..." or "cloud_proxy: ...". Firmware 3.9.0 also takes -// the change over its USB network adapter and says so; older firmware names the console. -var lanGateRefusals = []string{": change it from the cloud or over USB", ": change it from the cloud or the USB console"} - -// isLANGateRefusal reports whether msg is the firmware's refusal to change the company CA or -// the HTTP proxy from the LAN. -func isLANGateRefusal(msg string) bool { - for _, tail := range lanGateRefusals { - if verb, ok := strings.CutSuffix(strings.TrimSpace(msg), tail); ok { - return verb == "cloud_ca" || verb == "cloud_proxy" - } - } - return false -} - func newCloudCmd(g *globalFlags) *cobra.Command { root := &cobra.Command{ Use: "cloud", @@ -68,11 +48,12 @@ func newCloudCmd(g *globalFlags) *cobra.Command { Long: "Configure the pod's link to embeddedci.com on networks that need it.\n\n" + " ca a company root certificate, for networks whose proxy inspects TLS\n" + " proxy an HTTP proxy the pod tunnels its cloud connection through\n\n" + - "Both work over the pod's USB console (--connection usb) and through\n" + + "Both work over the pod's USB network adapter (--connection usb) and through\n" + "embeddedci.com (--connection embeddedci:; a change there needs an\n" + "organization owner or admin, and `cloud ca set` needs USB). The LAN\n" + - "(--connection
) can show them; current firmware refuses changes from\n" + - "the LAN, so change them over USB. The pod reconnects to the cloud after a change.", + "(--connection
) can show them; the pod refuses changes from the LAN,\n" + + "so change them over USB. The pod reconnects to the cloud after a change.\n" + + "USB networking off: `benchpod usb-network on --connection usb`.", Args: cobra.NoArgs, } root.AddCommand(newCloudCACmd(g), newCloudProxyCmd(g)) @@ -171,7 +152,7 @@ func newCloudProxyCmd(g *globalFlags) *cobra.Command { } password = pw } else if pf.password != "" || pf.passwordStdin { - return errors.New("cloud proxy set: --password needs --user") + return usageErrorf("cloud proxy set: --password needs --user") } return run(func(out, warn io.Writer) error { return runCloudProxy(g, "set", args[0], pf.user, password, out, warn) @@ -308,7 +289,7 @@ func readCAFile(path string) ([]byte, error) { } // printCACerts writes the certificate list the pod reports. -func printCACerts(out io.Writer, label string, certs []serialconsole.CACert, changed bool) { +func printCACerts(out io.Writer, label string, certs []podCACert, changed bool) { verb := ":" if changed { verb = " is now" @@ -356,31 +337,26 @@ func runCloudCA(g *globalFlags, action, file string, out, warn io.Writer) error return err } var label string - var certs []serialconsole.CACert + var certs []podCACert switch { case spec.IsCloud() && action == "set": return cloudCASetRefusal(what) case spec.IsCloud(): label, certs, err = cloudCACloud(g, spec, action) case spec.IsSerial(): - // Firmware 3.9.0+: over the USB network link, which may change the CA (physical presence). - if addr := g.usbLinkAddr(spec.Device, spec.Pod); addr != "" { - label = addr - certs, err = cloudCALAN(g, addr, action, upload, warn) - break - } - label, certs, err = cloudCAUSB(g, spec.Device, action, upload, warn) - if err != nil && strings.Contains(err.Error(), "moved to the network API") { - err = errors.New("this pod's firmware (3.9.0 or later) installs a CA over the network: its USB network " + - "adapter is not usable here (Wi-Fi configured on the pod turns it off: `benchpod clear-wifi`), so use the " + - "cloud (`--connection embeddedci:`) or turn USB networking back on") + // Over the USB network link, which may change the CA (physical presence). + var nt ConnSpec + if nt, err = g.networkTarget(what); err != nil { + return err } + label = nt.Addr + certs, err = cloudCALAN(g, nt.Addr, action, upload, warn) default: label = spec.Addr certs, err = cloudCALAN(g, spec.Addr, action, upload, warn) } if err != nil { - return cloudCfgError(what, caMissing, !spec.IsSerial(), err) + return cloudCfgError(what, err) } printCACerts(out, label, certs, action != "show") @@ -396,7 +372,7 @@ func runCloudCA(g *globalFlags, action, file string, out, warn io.Writer) error return nil } -func sameCerts(local []caCert, pod []serialconsole.CACert) bool { +func sameCerts(local []caCert, pod []podCACert) bool { if len(local) != len(pod) { return false } @@ -408,88 +384,26 @@ func sameCerts(local []caCert, pod []serialconsole.CACert) bool { return true } -// cloudCfgError turns a failed command into one clear line: old firmware, a locked LAN, a change -// the pod refuses from the LAN, or the pod's own reason. -func cloudCfgError(what, missing string, lan bool, err error) error { - if errors.Is(err, serialconsole.ErrUnknownCommand) { - return errors.New(missing) - } - // "unknown target": no code yet (a cloud_ca / cloud_proxy target older firmware lacks) - if isUnknownCommand(err) || strings.Contains(err.Error(), "unknown target") { - return errors.New(missing) - } +// cloudCfgError turns a failed command into one clear line: the pod's refusal (a locked LAN, a +// change the pod refuses from the LAN), worded from its code. +func cloudCfgError(what string, err error) error { if pe, ok := tcpclient.AsPodError(err); ok { - // A console refusal (Cmd set) came over USB, a JSON reply over the LAN. - lan = lan && pe.Cmd == "" - if lan && isLANGateRefusal(pe.Reason) { - return refusedWithHint(what, pe, lanGateHint) - } - return refusedError(what, pe, lan) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } -// ── USB console ───────────────────────────────────────────────────────────── - -// cloudConsole is the part of the USB console the cloud ca/proxy commands use. -type cloudConsole interface { - CloudCA(ctx context.Context) ([]serialconsole.CACert, error) - CloudCAClear(ctx context.Context) error - CloudProxy(ctx context.Context) (serialconsole.ProxyConfig, error) - CloudProxySet(ctx context.Context, addr, user, password string) (serialconsole.ProxyConfig, error) - CloudProxyClear(ctx context.Context) (serialconsole.ProxyConfig, error) - Upload(ctx context.Context, target string, data []byte, version int, progress func(done, total int)) error - Close() error -} - -// openCloudConsole opens the pod's USB console; tests replace it with a fake. -var openCloudConsole = func(g *globalFlags, device string, timeout time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) - if err != nil { - return nil, "", nil, cancel, err - } - return console, path, ctx, cancel, nil -} - -func cloudCAUSB(g *globalFlags, device, action string, upload []byte, warn io.Writer) (string, []serialconsole.CACert, error) { - console, path, ctx, cancel, err := openCloudConsole(g, device, g.effectiveTimeout(60*time.Second)) - if err != nil { - return "", nil, err - } - defer cancel() - defer console.Close() - label := "the pod on " + path - - switch action { - case "set": - // Ask first, so old firmware gets the clear message rather than a refused upload. - if _, err := console.CloudCA(ctx); err != nil { - return label, nil, err - } - fmt.Fprintf(warn, "Uploading %d bytes to %s ...\n", len(upload), label) - if err := console.Upload(ctx, "ca", upload, 0, nil); err != nil { - return label, nil, err - } - case "clear": - if err := console.CloudCAClear(ctx); err != nil { - return label, nil, err - } - } - certs, err := console.CloudCA(ctx) - return label, certs, err -} - // ── embeddedci.com ────────────────────────────────────────────────────────── // cloudCASetRefusal: installing a CA is an upload, which the command channel does not carry. func cloudCASetRefusal(what string) error { - return fmt.Errorf("%s does not work over embeddedci.com from the CLI: the certificate upload needs the pod's USB console. "+ + return fmt.Errorf("%s does not work over embeddedci.com from the CLI: the certificate upload needs the pod's USB network adapter. "+ "Run it with --connection usb", what) } // cloudCACloud shows or clears the company CA through embeddedci.com. The pod reconnects after a // clear, so the reply to the clear is what it reports; a read-back could race the reconnect. -func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []serialconsole.CACert, error) { +func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []podCACert, error) { req := map[string]any{"cmd": "cloud_ca"} if action == "clear" { req["clear"] = true @@ -502,7 +416,7 @@ func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []seria // cloudProxyCloud shows, sets or clears the HTTP proxy through embeddedci.com (HTTPS, so a proxy // password does not cross the network in the clear). Like the CA, a change makes the pod // reconnect, so the change's own reply is what it reports. -func cloudProxyCloud(g *globalFlags, spec ConnSpec, action, set, user, password string) (string, serialconsole.ProxyConfig, error) { +func cloudProxyCloud(g *globalFlags, spec ConnSpec, action, set, user, password string) (string, proxyConfig, error) { req := map[string]any{"cmd": "cloud_proxy"} switch action { case "set": @@ -549,8 +463,8 @@ func openLAN(ctx context.Context, addr string) (lanSession, error) { } type caReply struct { - Present bool `json:"present"` - Certs []serialconsole.CACert `json:"certs"` + Present bool `json:"present"` + Certs []podCACert `json:"certs"` } // otaReply is the pod's ota_* status. @@ -559,7 +473,7 @@ type otaReply struct { Error string `json:"error"` } -func cloudCALAN(g *globalFlags, addr, action string, upload []byte, warn io.Writer) ([]serialconsole.CACert, error) { +func cloudCALAN(g *globalFlags, addr, action string, upload []byte, warn io.Writer) ([]podCACert, error) { ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(60*time.Second)) defer cancel() defer installSignalHandler(ctx, cancel)() @@ -631,6 +545,18 @@ func uploadOTALAN(ctx context.Context, lan lanSession, data []byte, target strin return nil } +// podCACert is one company CA certificate the pod holds. +type podCACert struct { + Subject string `json:"subject"` + SHA256 string `json:"sha256"` // hex SHA-256 of the DER certificate +} + +// proxyConfig is the pod's HTTP proxy. Addr is "" when no proxy is set. +type proxyConfig struct { + Addr string // host:port + Auth bool // a user and password are stored (the pod never reports the password) +} + func valueOr(s, def string) string { if strings.TrimSpace(s) == "" { return def @@ -644,7 +570,7 @@ func valueOr(s, def string) string { func checkProxyAddr(addr string) (string, error) { addr = strings.TrimSpace(addr) if strings.Contains(addr, "://") { - return "", fmt.Errorf("give the proxy as host:port, without a scheme (got %q)", addr) + return "", usageErrorf("give the proxy as host:port, without a scheme (got %q)", addr) } host, port, err := net.SplitHostPort(addr) if err != nil { @@ -659,7 +585,7 @@ func checkProxyAddr(addr string) (string, error) { return net.JoinHostPort(strings.ToLower(host), port), nil } -func describeProxy(p serialconsole.ProxyConfig) string { +func describeProxy(p proxyConfig) string { switch { case p.Addr == "": return "none (the pod connects to the cloud directly)" @@ -686,24 +612,24 @@ func runCloudProxy(g *globalFlags, action, addr, user, password string, out, war return err } var label string - var p serialconsole.ProxyConfig + var p proxyConfig switch { case spec.IsCloud(): label, p, err = cloudProxyCloud(g, spec, action, addr, user, password) case spec.IsSerial(): - // Firmware 3.9.0+: over the USB network link, which may change the proxy (physical presence). - if link := g.usbLinkAddr(spec.Device, spec.Pod); link != "" { - label = link - p, err = cloudProxyLAN(g, link, action, addr, user, password) - break + // Over the USB network link, which may change the proxy (physical presence). + var nt ConnSpec + if nt, err = g.networkTarget(what); err != nil { + return err } - label, p, err = cloudProxyUSB(g, spec.Device, action, addr, user, password) + label = nt.Addr + p, err = cloudProxyLAN(g, nt.Addr, action, addr, user, password) default: label = spec.Addr p, err = cloudProxyLAN(g, spec.Addr, action, addr, user, password) } if err != nil { - err = cloudCfgError(what, proxyMissing, !spec.IsSerial(), err) + err = cloudCfgError(what, err) if password != "" && strings.Contains(err.Error(), password) { err = errors.New(strings.ReplaceAll(err.Error(), password, "***")) } @@ -724,26 +650,6 @@ func runCloudProxy(g *globalFlags, action, addr, user, password string, out, war return nil } -func cloudProxyUSB(g *globalFlags, device, action, addr, user, password string) (string, serialconsole.ProxyConfig, error) { - console, path, ctx, cancel, err := openCloudConsole(g, device, g.effectiveTimeout(15*time.Second)) - if err != nil { - return "", serialconsole.ProxyConfig{}, err - } - defer cancel() - defer console.Close() - label := "the pod on " + path - var p serialconsole.ProxyConfig - switch action { - case "set": - p, err = console.CloudProxySet(ctx, addr, user, password) - case "clear": - p, err = console.CloudProxyClear(ctx) - default: - p, err = console.CloudProxy(ctx) - } - return label, p, err -} - // proxyReply is the pod's JSON proxy report: {"host":"...","port":3128,"auth":true}, with no // host when none is set. type proxyReply struct { @@ -752,21 +658,21 @@ type proxyReply struct { Auth bool `json:"auth"` } -func (r proxyReply) config() serialconsole.ProxyConfig { +func (r proxyReply) config() proxyConfig { if r.Host == "" { - return serialconsole.ProxyConfig{} + return proxyConfig{} } - return serialconsole.ProxyConfig{Addr: net.JoinHostPort(r.Host, strconv.Itoa(r.Port)), Auth: r.Auth} + return proxyConfig{Addr: net.JoinHostPort(r.Host, strconv.Itoa(r.Port)), Auth: r.Auth} } -func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (serialconsole.ProxyConfig, error) { +func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (proxyConfig, error) { ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(15*time.Second)) defer cancel() defer installSignalHandler(ctx, cancel)() lan, err := openLAN(ctx, addr) if err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } defer lan.s.Close() @@ -782,13 +688,13 @@ func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (se } var rep proxyReply if err := lan.cmd(ctx, req, &rep); err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } if action != "show" { // Report what the pod holds now, not what the change's reply happened to carry. rep = proxyReply{} if err := lan.cmd(ctx, map[string]any{"cmd": "cloud_proxy"}, &rep); err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } } return rep.config(), nil diff --git a/cmd/benchpod-cli/cloudcfg_test.go b/cmd/benchpod-cli/cloudcfg_test.go index 9eb3b6e..eea9cb4 100644 --- a/cmd/benchpod-cli/cloudcfg_test.go +++ b/cmd/benchpod-cli/cloudcfg_test.go @@ -3,7 +3,6 @@ package main import ( "bufio" "bytes" - "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -25,7 +24,6 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // testCertPEM makes a self-signed certificate; isCA sets the CA basic constraint and cert-sign @@ -111,76 +109,6 @@ func TestCheckCAPEM(t *testing.T) { // ── USB ───────────────────────────────────────────────────────────────────── // fakeCloudConsole stands in for the pod's USB console. -type fakeCloudConsole struct { - certs []serialconsole.CACert - proxy serialconsole.ProxyConfig - err error // returned by every command - uploadTo string - uploaded []byte - calls []string -} - -func (f *fakeCloudConsole) CloudCA(context.Context) ([]serialconsole.CACert, error) { - f.calls = append(f.calls, "ca") - return f.certs, f.err -} - -func (f *fakeCloudConsole) CloudCAClear(context.Context) error { - f.calls = append(f.calls, "ca-clear") - if f.err == nil { - f.certs = nil - } - return f.err -} - -func (f *fakeCloudConsole) CloudProxy(context.Context) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, "proxy") - return f.proxy, f.err -} - -func (f *fakeCloudConsole) CloudProxySet(_ context.Context, addr, user, password string) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, strings.TrimSpace("proxy-set "+addr+" "+user+" "+password)) - if f.err != nil { - return serialconsole.ProxyConfig{}, f.err - } - f.proxy = serialconsole.ProxyConfig{Addr: addr, Auth: user != ""} - return f.proxy, nil -} - -func (f *fakeCloudConsole) CloudProxyClear(context.Context) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, "proxy-clear") - f.proxy = serialconsole.ProxyConfig{} - return f.proxy, f.err -} - -func (f *fakeCloudConsole) Upload(_ context.Context, target string, data []byte, _ int, _ func(int, int)) error { - f.calls = append(f.calls, "upload "+target) - f.uploadTo, f.uploaded = target, data - certs, _, err := checkCAPEM(data) - if err != nil { - return err - } - f.certs = nil - for _, c := range certs { - f.certs = append(f.certs, serialconsole.CACert{Subject: c.Subject, SHA256: c.SHA256}) - } - return nil -} - -func (f *fakeCloudConsole) Close() error { return nil } - -func withFakeCloudConsole(t *testing.T, fc *fakeCloudConsole) { - t.Helper() - saved := openCloudConsole - openCloudConsole = func(_ *globalFlags, device string, _ time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - if device == "" { - device = "/dev/cu.usbmodem1101" - } - return fc, device, context.Background(), func() {}, nil - } - t.Cleanup(func() { openCloudConsole = saved }) -} - func runCACapture(g *globalFlags, action, file string) (string, string, error) { var out, warn bytes.Buffer err := runCloudCA(g, action, file, &out, &warn) @@ -193,137 +121,91 @@ func runProxyCapture(g *globalFlags, action, addr, user, password string) (strin return out.String(), warn.String(), err } +// Over USB the company CA and the proxy go over the pod's USB network adapter (JSON, the USB link +// may change them). func TestCloudCAUSB(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "usb"} + pod := &lanCfgPod{t: t} + addr := pod.start() + g := &globalFlags{connection: "usb", usbAddr: addr} out, _, err := runCACapture(g, "show", "") - if err != nil || out != "Company CA of the pod on /dev/cu.usbmodem1101: none (the pod trusts only its built-in roots)\n" { + if err != nil || out != "Company CA of "+addr+": none (the pod trusts only its built-in roots)\n" { t.Fatalf("show = %q, %v", out, err) } - root := testCertPEM(t, "Acme Root CA", true) out, warn, err := runCACapture(g, "set", tempPEM(t, "acme.pem", root)) - if err != nil { - t.Fatalf("set: %v", err) - } - want := "Company CA of the pod on /dev/cu.usbmodem1101 is now 1 certificate\n" + - " CN=Acme Root CA,O=Acme Corp\n SHA-256 " + pemSHA(t, root) + "\n" - if out != want { - t.Fatalf("set = %q\nwant %q", out, want) - } - if fc.uploadTo != "ca" || !bytes.Equal(fc.uploaded, root) { - t.Fatalf("uploaded %q to %q", fc.uploaded, fc.uploadTo) + if err != nil || !strings.HasPrefix(out, "Company CA of "+addr+" is now 1 certificate\n") { + t.Fatalf("set = %q, %v", out, err) } if !strings.Contains(warn, "reconnects to the cloud") || strings.Contains(warn, "Warning") { t.Fatalf("warn = %q", warn) } - - out, warn, err = runCACapture(g, "clear", "") - if err != nil || !strings.HasSuffix(out, "is now none (the pod trusts only its built-in roots)\n") || - !strings.Contains(warn, "only its built-in roots") { - t.Fatalf("clear = %q, %q, %v", out, warn, err) + if !strings.Contains(pod.cmds(), "ota_begin,ota_data,ota_end,ota_commit") { + t.Fatalf("requests = %s", pod.cmds()) } - if got := strings.Join(fc.calls, ","); got != "ca,ca,upload ca,ca,ca-clear,ca" { - t.Fatalf("calls = %s", got) + out, _, err = runCACapture(g, "clear", "") + if err != nil || !strings.HasSuffix(out, "is now none (the pod trusts only its built-in roots)\n") { + t.Fatalf("clear = %q, %v", out, err) } } func TestCloudCANotMarkedCAWarns(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - _, warn, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "leaf.pem", testCertPEM(t, "leaf", false))) - if err != nil || !strings.Contains(warn, "Warning: CN=leaf,O=Acme Corp is not marked as a CA") { + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + _, warn, err := runCACapture(g, "set", tempPEM(t, "leaf.pem", testCertPEM(t, "leaf", false))) + if !strings.Contains(warn, "Warning: CN=leaf,O=Acme Corp is not marked as a CA") { t.Fatalf("warn = %q, %v", warn, err) } } -func TestCloudCAUSBOldFirmware(t *testing.T) { - fc := &fakeCloudConsole{err: serialconsole.ErrUnknownCommand} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "usb"} - for _, action := range []string{"show", "clear"} { - if _, _, err := runCACapture(g, action, ""); err == nil || err.Error() != caMissing { - t.Fatalf("%s: err = %v", action, err) - } - } - if _, _, err := runCACapture(g, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))); err == nil || err.Error() != caMissing { - t.Fatalf("set: err = %v", err) +func TestCloudCABadPEMTouchesNoPod(t *testing.T) { + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + _, _, err := runCACapture(g, "set", tempPEM(t, "bad.pem", []byte("not a certificate"))) + if err == nil || !strings.Contains(err.Error(), "no CERTIFICATE block") { + t.Fatalf("err = %v", err) } - if fc.uploadTo != "" { - t.Fatal("old firmware got an upload") + if pod.cmds() != "" { + t.Fatalf("a bad PEM reached the pod: %v", pod.cmds()) } - if _, _, err := runProxyCapture(g, "show", "", "", ""); err == nil || err.Error() != proxyMissing { - t.Fatalf("proxy: err = %v", err) + if _, _, err := runCACapture(g, "set", filepath.Join(t.TempDir(), "missing.pem")); err == nil { + t.Fatal("a missing file passed") } } -func TestCloudCAUSBUnknownTarget(t *testing.T) { - // Firmware that knows `ca` but whose upload path refuses the target still reads as old. - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - saved := openCloudConsole - openCloudConsole = func(g *globalFlags, d string, to time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - _, p, ctx, c, err := saved(g, d, to) - return uploadRefuser{fc}, p, ctx, c, err - } - _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - if err == nil || err.Error() != caMissing { - t.Fatalf("err = %v", err) +// Without the USB network adapter (and no network address that answers), the command says how to +// turn it on. +func TestCloudCfgUSBWithoutTheNetwork(t *testing.T) { + old := usbNetwork + usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { + return serialconsole.USBNet{PodIP: "10.237.8.85", HostIP: "10.237.8.86", OffBySetting: true}, nil } -} - -type uploadRefuser struct{ *fakeCloudConsole } - -func (uploadRefuser) Upload(context.Context, string, []byte, int, func(int, int)) error { - return fmt.Errorf("upload ca: begin: error unknown target") -} - -func TestCloudCABadPEMTouchesNoPod(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "bad.pem", []byte("not a certificate"))) - if err == nil || !strings.Contains(err.Error(), "no CERTIFICATE block") { + t.Cleanup(func() { usbNetwork = old }) + _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "show", "", "", "") + if err == nil || !strings.Contains(err.Error(), "usb-network on") { t.Fatalf("err = %v", err) } - if len(fc.calls) != 0 { - t.Fatalf("a bad PEM reached the pod: %v", fc.calls) - } - if _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", filepath.Join(t.TempDir(), "missing.pem")); err == nil { - t.Fatal("a missing file passed") - } } func TestCloudProxyUSB(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "/dev/cu.usbmodem9"} + pod := &lanCfgPod{t: t} + addr := pod.start() + g := &globalFlags{connection: "usb", usbAddr: addr} out, _, err := runProxyCapture(g, "show", "", "", "") - if err != nil || out != "HTTP proxy of the pod on /dev/cu.usbmodem9: none (the pod connects to the cloud directly)\n" { + if err != nil || out != "HTTP proxy of "+addr+": none (the pod connects to the cloud directly)\n" { t.Fatalf("show = %q, %v", out, err) } out, warn, err := runProxyCapture(g, "set", "Proxy.Corp:3128", "alice", "s3cret") - if err != nil || out != "HTTP proxy of the pod on /dev/cu.usbmodem9 is now proxy.corp:3128 (with a user and password)\n" { + if err != nil || out != "HTTP proxy of "+addr+" is now proxy.corp:3128 (with a user and password)\n" { t.Fatalf("set = %q, %v", out, err) } - if warn != "The pod reconnects to the cloud through proxy.corp:3128.\n" { + if warn != "The pod reconnects to the cloud through proxy.corp:3128.\n" || strings.Contains(out+warn, "s3cret") { t.Fatalf("warn = %q", warn) } - if strings.Contains(out+warn, "s3cret") { - t.Fatal("the password was printed") - } - out, warn, err = runProxyCapture(g, "clear", "", "", "") - if err != nil || !strings.HasSuffix(out, "is now none (the pod connects to the cloud directly)\n") || - warn != "The pod reconnects to the cloud directly, without a proxy.\n" { - t.Fatalf("clear = %q, %q, %v", out, warn, err) - } - - fc.err = &serialconsole.CommandError{Cmd: "proxy-set", Reason: "w25q write failed"} - _, _, err = runProxyCapture(g, "set", "p:1", "", "") - if err == nil || err.Error() != "cloud proxy set: the pod refused: w25q write failed" { - t.Fatalf("refusal: %v", err) + out, _, err = runProxyCapture(g, "clear", "", "", "") + if err != nil || !strings.HasSuffix(out, "is now none (the pod connects to the cloud directly)\n") { + t.Fatalf("clear = %q, %v", out, err) } } @@ -340,16 +222,16 @@ func TestCheckProxyAddr(t *testing.T) { t.Errorf("%q passed", in) } } - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - if _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "set", "http://p:1", "", ""); err == nil { + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + if _, _, err := runProxyCapture(g, "set", "http://p:1", "", ""); err == nil { t.Fatal("a bad address passed") } - if _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "set", "p:1", "alice", ""); err == nil { + if _, _, err := runProxyCapture(g, "set", "p:1", "alice", ""); err == nil { t.Fatal("a user without a password passed") } - if len(fc.calls) != 0 { - t.Fatalf("a bad value reached the pod: %v", fc.calls) + if pod.cmds() != "" { + t.Fatalf("a bad value reached the pod: %v", pod.cmds()) } } @@ -360,10 +242,9 @@ func TestCheckProxyAddr(t *testing.T) { type lanCfgPod struct { t *testing.T mu sync.Mutex - old bool // "unknown cmd" / "unknown target" locked string // the T2/T3 verbs refused with "locked: ..." gated bool // current firmware: every change refused from the LAN (pod_policy_cloud_link_gate) - certs []serialconsole.CACert + certs []podCACert proxy proxyReply staged []byte sha string @@ -407,6 +288,11 @@ func okReply(data any) string { return string(b) } +func codeReply(code string, args map[string]any) string { + b, _ := json.Marshal(map[string]any{"status": "error", "code": code, "args": args}) + return string(b) +} + func errReply(msg string) string { b, _ := json.Marshal(map[string]any{"status": "error", "message": msg}) return string(b) @@ -419,27 +305,21 @@ func (p *lanCfgPod) handle(req map[string]any) string { cmd, _ := req["cmd"].(string) changes := req["set"] != nil || req["clear"] != nil || strings.HasPrefix(cmd, "ota_") && cmd != "ota_abort" if p.locked != "" && changes { - return errReply("locked: " + cmd + " needs the cloud or the USB console") + return codeReply("BP0040", map[string]any{"cmd": cmd}) } if p.gated && (cmd == "cloud_ca" || cmd == "cloud_proxy") && changes { - return errReply(cmd + ": change it from the cloud or over USB") + return codeReply("BP0042", map[string]any{"setting": cmd}) } if p.gated && cmd == "ota_begin" && req["target"] == "ca" { - return errReply("cloud_ca: change it from the cloud or the USB console") + return codeReply("BP0042", map[string]any{"setting": "cloud_ca"}) } switch cmd { case "cloud_ca": - if p.old { - return errReply("unknown cmd") - } if req["clear"] == true { p.certs = nil } return okReply(map[string]any{"present": len(p.certs) > 0, "certs": p.certs}) case "cloud_proxy": - if p.old { - return errReply("unknown cmd") - } if req["clear"] == true { p.proxy = proxyReply{} } @@ -454,8 +334,8 @@ func (p *lanCfgPod) handle(req map[string]any) string { } return okReply(p.proxy) case "ota_begin": - if p.old || req["target"] != "ca" { - return errReply("unknown target") + if req["target"] != "ca" { + return codeReply("BP0060", map[string]any{"target": req["target"]}) } p.staged = make([]byte, int(req["size"].(float64))) p.sha, p.state = req["sha256"].(string), "receiving" @@ -480,13 +360,13 @@ func (p *lanCfgPod) handle(req map[string]any) string { } p.certs = nil for _, c := range certs { - p.certs = append(p.certs, serialconsole.CACert{Subject: c.Subject, SHA256: c.SHA256}) + p.certs = append(p.certs, podCACert{Subject: c.Subject, SHA256: c.SHA256}) } p.state = "installed" case "ota_abort": p.state = "idle" default: - return errReply("unknown cmd") + return codeReply("BP0002", map[string]any{"cmd": cmd}) } return okReply(map[string]any{"state": p.state, "target": "ca", "error": ""}) } @@ -537,15 +417,15 @@ func TestCloudCALANLocked(t *testing.T) { pod := &lanCfgPod{t: t, locked: "yes"} addr := pod.start() _, _, err := runCACapture(&globalFlags{connection: addr}, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - want := "cloud ca set: the pod refused: locked: ota_begin needs the cloud or the USB console (" + lockedUSBHint + ")" - if err == nil || err.Error() != want { + want := "cloud ca set: the pod refused: BP0040: The pod's LAN is locked: ota_begin needs the cloud or USB; run this over USB with --connection usb, or from the cloud" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("err = %v\nwant %s", err, want) } if !strings.HasSuffix(pod.cmds(), "ota_begin,ota_abort") { t.Fatalf("requests = %s", pod.cmds()) } _, _, err = runProxyCapture(&globalFlags{connection: addr}, "clear", "", "", "") - if err == nil || !strings.Contains(err.Error(), "locked: cloud_proxy needs") || !strings.Contains(err.Error(), "--connection usb") { + if err == nil || !strings.Contains(err.Error(), "BP0040: The pod's LAN is locked: cloud_proxy needs") || !strings.Contains(err.Error(), "--connection usb") { t.Fatalf("proxy clear: err = %v", err) } // Showing still works on a locked LAN. @@ -560,16 +440,16 @@ func TestCloudLANGated(t *testing.T) { g := &globalFlags{connection: addr} _, _, err := runCACapture(g, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - want := "cloud ca set: the pod refused: cloud_ca: change it from the cloud or the USB console (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want := "cloud ca set: the pod refused: BP0042: cloud_ca cannot be changed over the LAN: change it from the cloud or over USB; run this over USB with --connection usb, or from the cloud" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("ca set: err = %v\nwant %s", err, want) } if !strings.HasSuffix(pod.cmds(), "ota_begin,ota_abort") { t.Fatalf("requests = %s", pod.cmds()) } _, _, err = runCACapture(g, "clear", "") - want = "cloud ca clear: the pod refused: cloud_ca: change it from the cloud or over USB (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want = "cloud ca clear: the pod refused: BP0042: cloud_ca cannot be changed" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("ca clear: err = %v\nwant %s", err, want) } for _, action := range []string{"set", "clear"} { @@ -578,14 +458,11 @@ func TestCloudLANGated(t *testing.T) { addrArg, user, pw = "proxy.corp:3128", "alice", "s3cret" } _, _, err = runProxyCapture(g, action, addrArg, user, pw) - want = "cloud proxy " + action + ": the pod refused: cloud_proxy: change it from the cloud or over USB (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want = "cloud proxy " + action + ": the pod refused: BP0042: cloud_proxy cannot be changed over the LAN" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("proxy %s: err = %v\nwant %s", action, err, want) } } - if !strings.Contains(lanGateHint, "--connection usb") { - t.Fatalf("hint names no USB connection: %s", lanGateHint) - } // Reading still works from the LAN. if _, _, err := runCACapture(g, "show", ""); err != nil { t.Fatalf("ca show: %v", err) @@ -595,55 +472,6 @@ func TestCloudLANGated(t *testing.T) { } } -func TestCloudCfgErrorLANGate(t *testing.T) { - for _, tc := range []struct { - msg string - gate bool - }{ - {"cloud_ca: change it from the cloud or the USB console", true}, - {"cloud_proxy: change it from the cloud or the USB console", true}, - {"cloud_proxy: change it from the cloud or the USB console\n", true}, - {"lan_policy: change it from the cloud or the USB console", false}, - {"sig_policy: change it from the cloud or the USB console", false}, - {"cloud_proxy: bad host", false}, - {"", false}, - } { - if got := isLANGateRefusal(tc.msg); got != tc.gate { - t.Errorf("isLANGateRefusal(%q) = %v, want %v", tc.msg, got, tc.gate) - } - } - msg := "cloud_proxy: change it from the cloud or the USB console" - // Only a LAN connection gets the hint; the same words from elsewhere pass through as is. - if err := cloudCfgError("cloud proxy clear", proxyMissing, true, &tcpclient.PodError{Reason: msg}); !strings.Contains(err.Error(), lanGateHint) { - t.Fatalf("LAN: %v", err) - } - if err := cloudCfgError("cloud proxy clear", proxyMissing, false, &tcpclient.PodError{Reason: msg}); err.Error() != "cloud proxy clear: the pod refused: "+msg { - t.Fatalf("not LAN: %v", err) - } - ce := &serialconsole.CommandError{Cmd: "proxy", Reason: msg} - if err := cloudCfgError("cloud proxy clear", proxyMissing, false, ce); strings.Contains(err.Error(), lanGateHint) { - t.Fatalf("USB got the LAN hint: %v", err) - } -} - -func TestCloudLANOldFirmware(t *testing.T) { - pod := &lanCfgPod{t: t, old: true} - addr := pod.start() - g := &globalFlags{connection: addr} - if _, _, err := runCACapture(g, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))); err == nil || err.Error() != caMissing { - t.Fatalf("ca set: err = %v", err) - } - if strings.Contains(pod.cmds(), "ota_") { - t.Fatalf("old firmware got an upload: %s", pod.cmds()) - } - if _, _, err := runCACapture(g, "show", ""); err == nil || err.Error() != caMissing { - t.Fatalf("ca show: err = %v", err) - } - if _, _, err := runProxyCapture(g, "set", "p:1", "", ""); err == nil || err.Error() != proxyMissing { - t.Fatalf("proxy set: err = %v", err) - } -} - func TestCloudProxyLAN(t *testing.T) { pod := &lanCfgPod{t: t} addr := pod.start() diff --git a/cmd/benchpod-cli/commands_cloud.go b/cmd/benchpod-cli/commands_cloud.go index 0e211f6..93735d0 100644 --- a/cmd/benchpod-cli/commands_cloud.go +++ b/cmd/benchpod-cli/commands_cloud.go @@ -109,7 +109,7 @@ func newLogoutCmd(g *globalFlags) *cobra.Command { func runLogin(serverURL, tokenFile string, noOpen bool) error { if strings.TrimSpace(serverURL) == "" { - return errors.New("--server-url cannot be empty") + return usageErrorf("--server-url cannot be empty") } tokenPath, err := resolveTokenPath(tokenFile) if err != nil { diff --git a/cmd/benchpod-cli/commands_deregister.go b/cmd/benchpod-cli/commands_deregister.go index 7186f47..60392dc 100644 --- a/cmd/benchpod-cli/commands_deregister.go +++ b/cmd/benchpod-cli/commands_deregister.go @@ -58,12 +58,12 @@ func newDeregisterCmd(g *globalFlags) *cobra.Command { // that case there is nothing to unprovision locally, so the pod-side step is skipped. func runDeregister(g *globalFlags, serverURL, tokenFile, deviceName, deviceID string, keepPodConfig bool) error { if strings.TrimSpace(serverURL) == "" { - return errors.New("--server-url cannot be empty") + return usageErrorf("--server-url cannot be empty") } deviceName = strings.TrimSpace(deviceName) deviceID = strings.TrimSpace(deviceID) if deviceName != "" && deviceID != "" { - return errors.New("pass only one of --device-name or --device-id") + return usageErrorf("pass only one of --device-name or --device-id") } // Only the default (identify-by-key) path talks to the pod; an explicit selector means the // pod may be unreachable, which is exactly why the selector exists. diff --git a/cmd/benchpod-cli/commands_discover.go b/cmd/benchpod-cli/commands_discover.go index 8907485..10d5dcd 100644 --- a/cmd/benchpod-cli/commands_discover.go +++ b/cmd/benchpod-cli/commands_discover.go @@ -8,6 +8,7 @@ import ( "net" "os" "sort" + "strconv" "strings" "text/tabwriter" "time" @@ -43,6 +44,7 @@ type discoveredPod struct { // lanAddr is what gets saved, since it works from other machines and after the pod is unplugged. lanAddr string id string // full base64url Ed25519 pubkey (TXT id=) + api int // the pod's client API level (TXT api=); firmware 3.x sends none: 1 // Filled in by the health check. reachable bool @@ -80,7 +82,10 @@ func newDiscoverCmd(g *globalFlags) *cobra.Command { "with the cloud, not merely that something replied to a broadcast. When a pod\n" + "is reachable both ways the two entries are matched up as one physical pod.\n" + "When this machine is signed in (`benchpod login`), a registered pod is also\n" + - "checked against that account, so a pod on another account is called out.\n\n" + + "checked against that account, so a pod on another account is called out.\n" + + "A pod whose firmware this CLI does not drive is marked from the API level it\n" + + "advertises: \"needs firmware update\" (firmware before 4.0: `benchpod flash-self`)\n" + + "or \"needs a newer CLI\".\n\n" + "With --save and exactly one pod present, it is stored as the default connection\n" + "(like set-connection): its Ethernet or Wi-Fi address when it has one, else `usb`\n" + "for a pod only reached over its USB network link (that 10.237.x.y address only\n" + @@ -121,7 +126,7 @@ type discoverOpts struct { // explains rather than hiding behind an error. func runDiscover(g *globalFlags, o discoverOpts) error { if !o.usb && !o.network { - return errors.New("--no-usb and --no-network together leave nothing to look for") + return usageErrorf("--no-usb and --no-network together leave nothing to look for") } if raw := strings.TrimSpace(g.connection); raw != "" { if spec, err := parseTarget(raw); err == nil && spec.IsCloud() { @@ -240,6 +245,7 @@ func discoverPods(wait time.Duration) ([]discoveredPod, error) { instance: unescapeDNSSD(e.Instance), hostname: strings.TrimSuffix(e.HostName, "."), id: txtValue(e.Text, "id"), + api: txtAPI(e.Text), } ips[e.Instance] = append(ips[e.Instance], e.AddrIPv4...) // Prefer a numeric IPv4 over the .local name so we don't depend on @@ -390,6 +396,28 @@ func unescapeDNSSD(s string) string { return b.String() } +// txtAPI is the client API level a pod advertises (TXT api=, firmware 4.0 and later); 1 when it +// advertises none (firmware 3.x). +func txtAPI(txt []string) int { + n, err := strconv.Atoi(txtValue(txt, "api")) + if err != nil || n < 1 { + return 1 + } + return n +} + +// apiVerdict says what a pod's advertised API level needs: "" when this CLI drives it (or the +// level is not known: 0). +func apiVerdict(api int) string { + switch { + case api > 0 && api < tcpclient.MinPodAPI: + return "needs firmware update (`benchpod flash-self`)" + case api > tcpclient.ClientAPI: + return "needs a newer CLI" + } + return "" +} + // txtValue returns the value of key=... from a DNS-SD TXT record, or "". func txtValue(txt []string, key string) string { prefix := key + "=" @@ -755,6 +783,9 @@ func describeHealth(p discoveredPod) string { parts = append(parts, fmt.Sprintf("registered, cloud %s", strings.ToLower(strings.TrimSpace(p.cloud.State)))) } } + if v := apiVerdict(p.api); v != "" { + parts = append(parts, v) + } if p.lanAddr != "" && p.lanAddr != p.addr { parts = append(parts, "LAN address "+p.lanAddr) } @@ -810,7 +841,7 @@ func saveTarget(netPods []discoveredPod, serialPods []serialconsole.SerialPod) s func saveDiscovered(g *globalFlags, netPods []discoveredPod, serialPods []serialconsole.SerialPod) error { target := saveTarget(netPods, serialPods) if target == "" { - return fmt.Errorf("--save needs exactly one pod, found %d on the network and %d over USB; "+ + return usageErrorf("--save needs exactly one pod, found %d on the network and %d over USB; "+ "set it explicitly with `benchpod set-connection `", len(netPods), len(serialPods)) } cfgPath, err := resolveConfigPath(g.configFile) diff --git a/cmd/benchpod-cli/commands_discover_test.go b/cmd/benchpod-cli/commands_discover_test.go index 51e2900..7f3b43d 100644 --- a/cmd/benchpod-cli/commands_discover_test.go +++ b/cmd/benchpod-cli/commands_discover_test.go @@ -400,3 +400,26 @@ func TestDescribeSerialMACs(t *testing.T) { } } } + +// discover reads the API level from the mDNS TXT record and says what a pod needs. +func TestDiscoverAPILevel(t *testing.T) { + for _, c := range []struct { + txt []string + api int + want string + }{ + {[]string{"id=abc"}, 1, "needs firmware update (`benchpod flash-self`)"}, + {[]string{"id=abc", "api=2", "https_only=1", "tls=8443"}, 2, ""}, + {[]string{"api=3"}, 3, "needs a newer CLI"}, + {[]string{"api=x"}, 1, "needs firmware update"}, + } { + api := txtAPI(c.txt) + if api != c.api { + t.Errorf("%v: api %d, want %d", c.txt, api, c.api) + } + got := describeHealth(discoveredPod{reachable: true, api: api}) + if c.want == "" && got != "API ok" || c.want != "" && !strings.Contains(got, c.want) { + t.Errorf("%v: %q", c.txt, got) + } + } +} diff --git a/cmd/benchpod-cli/commands_register.go b/cmd/benchpod-cli/commands_register.go index 1cfdfce..f546d31 100644 --- a/cmd/benchpod-cli/commands_register.go +++ b/cmd/benchpod-cli/commands_register.go @@ -102,7 +102,7 @@ func defaultDeviceNameFromAddr(addr string) string { func runRegister(g *globalFlags, opts registerOptions) error { serverURL, tokenFile, deviceName := opts.serverURL, opts.tokenFile, opts.deviceName if strings.TrimSpace(serverURL) == "" { - return errors.New("--server-url cannot be empty") + return usageErrorf("--server-url cannot be empty") } host, port, tls, err := parseServerEndpoint(serverURL) if err != nil { diff --git a/cmd/benchpod-cli/commands_serial.go b/cmd/benchpod-cli/commands_serial.go index 5537733..9c2852d 100644 --- a/cmd/benchpod-cli/commands_serial.go +++ b/cmd/benchpod-cli/commands_serial.go @@ -2,349 +2,19 @@ package main import ( "bufio" - "context" "errors" "fmt" "os" "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/spf13/cobra" ) -// The commands in this file always use the firmware's USB CDC-ACM serial -// console — you cannot provision WiFi or trigger the bootloader over the -// network. They therefore ignore the wifi/serial choice of --connection and -// only honor an explicit device path from it (g.serialDevice()), falling -// back to auto-detection (USB VID 2E8A) otherwise. - -// ── set-wifi ───────────────────────────────────────────────────────────────── - -func newSetWifiCmd(g *globalFlags) *cobra.Command { - var ssid, password string - var passwordStdin, skipBlobs bool - cmd := &cobra.Command{ - Use: "set-wifi", - Short: "Save WiFi credentials and join (over the pod's USB console)", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - if strings.TrimSpace(ssid) == "" { - return errors.New("--ssid is required") - } - pw, err := resolveWifiPassword(password, passwordStdin) - if err != nil { - return fmt.Errorf("set-wifi: %w", err) - } - _, err = runSetWifi(g, ssid, pw, skipBlobs) - return err - }, - } - cmd.Flags().StringVar(&ssid, "ssid", "", "WiFi SSID (required)") - cmd.Flags().StringVar(&password, "password", "", "WiFi password (insecure: visible in shell history); omit to be prompted") - cmd.Flags().BoolVar(&passwordStdin, "password-stdin", false, "read the WiFi password from the first line of stdin") - cmd.Flags().BoolVar(&skipBlobs, "skip-blobs", false, "do not install a missing ESP32-C3 image first (not needed through a Wi-Fi bridge)") - return cmd -} - -// runSetWifi saves Wi-Fi credentials over the USB console and joins, returning the pod's -// address when the join is confirmed ("" when it is not). Shared by set-wifi and setup. -func runSetWifi(g *globalFlags, ssid, pw string, skipBlobs bool) (string, error) { - // wifi-set runs the full reconnect ladder on the device: probe the - // internal modem (with an EN-reset retry), then the external GPIO40/41 - // modem, then AT+CWJAP (up to ~15s) and TCP bring-up. That can take - // ~40s, so wait generously — the command returns as soon as the prompt - // reappears, this is only the upper bound. Override with --timeout. - device, err := g.usbDevice("set-wifi") - if err != nil { - return "", err - } - console, path, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(90*time.Second)) - if err != nil { - return "", err - } - defer cancel() - defer console.Close() - - // A Wi-Fi bridge on the pod's Ethernet port carries Wi-Fi instead of the ESP32-C3: it keeps - // the credentials itself and joins in the background. - before, _ := console.WifiShow(ctx) - if before.ViaBridge() { - return setWifiThroughBridge(ctx, console, path, ssid, pw) - } - - // Wi-Fi runs on the ESP32-C3, whose image the pod keeps in its W25Q: a pod without - // it (fresh board, no network) can only get it over this cable. - if !skipBlobs { - if err := ensureEspBlob(console); err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - } - - res, err := console.WifiSet(ctx, ssid, pw) - // Echo the firmware's WiFi/TCP/ESP32 bring-up lines (incl. the - // "[wifi] connected ip=" result) so the IP is visible — even - // when the join didn't confirm. - for _, line := range serialconsole.BringupLines(res.Raw) { - fmt.Fprintf(os.Stderr, " %s\n", line) - } - if err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - fmt.Fprintf(os.Stderr, "Wrote WiFi credentials for SSID %q via %s.\n", ssid, path) - - // Read the authoritative state back with wifi-show: the reconnect's - // "[wifi] connected ip=" line can be lost in the device's non-blocking - // USB console output, so don't rely on it alone to report the result. - st, _ := console.WifiShow(ctx) - ip := st.IP - if ip == "" { - ip = res.IP - } - state := strings.ToLower(st.State) - joined := res.Joined || ip != "" && ip != "(none)" || - strings.Contains(state, "ready") || strings.Contains(state, "connected") - if !joined { - fmt.Fprintln(os.Stderr, "Credentials saved; join not confirmed (run `benchpod show-network`).") - return "", nil - } - fmt.Fprintf(os.Stderr, "Joined %q, ip=%s\n", ssid, valueOrDash(ip)) - if ip == "(none)" || ip == "0.0.0.0" { - ip = "" - } - return ip, nil -} - -// bridgeJoinWait bounds how long set-wifi watches a Wi-Fi bridge join: it reports its state -// every few seconds and a WPA2/WPA3 join takes a few seconds more. -var bridgeJoinWait = 45 * time.Second - -// setWifiThroughBridge saves the credentials on the pod's Wi-Fi bridge (the pod seals the -// password for it) and waits for the bridge to join or fail. The pod's address does not change: -// the bridge carries its Ethernet traffic, so the IP is the one it already has. -func setWifiThroughBridge(ctx context.Context, console *serialconsole.Console, path, ssid, pw string) (string, error) { - if _, err := console.WifiSet(ctx, ssid, pw); err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q on the pod's Wi-Fi bridge via %s; waiting for it to join...\n", ssid, path) - deadline := time.Now().Add(bridgeJoinWait) - var st serialconsole.WifiStatus - for { - st, _ = console.WifiShow(ctx) - current := st.BridgeReports(ssid) - if current && st.BridgeJoined() { - ip := st.IP - if ip == "(none)" || ip == "0.0.0.0" { - ip = "" - } - fmt.Fprintf(os.Stderr, "The Wi-Fi bridge joined %q (rssi %s), pod ip=%s\n", ssid, valueOrDash(st.RSSI), valueOrDash(ip)) - return ip, nil - } - if why := st.BridgeJoinFailure(); current && why != "" { - return "", fmt.Errorf("set-wifi: %s (the credentials are saved on the bridge; run set-wifi again to change them)", why) - } - if time.Now().After(deadline) || ctx.Err() != nil { - break - } - select { - case <-ctx.Done(): - case <-time.After(3 * time.Second): - } - } - fmt.Fprintf(os.Stderr, "Credentials saved; the Wi-Fi bridge has not joined yet (state %s; run `benchpod show-network`).\n", valueOrDash(st.State)) - return "", nil -} - -// ensureEspBlob installs the blobs from the pod's firmware release when its ESP32-C3 slot is -// empty or holds a different image, so set-wifi works on a pod that has never had a network. -func ensureEspBlob(console *serialconsole.Console) error { - ctx, cancel := context.WithTimeout(context.Background(), blobsInstallTimeout) - defer cancel() - // Before Wi-Fi is set the pod's USB network is still on (firmware 3.9.0+): use it when up. - target, closeTarget, err := blobTargetFor(ctx, console, "the USB console") - if err != nil { - return err - } - defer closeTarget() - slots, err := target.Blobs(ctx) - missing, err := espBlobMissing(slots, err) - if err != nil || !missing { - return err - } - fmt.Fprintln(os.Stderr, "set-wifi: the pod has no ESP32-C3 image for Wi-Fi yet; installing it over USB first") - return installBlobs(ctx, target, releaseBlobSource(target.Release(ctx)), false, nil) -} - -// espBlobMissing reads the pod's blob listing for set-wifi: whether the ESP32-C3 image needs -// installing. Firmware without blob slots keeps the image built in, which is fine; any other -// error reading the slots is reported, with --skip-blobs as the way past it. -func espBlobMissing(slots []serialconsole.BlobSlot, err error) (bool, error) { - if errors.Is(err, serialconsole.ErrNoBlobSlots) { - return false, nil - } - if err != nil { - return false, fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) - } - for _, s := range slots { - if s.Name == "esp" && s.NeedsInstall() { - return true, nil - } - } - return false, nil -} - -// ── show-network ───────────────────────────────────────────────────────────── - -// newShowNetworkCmd reports the pod's network state. It is named for what it -// reports rather than for one of the interfaces it can report on: the IP is -// whichever address the pod is actually using, and the pod prefers its wired -// Ethernet lease, so on a cabled pod this prints an address and no SSID at all. -// (It was called show-wifi, which described only the minority case.) -func newShowNetworkCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "show-network", - Short: "Show the pod's network details: IP, plus stored SSID/state/RSSI (over the pod's USB console)", - Long: "Report the pod's network state over the pod's USB console.\n\n" + - "The IP is whichever address the pod is actually using: it prefers the wired\n" + - "Ethernet lease over Wi-Fi, so a pod on a cable reports an address here with no\n" + - "SSID at all. The SSID/state/RSSI fields describe the optional Wi-Fi interface.", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("show-network") - if err != nil { - return err - } - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(15*time.Second)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - st, err := console.WifiShow(ctx) - if err != nil { - return fmt.Errorf("show-network: %w", err) - } - out, closeOut, err := resolveOutput(g.outputFilename) - if err != nil { - return fmt.Errorf("show-network: open output: %w", err) - } - defer closeOut() - // IP first: it is the field that matters on any pod, and it is - // populated on a wired pod that has no SSID at all. - fmt.Fprintf(out, "IP: %s\n", valueOrDash(st.IP)) - fmt.Fprintf(out, "SSID: %s\n", valueOrDash(st.SSID)) - fmt.Fprintf(out, "State: %s\n", valueOrDash(st.State)) - fmt.Fprintf(out, "RSSI: %s\n", valueOrDash(st.RSSI)) - if st.Via != "" { - fmt.Fprintf(out, "Via: %s\n", st.Via) - } - if st.Problem != "" { - fmt.Fprintf(out, "Problem: %s\n", st.Problem) - } - return nil - }, - } -} - -// ── scan-wifi ──────────────────────────────────────────────────────────────── - -// newScanWifiCmd lists the networks the pod's Wi-Fi sees, to pick the SSID for set-wifi. -func newScanWifiCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "scan-wifi", - Short: "List the Wi-Fi networks the pod sees (over the pod's USB console)", - Long: "List the Wi-Fi networks the pod sees, strongest first, to pick the SSID for set-wifi.\n" + - "The pod scans with its built-in Wi-Fi (firmware 3.9.4 or later), or with a Wi-Fi bridge on\n" + - "its Ethernet port when one is plugged in. A scan takes a few seconds; a joined pod stays\n" + - "joined. On older firmware the command says so and how to join a network anyway (exit 0).", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("scan-wifi") - if err != nil { - return err - } - // 45 s: a pod that is joining waits for the join to finish (up to 30 s) before it scans. - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(45*time.Second)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - nets, err := console.WifiScan(ctx) - if errors.Is(err, serialconsole.ErrNoWifiScan) { - return scanWifiUnsupported(ctx, console) - } - if err != nil { - return fmt.Errorf("scan-wifi: %w", err) - } - out, closeOut, err := resolveOutput(g.outputFilename) - if err != nil { - return fmt.Errorf("scan-wifi: open output: %w", err) - } - defer closeOut() - fmt.Fprintf(out, "%-6s %-4s %-10s %s\n", "RSSI", "CH", "SECURITY", "SSID") - for _, n := range nets { - ssid := n.SSID - if ssid == "" { - ssid = "(hidden)" - } - fmt.Fprintf(out, "%-6d %-4d %-10s %s\n", n.RSSI, n.Channel, n.Auth, ssid) - } - fmt.Fprintf(os.Stderr, "%d networks\n", len(nets)) - return nil - }, - } -} - -// scanWifiUnsupported answers scan-wifi on firmware that cannot scan: not an error when the pod -// has built-in Wi-Fi (it can still join a network), an error when it has no Wi-Fi at all. -func scanWifiUnsupported(ctx context.Context, console *serialconsole.Console) error { - st, err := console.WifiShow(ctx) - if err != nil || st.State == "" { - return errors.New("scan-wifi: this pod has no Wi-Fi") - } - fmt.Println("This pod has built-in Wi-Fi, but its firmware cannot scan for networks:" + - " scanning needs firmware 3.9.4 or later (update with `benchpod flash-self`).") - fmt.Println("To join a network now: benchpod set-wifi --ssid ") - return nil -} - -// ── clear-wifi ─────────────────────────────────────────────────────────────── - -// clearWifiTimeout covers the C3 NVS erase that wifi-clear runs before it answers. 10 s was too -// short: the CLI gave up on pods that were still erasing (2026-10-15). -const clearWifiTimeout = 60 * time.Second - -func newClearWifiCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "clear-wifi", - Short: "Erase the stored Wi-Fi credentials (Wi-Fi goes down at once)", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("clear-wifi") - if err != nil { - return err - } - // The pod answers once it has also erased the ESP32-C3's NVS over the C3's ROM - // loader: about 3 s, and up to half a minute when the C3 is slow to answer. - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(clearWifiTimeout)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - if err := console.WifiClear(ctx); err != nil { - return fmt.Errorf("clear-wifi: %w", err) - } - fmt.Fprintln(os.Stderr, "Erased the stored Wi-Fi credentials. Wi-Fi is off; no reboot needed. "+ - "USB networking is on again (firmware 3.9.0+).") - return nil - }, - } -} +// The commands in this file always use the firmware's USB serial console: the +// bootloader cannot be reached over the network. They ignore a network choice +// of --connection and only honor an explicit device path from it +// (g.serialDevice()), falling back to auto-detection otherwise. // ── bootsel ────────────────────────────────────────────────────────────────── @@ -427,3 +97,10 @@ func newDfuCmd(g *globalFlags) *cobra.Command { cmd.Flags().BoolVar(&yes, "yes", false, "skip the confirmation prompt") return cmd } + +// confirmYes asks on stderr and reads stdin; only "yes" goes ahead. +func confirmYes(prompt string) bool { + fmt.Fprint(os.Stderr, prompt) + line, _ := bufio.NewReader(os.Stdin).ReadString('\n') + return strings.TrimSpace(line) == "yes" +} diff --git a/cmd/benchpod-cli/commands_tcp.go b/cmd/benchpod-cli/commands_tcp.go index 869a79a..c9d6fad 100644 --- a/cmd/benchpod-cli/commands_tcp.go +++ b/cmd/benchpod-cli/commands_tcp.go @@ -8,8 +8,6 @@ import ( "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/features" - "github.com/embeddedci-com/benchpod-cli/internal/spiflash" "github.com/spf13/cobra" ) @@ -57,23 +55,18 @@ func newPingCmd(g *globalFlags) *cobra.Command { func newGenerateCmd(g *globalFlags) *cobra.Command { var waveform, path string - var freq, sampleRate, sampleRateHz float64 - var amplitude, offset, durationMS int + var freq, sampleRateHz float64 var amplitudeV, offsetV, amplitudeMA, offsetMA float64 var duration time.Duration cmd := &cobra.Command{ Use: "generate", - Short: "Start DAC waveform output", + Short: "Start DAC waveform output (volts on a path, or mA on the 4-20 mA output)", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { if !validWaveform(waveform) { - return fmt.Errorf("--waveform is required (sine|square|sawtooth)") + return usageErrorf("--waveform is required (sine|square|sawtooth)") } - sampleRate, err := sampleRateMHz(cmd, sampleRateHz, sampleRate) - if err != nil { - return err - } - durationMS, err := wholeUnits(cmd, "duration", duration, "duration-ms", durationMS, time.Millisecond) + durationMS, err := wholeUnits(cmd, "duration", duration, time.Millisecond) if err != nil { return err } @@ -90,34 +83,14 @@ func newGenerateCmd(g *globalFlags) *cobra.Command { req := map[string]any{ "cmd": "generate", "waveform": waveform, - "freq": freq, - "amplitude": amplitude, - "offset": offset, + "freq_hz": freq, "duration_ms": durationMS, } - if calibrated != nil { - // Firmware before 3.9.1 ignores the volts and would play its default - // full-scale 8-bit waveform instead: check before sending. - status, err := pod.client.Command(ctx, features.StatusRequest()) - if err != nil { - return fmt.Errorf("generate: status: %w", err) - } - ok, err := spiflash.HasCap(status, "generate16") - if err != nil { - return fmt.Errorf("generate: %w", err) - } - if !ok { - return fmt.Errorf("generate: --amplitude-v/--amplitude-ma need firmware 3.9.1 or newer " + - "(the pod has no generate16); update it with `benchpod flash-self`, or use --amplitude/--offset levels") - } - delete(req, "amplitude") - delete(req, "offset") - for k, v := range calibrated { - req[k] = v - } + for k, v := range calibrated { + req[k] = v } - if sampleRate > 0 { - req["sample_rate_mhz"] = sampleRate + if sampleRateHz > 0 { + req["sample_rate_hz"] = sampleRateHz } data, err := pod.client.Command(ctx, req) if err != nil { @@ -138,84 +111,70 @@ func newGenerateCmd(g *globalFlags) *cobra.Command { } cmd.Flags().StringVar(&waveform, "waveform", "", "waveform: sine|square|sawtooth (required)") cmd.Flags().Var(newFrequencyValue(1000, &freq), "freq", "output frequency, e.g. 1kHz (a bare number is Hz)") - cmd.Flags().IntVar(&litude, "amplitude", 127, "half-scale amplitude in 8-bit levels 0-127") - cmd.Flags().IntVar(&offset, "offset", 128, "DC offset in 8-bit levels 0-255") - cmd.Flags().StringVar(&path, "path", "", "DAC output for --amplitude-v/--offset-v: 3v3|5v|12v (firmware 3.9.1+)") - cmd.Flags().Float64Var(&litudeV, "amplitude-v", 0, "peak in volts on --path, played calibrated at 16 bits (firmware 3.9.1+)") + cmd.Flags().StringVar(&path, "path", "", "DAC output for --amplitude-v/--offset-v: 3v3|5v|12v") + cmd.Flags().Float64Var(&litudeV, "amplitude-v", 0, "peak in volts on --path, played calibrated at 16 bits") cmd.Flags().Float64Var(&offsetV, "offset-v", 0, "center in volts on --path (with --amplitude-v)") - cmd.Flags().Float64Var(&litudeMA, "amplitude-ma", 0, "peak in mA on the 4-20 mA output, 16-bit (firmware 3.9.1+)") + cmd.Flags().Float64Var(&litudeMA, "amplitude-ma", 0, "peak in mA on the 4-20 mA output, 16-bit") cmd.Flags().Float64Var(&offsetMA, "offset-ma", 0, "center in mA on the 4-20 mA output (with --amplitude-ma)") cmd.Flags().DurationVar(&duration, "duration", 0, "how long to output, e.g. 2s or 500ms (0 = run until next command)") - cmd.Flags().IntVar(&durationMS, "duration-ms", 0, "duration in ms (0 = run until next command); same as --duration") cmd.Flags().Var(newFrequencyValue(0, &sampleRateHz), "sample-rate", "FPGA sample-clock rate, e.g. 10MHz (omit to auto-pick)") - cmd.Flags().Float64Var(&sampleRate, "sample-rate-mhz", 0, "FPGA sample-clock rate in MHz (omit to auto-pick); same as --sample-rate") return cmd } -// generateCalibrated turns the volts / milliamp flags into the calibrated generate fields -// (firmware 3.9.1+), or nil when none of them is set. The 8-bit --amplitude/--offset cannot be -// mixed in. +// generateCalibrated turns the volts / milliamp flags into the generate fields: path, +// amplitude_v and offset_v, or amplitude_ua and offset_ua. Firmware 4.0 takes only these (the +// 8-bit levels are gone), so one set is required. func generateCalibrated(cmd *cobra.Command, path string, ampV, offV, ampMA, offMA float64) (map[string]any, error) { f := cmd.Flags() volts := f.Changed("amplitude-v") || f.Changed("offset-v") || f.Changed("path") amps := f.Changed("amplitude-ma") || f.Changed("offset-ma") if !volts && !amps { - return nil, nil - } - if f.Changed("amplitude") || f.Changed("offset") { - return nil, fmt.Errorf("--amplitude/--offset are 8-bit levels: use them or the volts/mA flags, not both") + return nil, usageErrorf("give volts (--path, --amplitude-v, --offset-v) or mA (--amplitude-ma, --offset-ma)") } if volts && amps { - return nil, fmt.Errorf("give volts (--path, --amplitude-v, --offset-v) or mA (--amplitude-ma, --offset-ma), not both") + return nil, usageErrorf("give volts (--path, --amplitude-v, --offset-v) or mA (--amplitude-ma, --offset-ma), not both") } if amps { if !f.Changed("amplitude-ma") || !f.Changed("offset-ma") { - return nil, fmt.Errorf("--amplitude-ma and --offset-ma go together") + return nil, usageErrorf("--amplitude-ma and --offset-ma go together") } if !(ampMA > 0) { - return nil, fmt.Errorf("--amplitude-ma must be above 0") + return nil, usageErrorf("--amplitude-ma must be above 0") } return map[string]any{"amplitude_ua": math.Round(ampMA * 1000), "offset_ua": math.Round(offMA * 1000)}, nil } if path != "3v3" && path != "5v" && path != "12v" { - return nil, fmt.Errorf("--path must be 3v3, 5v or 12v with --amplitude-v") + return nil, usageErrorf("--path must be 3v3, 5v or 12v with --amplitude-v") } if !f.Changed("amplitude-v") || !f.Changed("offset-v") { - return nil, fmt.Errorf("--amplitude-v and --offset-v go together with --path") + return nil, usageErrorf("--amplitude-v and --offset-v go together with --path") } if !(ampV > 0) { - return nil, fmt.Errorf("--amplitude-v must be above 0") + return nil, usageErrorf("--amplitude-v must be above 0") } return map[string]any{"path": path, "amplitude_v": ampV, "offset_v": offV}, nil } -// ── capture / stream ───────────────────────────────────────────────────────── +// ── capture ────────────────────────────────────────────────────────────────── func newCaptureCmd(g *globalFlags) *cobra.Command { return newSampleCmd(g, "capture", "Blocking ADC snapshot") } -func newStreamCmd(g *globalFlags) *cobra.Command { - return newSampleCmd(g, "stream", "Async ADC capture") -} func newSampleCmd(g *globalFlags, name, short string) *cobra.Command { var samples int var output string - var sampleRate, sampleRateHz float64 + var sampleRateHz float64 cmd := &cobra.Command{ Use: name, Short: short, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - sampleRate, err := sampleRateMHz(cmd, sampleRateHz, sampleRate) - if err != nil { - return err - } if !validSamples(samples) { - return fmt.Errorf("--samples must be between 1 and 4096") + return usageErrorf("--samples must be between 1 and 4096") } if !validOutput(output) { - return fmt.Errorf("--output must be json, csv, or ndjson") + return usageErrorf("--format must be json, csv, or ndjson") } ctx, cancel, client, err := g.networkClient(name, 30*time.Second) if err != nil { @@ -224,8 +183,8 @@ func newSampleCmd(g *globalFlags, name, short string) *cobra.Command { defer cancel() req := map[string]any{"cmd": name, "samples": samples} - if sampleRate > 0 { - req["sample_rate_mhz"] = sampleRate + if sampleRateHz > 0 { + req["sample_rate_hz"] = sampleRateHz } got, err := client.Samples(ctx, req) if err != nil { @@ -235,9 +194,8 @@ func newSampleCmd(g *globalFlags, name, short string) *cobra.Command { }, } cmd.Flags().IntVar(&samples, "samples", 256, "number of ADC samples (1-4096)") - cmd.Flags().StringVar(&output, "output", "json", "output format: json|csv|ndjson") + cmd.Flags().StringVar(&output, "format", "json", "output format: json|csv|ndjson") cmd.Flags().Var(newFrequencyValue(0, &sampleRateHz), "sample-rate", "ADC sample rate, e.g. 100kHz (omit for the maximum, 400 kSPS)") - cmd.Flags().Float64Var(&sampleRate, "sample-rate-mhz", 0, "ADC sample rate in MHz, e.g. 0.1 (omit for the maximum, 400 kSPS); same as --sample-rate") return cmd } @@ -245,7 +203,7 @@ func newSampleCmd(g *globalFlags, name, short string) *cobra.Command { func newMeasureCmd(g *globalFlags) *cobra.Command { var waveform, output string - var freq, sampleRate, sampleRateHz float64 + var freq, sampleRateHz float64 var amplitude, offset, samples int cmd := &cobra.Command{ Use: "measure", @@ -253,17 +211,13 @@ func newMeasureCmd(g *globalFlags) *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { if !validWaveform(waveform) { - return fmt.Errorf("--waveform is required (sine|square|sawtooth)") - } - sampleRate, err := sampleRateMHz(cmd, sampleRateHz, sampleRate) - if err != nil { - return err + return usageErrorf("--waveform is required (sine|square|sawtooth)") } if !validSamples(samples) { - return fmt.Errorf("--samples must be between 1 and 4096") + return usageErrorf("--samples must be between 1 and 4096") } if !validOutput(output) { - return fmt.Errorf("--output must be json, csv, or ndjson") + return usageErrorf("--format must be json, csv, or ndjson") } ctx, cancel, client, err := g.networkClient("measure", 30*time.Second) if err != nil { @@ -274,13 +228,13 @@ func newMeasureCmd(g *globalFlags) *cobra.Command { req := map[string]any{ "cmd": "measure", "waveform": waveform, - "freq": freq, + "freq_hz": freq, "amplitude": amplitude, "offset": offset, "samples": samples, } - if sampleRate > 0 { - req["sample_rate_mhz"] = sampleRate + if sampleRateHz > 0 { + req["sample_rate_hz"] = sampleRateHz } got, err := client.Samples(ctx, req) if err != nil { @@ -295,8 +249,7 @@ func newMeasureCmd(g *globalFlags) *cobra.Command { cmd.Flags().IntVar(&offset, "offset", 128, "DC offset 0-255") cmd.Flags().IntVar(&samples, "samples", 256, "number of ADC samples (1-4096)") cmd.Flags().Var(newFrequencyValue(0, &sampleRateHz), "sample-rate", "sample-clock rate, e.g. 10MHz (omit to auto-pick)") - cmd.Flags().Float64Var(&sampleRate, "sample-rate-mhz", 0, "sample-clock rate in MHz (omit to auto-pick); same as --sample-rate") - cmd.Flags().StringVar(&output, "output", "json", "output format: json|csv|ndjson") + cmd.Flags().StringVar(&output, "format", "json", "output format: json|csv|ndjson") return cmd } @@ -311,10 +264,10 @@ func newTestCmd(g *globalFlags) *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { if !validSamples(samples) { - return fmt.Errorf("--samples must be between 1 and 4096") + return usageErrorf("--samples must be between 1 and 4096") } if !validOutput(output) { - return fmt.Errorf("--output must be json, csv, or ndjson") + return usageErrorf("--format must be json, csv, or ndjson") } // Mirror the firmware default: const when --value is given without @@ -348,7 +301,7 @@ func newTestCmd(g *globalFlags) *cobra.Command { cmd.Flags().StringVar(&pattern, "pattern", "", "pattern: sine|counter|ramp|const (default sine, or const when --value is set)") cmd.Flags().IntVar(&value, "value", 255, "constant byte value 0-255 (used by const pattern)") cmd.Flags().IntVar(&samples, "samples", 256, "number of samples (1-4096)") - cmd.Flags().StringVar(&output, "output", "json", "output format: json|csv|ndjson") + cmd.Flags().StringVar(&output, "format", "json", "output format: json|csv|ndjson") return cmd } @@ -359,7 +312,7 @@ func newLACmd(g *globalFlags) *cobra.Command { Use: "la", Short: "Logic-analyzer pin control (bank voltage, pull resistors, step pulses, pin list and directions)", } - cmd.AddCommand(newLAVoltageCmd(g), newLAPullCmd(g), newLAPullupCmd(g), newLAStatusCmd(g), newLAStepCmd(g), + cmd.AddCommand(newLAVoltageCmd(g), newLAPullCmd(g), newLAStatusCmd(g), newLAStepCmd(g), newLAPinsCmd(g), newLADirCmd(g)) return cmd } @@ -409,53 +362,13 @@ func newLAPullCmd(g *globalFlags) *cobra.Command { } } -func newLAPullupCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "pullup PIN STATE", - Short: "Older form of `la pull`: switch an LA pin's pull resistor on in its own direction, or off (STATE: on|off)", - Args: cobra.ExactArgs(2), - RunE: func(_ *cobra.Command, args []string) error { - pin, err := parseLAPin(args[0]) - if err != nil { - return err - } - var state string - switch strings.ToLower(strings.TrimSpace(args[1])) { - case "on", "1": - state = "on" - case "off", "0": - state = "off" - default: - return fmt.Errorf("invalid state %q (use on or off)", args[1]) - } - ctx, cancel, pod, err := g.podClient("la pullup", 30*time.Second) - if err != nil { - return err - } - defer cancel() - - data, err := pod.client.Command(ctx, map[string]any{"cmd": "la", "la": pin, "pullup": state}) - if err != nil { - return fmt.Errorf("la pullup: %w", err) - } - out, closeOut, err := resolveOutput(g.outputFilename) - if err != nil { - return fmt.Errorf("la pullup: open output: %w", err) - } - defer closeOut() - printJSON(out, data) - return nil - }, - } -} - func newLAStatusCmd(g *globalFlags) *cobra.Command { return &cobra.Command{ Use: "status [PIN]", Short: "Report LA pull-up state (one PIN, or the bitmask of all if omitted)", Args: cobra.MaximumNArgs(1), RunE: func(_ *cobra.Command, args []string) error { - req := map[string]any{"cmd": "la"} + req := map[string]any{"cmd": "la_pull"} if len(args) == 1 { pin, err := parseLAPin(args[0]) if err != nil { @@ -486,7 +399,7 @@ func newLAStatusCmd(g *globalFlags) *cobra.Command { func newLAStepCmd(g *globalFlags) *cobra.Command { var laArg, dirLAArg string - var steps, delayUS, direction int + var steps, direction int var delay time.Duration cmd := &cobra.Command{ Use: "step", @@ -494,25 +407,25 @@ func newLAStepCmd(g *globalFlags) *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { if laArg == "" { - return fmt.Errorf("--la is required") + return usageErrorf("--la is required") } pin, err := parseLAPin(laArg) if err != nil { return err } if steps <= 0 { - return fmt.Errorf("--steps must be positive") + return usageErrorf("--steps must be positive") } - delayUS, err := wholeUnits(cmd, "delay", delay, "delay-us", delayUS, time.Microsecond) + delayUS, err := wholeUnits(cmd, "delay", delay, time.Microsecond) if err != nil { return err } if delayUS <= 0 { - return fmt.Errorf("--delay (or --delay-us) must be positive") + return usageErrorf("--delay must be positive") } req := map[string]any{ - "cmd": "la", + "cmd": "la_step", "la": pin, "steps": steps, "delay_us": delayUS, @@ -520,15 +433,15 @@ func newLAStepCmd(g *globalFlags) *cobra.Command { if dirLAArg != "" { dirPin, err := parseLAPin(dirLAArg) if err != nil { - return fmt.Errorf("--dir-la: %w", err) + return usageErrorf("--dir-la: %w", err) } if direction != 0 && direction != 1 { - return fmt.Errorf("--direction must be 0 or 1") + return usageErrorf("--direction must be 0 or 1") } req["dir_la"] = dirPin req["direction"] = direction } else if cmd.Flags().Changed("direction") { - return fmt.Errorf("--direction requires --dir-la") + return usageErrorf("--direction requires --dir-la") } // The FPGA runs the train autonomously, but size the deadline to the @@ -560,8 +473,7 @@ func newLAStepCmd(g *globalFlags) *cobra.Command { } cmd.Flags().StringVar(&laArg, "la", "", "LA pin to pulse, e.g. 6 or la6 (required)") cmd.Flags().IntVar(&steps, "steps", 0, "number of pulses (required, positive)") - cmd.Flags().DurationVar(&delay, "delay", 0, "high/low half-period, e.g. 50us or 1ms (this or --delay-us is required)") - cmd.Flags().IntVar(&delayUS, "delay-us", 0, "high/low half-period in microseconds; same as --delay") + cmd.Flags().DurationVar(&delay, "delay", 0, "high/low half-period, e.g. 50us or 1ms (required)") cmd.Flags().StringVar(&dirLAArg, "dir-la", "", "optional direction LA pin, driven before stepping") cmd.Flags().IntVar(&direction, "direction", 0, "direction level 0|1 applied to --dir-la") return cmd diff --git a/cmd/benchpod-cli/connection.go b/cmd/benchpod-cli/connection.go index ea088c5..6ea63b1 100644 --- a/cmd/benchpod-cli/connection.go +++ b/cmd/benchpod-cli/connection.go @@ -81,12 +81,11 @@ func parseTarget(raw string) (ConnSpec, error) { "or save one with `benchpod set-connection `") } switch strings.ToLower(raw) { - // "usb" is the name this keyword goes by everywhere the CLI speaks to a - // user — it names what the person plugged in. "serial" is the older - // spelling, still accepted so saved configs and BENCHPOD_CONNECTION values - // written before the rename keep working; it is not advertised anywhere. - case "usb", "serial": + // "usb" names what the person plugged in (CLI 0.10 dropped the older "serial"). + case "usb": return ConnSpec{Kind: connSerial}, nil + case "serial": + return ConnSpec{}, usageErrorf("connection %q: CLI 0.10 calls it usb (--connection usb, or `benchpod set-connection usb`)", raw) } if strings.HasPrefix(strings.ToLower(raw), "usb:") { pod := serialconsole.NormalizePodName(raw[len("usb:"):]) @@ -172,16 +171,15 @@ func cloudRefusal(cmd string, c ConnSpec, usb bool) error { } // cloudCommandList names the commands that work over embeddedci.com, for messages and help. -const cloudCommandList = "status, ping, la voltage, la pull, la pullup, la status, la step, generate, " + +const cloudCommandList = "status, ping, la voltage, la pull, la status, la step, generate, " + "lan-policy, sig-policy, cloud ca show/clear, cloud proxy, deregister, flash --build, flash-self" // ── set-connection ─────────────────────────────────────────────────────────── func newSetConnectionCmd(g *globalFlags) *cobra.Command { return &cobra.Command{ - Use: "set-connection ", - Aliases: []string{"set-bench-pod"}, - Short: `Store the default connection: a network address, a pod name, a device path, "usb", or embeddedci:`, + Use: "set-connection ", + Short: `Store the default connection: a network address, a pod name, a device path, "usb", or embeddedci:`, Long: "Store the default connection in the config file, so later commands can leave out\n" + "--connection. The value is what --connection takes: the pod's network address\n" + "(192.168.1.5[:8080]), a USB device path, `usb` to auto-detect the pod on USB, or\n" + diff --git a/cmd/benchpod-cli/connection_test.go b/cmd/benchpod-cli/connection_test.go index 05d7a81..6fb73c1 100644 --- a/cmd/benchpod-cli/connection_test.go +++ b/cmd/benchpod-cli/connection_test.go @@ -16,7 +16,6 @@ func TestClassifyConnection(t *testing.T) { {"192.168.1.5:9000", true, "192.168.1.5:9000", ""}, {"benchpod.local", true, "benchpod.local:8080", ""}, {" 10.0.0.2 ", true, "10.0.0.2:8080", ""}, - {"serial", false, "", ""}, {"USB", false, "", ""}, {"/dev/tty.usbmodem1101", false, "", "/dev/tty.usbmodem1101"}, {"COM3", false, "", "COM3"}, @@ -101,9 +100,7 @@ func TestRequireNetwork(t *testing.T) { if err != nil && strings.Contains(err.Error(), "`usb`") { t.Errorf("RequireNetwork(cloud) offers USB to a network-only command: %v", err) } - // "serial" is still accepted as an input spelling, so both forms must land - // on the same USB transport and the same guidance. - for _, conn := range []string{"usb", "serial", "/dev/tty.usbmodem1101"} { + for _, conn := range []string{"usb", "/dev/tty.usbmodem1101"} { spec, _ := classifyConnection(conn) err := spec.RequireNetwork("ping") if err == nil { @@ -132,8 +129,11 @@ func TestIsSerialDevice(t *testing.T) { func TestDescribeConnSpeaksUSBNotSerial(t *testing.T) { // The keyword the user types and the wording the CLI echoes back must agree: - // "serial" is accepted as a legacy input spelling but is never presented. - for _, conn := range []string{"usb", "serial"} { + // CLI 0.10 dropped the older "serial" spelling: it is a usage error naming usb. + if _, err := classifyConnection("serial"); err == nil || !strings.Contains(err.Error(), "usb") || exitCode(err) != exitUsage { + t.Errorf("serial: %v", err) + } + for _, conn := range []string{"usb"} { spec, err := classifyConnection(conn) if err != nil { t.Fatalf("classifyConnection(%q): %v", conn, err) diff --git a/cmd/benchpod-cli/errors.go b/cmd/benchpod-cli/errors.go index 78e5d1f..eef2f92 100644 --- a/cmd/benchpod-cli/errors.go +++ b/cmd/benchpod-cli/errors.go @@ -3,7 +3,6 @@ package main import ( "errors" "fmt" - "regexp" "strings" "github.com/embeddedci-com/benchpod-cli/internal/cloudpod" @@ -14,159 +13,38 @@ import ( // ── refusals ──────────────────────────────────────────────────────────────── // -// Every refusal from the pod, over the LAN JSON API or the USB console, is a *tcpclient.PodError. -// A refusal with a stable code (BP0001...) is classified by tcpclient's code table (the exit code) -// and worded from the catalog (internal/errcatalog: its message and fix.cli, codedRefusal). A -// refusal without one (older firmware, or a refusal with no code yet) falls back to its text: the -// policy refusals carry a firmware prefix (locked:, busy:, forbidden:; internal/fwrefusals pins -// the texts) and explainRefusal is the one place that says what to do about each. Each text match -// below names what replaces it: a code, or "no code yet". - -const ( - lockedUSBHint = "the pod's external LAN policy is locked; run this over USB with --connection usb" - leaseBusyHint = "on the LAN the pod can only be read while a cloud job holds it; try again when the job ends" - heavyBusyHint = "the pod is running another long command; try again when it ends" - forbiddenHint = "API keys need the benchpod:admin scope" -) - -// laVoltageUnsetHint answers the firmware's "la voltage not set; ..." (it names the raw JSON command -// or the profile key rather than what a CLI user runs). The pod and the tools take the voltage from -// the wiring profile, so the lasting fix is to set it there. -const laVoltageUnsetHint = "the wiring profile sets no I/O voltage: set it in the profile (the I/O voltage " + - "at the top of the Pins pane in the web or desktop app), or for now `benchpod la voltage 3.3V` (or 1.8V)" - -// pinConflictRE matches the firmware's "pin conflict: LA%u is in use by %s; %s" (la_pins.c). -// A sensor pin names its function too: "is in use by sensor:env (i2c_sda); ...", and an I2C -// line several sensors share "sensor:env+1". -var pinConflictRE = regexp.MustCompile(`^pin conflict: (LA\d+) is in use by (\S+)(?: \(([a-z0-9_]+)\))?; (.*)$`) - -// emulationImageRE matches the refusal of a feature the emulation image lacks -// (command_handler_dac.c image_hint) and the image-switch refusal (fpga_image). -var emulationImageRE = regexp.MustCompile(`\{"cmd":"sensor_stop","all":true\} then \{"cmd":"fpga_image","image":"(loop|deep)"\}$`) - -// pinReleaseHints maps the firmware's release hints (la_pins.c release_hint) to what a CLI user -// does about them. The benchpod CLI has no command that holds a pin past its own run, so a pin in -// use is held by another client of the pod; the hint names where to free it. A hint missing from -// this map (a new owner) is shown as the firmware wrote it. -var pinReleaseHints = []struct { - prefix string // the firmware hint starts with this - hint string // %s = the pin (LA4) -}{ - {`release it with {"cmd":"gpio"`, "another session (the web app, a test or an MCP session) holds %s as a GPIO; " + - "release it there (gpio_release)"}, - {"stop the uart proxy first", "a UART session (the web app's Terminal, a test or an MCP session) " + - "is open on %s; close it there"}, - {"end the SWD session first", "an SWD session (a flash or an OpenOCD run) is using %s; wait for it to end"}, - {"stop the sensor emulation first", "an emulated sensor is running on %s; stop it with " + - "`benchpod sensor stop` (or where it was started: the web app, the SDK or MCP sensor_stop)"}, - {"stop the SPI session first", "an SPI session is open on %s; end it where it was started " + - "(the web app, the SDK or an MCP session)"}, - {"stop the I2C session first", "the I2C master is using %s; end it with `benchpod i2c stop`"}, -} - -// i2cPullupRE matches i2c_start's "I2C needs pull-ups: switch on LA1's with -// {"cmd":"la","la":1,"pullup":"on"}, or pass "pullups":"external"". -// Firmware with la_pull_dir names {"cmd":"la","la":1,"pull":"up"} instead. -var i2cPullupRE = regexp.MustCompile(`^(I2C needs pull-ups): switch on LA(\d+)'s with \{"cmd":"la","la":\d+,"(?:pullup":"on|pull":"up)"\}`) - -// translateRefusal rewords a refusal whose firmware text names a raw JSON command: it returns the -// text to show and the hint to add ("" for none). Other refusals come back unchanged with no hint. -func translateRefusal(msg string) (shown, hint string) { - msg = strings.TrimSpace(msg) - if strings.HasPrefix(msg, "la voltage not set") { // fallback: BP0001 replaces it - return msg, laVoltageUnsetHint - } - if m := i2cPullupRE.FindStringSubmatch(msg); m != nil { // no code yet - return m[1], fmt.Sprintf("pull LA%s up with `benchpod la pull %s up`, or pass --pullups external "+ - "when the board has its own", m[2], m[2]) - } - // fallback: BP0017 (gateware_too_old) replaces it - if strings.HasSuffix(msg, "need gateware v55+: update the pod's firmware") || - strings.HasSuffix(msg, "needs gateware v55+: update the pod's firmware") { - return msg, "update it with `benchpod flash-self`" - } - if m := emulationImageRE.FindStringSubmatchIndex(msg); m != nil { // no code yet - image := msg[m[2]:m[3]] - return strings.TrimSuffix(strings.TrimSpace(msg[:m[0]]), ":"), fmt.Sprintf( - "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image %s`", image) - } - if strings.HasPrefix(msg, "image switch refused:") { // no code yet - if i := strings.Index(msg, "; stop them first ("); i > 0 { - return msg[:i], "stop them with `benchpod sensor stop` first" - } - } - if m := pinConflictRE.FindStringSubmatch(msg); m != nil { // no code yet - owner := m[2] - if m[3] != "" { - owner += " (" + m[3] + ")" - } - if inst, ok := strings.CutPrefix(m[2], "sensor:"); ok { - inst, _, _ = strings.Cut(strings.TrimRight(inst, ";"), "+") - return "pin conflict: " + m[1] + " is in use by " + owner, fmt.Sprintf( - "the emulated sensor %s is using %s; stop it with `benchpod sensor stop %s`", inst, m[1], inst) - } - for _, h := range pinReleaseHints { - if strings.HasPrefix(m[4], h.prefix) { - return "pin conflict: " + m[1] + " is in use by " + owner, fmt.Sprintf(h.hint, m[1]) - } - } - } - return msg, "" -} - -// explainRefusal returns the hint for a refusal without a code, by its text, or "" when the -// message says it all. overLAN is whether the refusal came over the LAN JSON API: only the LAN -// refuses with locked: or a cloud lease, so elsewhere those texts stand alone. A coded refusal -// gets the catalog's fix.cli instead (refusalHint). -func explainRefusal(msg string, overLAN bool) string { - msg = strings.TrimSpace(msg) - switch tcpclient.ClassifyRefusal(msg) { - case tcpclient.Locked: // no code yet - if overLAN { - return lockedUSBHint - } - case tcpclient.Busy: - switch { - case overLAN && strings.HasPrefix(msg, "busy: a cloud job holds"): // fallback: BP0025 replaces it - return leaseBusyHint - case msg == "busy": // no code yet - return heavyBusyHint - } - case tcpclient.Forbidden: // no code yet - return forbiddenHint - } - _, hint := translateRefusal(msg) - return hint -} - -// refusalHint is what to do about a refusal: the catalog's fix.cli for a coded one, else -// explainRefusal's hint from the text ("" for none). -func refusalHint(pe *tcpclient.PodError, overLAN bool) string { +// Every refusal from the pod, over the JSON API (LAN, USB network, embeddedci.com) or the USB +// console, is a *tcpclient.PodError. A refusal with a stable code (BP0001...) is classified by +// tcpclient's code table (the exit code) and worded from the catalog (internal/errcatalog: its +// message and fix.cli, codedRefusal). A refusal without a code is shown as the pod wrote it: the +// CLI never matches on a refusal's text. + +// refusalHint is what to do about a refusal: the catalog's fix.cli for a coded one, "" otherwise. +func refusalHint(pe *tcpclient.PodError) string { if pe.Code != "" { if e, ok := errcatalog.Lookup(pe.Code); ok { return errcatalog.Fill(e.Fix["cli"], pe.Args) } } - return explainRefusal(pe.Reason, overLAN) + return "" } -// refusedError is the one line for a refusal from a command: ": the pod refused: ", -// plus refusalHint's hint (a coded refusal: the catalog's message and fix.cli). -func refusedError(what string, pe *tcpclient.PodError, overLAN bool) error { - return refusedWithHint(what, pe, refusalHint(pe, overLAN)) +// refusedError is the one line for a refusal from a command: ": the pod refused: " +// (a coded refusal: the catalog's message and fix.cli). +func refusedError(what string, pe *tcpclient.PodError) error { + return refusedWithHint(what, pe, "") } -// isUnknownCommand says the pod does not know the command it was sent: its firmware is older -// than the command. BP0002, else (firmware without codes) the text "unknown cmd". +// isUnknownCommand says the pod does not know the command it was sent (BP0002). func isUnknownCommand(err error) bool { return tcpclient.IsUnknownCommand(err) } -// refusedWithHint is refusedError with the hint given ("" for none). +// refusedWithHint is refusedError with a hint of the caller's for a refusal without a code ("" for +// none); a coded refusal always shows the catalog's fix. func refusedWithHint(what string, pe *tcpclient.PodError, hint string) error { if coded, ok := codedRefusal(pe); ok { return &shownRefusal{msg: what + ": the pod refused: " + coded, pe: pe} } - shown, _ := translateRefusal(pe.Reason) - msg := what + ": the pod refused: " + shown + msg := what + ": the pod refused: " + strings.TrimSpace(pe.Reason) if hint != "" { msg += " (" + hint + ")" } @@ -183,10 +61,9 @@ type shownRefusal struct { func (e *shownRefusal) Error() string { return e.msg } func (e *shownRefusal) Unwrap() error { return e.pe } -// withRefusalHint adds explainRefusal's hint to an error that carries a refusal and does not -// show the hint yet. Execute applies it to every command's error, so a command that just wraps -// the client's error (%w) still gets the hint. A JSON reply (no console command) came over the -// LAN. +// withRefusalHint words a coded refusal from the catalog in an error that does not show it yet. +// Execute applies it to every command's error, so a command that just wraps the client's error +// (%w) still gets the catalog's message and fix. func withRefusalHint(err error) error { // embeddedci.com's own failures (a held lease, a missing role) say what to do already. var ce *cloudpod.Error @@ -197,26 +74,15 @@ func withRefusalHint(err error) error { if !ok { return err } - if coded, ok := codedRefusal(pe); ok { - if strings.Contains(err.Error(), coded) { - return err - } - msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), coded, 1) - if msg == err.Error() { - msg = err.Error() + ": " + coded - } - return &shownRefusal{msg: msg, pe: pe} - } - hint := explainRefusal(pe.Reason, pe.Cmd == "") - if hint == "" || strings.Contains(err.Error(), hint) { + coded, ok := codedRefusal(pe) + if !ok || strings.Contains(err.Error(), coded) { return err } - if shown, _ := translateRefusal(pe.Reason); shown != strings.TrimSpace(pe.Reason) { - // Drop the raw JSON the firmware suggests; the hint says it in CLI terms. - msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), shown, 1) - return &shownRefusal{msg: msg + " (" + hint + ")", pe: pe} + msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), coded, 1) + if msg == err.Error() { + msg = err.Error() + ": " + coded } - return fmt.Errorf("%w (%s)", err, hint) + return &shownRefusal{msg: msg, pe: pe} } // withSavedConnectionHint adds where the address came from when the pod did not answer at the @@ -245,6 +111,7 @@ const ( exitBusy = 4 // the pod or one of its engines is in use (a cloud lease, another session) exitUnreachable = 5 // the pod did not answer on its address, no pod on USB, or offline on embeddedci.com exitUpdateCLI = 6 // the pod's firmware needs a newer CLI (its API level is above this CLI's, or BP0030) + exitUpdatePod = 7 // the pod's firmware is too old for this CLI or the command (below firmware 4.0, BP0002, BP0017) ) // exitCodesHelp is the exit-code table for the root command's help. @@ -256,7 +123,9 @@ const exitCodesHelp = "Exit codes:\n" + " 4 busy: the pod or one of its engines is in use (a cloud job's lease, another session)\n" + " 5 unreachable: nothing answered on the pod's address, no pod found on USB, or the\n" + " pod is offline on embeddedci.com\n" + - " 6 update the CLI: the pod's firmware needs a newer benchpod CLI" + " 6 update the CLI: the pod's firmware needs a newer benchpod CLI\n" + + " 7 update the pod: its firmware is too old for this CLI (firmware before 4.0:\n" + + " `benchpod flash-self`) or lacks what the command needs" // usageError marks a command-line mistake (exit code 2). type usageError struct{ err error } @@ -286,9 +155,18 @@ func exitCode(err error) int { if errors.As(err, &upd) { return exitUpdateCLI } + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &old) { + return exitUpdatePod + } if pe, ok := tcpclient.AsPodError(err); ok { - if pe.Kind() == tcpclient.Busy { + switch pe.Kind() { + case tcpclient.Busy: return exitBusy + case tcpclient.FirmwareTooOld: + return exitUpdatePod + case tcpclient.ClientTooOld: + return exitUpdateCLI } return exitRefused } @@ -303,6 +181,12 @@ func markUsageErrors(cmd *cobra.Command) { cmd.SetFlagErrorFunc(func(_ *cobra.Command, err error) error { return &usageError{err: err} }) var walk func(c *cobra.Command) walk = func(c *cobra.Command) { + // A command group (subcommands, nothing to run) prints its help; an unknown subcommand of + // it is a usage error, not the help with exit 0. + if c.HasSubCommands() && c.Run == nil && c.RunE == nil && c.HasParent() { + c.Args = cobra.NoArgs + c.RunE = func(c *cobra.Command, _ []string) error { return c.Help() } + } if args := c.Args; args != nil { c.Args = func(c *cobra.Command, a []string) error { if err := args(c, a); err != nil { @@ -328,5 +212,5 @@ func codedRefusal(pe *tcpclient.PodError) (string, bool) { if text, ok := errcatalog.Render(pe.Code, pe.Args, "cli"); ok { return text, true } - return fmt.Sprintf("%s: %s (%s)", pe.Code, strings.TrimSpace(pe.Reason), errcatalog.DocsURL(pe.Code)), true + return fmt.Sprintf("%s: %s (%s)", strings.ToUpper(pe.Code), strings.TrimSpace(pe.Reason), errcatalog.DocsURL(pe.Code)), true } diff --git a/cmd/benchpod-cli/errors_test.go b/cmd/benchpod-cli/errors_test.go index 27038db..4512c32 100644 --- a/cmd/benchpod-cli/errors_test.go +++ b/cmd/benchpod-cli/errors_test.go @@ -1,10 +1,12 @@ package main import ( + "bufio" "context" "encoding/json" "errors" "fmt" + "io" "log" "net" "net/http" @@ -14,54 +16,34 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/errcatalog" - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" "github.com/embeddedci-com/benchpod-cli/internal/serverapi" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) -// explainRefusal is the one place a policy refusal gets its hint; the texts come from the -// firmware (internal/fwrefusals). -func TestExplainRefusal(t *testing.T) { - for _, c := range []struct { - id string - overLAN bool - want string - }{ - {"lan_locked", true, lockedUSBHint}, - {"lan_locked", false, ""}, - {"lease_busy", true, leaseBusyHint}, - {"lease_busy", false, ""}, - {"heavy_busy", true, heavyBusyHint}, - {"heavy_busy", false, heavyBusyHint}, - {"tunnel_forbidden", false, forbiddenHint}, - {"psram_bus_busy", true, ""}, // says what to do already - {"swd_busy_spi_session", true, ""}, - {"unknown_cmd", true, ""}, - } { - if got := explainRefusal(fwrefusals.Example(c.id), c.overLAN); got != c.want { - t.Errorf("%s (LAN %v): got %q, want %q", c.id, c.overLAN, got, c.want) - } - } -} - -func TestWithRefusalHintAddsTheHintOnce(t *testing.T) { - msg := fwrefusals.Example("lan_locked") - err := withRefusalHint(fmt.Errorf("la pullup: %w", &tcpclient.PodError{Reason: msg})) - if got := err.Error(); got != "la pullup: "+msg+" ("+lockedUSBHint+")" { - t.Fatalf("got %q", got) +// A coded refusal is worded from the catalog once; a refusal without a code is shown as the pod +// wrote it, with no hint (the CLI never reads a refusal's text). +func TestWithRefusalHint(t *testing.T) { + pe := &tcpclient.PodError{Reason: "The pod's LAN is locked: flash needs the cloud or USB", Code: "BP0040", + Args: map[string]any{"cmd": "flash"}} + err := withRefusalHint(fmt.Errorf("flash: %w", pe)) + want := "flash: BP0040: The pod's LAN is locked: flash needs the cloud or USB; run this over USB with --connection usb, or from the cloud (" + + errcatalog.DocsURL("BP0040") + ")" + if err.Error() != want { + t.Fatalf("got %q\nwant %q", err, want) } if _, ok := tcpclient.AsPodError(err); !ok { t.Fatal("the hint hid the refusal") } - // Already explained (refusedError): left alone. - once := refusedError("cloud ca set", &tcpclient.PodError{Reason: msg}, true) - if got := withRefusalHint(once).Error(); strings.Count(got, lockedUSBHint) != 1 { + once := refusedError("flash", pe) + if got := withRefusalHint(once).Error(); got != once.Error() { t.Fatalf("got %q", got) } - // A console refusal did not come over the LAN, and other errors pass through. - usb := &tcpclient.PodError{Cmd: "proxy-set", Reason: msg} - if got := withRefusalHint(usb); got != error(usb) { - t.Fatalf("got %v", got) + plainRefusal := &tcpclient.PodError{Reason: "locked: flash needs the cloud or USB"} + if got := withRefusalHint(plainRefusal); got != error(plainRefusal) { + t.Fatalf("uncoded: got %v", got) + } + if got := refusedError("generate", &tcpclient.PodError{Reason: "unknown waveform"}).Error(); got != "generate: the pod refused: unknown waveform" { + t.Fatalf("uncoded refusedError: %q", got) } plain := errors.New("connect to pod at 10.0.0.1:8080: i/o timeout") if got := withRefusalHint(plain); got != plain { @@ -73,14 +55,16 @@ func TestWithRefusalHintAddsTheHintOnce(t *testing.T) { func TestExitCodes(t *testing.T) { t.Setenv("BENCHPOD_CONNECTION", "") t.Setenv("BENCHPOD_TIMEOUT", "") - reply := func(id string) string { - b, _ := json.Marshal(map[string]string{"status": "error", "message": fwrefusals.Example(id)}) + reply := func(code string) string { + b, _ := json.Marshal(map[string]any{"status": "error", "code": code, "args": map[string]any{"cmd": "ping"}}) return string(b) } - locked, _ := fakeLANPod(t, reply("lan_locked")) - leased, _ := fakeLANPod(t, reply("lease_busy")) - swd, _ := fakeLANPod(t, reply("swd_busy")) - forbidden, _ := fakeLANPod(t, reply("tunnel_forbidden")) + locked, _ := fakeLANPod(t, reply("BP0040")) + leased, _ := fakeLANPod(t, reply("BP0025")) + swd, _ := fakeLANPod(t, reply("BP0050")) + forbidden, _ := fakeLANPod(t, reply("BP0045")) + gateware, _ := fakeLANPod(t, reply("BP0017")) + uncoded, _ := fakeLANPod(t, `{"status":"error","message":"busy: anything"}`) ok, _ := fakeLANPod(t, `{"status":"ok","data":"pong"}`) // A port nothing listens on: grab one, then close it. ln, err := net.Listen("tcp", "127.0.0.1:0") @@ -98,11 +82,19 @@ func TestExitCodes(t *testing.T) { {[]string{"ping", "--connection", ok, "--no-such-flag"}, exitUsage}, {[]string{"ping", "--connection", ok, "extra"}, exitUsage}, {[]string{"no-such-command"}, exitUsage}, - {[]string{"la", "pullup", "1"}, exitUsage}, + // A command-line mistake the command finds itself is a usage error too. + {[]string{"capture", "--samples", "0", "--connection", ok}, exitUsage}, + {[]string{"la", "step", "--steps", "3", "--connection", ok}, exitUsage}, + {[]string{"generate", "--waveform", "sine", "--path", "9v", "--amplitude-v", "1", "--offset-v", "1", "--connection", ok}, exitUsage}, + {[]string{"discover", "--no-usb", "--no-network"}, exitUsage}, + {[]string{"flash", "--target-power", "3", "--connection", ok}, exitUsage}, + {[]string{"la", "pullup", "1", "on"}, exitUsage}, // gone in 0.10 {[]string{"ping", "--connection", locked}, exitRefused}, {[]string{"ping", "--connection", forbidden}, exitRefused}, {[]string{"ping", "--connection", leased}, exitBusy}, {[]string{"ping", "--connection", swd}, exitBusy}, + {[]string{"ping", "--connection", gateware}, exitUpdatePod}, + {[]string{"ping", "--connection", uncoded}, exitRefused}, // its text is never read {[]string{"ping", "--connection", closed, "--timeout", "1s"}, exitUnreachable}, } { if got := run(c.args); got != c.want { @@ -129,10 +121,10 @@ func TestShownRefusalsKeepTheirExitCode(t *testing.T) { err error want int }{ - {cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example("lan_locked")}), exitRefused}, - {cloudCfgError("cloud proxy clear", proxyMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example("cloud_proxy_from_lan")}), exitRefused}, - {cloudCfgError("cloud ca set", caMissing, false, &tcpclient.PodError{Cmd: "ca", Reason: fwrefusals.Example("ota_owner_busy")}), exitBusy}, - {cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, Message: fwrefusals.Example("sig_policy_loosen")}), exitRefused}, + {cloudCfgError("cloud ca set", &tcpclient.PodError{Reason: "x", Code: "BP0040"}), exitRefused}, + {cloudCfgError("cloud proxy clear", &tcpclient.PodError{Reason: "x", Code: "BP0042"}), exitRefused}, + {cloudCfgError("cloud ca set", &tcpclient.PodError{Reason: "x", Code: "BP0051"}), exitBusy}, + {cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusConflict, Code: "BP0041", Message: "BP0041"}), exitRefused}, {cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusForbidden}), exitRefused}, } { if got := exitCode(c.err); got != c.want { @@ -150,6 +142,7 @@ func TestEveryCodedRefusal(t *testing.T) { wantExit := map[tcpclient.RefusalKind]int{ tcpclient.Refused: exitRefused, tcpclient.Locked: exitRefused, tcpclient.Forbidden: exitRefused, tcpclient.Busy: exitBusy, + tcpclient.FirmwareTooOld: exitUpdatePod, tcpclient.ClientTooOld: exitUpdateCLI, } args := map[string]any{"cmd": "x", "arg": "la", "name": "k66", "rev": 3, "max": 8, "bytes": 9000, "expected": 0, "feature": "i2c", "min": 55, "la": 4, "rx": 1, "tx": 2, "have": "up", "want": "down", @@ -169,15 +162,15 @@ func TestEveryCodedRefusal(t *testing.T) { if !ok { t.Fatal("no kind") } - pe := &tcpclient.PodError{Reason: "pod returned an error", Code: code, Args: args} + pe, _ := tcpclient.AsPodError(tcpclient.RefusalError("", code, args)) // no message: 4.0 if got := exitCode(fmt.Errorf("x: %w", pe)); got != wantExit[kind] { t.Errorf("exit %d, want %d", got, wantExit[kind]) } fix := errcatalog.Fill(e.Fix["cli"], args) - if got := refusalHint(pe, true); got != fix { + if got := refusalHint(pe); got != fix { t.Errorf("hint %q, want %q", got, fix) } - msg := refusedError("cmd", pe, true).Error() + msg := refusedError("cmd", pe).Error() if !strings.Contains(msg, code+": "+errcatalog.Fill(e.Message, args)) || !strings.Contains(msg, fix) { t.Errorf("refusedError = %q", msg) } @@ -188,46 +181,65 @@ func TestEveryCodedRefusal(t *testing.T) { } } -// The text fallbacks still classify a refusal without a code as before (older firmware). -func TestUncodedRefusalsKeepTheirExitCodes(t *testing.T) { - for id, want := range map[string]int{ - "lan_locked": exitRefused, "lan_locked_v39": exitRefused, "tunnel_forbidden": exitRefused, - "lease_busy": exitBusy, "heavy_busy": exitBusy, "psram_bus_busy": exitBusy, "swd_busy": exitBusy, - "uart_busy": exitBusy, "spi_busy": exitBusy, "swd_or_spi_busy": exitBusy, "unknown_cmd": exitRefused, - "la_voltage_unset": exitRefused, "pin_conflict": exitRefused, - } { - if got := exitCode(&tcpclient.PodError{Reason: fwrefusals.Example(id)}); got != want { - t.Errorf("%s: exit %d, want %d", id, got, want) - } - } -} - -// One helper says "the firmware lacks this command": BP0002, or the old text. +// "The firmware lacks this command" is BP0002 only. func TestIsUnknownCommandHelper(t *testing.T) { - if !isUnknownCommand(fmt.Errorf("x: %w", &tcpclient.PodError{Code: "BP0002", Reason: "pod returned an error"})) || - !isUnknownCommand(&tcpclient.PodError{Reason: fwrefusals.Example("unknown_cmd")}) || + if !isUnknownCommand(fmt.Errorf("x: %w", &tcpclient.PodError{Code: "BP0002"})) || + isUnknownCommand(&tcpclient.PodError{Reason: "unknown cmd"}) || isUnknownCommand(&tcpclient.PodError{Code: "BP0006", Reason: "missing la"}) || isUnknownCommand(errors.New("unknown cmd")) { t.Fatal("isUnknownCommand") } } -// unknownCmdReplies are a pod's answers to a command its firmware lacks: the text of firmware -// without codes, and BP0002 (with no text: a build without texts). +// unknownCmdReplies are a pod's answers to a command its firmware lacks: BP0002, with no message. var unknownCmdReplies = []string{ - `{"status":"error","message":"unknown cmd"}`, `{"status":"error","code":"BP0002","args":{"cmd":"x"}}`, } -// A pod whose firmware announces a newer API than this CLI handles stops a command that reads -// its status, with its own exit code; so does BP0030. A pod with api 1 or none works. -func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { - newer, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.11.0","api":2,"min_client_api":0}}`) - newerPing, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.11.0","api":2,"min_client_api":0}}`) - same, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.10.14","api":1,"min_client_api":0}}`) - old, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.10.13"}}`) +// fakeLANPodByCmd is a LAN pod that answers each command by name ("" for any other). +func fakeLANPodByCmd(t *testing.T, replies map[string]string) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + line, _ := bufio.NewReader(conn).ReadString('\n') + var req map[string]any + _ = json.Unmarshal([]byte(line), &req) + cmd, _ := req["cmd"].(string) + reply, ok := replies[cmd] + if !ok { + reply = replies[""] + } + _, _ = io.WriteString(conn, reply+"\n") + conn.Close() + } + }() + return ln.Addr().String() +} + +// A pod whose firmware announces a newer API than this CLI handles, or one older than firmware 4.0 +// (api 1, or none), stops a command with its own exit code (6, 7); so does BP0030. The firmware +// commands (status and the update commands) still run against it. +func TestPodAPILevels(t *testing.T) { + apiProbe = true + defer func() { apiProbe = false; tcpclient.ResetAPIProbe() }() + pod := func(status string) string { + return fakeLANPodByCmd(t, map[string]string{"status": `{"status":"ok","data":` + status + `}`, "": `{"status":"ok","data":"pong"}`}) + } + newer := pod(`{"version":"5.0.0","api":3,"min_client_api":3}`) + same := pod(`{"version":"4.0.0","api":2,"min_client_api":2}`) + old := pod(`{"version":"3.10.13"}`) + dev := pod(`{"version":"3.10.14","api":1,"min_client_api":0}`) tooOld, _ := fakeLANPod(t, `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":2,"api":2},`+ - `"message":"update the BenchPod SDK, MCP or CLI: this firmware needs client API 2 or newer (this client sent 1)"}`) + `"message":"Update the BenchPod SDK, MCP or CLI: this firmware needs client API 2 or newer (this client sent 1)"}`) var logged strings.Builder log.SetOutput(&logged) defer log.SetOutput(os.Stderr) @@ -236,12 +248,17 @@ func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { want int msg string }{ - // status still shows the pod (it is how the user finds out), with the update line as a warning. + // status still shows the pod (it is how the user finds out), with the line as a warning. {[]string{"status", "--connection", newer}, exitOK, - "Warning: this pod's firmware 3.11.0 needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod"}, + "Warning: this pod's firmware 5.0.0 needs a newer benchpod CLI (pod API 3, this CLI handles 2): brew upgrade --cask benchpod"}, + {[]string{"status", "--connection", old}, exitOK, + "Warning: this pod's firmware 3.10.13 is too old for this benchpod CLI (pod API 1, this CLI needs 2): this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", newer}, exitUpdateCLI, "needs a newer benchpod CLI"}, + {[]string{"ping", "--connection", old}, exitUpdatePod, "this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", dev}, exitUpdatePod, "this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", same}, exitOK, ""}, {[]string{"ping", "--connection", tooOld}, exitUpdateCLI, - "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod"}, - {[]string{"ping", "--connection", newerPing}, exitOK, ""}, // ping reads no status + "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 2): brew upgrade --cask benchpod"}, } { logged.Reset() if got := run(c.args); got != c.want { @@ -251,17 +268,14 @@ func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { t.Errorf("%v: logged %q", c.args, logged.String()) } } - for _, addr := range []string{same, old} { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - _, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status", "caps": false}) - cancel() - if err != nil { - t.Errorf("%s: %v", addr, err) - } + if got := exitCode(fmt.Errorf("x: %w", &tcpclient.UpdateRequiredError{PodAPI: 3})); got != exitUpdateCLI { + t.Errorf("wrapped: exit %d", got) } - if got := exitCode(fmt.Errorf("x: %w", &tcpclient.UpdateRequiredError{PodAPI: 2})); got != exitUpdateCLI { + if got := exitCode(fmt.Errorf("x: %w", &tcpclient.FirmwareTooOldError{PodAPI: 1})); got != exitUpdatePod { t.Errorf("wrapped: exit %d", got) } + _ = context.Background + _ = time.Second } // Every JSON command the CLI sends carries client_api and client ("cli "), on the LAN and diff --git a/cmd/benchpod-cli/expansion.go b/cmd/benchpod-cli/expansion.go index 394edc6..9435d14 100644 --- a/cmd/benchpod-cli/expansion.go +++ b/cmd/benchpod-cli/expansion.go @@ -183,7 +183,7 @@ func startExpansionBus(ctx context.Context, g *globalFlags, t *podTarget, sda, s return i2cSession{}, usageErrorf("--sda and --scl are both LA%d; each needs its own pin", sdaPin) } var s i2cSession - req := map[string]any{"cmd": "i2c_start", "sda": sdaPin, "scl": sclPin, "hz": hz, "pullups": pullups} + req := map[string]any{"cmd": "i2c_start", "sda": sdaPin, "scl": sclPin, "clock_hz": hz, "pullups": pullups} if err := busCommand(ctx, t, "expansion", "I2C master", req, &s); err != nil { return i2cSession{}, err } diff --git a/cmd/benchpod-cli/expansion_test.go b/cmd/benchpod-cli/expansion_test.go index 30f0dc4..cfa8d0b 100644 --- a/cmd/benchpod-cli/expansion_test.go +++ b/cmd/benchpod-cli/expansion_test.go @@ -18,10 +18,10 @@ func fakeTCA9555(pod *fakeSensorPod, session bool) { if !active { return map[string]any{"active": false}, "" } - return map[string]any{"active": true, "sda": 5, "scl": 6, "hz": 100000, "pullups": "external"}, "" + return map[string]any{"active": true, "sda": 5, "scl": 6, "clock_hz": 100000, "pullups": "external"}, "" case "i2c_start": active = true - return map[string]any{"sda": req["sda"], "scl": req["scl"], "hz": req["hz"], "pullups": req["pullups"]}, "" + return map[string]any{"sda": req["sda"], "scl": req["scl"], "clock_hz": req["clock_hz"], "pullups": req["pullups"]}, "" case "i2c_stop": active = false return "i2c stopped", "" @@ -87,7 +87,7 @@ func TestExpansionOpensAndClosesItsOwnSession(t *testing.T) { if err != nil { t.Fatal(err) } - if got := reqJSON(pod.last("i2c_start")); got != `{"cmd":"i2c_start","hz":400000,"pullups":"pod","scl":2,"sda":1}` { + if got := reqJSON(pod.last("i2c_start")); got != `{"clock_hz":400000,"cmd":"i2c_start","pullups":"pod","scl":2,"sda":1}` { t.Fatalf("start %s", got) } if pod.last("i2c_stop") == nil { diff --git a/cmd/benchpod-cli/flash.go b/cmd/benchpod-cli/flash.go index 0e1aed4..d151a0b 100644 --- a/cmd/benchpod-cli/flash.go +++ b/cmd/benchpod-cli/flash.go @@ -12,7 +12,6 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/openocd" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/serverapi" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" @@ -158,7 +157,7 @@ func runFlash(g *globalFlags, f *flashFlags) error { return fmt.Errorf("pass either --file or an uploaded build (--build, --repo, --ref, --artifact), not both") } if !fromBuild && f.serverSideSet { - return fmt.Errorf("--server-side only applies to an uploaded build (--build, --repo, --ref)") + return usageErrorf("--server-side only applies to an uploaded build (--build, --repo, --ref)") } serverSide := spec.IsCloud() if f.serverSideSet { @@ -170,7 +169,7 @@ func runFlash(g *globalFlags, f *flashFlags) error { cloudConnPrefix, spec.Name) } if spec.IsCloud() && !serverSide { - return fmt.Errorf("--server-side=false needs a direct link to the pod: pass its network address or `usb` as --connection") + return usageErrorf("--server-side=false needs a direct link to the pod: pass its network address or `usb` as --connection") } if !isESPTarget(f.target) && (spec.IsNetwork() || spec.IsCloud()) { f.fillFromWiring(g) // an ESP32 target uses no SWD settings @@ -199,27 +198,27 @@ func runFlash(g *globalFlags, f *flashFlags) error { } } if strings.TrimSpace(f.swclk) == "" || strings.TrimSpace(f.swdio) == "" { - return fmt.Errorf("--swclk and --swdio are required (or set swd_swclk and swd_swdio in the pod's wiring profile)") + return usageErrorf("--swclk and --swdio are required (or set swd_swclk and swd_swdio in the pod's wiring profile)") } swclk, err := parseLAPin(f.swclk) if err != nil { - return fmt.Errorf("--swclk: %w", err) + return usageErrorf("--swclk: %w", err) } swdio, err := parseLAPin(f.swdio) if err != nil { - return fmt.Errorf("--swdio: %w", err) + return usageErrorf("--swdio: %w", err) } if swclk == swdio { - return fmt.Errorf("--swclk and --swdio must be different pins") + return usageErrorf("--swclk and --swdio must be different pins") } if strings.TrimSpace(f.file) != "" && strings.TrimSpace(f.target) == "" { if fromBuild { - return fmt.Errorf("--target is required: the build recorded none and the wiring profile has no swd_target") + return usageErrorf("--target is required: the build recorded none and the wiring profile has no swd_target") } - return fmt.Errorf("--file requires --target") + return usageErrorf("--file requires --target") } if f.targetPower != 0 && f.targetPower != 1 && f.targetPower != 2 { - return fmt.Errorf("--target-power must be 1 (internal 5V) or 2 (external)") + return usageErrorf("--target-power must be 1 (internal 5V) or 2 (external)") } if fromBuild && serverSide { return f.flashOnServer(g, spec, art, swclk, swdio) @@ -361,16 +360,16 @@ func printTargetUnreachableHint(f *flashFlags) { } } -// openDAP optionally powers the target, then arms the pod's CMSIS-DAP probe over -// the selected transport (dap_start over the network, the dap-start console command -// over USB) and returns the length-framed DAP stream to bridge to OpenOCD. +// openDAP optionally powers the target, then arms the pod's CMSIS-DAP probe (dap_start over +// the network, or over USB on the pod's USB network adapter) and returns the length-framed DAP +// stream to bridge to OpenOCD. // powerEfuse 0 leaves target power untouched; 1/2 enables that eFuse first. func openDAP(ctx context.Context, g *globalFlags, swclk, swdio int, powerEfuse int) (io.ReadWriteCloser, bool, error) { spec, err := g.resolveConnection() if err != nil { return nil, false, err } - spec = g.preferUSBNetwork(spec, "flash") // the probe over the USB network is much faster + spec = g.preferUSBNetwork(spec, "flash") if spec.IsNetwork() { client := &tcpclient.Client{Addr: spec.Addr} // Ask the pod whether it has the dedicated reset pin BEFORE arming the @@ -395,43 +394,9 @@ func openDAP(ctx context.Context, g *globalFlags, swclk, swdio int, powerEfuse i return conn, hasNRST, nil } - // Serial transport: open the console, optionally power the target, perform - // the dap-start handshake, and hand back the framed stream. DAPStart's - // returned closer owns the port (its Close sends a leave frame and closes it), - // so we only close the console explicitly when we bail out before the - // handshake succeeds. Same auto-detect as the other serial commands: explicit - // device verbatim, else probe USB serial ports for the bench-pod identifier. - console, path, err := g.openBenchpodSerial(spec.Device, 2*time.Second) - if err != nil { - return nil, false, err - } - // Same probe as the network path, on the console this time — and for the same - // reason it has to happen before dap-start: the console stops taking text - // commands once the probe is armed. The port is already open, so this costs - // one `status` round-trip and no extra connection. - hasNRST := true - if v, err := console.HasNRSTPin(ctx); err == nil { - hasNRST = v - } - if powerEfuse != 0 { - if err := console.TargetPower(ctx, powerEfuse, true); err != nil { - console.Close() - if errors.Is(err, serialconsole.ErrMovedToNetwork) || errors.Is(err, serialconsole.ErrUnknownCommand) { - return nil, false, fmt.Errorf("flash: this pod's console has no power command (firmware 3.9.0+ switches " + - "target power over the network API) and its USB network is not usable; drop --target-power, " + - "or connect over the network") - } - return nil, false, fmt.Errorf("flash: enable target-power eFuse %d over %s: %w", powerEfuse, path, err) - } - fmt.Fprintf(os.Stderr, "flash: target-power eFuse %d on\n", powerEfuse) - settle(ctx, targetPowerSettle) - } - conn, err := console.DAPStart(ctx, swclk, swdio) - if err != nil { - console.Close() - return nil, false, fmt.Errorf("flash: dap-start over %s: %w", path, err) - } - return conn, hasNRST, nil + // USB without a usable USB network adapter: firmware 4.0 has no probe on its console. + _, err = g.networkTarget("flash") + return nil, false, err } // settle waits for d or until ctx is cancelled, whichever comes first, so the @@ -516,7 +481,7 @@ func buildOpenOCDArgs(target, file, loadAddr string, noVerify, noReset, connectU prog := []string{"program", word} if a := strings.TrimSpace(loadAddr); a != "" { if !loadAddrRe.MatchString(a) { - return nil, fmt.Errorf("--load-address must be a number like 0x08000000, not %q", loadAddr) + return nil, usageErrorf("--load-address must be a number like 0x08000000, not %q", loadAddr) } prog = append(prog, a) } diff --git a/cmd/benchpod-cli/flash_build.go b/cmd/benchpod-cli/flash_build.go index 80779c8..d4c8335 100644 --- a/cmd/benchpod-cli/flash_build.go +++ b/cmd/benchpod-cli/flash_build.go @@ -99,10 +99,10 @@ func (f *flashFlags) flashOnServer(g *globalFlags, spec ConnSpec, art *serverapi strings.Join(localOnly, ", ")) } if strings.TrimSpace(f.target) == "" { - return fmt.Errorf("--target is required (an OpenOCD config such as target/stm32f4x.cfg), or set swd_target in the pod's wiring profile") + return usageErrorf("--target is required (an OpenOCD config such as target/stm32f4x.cfg), or set swd_target in the pod's wiring profile") } if spec.IsSerial() { - return fmt.Errorf("--server-side needs the pod's network address or --connection embeddedci:, not a USB connection") + return usageErrorf("--server-side needs the pod's network address or --connection embeddedci:, not a USB connection") } ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(flashTimeout)+time.Minute) defer cancel() diff --git a/cmd/benchpod-cli/flash_esp.go b/cmd/benchpod-cli/flash_esp.go index d438a31..d8c1719 100644 --- a/cmd/benchpod-cli/flash_esp.go +++ b/cmd/benchpod-cli/flash_esp.go @@ -153,7 +153,7 @@ func (f *flashFlags) espPins(w *podWiring) (map[string]any, error) { if strings.TrimSpace(val) != "" { n, err := parseLAPin(val) if err != nil { - return 0, fmt.Errorf("--%s: %w", flag, err) + return 0, usageErrorf("--%s: %w", flag, err) } return n, nil } @@ -178,14 +178,14 @@ func (f *flashFlags) espPins(w *podWiring) (map[string]any, error) { return nil, err } if rx == 0 || tx == 0 { - return nil, fmt.Errorf("--rx and --tx are required (the LA pins on the target's TXD0 and RXD0), or set uart_rx and uart_tx in the pod's wiring profile") + return nil, usageErrorf("--rx and --tx are required (the LA pins on the target's TXD0 and RXD0), or set uart_rx and uart_tx in the pod's wiring profile") } boot, err := pin("boot", f.espBoot, "", espBootSignals) if err != nil { return nil, err } if boot == 0 { - return nil, fmt.Errorf("--boot is required: the LA pin on the target's IO0 (IO9 on the C3/C6), or a wiring-profile signal named BOOT, IO0 or IO9") + return nil, usageErrorf("--boot is required: the LA pin on the target's IO0 (IO9 on the C3/C6), or a wiring-profile signal named BOOT, IO0 or IO9") } pins := map[string]any{"rx": rx, "tx": tx, "boot": boot, "en": "nrst"} if !f.nreset { diff --git a/cmd/benchpod-cli/flash_self.go b/cmd/benchpod-cli/flash_self.go index 84ba68c..4f14380 100644 --- a/cmd/benchpod-cli/flash_self.go +++ b/cmd/benchpod-cli/flash_self.go @@ -153,7 +153,7 @@ func newFlashSelfCmd(g *globalFlags) *cobra.Command { return runFlashSelfCloud(g, f, func(name string) bool { return cc.Flags().Changed(name) }, args, name) } if f.dryRun { - return errors.New("--dry-run is for an update through embeddedci.com (--connection embeddedci:)") + return usageErrorf("--dry-run is for an update through embeddedci.com (--connection embeddedci:)") } if f.network { return runFlashSelfNetwork(g, f, func(name string) bool { return cc.Flags().Changed(name) }, args) @@ -251,7 +251,7 @@ func newFlashSelfCmd(g *globalFlags) *cobra.Command { }, } fl := cmd.Flags() - fl.StringVar(&f.address, "address", stmDfuBaseAddr, "flash base address (STM32 main flash)") + fl.StringVar(&f.address, "addr", stmDfuBaseAddr, "flash base address (STM32 main flash)") fl.StringVar(&f.dfuUtil, "dfu-util", "", "path to the dfu-util binary; defaults to the one on PATH") fl.BoolVar(&f.noLeave, "no-leave", false, "stay in DFU after flashing instead of starting the new firmware") fl.BoolVar(&f.enterDfu, "enter-dfu", false, "first reboot a running pod into DFU over the USB console, then flash") @@ -548,9 +548,6 @@ func checkImageFitsPod(ctx context.Context, dfuPath, file string) error { return nil } -// skipUSBNetForBlobs keeps installBlobsAfterFlash on the console (tests). -var skipUSBNetForBlobs = false - // flashedPodSerial is the USB serial number of the pod flash-self rebooted into DFU over its // console ("" when it was put in DFU by hand): it finds the pod again after the update. var flashedPodSerial string @@ -562,6 +559,7 @@ var ( // adapter), and Windows installs drivers and may assign a new COM port before the console appears. flashedConsoleWait = 150 * time.Second flashedConsoleRetry = time.Second + flashedNetTries = 20 // seconds the computer may need to bring the USB network adapter up openFlashedConsole = func(g *globalFlags) (*serialconsole.Console, error) { device := g.serialDevice() if flashedPodSerial != "" { @@ -607,32 +605,26 @@ func installBlobsAfterFlash(g *globalFlags, src blobSource) (after podVersions, ctx, cancel := context.WithTimeout(context.Background(), blobsInstallTimeout) defer cancel() after = consoleVersions(ctx, console) - target := blobTarget(consoleBlobs{Console: console, path: "the USB console"}) - if !skipUSBNetForBlobs { - // Firmware before 3.9.0: the console. 3.9.0+: the USB network (or the pod's network - // address), which may need some seconds on the computer's side after the reboot. - var lastErr error - for i := 0; i < 20; i++ { - t, closeT, err := blobTargetFor(ctx, console, "the USB console") - if err == nil { - target = t - defer closeT() - lastErr = nil - if _, ok := t.(lanBlobs); ok || i >= 10 { - break - } - if u, uerr := console.USBNetwork(ctx); uerr != nil || !u.On { - break // older firmware, or USB networking off: no point waiting for it - } - } else { - lastErr = err - } - time.Sleep(time.Second) + // The USB network (or the pod's network address), which may need some seconds on the + // computer's side after the reboot. + var target blobTarget + var lastErr error + for i := 0; i < flashedNetTries; i++ { + t, closeT, err := blobTargetFor(ctx, console, "the USB console") + if err == nil { + target, lastErr = t, nil + defer closeT() + break } - if lastErr != nil { - return after, installed, fmt.Errorf("flash-self: the firmware is flashed, but its blobs are not installed: %w "+ - "(retry with `benchpod install-blobs`)", lastErr) + lastErr = err + if u, uerr := console.USBNetwork(ctx); uerr != nil || !u.On { + break // firmware before 3.9.0, or USB networking off: no point waiting for it } + time.Sleep(time.Second) + } + if lastErr != nil { + return after, installed, fmt.Errorf("flash-self: the firmware is flashed, but its blobs are not installed: %w "+ + "(retry with `benchpod install-blobs`)", lastErr) } if _, err := target.Blobs(ctx); err != nil { if errors.Is(err, serialconsole.ErrNoBlobSlots) { diff --git a/cmd/benchpod-cli/flash_self_cloud.go b/cmd/benchpod-cli/flash_self_cloud.go index 774b0e4..491ff81 100644 --- a/cmd/benchpod-cli/flash_self_cloud.go +++ b/cmd/benchpod-cli/flash_self_cloud.go @@ -49,7 +49,7 @@ func (g *globalFlags) explicitCloud() (string, bool) { func runFlashSelfCloud(g *globalFlags, f *flashSelfFlags, changed func(string) bool, args []string, name string) error { for _, flag := range dfuOnlyFlags { if changed(flag) { - return fmt.Errorf("--%s is for USB DFU and does not apply through embeddedci.com", flag) + return usageErrorf("--%s is for USB DFU and does not apply through embeddedci.com", flag) } } arg := "" diff --git a/cmd/benchpod-cli/flash_self_cloud_test.go b/cmd/benchpod-cli/flash_self_cloud_test.go index 30ecceb..7e800da 100644 --- a/cmd/benchpod-cli/flash_self_cloud_test.go +++ b/cmd/benchpod-cli/flash_self_cloud_test.go @@ -76,6 +76,7 @@ func (o *otaServer) start() *serverapi.Client { var cloudFlashGlobals = &globalFlags{connection: "embeddedci:benchpod-7a32b5", noFirmwareReport: true} func TestFlashSelfCloudUploadsImageAndSig(t *testing.T) { + allowAnyPodAPI(t) images, sigs := sigVectors(t) fw := filepath.Join(t.TempDir(), "bench_pod_stm32.bin") writeFile(t, fw, images["firmware"]) @@ -113,6 +114,7 @@ func TestFlashSelfCloudUploadsImageAndSig(t *testing.T) { } func TestFlashSelfCloudLatestRelease(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t, phases: []map[string]any{{"phase": "done", "version_after": "3.10.2"}}} o.start() if err := runFlashSelfCloud(cloudFlashGlobals, &flashSelfFlags{network: true}, noFlagChanged, nil, "benchpod-7a32b5"); err != nil { @@ -138,6 +140,7 @@ func TestFlashSelfCloudLatestRelease(t *testing.T) { // --skip-blobs (or --blobs-dir) with a release is noted and ignored: the server installs the // release's blobs with it, and there is nothing to skip on its side. func TestFlashSelfCloudReleaseIgnoresSkipBlobs(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t, phases: []map[string]any{{"phase": "done", "version_after": "3.10.6"}}} o.start() var err error @@ -157,6 +160,7 @@ func TestFlashSelfCloudReleaseIgnoresSkipBlobs(t *testing.T) { } func TestFlashSelfCloudRefusals(t *testing.T) { + allowAnyPodAPI(t) fw, _ := fwImage(t, 4096, 1024) for _, tc := range []struct { status int @@ -186,6 +190,7 @@ func TestFlashSelfCloudRefusals(t *testing.T) { } func TestFlashSelfCloudFailedJob(t *testing.T) { + allowAnyPodAPI(t) fw, _ := fwImage(t, 4096, 1024) o := &otaServer{t: t, phases: []map[string]any{{"phase": "error", "error": "signature refused by the pod's policy"}}} o.start() @@ -199,6 +204,7 @@ func TestFlashSelfCloudFailedJob(t *testing.T) { } func TestFlashSelfCloudTooBigAndDFUFlags(t *testing.T) { + allowAnyPodAPI(t) (&otaServer{t: t}).start() fw, _ := fwImage(t, 4096, 2048) err := runFlashSelfCloud(cloudFlashGlobals, &flashSelfFlags{}, noFlagChanged, []string{fw}, "benchpod-7a32b5") @@ -212,6 +218,7 @@ func TestFlashSelfCloudTooBigAndDFUFlags(t *testing.T) { } func TestAbortCloudOTA(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t} api := o.start() pod := &cloudpod.Client{API: api, Credential: "tok", DeviceID: "id-1", Name: "benchpod-7a32b5"} @@ -226,6 +233,7 @@ func TestAbortCloudOTA(t *testing.T) { } func TestExplicitCloud(t *testing.T) { + allowAnyPodAPI(t) if name, ok := (&globalFlags{connection: "embeddedci:benchpod-7a32b5"}).explicitCloud(); !ok || name != "benchpod-7a32b5" { t.Errorf("%q %v", name, ok) } diff --git a/cmd/benchpod-cli/flash_self_network.go b/cmd/benchpod-cli/flash_self_network.go index 6f760bd..981c9f8 100644 --- a/cmd/benchpod-cli/flash_self_network.go +++ b/cmd/benchpod-cli/flash_self_network.go @@ -36,7 +36,7 @@ var ( ) // dfuOnlyFlags are the flash-self flags that only mean something for DFU. -var dfuOnlyFlags = []string{"enter-dfu", "no-leave", "dfu-util", "address", "wait"} +var dfuOnlyFlags = []string{"enter-dfu", "no-leave", "dfu-util", "addr", "wait"} // podStatusInfo is what flash-self --network reads from the pod's JSON status. type podStatusInfo struct { @@ -137,9 +137,8 @@ func uploadFirmwareLAN(ctx context.Context, lan lanSession, image, manifest []by if err := lan.cmd(ctx, map[string]any{"cmd": "ota_commit"}, nil); err != nil && !lan.s.Broken() { // A refusal (no verified image, busy, locked, signature policy) comes back as the pod's // error reply. A connection that drops is the pod restarting: the expected end. - if pe, ok := tcpclient.AsPodError(err); ok && !strings.Contains(strings.ToLower(pe.Reason), "timeout") && - !errors.Is(err, context.DeadlineExceeded) { - return fmt.Errorf("commit: %s", pe.Reason) + if _, ok := tcpclient.AsPodError(err); ok && !errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("commit: %w", err) } } return nil @@ -187,7 +186,7 @@ func waitForPodOnNetwork(g *globalFlags, ctx context.Context) (lanSession, strin func runFlashSelfNetwork(g *globalFlags, f *flashSelfFlags, changed func(string) bool, args []string) error { for _, name := range dfuOnlyFlags { if changed(name) { - return fmt.Errorf("--%s is for USB DFU and does not apply with --network", name) + return usageErrorf("--%s is for USB DFU and does not apply with --network", name) } } ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(flashSelfTimeout)) diff --git a/cmd/benchpod-cli/flash_self_network_test.go b/cmd/benchpod-cli/flash_self_network_test.go index 0b7716a..9f00933 100644 --- a/cmd/benchpod-cli/flash_self_network_test.go +++ b/cmd/benchpod-cli/flash_self_network_test.go @@ -85,13 +85,13 @@ func (p *fwNetPod) handle(req map[string]any) (string, bool) { if p.blobErr != "" { return errReply(p.blobErr), false } - return errReply("unknown cmd"), false + return codeReply("BP0002", map[string]any{"cmd": "blob_status"}), false case "ota_begin": if p.refuse != "" { return errReply(p.refuse), false } if _, ok := req["target"]; ok { - return errReply("unknown target"), false + return codeReply("BP0060", map[string]any{"target": req["target"]}), false } p.staged = make([]byte, int(req["size"].(float64))) p.sha, p.state = req["sha256"].(string), "receiving" @@ -114,7 +114,7 @@ func (p *fwNetPod) handle(req map[string]any) (string, bool) { case "ota_abort": p.state = "idle" default: - return errReply("unknown cmd"), false + return codeReply("BP0002", map[string]any{"cmd": cmd}), false } return okReply(map[string]any{"state": p.state}), false } @@ -149,6 +149,7 @@ func fastNetworkFlash(t *testing.T) { func noFlagChanged(string) bool { return false } func TestFlashSelfNetworkUpdates(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048} addr := pod.start() @@ -170,6 +171,7 @@ func TestFlashSelfNetworkUpdates(t *testing.T) { } func TestFlashSelfNetworkVerifyFailureWritesNothing(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, corrupt: true} addr := pod.start() @@ -187,6 +189,7 @@ func TestFlashSelfNetworkVerifyFailureWritesNothing(t *testing.T) { } func TestFlashSelfNetworkPodRefusal(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, refuse: "locked: ota_begin needs the cloud or USB"} addr := pod.start() @@ -198,6 +201,7 @@ func TestFlashSelfNetworkPodRefusal(t *testing.T) { } func TestFlashSelfNetworkImageTooBig(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 1024} addr := pod.start() file, _ := fwImage(t, 2000, 2048) @@ -211,6 +215,7 @@ func TestFlashSelfNetworkImageTooBig(t *testing.T) { } func TestFlashSelfNetworkRefusesDFUFlags(t *testing.T) { + allowAnyPodAPI(t) err := runFlashSelfNetwork(&globalFlags{connection: "127.0.0.1:1"}, &flashSelfFlags{network: true}, func(name string) bool { return name == "enter-dfu" }, nil) if err == nil || !strings.Contains(err.Error(), "--enter-dfu is for USB DFU") { @@ -237,6 +242,7 @@ func blobsDirWith(t *testing.T, names ...string) string { // look like one with nothing to install: flash-self warns, naming the skipped blobs and the // retry, and keeps its exit status (the firmware itself is in). func TestFlashSelfNetworkWarnsWhenBlobStatusFails(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, blobErr: "reply too large"} addr := pod.start() @@ -265,6 +271,7 @@ func TestFlashSelfNetworkWarnsWhenBlobStatusFails(t *testing.T) { // install-blobs (installBlobsList) fails when the pod does not list its slots. func TestInstallBlobsFailsWhenBlobStatusFails(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.10.3", flashKB: 2048, blobErr: "reply too large"} addr := pod.start() ctx := context.Background() @@ -289,6 +296,7 @@ func TestInstallBlobsFailsWhenBlobStatusFails(t *testing.T) { // "unknown cmd" still means firmware with its blobs built in, not a failure. func TestInstallBlobsBuiltInIsNotABlobStatusFailure(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.4.0", flashKB: 2048} addr := pod.start() ctx := context.Background() diff --git a/cmd/benchpod-cli/flash_self_test.go b/cmd/benchpod-cli/flash_self_test.go index b7d31ad..54fdfaa 100644 --- a/cmd/benchpod-cli/flash_self_test.go +++ b/cmd/benchpod-cli/flash_self_test.go @@ -113,29 +113,3 @@ func TestInstallBlobsAfterFlashFailsWhenTheConsoleNeverReturns(t *testing.T) { t.Fatalf("err = %v, want an error naming install-blobs", err) } } - -// After a DFU flash, a pod that does not list its blob slots gets a warning naming the skipped -// blobs and the retry; flash-self keeps its exit status (the firmware itself is in). -func TestInstallBlobsAfterFlashWarnsWhenTheSlotsAreNotListed(t *testing.T) { - oldWait, oldRetry, oldOpen, oldSkip := flashedConsoleWait, flashedConsoleRetry, openFlashedConsole, skipUSBNetForBlobs - t.Cleanup(func() { - flashedConsoleWait, flashedConsoleRetry, openFlashedConsole, skipUSBNetForBlobs = oldWait, oldRetry, oldOpen, oldSkip - }) - skipUSBNetForBlobs = true - openFlashedConsole = func(*globalFlags) (*serialconsole.Console, error) { - return serialconsole.NewConsole(&textConsole{status: " device : benchpod\r\n"}), nil - } - var err error - var installed []blobEntry - out := captureStderr(t, func() { - _, installed, err = installBlobsAfterFlash(&globalFlags{}, blobSource{base: blobsDirWith(t, "gw0", "gw2", "esp")}) - }) - if err != nil || len(installed) != 0 { - t.Fatalf("err = %v, installed = %v; want a warning only", err, installed) - } - for _, want := range []string{"WARNING", "NOT installed: gw0, gw2, esp", "benchpod install-blobs"} { - if !strings.Contains(out, want) { - t.Fatalf("stderr lacks %q:\n%s", want, out) - } - } -} diff --git a/cmd/benchpod-cli/gateware_reload_test.go b/cmd/benchpod-cli/gateware_reload_test.go index 9692527..0605457 100644 --- a/cmd/benchpod-cli/gateware_reload_test.go +++ b/cmd/benchpod-cli/gateware_reload_test.go @@ -160,6 +160,7 @@ func installOnGWPod(t *testing.T, pod *gwPod, version int) string { // The bench case: back from a v55 dev build to a release that carries v54, with the emulation // image running (firmware 3.10.3 does not check after a gw2 install). The CLI reloads image 2. func TestInstallBlobsReloadsStaleGateware(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 2, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}} out := installOnGWPod(t, pod, 54) if pod.running != 54 || pod.kind != 2 { @@ -178,6 +179,7 @@ func TestInstallBlobsReloadsStaleGateware(t *testing.T) { // When the firmware's own check already reloaded the gateware, the CLI only looks. func TestInstallBlobsLeavesMatchingGatewareAlone(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 0, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}, hookFixes: true} out := installOnGWPod(t, pod, 54) if strings.Contains(pod.cmds(), "fpga_image") || strings.Contains(out, "reloading") { @@ -186,6 +188,7 @@ func TestInstallBlobsLeavesMatchingGatewareAlone(t *testing.T) { } func TestInstallBlobsReportsAFailedReload(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 1, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}, failImage: "busy"} out := installOnGWPod(t, pod, 54) if !strings.Contains(out, "the reload failed (busy)") || !strings.Contains(out, "restart the pod (tap RESET) to load gateware v54") { @@ -195,6 +198,7 @@ func TestInstallBlobsReportsAFailedReload(t *testing.T) { // reloadStaleGateware on its own: no reload without a mismatch, or with a version unknown. func TestReloadStaleGatewareOnlyOnAMismatch(t *testing.T) { + allowAnyPodAPI(t) for _, st := range []map[string]any{ {"gateware": 54, "gateware_embedded": 54}, {"gateware": 54}, @@ -216,6 +220,7 @@ func TestReloadStaleGatewareOnlyOnAMismatch(t *testing.T) { } func TestInstalledGateware(t *testing.T) { + allowAnyPodAPI(t) if installedGateware([]blobEntry{{Name: "esp"}}) || !installedGateware([]blobEntry{{Name: "esp"}, {Name: "gw2"}}) { t.Fatal("installedGateware") } diff --git a/cmd/benchpod-cli/generate16_test.go b/cmd/benchpod-cli/generate16_test.go deleted file mode 100644 index 306f65b..0000000 --- a/cmd/benchpod-cli/generate16_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package main - -import ( - "encoding/json" - "testing" -) - -// generate --amplitude-v/--amplitude-ma: the calibrated 16-bit form (firmware 3.9.1+). The CLI -// asks the pod for its caps first, because older firmware would ignore the volts and play its -// default full-scale 8-bit waveform. -func TestGenerateCalibrated(t *testing.T) { - t.Setenv("BENCHPOD_CONNECTION", "") - t.Setenv("BENCHPOD_TIMEOUT", "") - addr, got := fakeLANPod(t, `{"status":"ok","data":{"caps":["dac","generate16"],"bits":16}}`) - sent := func() map[string]any { - t.Helper() - var req map[string]any - if err := json.Unmarshal([]byte(<-got), &req); err != nil { - t.Fatal(err) - } - return req - } - - if code := run([]string{"generate", "--waveform", "sine", "--freq", "1kHz", "--path", "3v3", - "--amplitude-v", "1.48", "--offset-v", "1.65", "--connection", addr}); code != exitOK { - t.Fatalf("volts: exit %d", code) - } - if st := sent(); st["cmd"] != "status" { - t.Fatalf("first request = %v, want status", st) - } - req := sent() - if req["path"] != "3v3" || req["amplitude_v"] != 1.48 || req["offset_v"] != 1.65 { - t.Fatalf("volts request = %v", req) - } - if _, ok := req["amplitude"]; ok { - t.Fatalf("8-bit amplitude sent with volts: %v", req) - } - - if code := run([]string{"generate", "--waveform", "square", "--amplitude-ma", "4", "--offset-ma", "12", - "--connection", addr}); code != exitOK { - t.Fatalf("mA: exit %d", code) - } - sent() - if req := sent(); req["amplitude_ua"] != 4000.0 || req["offset_ua"] != 12000.0 || req["path"] != nil { - t.Fatalf("mA request = %v", req) - } -} - -func TestGenerateCalibratedNeedsFirmware391(t *testing.T) { - t.Setenv("BENCHPOD_CONNECTION", "") - t.Setenv("BENCHPOD_TIMEOUT", "") - addr, got := fakeLANPod(t, `{"status":"ok","data":{"caps":["dac"]}}`) - if code := run([]string{"generate", "--waveform", "sine", "--path", "5v", "--amplitude-v", "0.1", - "--offset-v", "2.5", "--connection", addr}); code == exitOK { - t.Fatal("generate with volts accepted on a pod without generate16") - } - if st := <-got; st != `{"caps":false,"cmd":"status"}` { - t.Fatalf("request = %s", st) - } - select { - case req := <-got: - t.Fatalf("sent %s to a pod without generate16", req) - default: - } -} - -func TestGenerateCalibratedFlagErrors(t *testing.T) { - t.Setenv("BENCHPOD_CONNECTION", "") - for _, args := range [][]string{ - {"--path", "3v3", "--amplitude-v", "1"}, // no offset - {"--path", "ext", "--amplitude-v", "1", "--offset-v", "1"}, // bad path - {"--amplitude-v", "1", "--offset-v", "1"}, // no path - {"--path", "3v3", "--amplitude-v", "1", "--offset-v", "1", "--amplitude", "5"}, // mixed with levels - {"--path", "3v3", "--amplitude-v", "1", "--offset-v", "1", "--amplitude-ma", "4", "--offset-ma", "12"}, - {"--amplitude-ma", "0", "--offset-ma", "12"}, - } { - if code := run(append([]string{"generate", "--waveform", "sine", "--connection", "127.0.0.1:1"}, args...)); code == exitOK { - t.Errorf("%v accepted", args) - } - } -} diff --git a/cmd/benchpod-cli/helpers.go b/cmd/benchpod-cli/helpers.go index f8e1d11..1b9d50a 100644 --- a/cmd/benchpod-cli/helpers.go +++ b/cmd/benchpod-cli/helpers.go @@ -227,7 +227,7 @@ const laPinCount = 14 // parseLAPin parses a logic-analyzer pin reference for SWD wiring. These are no // longer GPIO numbers: they are the pod's LA pins (1-14) that map to the // ice40/FPGA. Accepts an optional "la" prefix, so "la1", "1", "la14", and "14" -// are all valid. LA13/LA14 need pod firmware 3.1 or newer; older firmware rejects them. +// are all valid. func parseLAPin(s string) (int, error) { orig := strings.TrimSpace(s) v := strings.TrimPrefix(strings.ToLower(orig), "la") diff --git a/cmd/benchpod-cli/identity.go b/cmd/benchpod-cli/identity.go index 093d363..daaf6e5 100644 --- a/cmd/benchpod-cli/identity.go +++ b/cmd/benchpod-cli/identity.go @@ -3,6 +3,7 @@ package main import ( "bufio" "context" + "encoding/json" "errors" "fmt" "io" @@ -20,8 +21,10 @@ import ( // // The pod's device identity is an Ed25519 key in its own flash sector. The firmware generates it // once, on a blank sector, and never writes over a record it does not recognize: such a pod stays -// offline and says why. `identity wipe` is the deliberate way back. It runs on the USB console -// only (physical presence); the pod refuses it over the LAN and the cloud. +// offline and says why. `identity wipe` is the deliberate way back. The state comes from the USB +// console's `identity`; the wipe is the JSON identity_wipe over the pod's USB network adapter +// (physical presence; firmware 4.0 has no console identity-wipe). The pod refuses it over the LAN +// and the cloud (BP0043). // // embeddedci.com knows a pod by its public key, so after a wipe the pod is a new pod there: the old // device record keeps its data and its login state, and the pod is registered again as a new @@ -33,10 +36,30 @@ const identityMissing = "this firmware has no identity commands; update the pod' // identityConsole is the part of the USB console the identity commands use. type identityConsole interface { Identity(ctx context.Context) (serialconsole.IdentityState, error) - IdentityWipe(ctx context.Context, token string) (string, error) Close() error } +// wipeIdentity sends identity_wipe with the confirm token over the pod's USB network adapter and +// returns the new short id. A variable so tests can replace it. +var wipeIdentity = func(ctx context.Context, g *globalFlags, device, token string) (string, error) { + addr := g.usbLinkAddr(device, g.usbPodName()) + if addr == "" { + return "", errors.New("the pod's USB network adapter is not up: the pod wipes its identity only over its USB link. " + + usbNetworkOffHint) + } + raw, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "identity_wipe", "confirm": token}) + if err != nil { + return "", err + } + var rep struct { + ShortID string `json:"short_id"` + } + if json.Unmarshal(raw, &rep) != nil || rep.ShortID == "" { + return "", fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) + } + return rep.ShortID, nil +} + // openIdentityConsole opens the pod's USB console; tests replace it with a fake. var openIdentityConsole = func(g *globalFlags, device string, timeout time.Duration) (identityConsole, string, context.Context, context.CancelFunc, error) { console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) @@ -79,10 +102,12 @@ func newIdentityCmd(g *globalFlags) *cobra.Command { var yes bool wipe := &cobra.Command{ Use: "wipe", - Short: "Erase the pod's identity key and make a new one (USB console only)", - Long: "Erase the pod's identity and generate a fresh key, over the pod's USB\n" + - "console (--connection usb or a serial device path). The pod refuses this over the\n" + - "LAN and the cloud: it needs someone at the pod.\n\n" + + Short: "Erase the pod's identity key and make a new one (over USB only)", + Long: "Erase the pod's identity and generate a fresh key, over USB (--connection usb or a\n" + + "serial device path): the CLI reads the identity on the pod's console and sends the\n" + + "wipe over its USB network adapter. The pod refuses this over the LAN and the cloud:\n" + + "it needs someone at the pod. USB networking off: `benchpod usb-network on\n" + + "--connection usb` (the pod's console `usb-network on`).\n\n" + "Use it to recover a pod that reports an unknown identity record, or to retire a\n" + "key. The pod is a NEW pod to embeddedci.com afterwards: deregister the old record\n" + "and register the pod again (the command prints the steps).\n\n" + @@ -137,7 +162,7 @@ func identityErr(what string, err error) error { return errors.New(identityMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } @@ -193,7 +218,7 @@ func runIdentityWipe(g *globalFlags, yes bool, in io.Reader, out io.Writer) erro return errors.New("identity wipe: cancelled, nothing changed") } } - newID, err := console.IdentityWipe(ctx, st.ConfirmToken()) + newID, err := wipeIdentity(ctx, g, device, st.ConfirmToken()) if err != nil { return identityErr("identity wipe", err) } diff --git a/cmd/benchpod-cli/identity_test.go b/cmd/benchpod-cli/identity_test.go index 1c0a5a8..040fe0a 100644 --- a/cmd/benchpod-cli/identity_test.go +++ b/cmd/benchpod-cli/identity_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // fakeIdentityConsole stands in for the pod's USB console. @@ -43,7 +44,11 @@ func withFakeIdentityConsole(t *testing.T, fc *fakeIdentityConsole, tty bool) { return fc, device, context.Background(), func() {}, nil } stdinIsTerminal = func() bool { return tty } - t.Cleanup(func() { openIdentityConsole, stdinIsTerminal = saved, savedTTY }) + savedWipe := wipeIdentity + wipeIdentity = func(ctx context.Context, _ *globalFlags, _, token string) (string, error) { + return fc.IdentityWipe(ctx, token) + } + t.Cleanup(func() { openIdentityConsole, stdinIsTerminal, wipeIdentity = saved, savedTTY, savedWipe }) } func TestIdentityWipeOnlyOverUSB(t *testing.T) { @@ -126,16 +131,39 @@ func TestIdentityWipeNeedsTerminalOrYes(t *testing.T) { func TestIdentityWipeRefusalAndOldFirmware(t *testing.T) { fc := &fakeIdentityConsole{state: serialconsole.IdentityState{ShortID: "a1b2c3"}, - wipeErr: &serialconsole.IdentityError{Cmd: "identity-wipe", Reason: "hardware RNG failed; nothing was erased"}} + wipeErr: &tcpclient.PodError{Reason: "identity_wipe: hardware RNG failed; nothing was erased"}} withFakeIdentityConsole(t, fc, true) err := runIdentityWipe(&globalFlags{connection: "usb"}, true, nil, &bytes.Buffer{}) - if err == nil || err.Error() != "identity wipe: the pod refused: hardware RNG failed; nothing was erased" { + if err == nil || err.Error() != "identity wipe: the pod refused: identity_wipe: hardware RNG failed; nothing was erased" { t.Fatalf("err = %v", err) } - fc.wipeErr = serialconsole.ErrIdentityUnsupported + // Not over the USB link: BP0043. + fc.wipeErr = tcpclient.RefusalError("", "BP0043", map[string]any{"setting": "identity_wipe"}) err = runIdentityWipe(&globalFlags{connection: "usb"}, true, nil, &bytes.Buffer{}) - if err == nil || err.Error() != identityMissing { - t.Fatalf("old firmware: err = %v", err) + if err == nil || !strings.Contains(err.Error(), "BP0043: identity_wipe can only be changed on the device") || exitCode(err) != exitRefused { + t.Fatalf("BP0043: err = %v", err) + } +} + +// The real wipe sends identity_wipe with the confirm token over the USB link. +func TestIdentityWipeSendsJSON(t *testing.T) { + pod, addr := startJSONPod(t, func(req map[string]any) string { + return okReply(map[string]any{"short_id": "d4e5f6"}) + }) + old := localUSBPod + localUSBPod = func(string) string { return addr } + t.Cleanup(func() { localUSBPod = old }) + id, err := wipeIdentity(context.Background(), &globalFlags{connection: "usb"}, "", "a1b2c3") + if err != nil || id != "d4e5f6" { + t.Fatalf("id %q, err %v", id, err) + } + if r := pod.last("identity_wipe"); r["confirm"] != "a1b2c3" { + t.Fatalf("sent %v", r) + } + // No USB link: says how to turn USB networking on. + localUSBPod = func(string) string { return "" } + if _, err := wipeIdentity(context.Background(), &globalFlags{connection: "usb"}, "", "a1b2c3"); err == nil || !strings.Contains(err.Error(), "usb-network on") { + t.Fatalf("no link: err = %v", err) } } diff --git a/cmd/benchpod-cli/lantls.go b/cmd/benchpod-cli/lantls.go index e9929e7..bef5f07 100644 --- a/cmd/benchpod-cli/lantls.go +++ b/cmd/benchpod-cli/lantls.go @@ -20,16 +20,15 @@ import ( // ── lan-tls ───────────────────────────────────────────────────────────────── // -// The pod's LAN API over TLS (firmware 3.9.3+, benchpod-firmware docs/design/lan-tls.md): the -// certificate on port 8443 and the HTTPS-only setting. The client side (TLS by default, pinning) -// is internal/tcpclient/tls.go. +// The pod's LAN API over TLS (benchpod-firmware docs/design/lan-tls.md): the certificate on port +// 8443, the HTTPS-only setting and SCPI. The client side (TLS by default, pinning) is +// internal/tcpclient/tls.go. // -// The pod takes changes (https-only off, regenerate, set-cert) over TLS, over USB and from the -// cloud, never over plaintext Ethernet or Wi-Fi. +// The pod takes changes (https-only, scpi, regenerate, set-cert) over its USB network adapter or +// from the cloud only, never over Ethernet or Wi-Fi (BP0042), TLS or not. const ( - lanTLSMissing = "this pod's firmware has no LAN TLS; update its firmware (3.9.3 or later)" - lanTLSPlainHint = "the pod takes this only over TLS, USB or embeddedci.com, not over plaintext; connect with --tls on, --connection usb or --connection embeddedci:" + lanTLSMissing = "this pod's firmware has no LAN TLS; update its firmware with `benchpod flash-self`" lanTLSMaxUpload = 7664 // the pod's limit on the certificate + key bundle (LAN_TLS_UPLOAD_MAX) ) @@ -37,6 +36,7 @@ const ( type lanTLSReply struct { Port int `json:"port"` HTTPSOnly bool `json:"https_only"` + SCPI bool `json:"scpi"` Sessions int `json:"sessions"` Origin string `json:"origin"` Key string `json:"key"` @@ -67,20 +67,23 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { } root := &cobra.Command{ Use: "lan-tls [show]", - Short: "Show or change the pod's LAN TLS certificate and the HTTPS-only setting", - Long: "The pod serves its API on port 8443 with TLS as well as on plaintext 8080\n" + - "(firmware 3.9.3+). benchpod connects with TLS when the pod has it and pins the\n" + - "pod's certificate the first time (trust on first use, in known_pods.json next to\n" + - "the CLI config). --tls off forces plaintext; --tls-ca verifies a certificate\n" + - "signed by your own CA instead of pinning.\n\n" + - " show the certificate, its SHA-256 and whether it is pinned here\n" + - " https-only on: the pod answers plaintext 8080 only on its USB link\n" + + Short: "Show or change the pod's LAN TLS certificate, HTTPS-only and SCPI", + Long: "Firmware 4.0 serves its API on Ethernet and Wi-Fi on port 8443 with TLS only;\n" + + "plaintext 8080 answers on its USB network adapter. benchpod connects to a LAN pod\n" + + "with TLS and pins the pod's certificate the first time (trust on first use, in\n" + + "known_pods.json next to the CLI config): nothing to set up. --tls-ca verifies a\n" + + "certificate signed by your own CA instead of pinning.\n\n" + + " show the certificate, its SHA-256, the settings and whether it is pinned here\n" + + " https-only on (the default): the LAN takes TLS only; off: plaintext 8080 on the LAN too\n" + + " scpi on: SCPI answers on the pod's TCP ports (off by default)\n" + " regenerate a new key and self-signed certificate\n" + " set-cert install your own certificate and key\n" + " trust pin the certificate the pod presents now\n" + " forget drop the pin for this pod\n\n" + - "Turning HTTPS-only off, regenerating and set-cert need a TLS, USB or\n" + - "embeddedci.com connection: the pod refuses them over plaintext Ethernet or Wi-Fi.", + "https-only, scpi, regenerate and set-cert only work over USB (--connection usb,\n" + + "the pod's USB network adapter) or through embeddedci.com (--connection\n" + + "embeddedci:): the pod refuses them from Ethernet and Wi-Fi, TLS or not. The\n" + + "pod's USB console has the same switches (`lan-tls https-only on|off`, `lan-tls scpi on|off`).", Args: cobra.NoArgs, RunE: show, } @@ -94,8 +97,8 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { Short: "Install your own certificate and private key for port 8443", Long: "Install a certificate (optionally followed by its chain) and its unencrypted\n" + "private key (EC P-256/P-384 or RSA 2048-4096). The pod checks both and that the\n" + - "key matches before it stores them; new TLS connections use it. Over the network\n" + - "only (TLS or the USB network adapter). This computer's pin is updated.", + "key matches before it stores them; new TLS connections use it. Over the pod's USB\n" + + "network adapter only (--connection usb). This computer's pin is updated.", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { return run(func(out, warn io.Writer) error { return runLanTLSSetCert(g, certFile, keyFile, out, warn) }) @@ -116,50 +119,53 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { } trust.Flags().StringVar(&expect, "sha256", "", "only trust a certificate with this SHA-256 (from the pod's console `lan-tls` or the web app)") - root.AddCommand(showCmd, &cobra.Command{ - Use: "https-only ", - Short: "Turn plaintext 8080 off (on) or back on (off) for Ethernet and Wi-Fi", - Args: cobra.ExactArgs(1), - ValidArgs: []string{"on", "off"}, - RunE: func(_ *cobra.Command, args []string) error { - v := strings.ToLower(strings.TrimSpace(args[0])) - if v != "on" && v != "off" { - return fmt.Errorf("lan-tls https-only: %q is not on or off", args[0]) - } - return run(func(out, warn io.Writer) error { - return runLanTLS(g, map[string]any{"https_only": v == "on"}, out, warn) - }) - }, - }, &cobra.Command{ - Use: "regenerate", - Short: "Make a new key and self-signed certificate on the pod", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - return run(func(out, warn io.Writer) error { - return runLanTLS(g, map[string]any{"regenerate": true}, out, warn) - }) - }, - }, setCert, trust, &cobra.Command{ - Use: "forget", - Short: "Drop this computer's pin for the pod", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - return run(func(out, _ io.Writer) error { return runLanTLSForget(g, out) }) - }, - }) + onOffCmd := func(use, key, short string) *cobra.Command { + return &cobra.Command{ + Use: use + " ", + Short: short + " (over USB or embeddedci.com only)", + Args: cobra.ExactArgs(1), + ValidArgs: []string{"on", "off"}, + RunE: func(_ *cobra.Command, args []string) error { + v := strings.ToLower(strings.TrimSpace(args[0])) + if v != "on" && v != "off" { + return usageErrorf("lan-tls %s: %q is not on or off", use, args[0]) + } + return run(func(out, warn io.Writer) error { + return runLanTLS(g, map[string]any{key: v == "on"}, out, warn) + }) + }, + } + } + root.AddCommand(showCmd, + onOffCmd("https-only", "https_only", "Take only TLS on Ethernet and Wi-Fi (on, the default) or plaintext 8080 too (off)"), + onOffCmd("scpi", "scpi", "Turn SCPI on the pod's TCP ports on or off (off by default)"), + &cobra.Command{ + Use: "regenerate", + Short: "Make a new key and self-signed certificate on the pod", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return run(func(out, warn io.Writer) error { + return runLanTLS(g, map[string]any{"regenerate": true}, out, warn) + }) + }, + }, setCert, trust, &cobra.Command{ + Use: "forget", + Short: "Drop this computer's pin for the pod", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return run(func(out, _ io.Writer) error { return runLanTLSForget(g, out) }) + }, + }) return root } // lanTLSError turns a refusal into one clear line. func lanTLSError(what string, err error) error { if pe, ok := tcpclient.AsPodError(err); ok { - r := pe.Reason - switch { - case isUnknownCommand(err): + if isUnknownCommand(err) { return errors.New(lanTLSMissing) - case strings.Contains(r, "change it over TLS"): - return fmt.Errorf("%s: %s", what, lanTLSPlainHint) } + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } @@ -194,9 +200,11 @@ func runLanTLS(g *globalFlags, change map[string]any, out, warn io.Writer) error } } printLanTLS(out, t.label, addr, rep, lastTLS(t)) - if hs, ok := change["https_only"].(bool); ok && hs { - fmt.Fprintln(warn, "Plaintext port 8080 now answers only on the pod's USB link. Tools that need it there:\n"+ - "VISA raw sockets and older benchpod/SDK releases (see the pod's API docs, LAN TLS).") + if hs, ok := change["https_only"].(bool); ok && !hs { + fmt.Fprintln(warn, "Plaintext port 8080 now answers on Ethernet and Wi-Fi too: anyone on the LAN can read and drive the pod without TLS.") + } + if sc, ok := change["scpi"].(bool); ok && sc && rep.HTTPSOnly { + fmt.Fprintln(warn, "SCPI answers on 8443 (TLS) and on plaintext 8080; on the LAN 8080 takes SCPI only while https-only is on.") } return nil } @@ -224,6 +232,7 @@ func printLanTLS(out io.Writer, label, addr string, r lanTLSReply, via string) { fmt.Fprintf(out, "LAN TLS of %s (connected over %s)\n", label, via) fmt.Fprintf(out, " port %d\n", r.Port) fmt.Fprintf(out, " https-only %s\n", onOff[r.HTTPSOnly]) + fmt.Fprintf(out, " scpi %s\n", onOff[r.SCPI]) fmt.Fprintf(out, " sessions %d\n", r.Sessions) if r.SHA256 == "" { fmt.Fprintf(out, " certificate none (%s)\n", valueOr(r.Error, "unknown")) diff --git a/cmd/benchpod-cli/lantls_test.go b/cmd/benchpod-cli/lantls_test.go index 4c54ec6..9669b9a 100644 --- a/cmd/benchpod-cli/lantls_test.go +++ b/cmd/benchpod-cli/lantls_test.go @@ -1,57 +1,58 @@ package main import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" + "encoding/json" + "log" "os" - "path/filepath" "strings" "testing" - "time" ) -func writeCertKey(t *testing.T, dir, name string) (certFile, keyFile string) { - t.Helper() - key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, - NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), DNSNames: []string{name + ".local"}} - der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) - if err != nil { - t.Fatal(err) +// lan-tls scpi and https-only send the lan_tls switches; the LAN refusal (BP0042) says to use USB +// or the cloud. +func TestLanTLSSwitches(t *testing.T) { + t.Setenv("BENCHPOD_CONNECTION", "") + addr, got := fakeLANPod(t, `{"status":"ok","data":{"port":8443,"https_only":true,"scpi":true,"sessions":0,`+ + `"origin":"generated","key":"EC P-256","subject":"CN=benchpod-a1b2c3","sha256":"ab"}}`) + out := t.TempDir() + "/out.txt" + for _, c := range []struct { + args []string + want map[string]any + }{ + {[]string{"lan-tls", "scpi", "on"}, map[string]any{"cmd": "lan_tls", "scpi": true}}, + {[]string{"lan-tls", "https-only", "off"}, map[string]any{"cmd": "lan_tls", "https_only": false}}, + {[]string{"lan-tls"}, map[string]any{"cmd": "lan_tls"}}, + } { + if code := run(append(c.args, "--connection", addr, "--out", out)); code != exitOK { + t.Fatalf("%v: exit %d", c.args, code) + } + var req map[string]any + _ = json.Unmarshal([]byte(<-got), &req) + if len(req) != len(c.want) { + t.Fatalf("%v: sent %v", c.args, req) + } + for k, v := range c.want { + if req[k] != v { + t.Fatalf("%v: sent %v", c.args, req) + } + } } - kder, _ := x509.MarshalECPrivateKey(key) - certFile, keyFile = filepath.Join(dir, name+".pem"), filepath.Join(dir, name+".key") - os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600) - os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kder}), 0o600) - return -} - -func TestCheckCertKey(t *testing.T) { - dir := t.TempDir() - c1, k1 := writeCertKey(t, dir, "pod1") - _, k2 := writeCertKey(t, dir, "pod2") - - bundle, leaf, err := checkCertKey(c1, k1) - if err != nil { - t.Fatalf("matching pair refused: %v", err) + b, _ := os.ReadFile(out) + if !strings.Contains(string(b), " scpi on\n") || !strings.Contains(string(b), " https-only on\n") { + t.Fatalf("show:\n%s", b) } - if leaf.Subject.CommonName != "pod1" { - t.Errorf("leaf = %v", leaf.Subject) + if code := run([]string{"lan-tls", "scpi", "maybe", "--connection", addr}); code != exitUsage { + t.Fatalf("bad value: exit %d", code) } - if !strings.Contains(string(bundle), "BEGIN CERTIFICATE") || !strings.Contains(string(bundle), "BEGIN EC PRIVATE KEY") { - t.Errorf("bundle lacks the certificate or the key:\n%s", bundle) - } - if _, _, err := checkCertKey(c1, k2); err == nil { - t.Error("a key that does not match the certificate was accepted") + + refused, _ := fakeLANPod(t, `{"status":"error","code":"BP0042","args":{"setting":"lan_tls"}}`) + var logged strings.Builder + log.SetOutput(&logged) + defer log.SetOutput(os.Stderr) + if code := run([]string{"lan-tls", "scpi", "on", "--connection", refused}); code != exitRefused { + t.Fatalf("LAN: exit %d", code) } - enc := filepath.Join(dir, "enc.key") - os.WriteFile(enc, []byte("-----BEGIN ENCRYPTED PRIVATE KEY-----\nAAAA\n-----END ENCRYPTED PRIVATE KEY-----\n"), 0o600) - if _, _, err := checkCertKey(c1, enc); err == nil || !strings.Contains(err.Error(), "encrypted") { - t.Errorf("encrypted key: err = %v", err) + if !strings.Contains(logged.String(), "BP0042: lan_tls cannot be changed over the LAN") || !strings.Contains(logged.String(), "--connection usb") { + t.Fatalf("LAN refusal: %s", logged.String()) } } diff --git a/cmd/benchpod-cli/lapins_subset_test.go b/cmd/benchpod-cli/lapins_subset_test.go index 49999fe..919d6b4 100644 --- a/cmd/benchpod-cli/lapins_subset_test.go +++ b/cmd/benchpod-cli/lapins_subset_test.go @@ -3,10 +3,10 @@ package main import ( "context" "encoding/json" - "errors" "reflect" - "strings" "testing" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // fakeLAPins answers la_pins like the firmware: "la" selects pins when subset is true (firmware @@ -23,7 +23,7 @@ func (f *fakeLAPins) Command(_ context.Context, req map[string]any) (json.RawMes has = false } if !has && f.tooLarge { - return nil, errors.New("pod error: reply too large") + return nil, tcpclient.RefusalError("", "BP0053", nil) } var pins []map[string]any for la := 1; la <= 14; la++ { @@ -60,19 +60,13 @@ func TestLAPinsSubset(t *testing.T) { if got := pinNumbers(t, raw); !reflect.DeepEqual(got, []int{3, 9}) { t.Fatalf("pins %v", got) } - // Older firmware ignores "la": the CLI keeps the pins asked for. - f = &fakeLAPins{} - raw, _ = laPinsFetch(context.Background(), f, []int{5}) - if got := pinNumbers(t, raw); !reflect.DeepEqual(got, []int{5}) { - t.Fatalf("old firmware pins %v", got) - } - // Without PINS the request is as before. _, _ = laPinsFetch(context.Background(), f, nil) if last := f.sent[len(f.sent)-1]; !reflect.DeepEqual(last, map[string]any{"cmd": "la_pins"}) { t.Fatalf("plain request %v", last) } } +// A full listing too large for one reply (BP0053) is read in two halves and joined. func TestLAPinsTooLargeReadsInTwoParts(t *testing.T) { f := &fakeLAPins{subset: true, tooLarge: true} raw, err := laPinsFetch(context.Background(), f, nil) @@ -86,11 +80,4 @@ func TestLAPinsTooLargeReadsInTwoParts(t *testing.T) { if len(f.sent) != 3 { t.Fatalf("requests %v", f.sent) } - // Firmware without the subset cannot help: the error stands. - f = &fakeLAPins{tooLarge: true} - _, err = laPinsFetch(context.Background(), f, nil) - if err == nil || !strings.Contains(err.Error(), "reply too large") || - !strings.Contains(err.Error(), "firmware after 3.10.12 reads this list in parts") { - t.Fatalf("want the too-large error with the update hint, got %v", err) - } } diff --git a/cmd/benchpod-cli/lavoltage.go b/cmd/benchpod-cli/lavoltage.go index 8918d81..8f6decf 100644 --- a/cmd/benchpod-cli/lavoltage.go +++ b/cmd/benchpod-cli/lavoltage.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -31,7 +30,7 @@ func newLAVoltageCmd(g *globalFlags) *cobra.Command { "DUT's I/O voltage. The pod refuses LA capture, UART, SWD flash, pull-ups and\n" + "sensor emulation until it is set. 1.8V needs a v3 pod, and the pod refuses a\n" + "change while any LA pin is in use.\n\n" + - "VOLTAGE is 1.8V or 3.3V (also 1800mV, 3.3, or 3300).\n\n" + + "VOLTAGE is 1.8V or 3.3V (also 1800mV, or 3.3: a bare number is volts).\n\n" + "5V (5.0, 5000) works on a pod with the digital board v3r4: pin 21, the pull-up rail,\n" + "goes to 5V and outputs reach 5V through their pull-ups (benchpod la pull PIN up). The\n" + "output then shows pin 21. BP0028: 5V did not come up. Other pods refuse 5000. Details:\n" + @@ -65,21 +64,6 @@ func newLAVoltageCmd(g *globalFlags) *cobra.Command { } } -// laVoltageConsole is the part of the USB console la voltage uses. -type laVoltageConsole interface { - LAVoltage(ctx context.Context, mv int) (int, error) - Close() error -} - -// openLAVoltageConsole opens the pod's USB console; tests replace it with a fake. -var openLAVoltageConsole = func(g *globalFlags, device string, timeout time.Duration) (laVoltageConsole, string, context.Context, context.CancelFunc, error) { - console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) - if err != nil { - return nil, "", nil, cancel, err - } - return console, path, ctx, cancel, nil -} - // laVoltageReply is the pod's JSON answer to la_voltage. type laVoltageReply struct { MV int `json:"mv"` @@ -141,50 +125,12 @@ func runLAVoltage(g *globalFlags, mv int, out, warn io.Writer) error { fmt.Fprintln(warn, "Warning: "+w) } } - if mv != 0 && podStoresWiring(g) { - fmt.Fprintln(out, "Not saved: the pod uses the I/O voltage in its wiring profile after a restart (change it there with `benchpod wiring save`, or in the Pins pane).") - return nil - } if mv != 0 { - if id := accountDeviceForConnection(g); id != "" { - changed, err := saveLaMVToProfile(id, rep.MV) - switch { - case err != nil: - fmt.Fprintf(warn, "Warning: could not save it to the pod's wiring profile on embeddedci.com: %v\n", err) - case changed: - fmt.Fprintln(out, "Saved to the pod's wiring profile on embeddedci.com (applied on every connect).") - } - } + fmt.Fprintln(out, "Not saved: the pod uses the I/O voltage in its wiring profile after a restart (change it there with `benchpod wiring save`, or in the Pins pane).") } return nil } -// accountDeviceForConnection returns the cloud device id of the pod behind g's network or -// embeddedci.com connection when this machine is signed in and the pod is registered to that -// account, so its wiring profile can be written; "" otherwise (also over USB, and whenever it -// cannot tell). It never prompts or fails. A variable so tests can replace it. -var accountDeviceForConnection = func(g *globalFlags) string { - spec, err := g.resolveTarget() - if err != nil { - return "" - } - if spec = g.preferUSBNetwork(spec, "la voltage"); spec.IsSerial() { - return "" - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - api := newServerAPI(cloudServerURL()) - cred, err := cloudCredential(ctx, api) - if err != nil { - return "" - } - id, err := cloudDeviceID(ctx, api, cred, spec) - if err != nil { - return "" - } - return id -} - // saveLaMVToProfile stores mv as la_mv in the wiring profile of the pod with this cloud device id // on embeddedci.com (read-modify-write: every other field is kept). changed is false when the // profile already had it. A variable so tests can replace it. @@ -208,28 +154,12 @@ func laVoltageDo(g *globalFlags, mv int) (string, laVoltageReply, error) { if err != nil { return "", laVoltageReply{}, err } - spec = g.preferUSBNetwork(spec, what) var rep laVoltageReply if spec.IsSerial() { - console, path, ctx, cancel, err := openLAVoltageConsole(g, spec.Device, g.effectiveTimeout(15*time.Second)) - if err != nil { + // Over USB: the pod's USB network adapter (podClient says why when it is not usable). + if _, err := g.networkTarget(what); err != nil { return "", rep, err } - defer cancel() - defer console.Close() - rep.MV, err = console.LAVoltage(ctx, mv) - if errors.Is(err, serialconsole.ErrMovedToNetwork) || - (errors.Is(err, serialconsole.ErrUnknownCommand) && consoleHasUSBNet(ctx, console)) { - // Firmware 3.9.0+ moved la-voltage from the console to the JSON API; preferUSBNetwork - // already found the USB network unusable, so say why. - _, nerr := g.networkTarget(what) - return "", rep, fmt.Errorf("%s: this pod's console has no la-voltage (firmware 3.9.0+ sets it over the "+ - "network API) and its USB network is not usable: %v", what, nerr) - } - if err != nil { - return "", rep, laVoltageError(what, err) - } - return "the pod on " + path, rep, nil } ctx, cancel, pod, err := g.podClient(what, 15*time.Second) if err != nil { @@ -262,31 +192,15 @@ func laVoltageLAN(ctx context.Context, client podCommander, mv int) (laVoltageRe // laVoltageError says when the firmware is too old, and leaves other refusals to the pod. func laVoltageError(what string, err error) error { - if errors.Is(err, serialconsole.ErrUnknownCommand) { - return errors.New(laVoltageMissing) - } if pe, ok := tcpclient.AsPodError(err); ok { if isUnknownCommand(err) { return errors.New(laVoltageMissing) } - return refusedError(what, pe, pe.Cmd == "") + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } -// consoleHasUSBNet: the pod's console reports a USB network adapter (firmware 3.9.0+), which -// tells a console that moved a command to the JSON API from one too old to have it. -func consoleHasUSBNet(ctx context.Context, c laVoltageConsole) bool { - u, ok := c.(interface { - USBNetwork(context.Context) (serialconsole.USBNet, error) - }) - if !ok { - return false - } - _, err := u.USBNetwork(ctx) - return err == nil -} - // formatMV is 3300 -> "3.3 V". func formatMV(mv int) string { return strings.TrimSuffix(strings.TrimRight(fmt.Sprintf("%.3f", float64(mv)/1000), "0"), ".") + " V" diff --git a/cmd/benchpod-cli/lavoltage_test.go b/cmd/benchpod-cli/lavoltage_test.go index 674821f..8de7868 100644 --- a/cmd/benchpod-cli/lavoltage_test.go +++ b/cmd/benchpod-cli/lavoltage_test.go @@ -2,63 +2,23 @@ package main import ( "bytes" - "context" - "errors" "strings" "testing" - "time" - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" ) -// stubLAVoltageProfile replaces the embeddedci.com side of `la voltage` for one test: id is the -// device the connection resolves to on the signed-in account ("" = not on it), and the returned -// slice records each save. -func stubLAVoltageProfile(t *testing.T, id string, changed bool, err error) *[]int { +// stubLAVoltageProfile records any save to embeddedci.com (la voltage makes none: the pod keeps +// the I/O voltage in its own wiring profile). +func stubLAVoltageProfile(t *testing.T, _ string, _ bool, _ error) *[]int { t.Helper() - savedAcct, savedSave := accountDeviceForConnection, saveLaMVToProfile - t.Cleanup(func() { accountDeviceForConnection, saveLaMVToProfile = savedAcct, savedSave }) + saved := saveLaMVToProfile + t.Cleanup(func() { saveLaMVToProfile = saved }) var saves []int - accountDeviceForConnection = func(*globalFlags) string { return id } - saveLaMVToProfile = func(dev string, mv int) (bool, error) { - if dev != id { - t.Errorf("saved to %q, want %q", dev, id) - } - saves = append(saves, mv) - return changed, err - } + saveLaMVToProfile = func(_ string, mv int) (bool, error) { saves = append(saves, mv); return true, nil } return &saves } -func TestLAVoltageSavesToTheProfile(t *testing.T) { - addr, _ := fakeLANPod(t, `{"status":"ok","data":{"mv":3300,"st":1,"readback_mv":3300}}`) - saves := stubLAVoltageProfile(t, "dev-1", true, nil) - var out, warn bytes.Buffer - if err := runLAVoltage(&globalFlags{connection: addr}, 3300, &out, &warn); err != nil { - t.Fatal(err) - } - if len(*saves) != 1 || (*saves)[0] != 3300 || !strings.Contains(out.String(), "Saved to the pod's wiring profile on embeddedci.com") { - t.Fatalf("saves %v out %q", *saves, out.String()) - } - // A failed save warns; the command still succeeds. - addr, _ = fakeLANPod(t, `{"status":"ok","data":{"mv":3300,"st":1,"readback_mv":3300}}`) - stubLAVoltageProfile(t, "dev-1", false, errors.New("403 forbidden")) - out.Reset() - if err := runLAVoltage(&globalFlags{connection: addr}, 3300, &out, &warn); err != nil { - t.Fatal(err) - } - if !strings.Contains(warn.String(), "could not save it to the pod's wiring profile on embeddedci.com: 403 forbidden") { - t.Fatalf("warn %q", warn.String()) - } - // Showing the voltage never writes the profile. - addr, _ = fakeLANPod(t, `{"status":"ok","data":{"mv":3300,"st":1,"readback_mv":3300}}`) - saves = stubLAVoltageProfile(t, "dev-1", true, nil) - if err := runLAVoltage(&globalFlags{connection: addr}, 0, &bytes.Buffer{}, &bytes.Buffer{}); err != nil || len(*saves) != 0 { - t.Fatalf("err %v saves %v", err, *saves) - } -} - func TestLAVoltageLAN(t *testing.T) { stubLAVoltageProfile(t, "", false, nil) addr, got := fakeLANPod(t, `{"status":"ok","data":{"mv":3300,"st":1,"readback_mv":3300}}`) @@ -70,7 +30,7 @@ func TestLAVoltageLAN(t *testing.T) { if req := <-got; req != `{"cmd":"la_voltage","mv":3300}` { t.Fatalf("request = %s", req) } - if want := "LA voltage of " + addr + " is now 3.3 V\n"; out.String() != want || warn.Len() != 0 { + if want := "LA voltage of " + addr + " is now 3.3 V\n"; !strings.HasPrefix(out.String(), want) || warn.Len() != 0 { t.Fatalf("out = %q, warn = %q", out.String(), warn.String()) } @@ -104,10 +64,9 @@ func TestLAVoltageLANRefusals(t *testing.T) { t.Fatalf("old firmware: %v", err) } } - msg := fwrefusals.Example("lan_locked") - addr, _ := fakeLANPod(t, `{"status":"error","message":"`+msg+`"}`) + addr, _ := fakeLANPod(t, `{"status":"error","code":"BP0040","args":{"cmd":"la_voltage"}}`) err := runLAVoltage(&globalFlags{connection: addr}, 3300, &bytes.Buffer{}, &bytes.Buffer{}) - if err == nil || err.Error() != "la voltage: the pod refused: "+msg+" ("+lockedUSBHint+")" { + if err == nil || !strings.HasPrefix(err.Error(), "la voltage: the pod refused: BP0040: The pod's LAN is locked: la_voltage needs the cloud or USB; run this over USB") { t.Fatalf("locked: %v", err) } if code := exitCode(err); code != exitRefused { @@ -115,54 +74,28 @@ func TestLAVoltageLANRefusals(t *testing.T) { } } -type fakeLAVoltageConsole struct { - mv int - err error - set []int -} - -func (f *fakeLAVoltageConsole) LAVoltage(_ context.Context, mv int) (int, error) { - f.set = append(f.set, mv) - if f.err != nil { - return 0, f.err - } - if mv != 0 { - f.mv = mv - } - return f.mv, nil -} -func (f *fakeLAVoltageConsole) Close() error { return nil } - +// Over USB la voltage goes over the pod's USB network adapter; without it, it says why. func TestLAVoltageUSB(t *testing.T) { stubLAVoltageProfile(t, "", false, nil) - fc := &fakeLAVoltageConsole{} - saved := openLAVoltageConsole - t.Cleanup(func() { openLAVoltageConsole = saved }) - openLAVoltageConsole = func(_ *globalFlags, device string, _ time.Duration) (laVoltageConsole, string, context.Context, context.CancelFunc, error) { - return fc, "/dev/cu.usbmodem1", context.Background(), func() {}, nil - } + addr, got := fakeLANPod(t, `{"status":"ok","data":{"mv":1800,"st":1,"readback_mv":1800}}`) var out bytes.Buffer - if err := runLAVoltage(&globalFlags{connection: "usb"}, 1800, &out, &bytes.Buffer{}); err != nil { + if err := runLAVoltage(&globalFlags{connection: "usb", usbAddr: addr}, 1800, &out, &bytes.Buffer{}); err != nil { t.Fatal(err) } - if out.String() != "LA voltage of the pod on /dev/cu.usbmodem1 is now 1.8 V\n" || len(fc.set) != 1 || fc.set[0] != 1800 { - t.Fatalf("out = %q, set = %v", out.String(), fc.set) + if !strings.HasPrefix(out.String(), "LA voltage of "+addr+" is now 1.8 V\n") { + t.Fatalf("out = %q", out.String()) } - - fc.err = &serialconsole.CommandError{Cmd: "la-voltage", Reason: "1.8 V needs a v3 pod; this board is v2 (its TPS2116 has no 1.8 V setting)"} - err := runLAVoltage(&globalFlags{connection: "usb"}, 1800, &bytes.Buffer{}, &bytes.Buffer{}) - if err == nil || err.Error() != "la voltage: the pod refused: "+fc.err.(*serialconsole.CommandError).Reason { - t.Fatalf("refusal: %v", err) + if req := <-got; !strings.Contains(req, `"cmd":"la_voltage"`) || !strings.Contains(req, `"mv":1800`) { + t.Fatalf("request %s", req) } - fc.err = serialconsole.ErrUnknownCommand - if err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}); err == nil || err.Error() != laVoltageMissing { - t.Fatalf("old firmware: %v", err) + old := usbNetwork + usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { + return serialconsole.USBNet{PodIP: "10.237.8.85", HostIP: "10.237.8.86", OffBySetting: true}, nil } - // A 3.9.0 console moved la-voltage to the network API, and the USB network was not usable. - fc.err = serialconsole.ErrMovedToNetwork - if err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}); err == nil || - !strings.Contains(err.Error(), "network API") || !strings.Contains(err.Error(), "USB network is not usable") { - t.Fatalf("3.9.0 console without a usable USB network: %v", err) + t.Cleanup(func() { usbNetwork = old }) + err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "usb-network on") { + t.Fatalf("no USB network: %v", err) } } @@ -178,9 +111,6 @@ func TestLAVoltageArgIsAUsageError(t *testing.T) { func TestLAVoltageSavesNothingWhenThePodStoresProfiles(t *testing.T) { addr, _ := fakeLANPod(t, `{"status":"ok","data":{"mv":3300,"st":1,"readback_mv":3300}}`) saves := stubLAVoltageProfile(t, "dev-1", true, nil) - saved := podStoresWiring - t.Cleanup(func() { podStoresWiring = saved }) - podStoresWiring = func(*globalFlags) bool { return true } var out, warn bytes.Buffer if err := runLAVoltage(&globalFlags{connection: addr}, 3300, &out, &warn); err != nil { t.Fatal(err) diff --git a/cmd/benchpod-cli/newerpod_test.go b/cmd/benchpod-cli/newerpod_test.go index e2b56b2..3b2b31b 100644 --- a/cmd/benchpod-cli/newerpod_test.go +++ b/cmd/benchpod-cli/newerpod_test.go @@ -16,21 +16,21 @@ func TestAllowsNewerPod(t *testing.T) { return c } for _, name := range []string{"status", "flash-self", "install-blobs", "dfu", "bootsel", "discover", "identity"} { - if !allowsNewerPod(sub(name, root)) { + if !allowsAnyPodAPI(sub(name, root)) { t.Errorf("%s: want allowed", name) } } for _, name := range []string{"uart", "la", "power"} { - if allowsNewerPod(sub(name, root)) { + if allowsAnyPodAPI(sub(name, root)) { t.Errorf("%s: want stopped", name) } } // A nested "status" (sensor status, bus status) is not the top-level status. sensor := sub("sensor", root) - if allowsNewerPod(sub("status", sensor)) { + if allowsAnyPodAPI(sub("status", sensor)) { t.Error("sensor status: want stopped") } - if allowsNewerPod(root) { + if allowsAnyPodAPI(root) { t.Error("root: want stopped") } } diff --git a/cmd/benchpod-cli/podclient.go b/cmd/benchpod-cli/podclient.go index 63c5432..f60257c 100644 --- a/cmd/benchpod-cli/podclient.go +++ b/cmd/benchpod-cli/podclient.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "log" - "net/http" "os" "strings" "time" @@ -216,60 +215,18 @@ const wiringSource = "the pod's wiring profile" // that has its flags anyway. const wiringLookupTimeout = 6 * time.Second -// loadPodWiring returns the wiring profile of the pod behind g's connection, or nil when there is -// none to use: over USB, without a sign-in, for a pod not on the account, or when the lookup -// fails (then it writes one warning line to warn). A variable so tests can replace it. +// loadPodWiring returns the wiring profile stored on the pod behind g's connection +// (--wiring-profile, else its default), or nil when there is none to use. A variable so tests can +// replace it. (Firmware before 3.10.8 kept the profile on embeddedci.com; CLI 0.10 reads the pod's.) var loadPodWiring = func(g *globalFlags, warn io.Writer) *podWiring { // Firmware that stores profiles: the pod's own (--wiring-profile, else its default). if w, ok := loadPodWiringFromPod(g, warn); ok { return w } if g.wiringProfile != "" { - fmt.Fprintf(warn, "Warning: --wiring-profile %s: %v; using the flags only\n", g.wiringProfile, errNoWiringStore) - return nil + fmt.Fprintf(warn, "Warning: --wiring-profile %s: could not read the pod's wiring profiles; using the flags only\n", g.wiringProfile) } - spec, err := g.resolveTarget() - if err != nil { - return nil - } - if spec = g.preferUSBNetwork(spec, "wiring"); spec.IsSerial() { - return nil - } - ctx, cancel := context.WithTimeout(context.Background(), wiringLookupTimeout) - defer cancel() - api := newServerAPI(cloudServerURL()) - cred, err := cloudCredential(ctx, api) - if err != nil { - if !errors.Is(err, errNoCloudCredential) { - fmt.Fprintf(warn, "Warning: could not read the pod's wiring profile from embeddedci.com (%v); using the flags only\n", err) - } - return nil - } - id, err := cloudDeviceID(ctx, api, cred, spec) - if err != nil { - fmt.Fprintf(warn, "Warning: could not read the pod's wiring profile from embeddedci.com (%v); using the flags only\n", err) - return nil - } - if id == "" { - log.Printf("wiring: the pod is not on the signed-in account; using the flags only") - return nil - } - raw, err := api.GetDeviceWiringProfile(ctx, cred, id) - var apiErr *serverapi.APIError - if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound { - raw, err = api.GetDeviceWiring(ctx, cred, id) // a server without the profile route - } - if err != nil { - fmt.Fprintf(warn, "Warning: could not read the pod's wiring profile from embeddedci.com (%v); using the flags only\n", err) - return nil - } - b, _ := json.Marshal(raw) - var w podWiring - if err := json.Unmarshal(b, &w); err != nil { - fmt.Fprintf(warn, "Warning: the pod's wiring profile on embeddedci.com does not parse (%v); using the flags only\n", err) - return nil - } - return &w + return nil } // cloudDeviceID is the pod's id on embeddedci.com when it is on the credential's account, else diff --git a/cmd/benchpod-cli/podclient_test.go b/cmd/benchpod-cli/podclient_test.go index 25ed5ab..e29d694 100644 --- a/cmd/benchpod-cli/podclient_test.go +++ b/cmd/benchpod-cli/podclient_test.go @@ -36,6 +36,9 @@ func TestMain(m *testing.M) { // Requests compare whole: without client_api and client (TestEveryRequestCarriesTheClientFields // turns them on). tcpclient.SetClientFields(false) + // Fake pods answer status without an api: no API probe before their commands + // (TestAPIProbe turns it on). + apiProbe = false // Never probe this machine's USB ports for a pod's USB network adapter. usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { return serialconsole.USBNet{}, errors.New("no pod on USB (tests)") @@ -122,7 +125,7 @@ func podReplies(replies map[string]string) func(map[string]any) (int, string) { func runOut(t *testing.T, args ...string) (int, string) { t.Helper() out := filepath.Join(t.TempDir(), "out.txt") - code := run(append(args, "--output-filename", out)) + code := run(append(args, "--out", out)) b, _ := os.ReadFile(out) return code, string(b) } @@ -134,11 +137,11 @@ func TestCloudPingStatusAndLAVoltage(t *testing.T) { f := &fakeCloud{reply: podReplies(map[string]string{ "ping": `"pong"`, - "status": `{"version":"3.8.0","ip":"192.168.1.220","net":"eth","la_vccio_mv":3300,"gateware":48}`, + "status": `{"version":"4.0.0","ip":"192.168.1.220","net":"eth","la_vccio_mv":3300,"gateware":48,"api":2,"min_client_api":2}`, "cloud_status": `{"state":"connected","configured":true,"device_id":"id-1"}`, - "target_status": `{"efuse1":{"enabled":1,"fault":0},"efuse2":{"enabled":0,"fault":0}}`, + "target_status": `{"efuse1":{"enabled":true,"fault":false},"efuse2":{"enabled":false,"fault":false}}`, "la_voltage": `{"mv":3300,"readback_mv":3300}`, - "la": `{"pullups":0}`, + "la_pull": `{"pullups":0}`, })} f.start(t) conn := "embeddedci:bench-1" @@ -150,7 +153,7 @@ func TestCloudPingStatusAndLAVoltage(t *testing.T) { if code != exitOK { t.Fatalf("status: exit %d", code) } - for _, want := range []string{"BenchPod bench-1 on embeddedci.com", "3.8.0", "3.3 V", "internal 5 V on", "on your account as bench-1"} { + for _, want := range []string{"BenchPod bench-1 on embeddedci.com", "4.0.0", "3.3 V", "internal 5 V on", "on your account as bench-1"} { if !strings.Contains(out, want) { t.Errorf("status output lacks %q:\n%s", want, out) } @@ -302,70 +305,6 @@ func TestCloudProxyAndCA(t *testing.T) { // ── wiring profile ────────────────────────────────────────────────────────── -func TestWiringProfileOverCloud(t *testing.T) { - f := &fakeCloud{profile: `{"swd_swclk":11,"swd_swdio":12,"swd_nreset":true,"swd_target":"target/stm32f4x.cfg","spi_sclk":3,"spi_mosi":4,"spi_miso":5,"spi_cs":null}`} - f.start(t) - var warn bytes.Buffer - w := loadPodWiring(&globalFlags{connection: "embeddedci:bench-1"}, &warn) - if w == nil || *w.SwdSwclk != 11 || *w.SwdSwdio != 12 || !*w.SwdNreset || w.SwdTarget != "target/stm32f4x.cfg" || w.SpiCs != nil { - t.Fatalf("wiring %+v (warn %q)", w, warn.String()) - } - - // A server without the profile route: the stored map. - f2 := &fakeCloud{stored: `{"swd_swclk":7}`} - f2.start(t) - w = loadPodWiring(&globalFlags{connection: "embeddedci:bench-1"}, &warn) - if w == nil || *w.SwdSwclk != 7 || w.SwdSwdio != nil { - t.Fatalf("stored fallback %+v", w) - } - if warn.Len() != 0 { - t.Errorf("warned: %q", warn.String()) - } -} - -// Over the network the pod's cloud_status names its id, which must be on the account. -func TestWiringProfileOverNetwork(t *testing.T) { - f := &fakeCloud{profile: `{"swd_swclk":11,"swd_swdio":12,"swd_nreset":false}`} - f.start(t) - for id, want := range map[string]bool{"id-1": true, "id-other": false} { - addr := fakeCloudStatusPod(t, id) - var warn bytes.Buffer - w := loadPodWiring(&globalFlags{connection: addr}, &warn) - if (w != nil) != want { - t.Errorf("device %s: wiring %+v, want found=%v", id, w, want) - } - if warn.Len() != 0 { - t.Errorf("device %s: warned %q", id, warn.String()) - } - } - // Not signed in: no lookup, no warning. - t.Setenv("BENCHPOD_API_KEY", "") - var warn bytes.Buffer - if w := loadPodWiring(&globalFlags{connection: fakeCloudStatusPod(t, "id-1")}, &warn); w != nil || warn.Len() != 0 { - t.Errorf("signed out: %+v, %q", w, warn.String()) - } - // USB: never. - if w := loadPodWiring(&globalFlags{connection: "usb"}, &warn); w != nil { - t.Errorf("usb: %+v", w) - } -} - -func TestWiringProfileFailureWarnsOnce(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - defer ts.Close() - t.Setenv("BENCHPOD_API_BASE", ts.URL) - t.Setenv("BENCHPOD_API_KEY", "eci_test") - var warn bytes.Buffer - if w := loadPodWiring(&globalFlags{connection: "embeddedci:bench-1"}, &warn); w != nil { - t.Fatalf("wiring %+v", w) - } - if n := strings.Count(warn.String(), "\n"); n != 1 || !strings.Contains(warn.String(), "using the flags only") { - t.Errorf("warn = %q", warn.String()) - } -} - func TestFlashTakesSWDFromWiringFlagsWin(t *testing.T) { old := loadPodWiring t.Cleanup(func() { loadPodWiring = old }) @@ -417,3 +356,12 @@ func fakeCloudStatusPod(t *testing.T, id string) string { }() return ln.Addr().String() } + +// allowAnyPodAPI is what the root command does for the firmware commands (flash-self, +// install-blobs, status, ...): they run against a pod of any API level, a 3.x one included. For +// tests that call such a command's code directly. +func allowAnyPodAPI(t *testing.T) { + t.Helper() + tcpclient.SetAllowAnyPodAPI(true) + t.Cleanup(func() { tcpclient.SetAllowAnyPodAPI(false) }) +} diff --git a/cmd/benchpod-cli/policy.go b/cmd/benchpod-cli/policy.go index e001e19..42a6527 100644 --- a/cmd/benchpod-cli/policy.go +++ b/cmd/benchpod-cli/policy.go @@ -23,8 +23,8 @@ import ( // // - lan-policy: open | locked | off. Settable from the cloud and the USB console, never from // the LAN itself. -// - sig-policy: audit < permissive < required. The cloud may only make it stricter; the USB -// console may set anything. The LAN can never change it. +// - sig-policy: always required from firmware 4.0 (signatures cannot be loosened; BP0074), so +// the CLI only shows it (with the number of trusted keys). // // The target follows the CLI's conventions: --device-name / --device-id or --connection // embeddedci: go through embeddedci.com (like deregister), otherwise --connection picks the @@ -36,11 +36,14 @@ type podPolicy struct { jsonCmd string // the pod's JSON verb, e.g. "lan_policy" title string // "LAN policy", starts a sentence noun string // "LAN policy", inside a sentence - values []string // in order of strictness for sig-policy + values []string // the values set takes; none: show only meaning map[string]string // one-line explanation of each value missing string // what to say when the pod's firmware lacks the policy } +// settable says the policy has a set subcommand. +func (p podPolicy) settable() bool { return len(p.values) > 1 } + var lanPolicy = podPolicy{ cmd: "lan-policy", jsonCmd: "lan_policy", @@ -60,11 +63,9 @@ var sigPolicy = podPolicy{ jsonCmd: "sig_policy", title: "Signature policy", noun: "signature policy", - values: []string{"audit", "permissive", "required"}, + values: []string{"required"}, meaning: map[string]string{ - "audit": "every image is accepted; signatures are only reported", - "permissive": "unsigned images are accepted, a bad signature is refused", - "required": "unsigned images are refused", + "required": "only signed images are installed", }, missing: "this firmware has no signature policy; update the pod's firmware", } @@ -114,15 +115,14 @@ func newLanPolicyCmd(g *globalFlags) *cobra.Command { func newSigPolicyCmd(g *globalFlags) *cobra.Command { return newPolicyCmd(g, sigPolicy, - "Show or set the pod's signature policy (audit, permissive, required)", - "Show or set how the pod treats firmware and blob signatures.\n\n"+ - " audit every image is accepted; signatures are only reported\n"+ - " permissive unsigned images are accepted, a bad signature is refused\n"+ - " required unsigned images are refused\n\n"+ - "Over the cloud (--device-name, --device-id or --connection embeddedci:)\n"+ - "the policy can only be made stricter, and only by an organization owner or\n"+ - "admin. Only the USB console (--connection usb) can loosen it. The LAN can only\n"+ - "show it.") + "Show the pod's signature policy (always required)", + "Show how the pod treats firmware and blob signatures, and how many release keys\n"+ + "it trusts. Firmware 4.0 installs only signed images on every path (LAN, USB and\n"+ + "the cloud): the policy is always required and cannot be loosened (BP0074).\n"+ + "Install firmware you built yourself over USB DFU (`benchpod flash-self` with a\n"+ + "local .bin).\n\n"+ + "Over the cloud (--device-name, --device-id or --connection embeddedci:), over\n"+ + "USB (the pod's USB network adapter) or over the LAN.") } func newPolicyCmd(g *globalFlags, p podPolicy, short, long string) *cobra.Command { @@ -149,13 +149,16 @@ func newPolicyCmd(g *globalFlags, p podPolicy, short, long string) *cobra.Comman Short: "Show the pod's " + p.noun, Args: cobra.NoArgs, RunE: show, - }, &cobra.Command{ - Use: "set <" + strings.Join(p.values, "|") + ">", - Short: "Set the pod's " + p.noun, - Args: cobra.ExactArgs(1), - ValidArgs: p.values, - RunE: func(_ *cobra.Command, args []string) error { return run(args[0]) }, }) + if p.settable() { + root.AddCommand(&cobra.Command{ + Use: "set <" + strings.Join(p.values, "|") + ">", + Short: "Set the pod's " + p.noun, + Args: cobra.ExactArgs(1), + ValidArgs: p.values, + RunE: func(_ *cobra.Command, args []string) error { return run(args[0]) }, + }) + } pf := root.PersistentFlags() pf.StringVar(&t.serverURL, "server-url", "https://www.embeddedci.com", "embeddedci-server base URL") pf.StringVar(&t.tokenFile, "token-file", "", "path to token cache (default: ~/.config/benchpod-cli/token.json)") @@ -170,11 +173,11 @@ func runPolicy(g *globalFlags, p podPolicy, t policyTarget, set string, out, war t.deviceName = strings.TrimSpace(t.deviceName) t.deviceID = strings.TrimSpace(t.deviceID) set = strings.ToLower(strings.TrimSpace(set)) - if set != "" && !p.valid(set) { - return fmt.Errorf("%s set: %q is not a policy; use one of %s", p.cmd, set, strings.Join(p.values, ", ")) + if set != "" && (!p.settable() || !p.valid(set)) { + return usageErrorf("%s set: %q is not a policy; use one of %s", p.cmd, set, strings.Join(p.values, ", ")) } if t.deviceName != "" && t.deviceID != "" { - return errors.New("pass only one of --device-name or --device-id") + return usageErrorf("pass only one of --device-name or --device-id") } if t.cloud() { return runPolicyCloud(g, p, t, set, out, warn) @@ -196,14 +199,22 @@ func runPolicy(g *globalFlags, p podPolicy, t policyTarget, set string, out, war return runPolicyCloud(g, p, t, set, out, warn) } if spec.IsSerial() { - // Showing is a read the pod's USB network link answers (firmware 3.9.0+), with no - // console: a Linux user outside the dialout group cannot open it. Changes stay on the + // Showing is a read the pod's USB network link answers, with no console: a Linux user + // outside the dialout group cannot open it. The signature policy is on the network API + // only (firmware 4.0 has no console sig-policy). Changing the LAN policy stays on the // console (physical presence). if set == "" && spec.Device == "" { if addr := localUSBPod(spec.Pod); addr != "" { return runPolicyLAN(g, p, addr, out) } } + if p.cmd == sigPolicy.cmd { + nt, err := g.networkTarget(p.cmd) + if err != nil { + return err + } + return runPolicyLAN(g, p, nt.Addr, out) + } return runPolicyUSB(g, p, spec.Device, set, out, warn) } if set != "" { @@ -237,7 +248,7 @@ func warnLanOff(warn io.Writer) { func runPolicyCloud(g *globalFlags, p podPolicy, t policyTarget, set string, out, warn io.Writer) error { if strings.TrimSpace(t.serverURL) == "" { - return errors.New("--server-url cannot be empty") + return usageErrorf("--server-url cannot be empty") } tokenPath, err := resolveTokenPath(t.tokenFile) if err != nil { @@ -293,7 +304,7 @@ func runPolicyCloud(g *globalFlags, p podPolicy, t policyTarget, set string, out const adminNeeded = "this needs an organization owner or admin (API keys: the benchpod:admin scope)" // cloudPolicyError turns a failed policy call into one clear line: the server's or pod's own -// message, plus the USB way out when the cloud refused to loosen the signature policy. +// message, or a coded refusal of the pod's worded from the catalog. func cloudPolicyError(p podPolicy, set string, err error) error { what := p.cmd if set != "" { @@ -313,10 +324,11 @@ func cloudPolicyError(p podPolicy, set string, err error) error { if msg == "" { return fmt.Errorf("%s: %w", what, err) } - // "loosen": no code yet (sig_policy's "only the USB console can loosen the policy") - if set != "" && p.cmd == sigPolicy.cmd && strings.Contains(strings.ToLower(msg), "loosen") { - return relayedRefusal(p, fmt.Sprintf("%s: the pod refused: %s. Loosen it over the pod's USB console: benchpod sig-policy set %s --connection usb", - what, msg, set), msg) + // A refusal the pod sent with a code, relayed by the server: worded from the catalog. + if strings.HasPrefix(strings.ToUpper(apiErr.Code), "BP") { + if pe, ok := tcpclient.AsPodError(tcpclient.RefusalError(msg, apiErr.Code, nil)); ok { + return refusedError(what, pe) + } } if set != "" { return relayedRefusal(p, what+": the pod refused: "+msg, msg) @@ -376,7 +388,7 @@ func runPolicyUSB(g *globalFlags, p podPolicy, device, set string, out, warn io. return errors.New(p.missing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/policy_test.go b/cmd/benchpod-cli/policy_test.go index fb9181a..24f8e83 100644 --- a/cmd/benchpod-cli/policy_test.go +++ b/cmd/benchpod-cli/policy_test.go @@ -81,7 +81,7 @@ func runPolicyCapture(t *testing.T, g *globalFlags, p podPolicy, target policyTa } func TestPolicyCloudShowAndSet(t *testing.T) { - srv := &policyServer{t: t, supported: true, policy: map[string]string{"lan-policy": "open", "sig-policy": "audit"}} + srv := &policyServer{t: t, supported: true, policy: map[string]string{"lan-policy": "open", "sig-policy": "required"}} target := cloudTarget(t, srv.start().URL) out, _, err := runPolicyCapture(t, &globalFlags{}, lanPolicy, target, "") @@ -108,11 +108,15 @@ func TestPolicyCloudShowAndSet(t *testing.T) { t.Fatalf("set off: err %v, warning %q", err, warn) } - out, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "required") - if err != nil || !strings.HasPrefix(out, "Signature policy of benchpod-baea06 is now required (") { - t.Fatalf("sig set = %q, %v", out, err) + out, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "") + if err != nil || out != "Signature policy of benchpod-baea06: required (only signed images are installed)\n" { + t.Fatalf("sig show = %q, %v", out, err) + } + // The signature policy has no set: it is always required. + if _, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "permissive"); exitCode(err) != exitUsage { + t.Fatalf("sig set: %v", err) } - if got := strings.Join(srv.puts, ","); got != "lan-policy=locked,lan-policy=off,sig-policy=required" { + if got := strings.Join(srv.puts, ","); got != "lan-policy=locked,lan-policy=off" { t.Fatalf("puts = %s", got) } } @@ -150,18 +154,21 @@ func TestPolicyCloudForbidden(t *testing.T) { } } -func TestPolicyCloudRefusedLoosening(t *testing.T) { - srv := &policyServer{t: t, supported: true, policy: map[string]string{"sig-policy": "required"}, - put: func(w http.ResponseWriter, _, _ string) bool { - w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"error":"sig_policy: only the USB console can loosen the policy (now required)"}`)) - return true - }} - _, _, err := runPolicyCapture(t, &globalFlags{}, sigPolicy, cloudTarget(t, srv.start().URL), "permissive") - want := "sig-policy set: the pod refused: only the USB console can loosen the policy (now required). " + - "Loosen it over the pod's USB console: benchpod sig-policy set permissive --connection usb" - if err == nil || err.Error() != want { - t.Fatalf("err = %v\nwant %q", err, want) +// sig-policy has no set subcommand any more; a relayed BP0074 is worded from the catalog. +func TestSigPolicyCannotBeLoosened(t *testing.T) { + g := &globalFlags{} + cmd := newSigPolicyCmd(g) + for _, c := range cmd.Commands() { + if c.Name() == "set" { + t.Fatal("sig-policy still has set") + } + } + if code := run([]string{"sig-policy", "set", "audit"}); code != exitUsage { + t.Fatalf("sig-policy set: exit %d", code) + } + err := cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusConflict, Code: "BP0074", Message: "BP0074"}) + if err == nil || !strings.Contains(err.Error(), "BP0074: ") || !strings.Contains(err.Error(), "this firmware installs only signed images") { + t.Fatalf("err = %v", err) } } @@ -209,25 +216,21 @@ func withFakeConsole(t *testing.T, fc *fakePolicyConsole) { } func TestPolicyUSBShowAndSet(t *testing.T) { - fc := &fakePolicyConsole{rep: serialconsole.PolicyReply{Policy: "required", Keys: 3}} + fc := &fakePolicyConsole{rep: serialconsole.PolicyReply{Policy: "open", Keys: -1}} withFakeConsole(t, fc) - g := &globalFlags{connection: "usb"} - - out, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") + // The signature policy goes over the pod's USB network adapter, not the console. + addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"required","keys":3}}`) + out, _, err := runPolicyCapture(t, &globalFlags{connection: "usb", usbAddr: addr}, sigPolicy, policyTarget{}, "") if err != nil { t.Fatalf("show: %v", err) } - if want := "Signature policy of the pod on /dev/cu.usbmodem1101: required (unsigned images are refused), 3 trusted keys\n"; out != want { + if want := "Signature policy of " + addr + ": required (only signed images are installed), 3 trusted keys\n"; out != want { t.Fatalf("show = %q, want %q", out, want) } - - // The USB console may loosen the policy. - out, _, err = runPolicyCapture(t, g, sigPolicy, policyTarget{}, "audit") - if err != nil || !strings.HasPrefix(out, "Signature policy of the pod on /dev/cu.usbmodem1101 is now audit (") { - t.Fatalf("set = %q, %v", out, err) + if req := <-got; req != `{"cmd":"sig_policy"}` { + t.Fatalf("request %s", req) } - fc.rep = serialconsole.PolicyReply{Policy: "open", Keys: -1} out, warn, err := runPolicyCapture(t, &globalFlags{connection: "/dev/cu.usbmodem9"}, lanPolicy, policyTarget{}, "off") if err != nil { t.Fatalf("lan set: %v", err) @@ -240,7 +243,7 @@ func TestPolicyUSBShowAndSet(t *testing.T) { t.Fatalf("warning %q does not mention %q", warn, w) } } - if got := strings.Join(fc.calls, ","); got != "sig-policy,sig-policy audit,lan-policy off" { + if got := strings.Join(fc.calls, ","); got != "lan-policy off" { t.Fatalf("console calls = %s", got) } } @@ -250,8 +253,8 @@ func TestPolicyUSBOldFirmwareAndRefusal(t *testing.T) { withFakeConsole(t, fc) g := &globalFlags{connection: "usb"} - _, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") - if err == nil || err.Error() != "this firmware has no signature policy; update the pod's firmware" { + _, _, err := runPolicyCapture(t, g, lanPolicy, policyTarget{}, "") + if err == nil || err.Error() != "this firmware has no LAN policy; update the pod's firmware" { t.Fatalf("old firmware: err = %v", err) } @@ -287,14 +290,14 @@ func fakeLANPod(t *testing.T, reply string) (addr string, got chan string) { } func TestPolicyLANShowOnly(t *testing.T) { - addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"audit","enforces":true,"keys":1}}`) + addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"required","enforces":true,"keys":1}}`) g := &globalFlags{connection: addr} out, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") if err != nil { t.Fatalf("show: %v", err) } - if want := "Signature policy of " + addr + ": audit (every image is accepted; signatures are only reported), 1 trusted key\n"; out != want { + if want := "Signature policy of " + addr + ": required (only signed images are installed), 1 trusted key\n"; out != want { t.Fatalf("show = %q, want %q", out, want) } if req := <-got; req != `{"cmd":"sig_policy"}` { diff --git a/cmd/benchpod-cli/pull.go b/cmd/benchpod-cli/pull.go index 0bd6b54..9ecf433 100644 --- a/cmd/benchpod-cli/pull.go +++ b/cmd/benchpod-cli/pull.go @@ -3,67 +3,10 @@ package main import ( "context" "encoding/json" - "fmt" - - "github.com/embeddedci-com/benchpod-cli/internal/features" - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) -// pullHW is one LA pin's pull resistor on a board: the directions it can pull (the first is the -// one `la pullup PIN on` engages) and its value. -type pullHW struct { - dirs []string - ohms string -} - -// pullTableV3 is today's boards (every v3 board): LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 none. -// The firmware has the same table (la_pins.c) and reports it per pin (dirs); the CLI only uses this -// one for firmware without the la_pull_dir feature, which takes pullup on/off only. -var pullTableV3 = map[int]pullHW{ - 1: {[]string{"up"}, "4.7k"}, 2: {[]string{"up"}, "4.7k"}, - 3: {[]string{"up"}, "2.2k"}, 4: {[]string{"up"}, "2.2k"}, - 5: {[]string{"up"}, "10k"}, 6: {[]string{"up"}, "10k"}, - 7: {[]string{"down"}, "10k"}, 8: {[]string{"down"}, "10k"}, -} - -// pullRefusal is the pod's own BP0023 / BP0024, for what the CLI refuses before asking older -// firmware. -func pullRefusal(la int, want string, hw pullHW, ok bool) error { - if !ok { - return &tcpclient.PodError{Reason: fmt.Sprintf("LA%d has no pull resistor on this board", la), - Code: "BP0023", Args: map[string]any{"la": la}} - } - have := hw.dirs[0] - return &tcpclient.PodError{Reason: fmt.Sprintf("LA%d supports pull-%s only on this board", la, have), - Code: "BP0024", Args: map[string]any{"la": la, "want": want, "have": have}} -} - -// setLAPull pulls LA la "up", "down" or "off". Firmware with la_pull_dir gets {"pull":...} and -// decides; older firmware gets {"pullup":"on"|"off"}, which engages the pin's one direction, so the -// direction is checked here first ("up" must never engage LA7's pull-down). +// setLAPull pulls LA la "up", "down" or "off" (la_pull with pull; the pod checks the direction +// against the pin's resistor: BP0023, BP0024). func setLAPull(ctx context.Context, c podCommander, la int, want string) (json.RawMessage, error) { - st, err := c.Command(ctx, features.StatusRequest()) - if err != nil { - return nil, fmt.Errorf("status: %w", err) - } - byDir, err := features.Has(st, "la_pull_dir") - if err != nil { - return nil, err - } - if byDir { - return c.Command(ctx, map[string]any{"cmd": "la", "la": la, "pull": want}) - } - hw, ok := pullTableV3[la] - if want != "off" && (!ok || hw.dirs[0] != want) { - return nil, pullRefusal(la, want, hw, ok) - } - if !ok { // off on a pin without a resistor: nothing to switch (older firmware refuses the query) - return json.Marshal(map[string]any{"la": la, "pullup": 0, "ohms": "", "pull": "none", "state": "off", - "dirs": []string{}}) - } - state := "off" - if want != "off" { - state = "on" - } - return c.Command(ctx, map[string]any{"cmd": "la", "la": la, "pullup": state}) + return c.Command(ctx, map[string]any{"cmd": "la_pull", "la": la, "pull": want}) } diff --git a/cmd/benchpod-cli/pull_test.go b/cmd/benchpod-cli/pull_test.go index 1a2413d..3b9e5ec 100644 --- a/cmd/benchpod-cli/pull_test.go +++ b/cmd/benchpod-cli/pull_test.go @@ -3,94 +3,31 @@ package main import ( "context" "encoding/json" - "errors" "reflect" - "strings" "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) -// pullPod answers status (features_rev) and records the la requests. +// pullPod records the la_pull requests. type pullPod struct { - rev int sent []map[string]any } func (p *pullPod) Command(_ context.Context, req map[string]any) (json.RawMessage, error) { - if req["cmd"] == "status" { - return json.Marshal(map[string]any{"version": "3.10.11", "features_rev": p.rev, "gateware": 58, - "fpga_image": "deep", "hw": []string{"nrst_pin"}}) - } p.sent = append(p.sent, req) return json.Marshal(map[string]any{"la": req["la"], "ok": true}) } -func TestLAPullSendsTheDirectionToNewFirmware(t *testing.T) { - p := &pullPod{rev: 3} +// la pull sends la_pull with the direction; the pod decides (and refuses LA7 up itself). +func TestLAPullSendsTheDirection(t *testing.T) { + p := &pullPod{} for _, want := range []string{"up", "down", "off"} { if _, err := setLAPull(context.Background(), p, 7, want); err != nil { t.Fatal(err) } } - want := []map[string]any{{"cmd": "la", "la": 7, "pull": "up"}, {"cmd": "la", "la": 7, "pull": "down"}, - {"cmd": "la", "la": 7, "pull": "off"}} - if !reflect.DeepEqual(p.sent, want) { - t.Fatalf("sent %v", p.sent) // the pod decides (and refuses LA7 up itself) - } -} - -func TestLAPullFallsBackToPullupOnOlderFirmware(t *testing.T) { - p := &pullPod{rev: 2} - ctx := context.Background() - if _, err := setLAPull(ctx, p, 1, "up"); err != nil { - t.Fatal(err) - } - if _, err := setLAPull(ctx, p, 7, "down"); err != nil { - t.Fatal(err) - } - if _, err := setLAPull(ctx, p, 7, "off"); err != nil { - t.Fatal(err) - } - want := []map[string]any{{"cmd": "la", "la": 1, "pullup": "on"}, {"cmd": "la", "la": 7, "pullup": "on"}, - {"cmd": "la", "la": 7, "pullup": "off"}} + want := []map[string]any{{"cmd": "la_pull", "la": 7, "pull": "up"}, {"cmd": "la_pull", "la": 7, "pull": "down"}, + {"cmd": "la_pull", "la": 7, "pull": "off"}} if !reflect.DeepEqual(p.sent, want) { t.Fatalf("sent %v", p.sent) } - // the CLI refuses what "pullup":"on" would do wrong, with the pod's own codes - for _, c := range []struct { - la int - want, code string - text string - }{ - {7, "up", "BP0024", "LA7 supports pull-down only on this board"}, - {3, "down", "BP0024", "LA3 supports pull-up only on this board"}, - {9, "up", "BP0023", "LA9 has no pull resistor on this board"}, - } { - _, err := setLAPull(ctx, p, c.la, c.want) - var pe *tcpclient.PodError - if !errors.As(err, &pe) || pe.Code != c.code || !strings.Contains(pe.Reason, c.text) { - t.Fatalf("LA%d %s: err = %v", c.la, c.want, err) - } - if text, ok := codedRefusal(pe); !ok || !strings.Contains(text, c.code) { - t.Fatalf("codedRefusal = %q", text) - } - } - // off on a pin without a resistor: nothing to switch, nothing sent - n := len(p.sent) - data, err := setLAPull(ctx, p, 12, "off") - if err != nil || len(p.sent) != n || !strings.Contains(string(data), `"state":"off"`) { - t.Fatalf("data %s err %v sent %d", data, err, len(p.sent)-n) - } -} - -func TestLAPullRefusesABadDirection(t *testing.T) { - g := &globalFlags{connection: "127.0.0.1:1"} - cmd := newLAPullCmd(g) - cmd.SetArgs([]string{"1", "sideways"}) - cmd.SilenceUsage, cmd.SilenceErrors = true, true - err := cmd.Execute() - if err == nil || exitCode(err) != exitUsage || !strings.Contains(err.Error(), "up, down or off") { - t.Fatalf("err = %v", err) - } } diff --git a/cmd/benchpod-cli/refusals_test.go b/cmd/benchpod-cli/refusals_test.go deleted file mode 100644 index ab7e24c..0000000 --- a/cmd/benchpod-cli/refusals_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" - "github.com/embeddedci-com/benchpod-cli/internal/serverapi" - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// The hints the CLI adds to a refusal hang on the firmware's exact wording -// (internal/fwrefusals pins it against the firmware source). - -func TestALockedLANRefusalGetsTheUSBHint(t *testing.T) { - msg := fwrefusals.Example("lan_locked") - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: msg}) - if !strings.Contains(err.Error(), msg) || !strings.Contains(err.Error(), lockedUSBHint) { - t.Fatalf("got %v", err) - } - // Not over the cloud or USB: there the refusal stands alone. - if err := cloudCfgError("cloud ca set", caMissing, false, &tcpclient.PodError{Reason: msg}); strings.Contains(err.Error(), lockedUSBHint) { - t.Fatalf("got %v", err) - } -} - -func TestTheCloudLinkGateRefusalsGetTheLANHint(t *testing.T) { - for _, id := range []string{"cloud_ca_from_lan", "cloud_proxy_from_lan"} { - msg := fwrefusals.Example(id) - if !isLANGateRefusal(msg) { - t.Errorf("%s: %q not recognized", id, msg) - } - if err := cloudCfgError("cloud", caMissing, true, &tcpclient.PodError{Reason: msg}); !strings.Contains(err.Error(), lanGateHint) { - t.Errorf("%s: got %v", id, err) - } - } - // The policy commands use the same tail, but they are not cloud link settings. - for _, id := range []string{"sig_policy_from_lan", "lan_policy_from_lan", "lan_locked"} { - if isLANGateRefusal(fwrefusals.Example(id)) { - t.Errorf("%s: %q taken for a cloud link refusal", id, fwrefusals.Example(id)) - } - } -} - -func TestOldFirmwareRefusalsMeanTheFeatureIsMissing(t *testing.T) { - // Firmware without codes: the texts. - for _, id := range []string{"unknown_cmd", "unknown_target"} { - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example(id)}) - if err.Error() != caMissing { - t.Errorf("%s: got %v", id, err) - } - } - // With codes: BP0002, whatever the text (a build without texts sends none). - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: "pod returned an error", Code: "BP0002", - Args: map[string]any{"cmd": "cloud_ca"}}) - if err.Error() != caMissing { - t.Errorf("BP0002: got %v", err) - } -} - -func TestACloudRefusalToLoosenTheSignaturePolicyPointsAtUSB(t *testing.T) { - msg := fwrefusals.Example("sig_policy_loosen") - err := cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, Message: msg}) - if !strings.Contains(err.Error(), "only the USB console can loosen") || - !strings.Contains(err.Error(), "benchpod sig-policy set audit --connection usb") { - t.Fatalf("got %v", err) - } - // Other refusals get no USB recipe. - err = cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, - Message: fwrefusals.Example("sig_policy_unknown")}) - if strings.Contains(err.Error(), "--connection usb") { - t.Fatalf("got %v", err) - } -} - -func TestFirmwareRefusalsKeepTheirPrefixes(t *testing.T) { - // The SDK and MCP classify by these prefixes (locked:, busy:, forbidden:); the CLI shows them - // as they are. Pin the prefix of each policy refusal. - for id, prefix := range map[string]string{ - "lan_locked": "locked: ", - "lease_busy": "busy: ", - "ota_owner_busy": "busy: ", - "psram_bus_busy": "busy: ", - "tunnel_forbidden": "forbidden: ", - } { - if msg := fwrefusals.Example(id); !strings.HasPrefix(msg, prefix) { - t.Errorf("%s: %q does not start with %q", id, msg, prefix) - } - } -} - -func TestTheLAVoltageRefusalNamesTheCLICommand(t *testing.T) { - pe := &tcpclient.PodError{Reason: fwrefusals.Example("la_voltage_unset")} - err := withRefusalHint(fmt.Errorf("flash: %w", pe)) - if !strings.Contains(err.Error(), "benchpod la voltage 3.3V") || !strings.Contains(err.Error(), "Pins pane") { - t.Fatalf("got %v", err) - } - if exitCode(err) != exitRefused { - t.Fatalf("exit code %d", exitCode(err)) - } -} - -func TestPinConflictHintsAreTranslated(t *testing.T) { - for _, tc := range []struct{ owner, hintID, want string }{ - {"gpio", "pin_hint_gpio", "holds LA4 as a GPIO"}, - {"uart_rx", "pin_hint_uart", "UART session"}, - {"swd_clk", "pin_hint_swd", "SWD session"}, - {"i2c_sda", "pin_hint_sensor", "benchpod sensor stop"}, - {"spi_sck", "pin_hint_spi", "SPI session"}, - } { - msg := "pin conflict: LA4 is in use by " + tc.owner + "; " + fwrefusals.Example(tc.hintID) - err := withRefusalHint(fmt.Errorf("la step: %w", &tcpclient.PodError{Reason: msg})) - if !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), `{"cmd"`) { - t.Errorf("%s: got %v", tc.hintID, err) - } - if !strings.Contains(err.Error(), "pin conflict: LA4 is in use by "+tc.owner) || exitCode(err) != exitRefused { - t.Errorf("%s: got %v (exit %d)", tc.hintID, err, exitCode(err)) - } - } - // A user-defined sensor instance owns its pins as sensor:. - msg0 := `pin conflict: LA2 is in use by sensor:env; stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})` - if err := withRefusalHint(&tcpclient.PodError{Reason: msg0}); !strings.Contains(err.Error(), "`benchpod sensor stop env`") || - strings.Contains(err.Error(), `{"cmd"`) { - t.Fatalf("got %v", err) - } - // The firmware also names the pin's function, and a shared I2C line "sensor:env+1". - msg1 := `pin conflict: LA2 is in use by sensor:env+1 (i2c_sda); stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})` - if shown, hint := translateRefusal(msg1); shown != "pin conflict: LA2 is in use by sensor:env+1 (i2c_sda)" || - !strings.Contains(hint, "`benchpod sensor stop env`") { - t.Fatalf("got %q / %q", shown, hint) - } - // The emulation image refusals name the CLI's commands. - msg2 := `control loop is not in the emulation image, which the emulated sensors use: {"cmd":"sensor_stop","all":true} then {"cmd":"fpga_image","image":"loop"}` - if shown, hint := translateRefusal(msg2); shown != "control loop is not in the emulation image, which the emulated sensors use" || - hint != "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image loop`" { - t.Fatalf("got %q / %q", shown, hint) - } - msg3 := `image switch refused: the emulated sensors env, imu need the emulation image; stop them first ({"cmd":"sensor_stop","all":true})` - if shown, hint := translateRefusal(msg3); strings.Contains(shown, `{"cmd"`) || !strings.Contains(hint, "benchpod sensor stop") { - t.Fatalf("got %q / %q", shown, hint) - } - // The pinned example renders the gpio case. - if shown, hint := translateRefusal(fwrefusals.Example("pin_conflict")); shown != "pin conflict: LA4 is in use by gpio" || hint == "" { - t.Fatalf("got %q / %q", shown, hint) - } - // A hint the CLI does not know (the step train's is already plain) stays as the pod wrote it. - msg := "pin conflict: LA2 is in use by step; " + fwrefusals.Example("pin_hint_step") - if err := withRefusalHint(&tcpclient.PodError{Reason: msg}); err.Error() != (&tcpclient.PodError{Reason: msg}).Error() { - t.Fatalf("got %v", err) - } - // refusedError shows the translated text too. - pe := &tcpclient.PodError{Reason: fwrefusals.Example("pin_conflict")} - if err := refusedError("flash", pe, true); strings.Contains(err.Error(), `{"cmd"`) || !strings.Contains(err.Error(), "gpio_release") { - t.Fatalf("got %v", err) - } -} diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index fe93b43..6c9cf9d 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -62,36 +62,38 @@ func newRootCmd() *cobra.Command { "New pod? Run `benchpod setup`: it finds the pod, gets it on the network, sets\n" + "the board I/O voltage, registers it with embeddedci.com and saves the connection.\n\n" + "--connection says where and how to reach the pod; the transport follows from\n" + - "its value. An address (192.168.1.5[:8080]) uses the pod's network (TCP/JSON) API;\n" + - "a device path (/dev/tty..., COM3) or `usb` uses the pod's USB console, and its\n" + - "USB network adapter for the network commands (firmware 3.9.0+, no Wi-Fi set);\n" + - "embeddedci: goes through embeddedci.com to the pod with that name on your\n" + - "account (signed in with `benchpod login`, or BENCHPOD_API_KEY). Omit --connection\n" + - "to use the default saved by `benchpod discover --save` or `benchpod set-connection`.\n" + + "its value. An address (192.168.1.5) uses the pod's network API (TLS on 8443,\n" + + "pinned on first use); a device path (/dev/tty..., COM3) or `usb` uses the pod's\n" + + "USB network adapter; embeddedci: goes through embeddedci.com to the pod\n" + + "with that name on your account (signed in with `benchpod login`, or\n" + + "BENCHPOD_API_KEY). Omit --connection to use the default saved by\n" + + "`benchpod discover --save` or `benchpod set-connection`.\n" + "--org (or BENCHPOD_ORG) picks which of your embeddedci.com organizations cloud\n" + "calls act in, by id, slug or name; the default is the one active in the web app.\n\n" + - "Over the network: every pod command but the USB-only ones below. Over the USB\n" + - "console: status, la voltage, flash (SWD), lan-policy, sig-policy, cloud ca and\n" + - "cloud proxy; the rest over the pod's USB network adapter when it is up.\n" + - "Through embeddedci.com: status, ping, la voltage, la pull, la pullup, la status, la step,\n" + + "This CLI drives firmware 4.0. Against firmware 3.x only status, flash-self,\n" + + "install-blobs, dfu, bootsel, discover and identity run (exit code 7 otherwise:\n" + + "update the pod with `benchpod flash-self`).\n\n" + + "Over USB every pod command sends JSON over the pod's USB network adapter; the\n" + + "USB console is only for status, dfu, bootsel, identity, lan-policy, usb-network\n" + + "and net-reset. USB networking off: `benchpod usb-network on --connection usb`.\n" + + "Through embeddedci.com: status, ping, la voltage, la pull, la status, la step,\n" + "la pins, la dir, i2c, generate, sensor, lan-policy, sig-policy, cloud ca\n" + - "show/clear, cloud proxy, deregister and flash-self (embeddedci.com runs the update).\n" + - "Always over the USB console: set-wifi, show-network, clear-wifi, identity,\n" + - "install-blobs, bootsel, dfu, usb-bridge and usb-reattach; flash-self reflashes\n" + - "the pod over USB DFU unless --network or an embeddedci: connection. A command\n" + - "that cannot use the connection says so and names what to use instead.\n\n" + - "flash and spi-flash over the network take the pins you leave out from the pod's\n" + - "wiring profile on embeddedci.com when you are signed in and the pod is on your\n" + - "account.\n\n" + + "show/clear, cloud proxy, the Wi-Fi commands, deregister and flash-self\n" + + "(embeddedci.com runs the update). flash-self reflashes the pod over USB DFU\n" + + "unless --network or an embeddedci: connection. A command that cannot use the\n" + + "connection says so and names what to use instead.\n\n" + + "Commands that take pins default the ones you leave out from the pod's wiring\n" + + "profile (--wiring-profile, else the pod's default).\n\n" + exitCodesHelp, SilenceUsage: true, SilenceErrors: true, // Apply Viper precedence (flag > env > default) into g before any RunE. PersistentPreRunE: func(c *cobra.Command, _ []string) error { - tcpclient.SetAllowNewerPod(allowsNewerPod(c)) + tcpclient.SetAllowAnyPodAPI(allowsAnyPodAPI(c)) + tcpclient.SetAPIProbe(apiProbe) g.connection = viper.GetString("connection") g.configFile = viper.GetString("config-file") - g.outputFilename = viper.GetString("output-filename") + g.outputFilename = viper.GetString("out") g.timeout = viper.GetDuration("timeout") g.tls = viper.GetString("tls") g.tlsCA = viper.GetString("tls-ca") @@ -112,10 +114,10 @@ func newRootCmd() *cobra.Command { pf.StringVar(&g.connection, "connection", "", `how to reach the pod: its network address (192.168.1.5[:8080]), its name (benchpod-a1b2c3 or a1b2c3, found on the LAN over mDNS, else on USB), a device path (/dev/tty..., COM3), "usb" to auto-detect the pod over USB (its console, and its USB network adapter for the network commands), usb: for one of several pods on USB, or embeddedci: to go through embeddedci.com (default: the saved set-connection target)`) pf.StringVar(&g.configFile, "config-file", "", "path to config file") - pf.StringVar(&g.outputFilename, "output-filename", "", "write command output to this file instead of stdout") + pf.StringVar(&g.outputFilename, "out", "", "write command output to this file instead of stdout (benchpod ci: the run folder)") pf.DurationVar(&g.timeout, "timeout", 0, "overall command deadline (0 = per-command default)") pf.StringVar(&g.tls, "tls", "auto", - "TLS to the pod's LAN API: auto (TLS on 8443 when the pod has it, pinned on first use), on (TLS only) or off (plaintext 8080)") + "TLS to the pod's LAN API: auto (TLS on 8443 when the pod has it, pinned on first use), on (TLS only) or off (plaintext 8080: firmware 4.0 answers it on the LAN only after `benchpod lan-tls https-only off`)") pf.StringVar(&g.tlsCA, "tls-ca", "", "PEM file of CA certificates: verify the pod's TLS certificate and name against them instead of pinning") pf.StringVar(&g.org, "org", "", "embeddedci.com organization for cloud calls (embeddedci:, login-backed commands): its id, slug or name (default: the active organization in the web app; also BENCHPOD_ORG)") @@ -127,7 +129,7 @@ func newRootCmd() *cobra.Command { viper.SetEnvPrefix("BENCHPOD") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) viper.AutomaticEnv() - for _, name := range []string{"connection", "config-file", "output-filename", "timeout", "tls", "tls-ca", "org", "wiring-profile"} { + for _, name := range []string{"connection", "config-file", "out", "timeout", "tls", "tls-ca", "org", "wiring-profile"} { _ = viper.BindPFlag(name, pf.Lookup(name)) } @@ -138,7 +140,7 @@ func newRootCmd() *cobra.Command { }{ {"setup", "Setup:", []*cobra.Command{ newSetupCmd(g), newDiscoverCmd(g), newSetConnectionCmd(g), - newSetWifiCmd(g), newShowNetworkCmd(g), newScanWifiCmd(g), newClearWifiCmd(g), + newSetWifiCmd(g), newShowNetworkCmd(g), newScanWifiCmd(g), newClearWifiCmd(g), newNetResetCmd(g), newUSBBridgeCmd(g), newUSBReattachCmd(g), }}, {"pod", "The pod:", []*cobra.Command{ @@ -149,7 +151,7 @@ func newRootCmd() *cobra.Command { }}, {"target", "The target (DUT) and analog I/O:", []*cobra.Command{ newFlashCmd(g), newSPIFlashCmd(g), newGenerateCmd(g), newCaptureCmd(g), - newStreamCmd(g), newMeasureCmd(g), newTestCmd(g), newADCRangeCmd(g), newSensorCmd(g), newI2CCmd(g), newExpansionCmd(g), + newMeasureCmd(g), newTestCmd(g), newADCRangeCmd(g), newSensorCmd(g), newI2CCmd(g), newExpansionCmd(g), }}, {"ci", "Continuous integration:", []*cobra.Command{newCICmd(g)}}, {"cloud", "embeddedci.com:", []*cobra.Command{ @@ -194,19 +196,31 @@ func run(args []string) int { } log.Printf("%v", withSavedConnectionHint(withRefusalHint(err), savedConnectionUsed)) if cmd != nil && isCICommand(cmd) { - return ci.ExitSetup // benchpod ci: a usage error is a setup error (exit 1), see its exit codes + // benchpod ci: the CLI's codes 2 (usage), 5, 6 and 7 mean the same there; anything else + // before the run is a setup error. + switch c := exitCode(err); c { + case exitUsage, exitUnreachable, exitUpdateCLI, exitUpdatePod: + return c + } + return ci.ExitSetup } return exitCode(err) } -// newerPodCommands still run against a pod whose firmware needs a newer CLI (exit code 6 -// otherwise): they show the pod's state or change its firmware, which is how such a pod is -// rolled back or looked at. `status` prints a warning instead. -var newerPodCommands = map[string]bool{ +// apiProbe: before a pod's first command, read its status once and stop on an API level this CLI +// does not drive (tcpclient.SetAPIProbe). Tests whose fake pods answer status without an api +// turn it off. +var apiProbe = true + +// anyPodAPICommands still run against a pod whose firmware this CLI does not drive: one that needs +// a newer CLI (exit code 6 otherwise) or one older than firmware 4.0 (exit code 7 otherwise). They +// show the pod's state or change its firmware, which is how such a pod is upgraded, rolled back +// or looked at; over firmware 3.x they keep the requests 3.x takes. `status` prints a warning. +var anyPodAPICommands = map[string]bool{ "status": true, "flash-self": true, "install-blobs": true, "dfu": true, "bootsel": true, "discover": true, "identity": true, } -func allowsNewerPod(c *cobra.Command) bool { - return c.Parent() != nil && !c.Parent().HasParent() && newerPodCommands[c.Name()] +func allowsAnyPodAPI(c *cobra.Command) bool { + return c.Parent() != nil && !c.Parent().HasParent() && anyPodAPICommands[c.Name()] } diff --git a/cmd/benchpod-cli/sensor.go b/cmd/benchpod-cli/sensor.go index 544d0ae..3de7c97 100644 --- a/cmd/benchpod-cli/sensor.go +++ b/cmd/benchpod-cli/sensor.go @@ -234,7 +234,7 @@ func newSensorExportCmd(g *globalFlags) *cobra.Command { return nil }, } - c.Flags().StringVarP(&outFile, "output", "o", "", "write to this file instead of stdout") + c.Flags().StringVarP(&outFile, "out", "o", "", "write to this file instead of stdout") c.Flags().StringVar(&version, "version", "", "library version (default: the pinned one, BENCHPOD_SENSOR_LIBRARY or the saved default)") c.Flags().BoolVar(&format, "format-doc", false, "write the library's format reference (docs/format.md) instead; is then ignored") return c @@ -295,7 +295,7 @@ func sensorCommand(ctx context.Context, t *podTarget, what string, req map[strin raw, err := t.client.Command(ctx, req) if err != nil { if pe, ok := tcpclient.AsPodError(err); ok { - return nil, refusedError(what, pe, !t.spec.IsCloud()) + return nil, refusedError(what, pe) } return nil, fmt.Errorf("%s: %w", what, err) } @@ -420,7 +420,7 @@ func newSensorStartCmd(g *globalFlags) *cobra.Command { } c.Flags().StringVar(&f.instance, "instance", "", "instance name, 1 to 16 characters of a-z, 0-9 and _ (default: the definition's name)") c.Flags().StringArrayVar(&f.pins, "pin", nil, "pin as role=channel, e.g. --pin sda=2 --pin scl=1 (repeatable)") - c.Flags().StringVar(&f.address, "address", "", "I2C address: the definition's address or one of its alt_addresses (e.g. 0x77)") + c.Flags().StringVar(&f.address, "addr", "", "I2C address: the definition's address or one of its alt_addresses (e.g. 0x77)") c.Flags().StringArrayVar(&f.values, "set", nil, "initial value as key=number, e.g. --set temperature_c=30 (repeatable)") c.Flags().IntVar(&f.baud, "baud", 0, "UART: override the definition's baud rate") c.Flags().StringVar(&f.version, "version", "", "library version for a library name") @@ -504,10 +504,10 @@ func sensorPins(g *globalFlags, kind string, flags []string) (map[string]any, er role, val, ok := strings.Cut(p, "=") role = strings.ToLower(strings.TrimSpace(role)) if !ok || role == "" { - return nil, fmt.Errorf("--pin is role=channel (e.g. sda=2), got %q", p) + return nil, usageErrorf("--pin is role=channel (e.g. sda=2), got %q", p) } if _, dup := pins[role]; dup { - return nil, fmt.Errorf("--pin %s given twice", role) + return nil, usageErrorf("--pin %s given twice", role) } v, err := sensors.PinValue(role, val) if err != nil { diff --git a/cmd/benchpod-cli/sensor_test.go b/cmd/benchpod-cli/sensor_test.go index 3a3fee4..47d9fab 100644 --- a/cmd/benchpod-cli/sensor_test.go +++ b/cmd/benchpod-cli/sensor_test.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/base64" "encoding/json" + "github.com/embeddedci-com/benchpod-cli/internal/features" "io" "net" "os" @@ -46,7 +47,9 @@ func newFakeSensorPod(t *testing.T, caps ...string) (*fakeSensorPod, *globalFlag _ = json.Unmarshal([]byte(line), &req) data, msg := p.handle(req) var out []byte - if msg != "" { + if code, args, ok := codedFakeError(msg); ok { + out, _ = json.Marshal(map[string]any{"status": "error", "code": code, "args": args}) + } else if msg != "" { out, _ = json.Marshal(map[string]any{"status": "error", "message": msg}) } else { out, _ = json.Marshal(map[string]any{"status": "ok", "data": data}) @@ -61,6 +64,21 @@ func newFakeSensorPod(t *testing.T, caps ...string) (*fakeSensorPod, *globalFlag return p, &globalFlags{connection: ln.Addr().String(), configFile: filepath.Join(t.TempDir(), "config.json")} } +// codedFakeError reads a fake's error "BP0061" or "BP0061 {"la":1}" as a coded refusal (firmware +// 4.0 sends a code and its args, no message). +func codedFakeError(msg string) (string, map[string]any, bool) { + if len(msg) < 6 || !strings.HasPrefix(msg, "BP") { + return "", nil, false + } + var args map[string]any + if rest := strings.TrimSpace(msg[6:]); rest != "" { + if json.Unmarshal([]byte(rest), &args) != nil { + return "", nil, false + } + } + return msg[:6], args, true +} + func (p *fakeSensorPod) handle(req map[string]any) (any, string) { p.mu.Lock() defer p.mu.Unlock() @@ -72,7 +90,13 @@ func (p *fakeSensorPod) handle(req map[string]any) (any, string) { } switch req["cmd"] { case "status": - return map[string]any{"board": "stm32h563", "caps": p.caps}, "" + st := map[string]any{"board": "stm32h563", "api": 2, "min_client_api": 2} + for _, c := range p.caps { + if c == "sensors" { // a pod with the feature: the table decides from features_rev + st["features_rev"], st["gateware"], st["fpga_image"] = features.Revision(), 60, "emu" + } + } + return st, "" case "sensor_define", "sensor_stimulus": key, _ := req["instance"].(string) chunk, _ := base64.StdEncoding.DecodeString(req["data_b64"].(string)) diff --git a/cmd/benchpod-cli/spiflash.go b/cmd/benchpod-cli/spiflash.go index 0b96f8d..bcd40cf 100644 --- a/cmd/benchpod-cli/spiflash.go +++ b/cmd/benchpod-cli/spiflash.go @@ -101,24 +101,24 @@ func (f *spiFlags) config() (spiflash.Config, error) { vals := [4]string{f.sck, f.mosi, f.miso, f.cs} for i, v := range vals { if strings.TrimSpace(v) == "" { - return spiflash.Config{}, fmt.Errorf("--sck, --mosi, --miso and --cs are required (or set spi_sclk, spi_mosi, spi_miso and spi_cs in the pod's wiring profile on embeddedci.com)") + return spiflash.Config{}, usageErrorf("--sck, --mosi, --miso and --cs are required (or set spi_sclk, spi_mosi, spi_miso and spi_cs in the pod's wiring profile on embeddedci.com)") } n, err := parseLAPin(v) if err != nil { - return spiflash.Config{}, fmt.Errorf("--%s: %w", names[i], err) + return spiflash.Config{}, usageErrorf("--%s: %w", names[i], err) } for j := 0; j < i; j++ { if pins[j] == n { - return spiflash.Config{}, fmt.Errorf("--%s and --%s are both LA%d; each needs its own pin", names[j], names[i], n) + return spiflash.Config{}, usageErrorf("--%s and --%s are both LA%d; each needs its own pin", names[j], names[i], n) } } pins[i] = n } if f.mode < 0 || f.mode > 3 { - return spiflash.Config{}, fmt.Errorf("--mode must be 0, 1, 2 or 3") + return spiflash.Config{}, usageErrorf("--mode must be 0, 1, 2 or 3") } if f.hz <= 0 { - return spiflash.Config{}, fmt.Errorf("--hz must be positive") + return spiflash.Config{}, usageErrorf("--hz must be positive") } return spiflash.Config{SCK: pins[0], MOSI: pins[1], MISO: pins[2], CS: pins[3], Hz: f.hz, Mode: f.mode}, nil } @@ -257,7 +257,7 @@ func newSPIFlashWriteCmd(g *globalFlags, f *spiFlags) *cobra.Command { RunE: func(_ *cobra.Command, args []string) error { addr, err := parseSize(addrS) if err != nil { - return fmt.Errorf("--addr: %w", err) + return usageErrorf("--addr: %w", err) } data, err := os.ReadFile(args[0]) if err != nil { @@ -324,12 +324,12 @@ func newSPIFlashReadCmd(g *globalFlags, f *spiFlags) *cobra.Command { RunE: func(_ *cobra.Command, args []string) error { addr, err := parseSize(addrS) if err != nil { - return fmt.Errorf("--addr: %w", err) + return usageErrorf("--addr: %w", err) } n := 0 if strings.TrimSpace(lenS) != "" { if n, err = parseSize(lenS); err != nil || n <= 0 { - return fmt.Errorf("--len must be a positive size, e.g. 4096, 0x1000 or 1M") + return usageErrorf("--len must be a positive size, e.g. 4096, 0x1000 or 1M") } } return runSPI(g, f, "read", time.Hour, func(ctx context.Context, p *spiflash.Pod, _ spiflash.Started) error { @@ -397,10 +397,10 @@ func newSPIFlashEraseCmd(g *globalFlags, f *spiFlags) *cobra.Command { } else { var err error if addr, err = parseSize(addrS); err != nil { - return fmt.Errorf("--addr: %w", err) + return usageErrorf("--addr: %w", err) } if n, err = parseSize(lenS); err != nil || n <= 0 { - return fmt.Errorf("--len is required (or --chip), e.g. 4096 or 1M") + return usageErrorf("--len is required (or --chip), e.g. 4096 or 1M") } } return runSPI(g, f, "erase", time.Hour, func(ctx context.Context, p *spiflash.Pod, _ spiflash.Started) error { diff --git a/cmd/benchpod-cli/status.go b/cmd/benchpod-cli/status.go index e92a04c..597c88e 100644 --- a/cmd/benchpod-cli/status.go +++ b/cmd/benchpod-cli/status.go @@ -57,7 +57,7 @@ func newStatusCmd(g *globalFlags) *cobra.Command { return fmt.Errorf("status: %w", err) } if upd := tcpclient.CheckPodAPI(data); upd != nil { - // Shown, not refused: status is how the user finds out (see allowsNewerPod). + // Shown, not refused: status is how the user finds out (see allowsAnyPodAPI). log.Printf("Warning: %v", upd) } out, closeOut, err := resolveOutput(g.outputFilename) @@ -123,6 +123,13 @@ type podStatus struct { SafeMode bool `json:"safe_mode"` SafeReason string `json:"safe_reason"` USB *podUSB `json:"usb"` // firmware 3.9.0+ + // Module is the analog module of a two-board pod (left out on other boards). DacPinoutOK is + // false when the digital board and the module use different flat-cable pinouts: the pod + // keeps the DAC off (BP0080). + Module *struct { + Present bool `json:"present"` + DacPinoutOK *bool `json:"dac_pinout_ok"` + } `json:"module"` // The MACs (firmware after 3.10.7, full form only). WiFiMAC is absent on a pod without Wi-Fi // and null until the pod knows it (a Wi-Fi scan or a join tells it). EthMAC string `json:"eth_mac"` @@ -136,14 +143,13 @@ type podStatus struct { // podUSB is status.usb: the USB network adapter and what the USB-C source advertises. type podUSB struct { - Net string `json:"net"` - Setting string `json:"setting"` // the usb-network setting, "" before it existed - OffReason string `json:"off_reason"` // "setting" or "wifi" when Net is "off" - Link bool `json:"link"` - IP string `json:"ip"` - HostIP string `json:"host_ip"` - Source string `json:"source"` // "none", "default", "1.5A", "3.0A"; "" on v2 - SourceMA *int `json:"source_ma"` // nil on v2 + Net flexBool `json:"net"` + OffReason string `json:"off_reason"` // "setting" or "wifi" when Net is off + Link bool `json:"link"` + IP string `json:"ip"` + HostIP string `json:"host_ip"` + Source string `json:"source"` // "none", "default", "1.5A", "3.0A"; "" on v2 + SourceMA *int `json:"source_ma"` // nil on v2 } // describeUSB is the status row for the USB side, with a warning when the port powering the pod @@ -151,9 +157,9 @@ type podUSB struct { func describeUSB(u podUSB) string { var parts []string switch { - case u.Net == "off" && u.OffReason == "setting": - parts = append(parts, "network off (turned off on the pod: `benchpod usb-network on` over its USB console)") - case u.Net == "off": + case !bool(u.Net) && u.OffReason == "setting": + parts = append(parts, "network off (turned off on the pod: `benchpod usb-network on --connection usb`)") + case !bool(u.Net): parts = append(parts, "network off (Wi-Fi is configured)") case u.Link: parts = append(parts, "network "+u.IP+" (this computer "+u.HostIP+")") @@ -192,10 +198,10 @@ type powerRail struct { func describePowerDraw(d powerDraw, tp *targetPower) string { ma := func(ua int) string { return fmt.Sprintf("%d mA", (ua+500)/1000) } var parts []string - if d.Internal.OK && (tp == nil || tp.Efuse1.Enabled != 0) { + if d.Internal.OK && (tp == nil || bool(tp.Efuse1.Enabled)) { parts = append(parts, fmt.Sprintf("internal 5 V rail %s at %s", ma(d.Internal.CurrentUA), formatMV(d.Internal.BusMV))) } - if d.External.OK && (tp == nil || tp.Efuse2.Enabled != 0) { + if d.External.OK && (tp == nil || bool(tp.Efuse2.Enabled)) { parts = append(parts, fmt.Sprintf("external rail %s at %s", ma(d.External.CurrentUA), formatMV(d.External.BusMV))) } if d.Pod != nil && d.Pod.OK { @@ -211,15 +217,31 @@ func describePowerDraw(d powerDraw, tp *targetPower) string { // the external supply. type targetPower struct { Efuse1 struct { - Enabled int `json:"enabled"` - Fault int `json:"fault"` + Enabled flexBool `json:"enabled"` + Fault flexBool `json:"fault"` } `json:"efuse1"` Efuse2 struct { - Enabled int `json:"enabled"` - Fault int `json:"fault"` + Enabled flexBool `json:"enabled"` + Fault flexBool `json:"fault"` } `json:"efuse2"` } +// flexBool reads a firmware 4.0 boolean (true/false) and, for status against firmware 3.x (which +// status still shows), the 3.x forms: 1/0 and "on"/"off". +type flexBool bool + +func (b *flexBool) UnmarshalJSON(data []byte) error { + switch strings.Trim(strings.TrimSpace(string(data)), `"`) { + case "true", "1", "on": + *b = true + case "false", "0", "off", "null", "": + *b = false + default: + return fmt.Errorf("not a boolean: %s", data) + } + return nil +} + // statusSummary is everything the summary prints; the extras are optional (nil/"" = unknown). type statusSummary struct { addr string // the pod's address, or " on embeddedci.com" @@ -325,17 +347,21 @@ func printStatusSummary(out io.Writer, s statusSummary) { row("Lease", fmt.Sprintf("held by cloud job %s (%d s left); the LAN is read-only until it ends", valueOrDash(st.Lease.Holder), st.Lease.LeftS)) } + if st.Module != nil && st.Module.DacPinoutOK != nil && !*st.Module.DacPinoutOK { + row("DAC", "off: board/module pinout mismatch (the digital board and the analog module use different "+ + "flat-cable pinouts; `benchpod explain BP0080`)") + } if st.SafeMode { row("Safe mode", valueOrDash(st.SafeReason)) } } func describeTargetPower(p targetPower) string { - rail := func(name string, enabled, fault int) string { + rail := func(name string, enabled, fault flexBool) string { switch { - case fault != 0: + case bool(fault): return name + " FAULT" - case enabled != 0: + case bool(enabled): return name + " on" } return "" diff --git a/cmd/benchpod-cli/status_test.go b/cmd/benchpod-cli/status_test.go index 19e175b..e342138 100644 --- a/cmd/benchpod-cli/status_test.go +++ b/cmd/benchpod-cli/status_test.go @@ -19,7 +19,7 @@ func TestStatusSummaryIsReadable(t *testing.T) { t.Fatal(err) } p := targetPower{} - p.Efuse1.Enabled = 1 + p.Efuse1.Enabled = true var out bytes.Buffer printStatusSummary(&out, statusSummary{ addr: "192.168.1.221:8080", st: st, power: &p, latest: "v3.9.0", @@ -121,3 +121,23 @@ func TestStatusMACs(t *testing.T) { t.Fatalf("summary:\n%s", b.String()) } } + +// A two-board pod whose board and module use different flat-cable pinouts keeps its DAC off: +// status says so (status.module.dac_pinout_ok false). +func TestStatusShowsADACPinoutMismatch(t *testing.T) { + for raw, want := range map[string]bool{ + `{"version":"4.0.0","module":{"present":true,"dac_pinout_ok":false}}`: true, + `{"version":"4.0.0","module":{"present":true,"dac_pinout_ok":true}}`: false, + `{"version":"4.0.0"}`: false, + } { + var st podStatus + if err := json.Unmarshal([]byte(raw), &st); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + printStatusSummary(&out, statusSummary{addr: "pod", st: st}) + if got := strings.Contains(out.String(), "DAC off: board/module pinout mismatch"); got != want { + t.Errorf("%s:\n%s", raw, out.String()) + } + } +} diff --git a/cmd/benchpod-cli/units.go b/cmd/benchpod-cli/units.go index 5e24bf5..e7bb7af 100644 --- a/cmd/benchpod-cli/units.go +++ b/cmd/benchpod-cli/units.go @@ -101,17 +101,13 @@ func formatSI(v float64, unit string) string { // parseLAVoltage reads the LA bank voltage as the pod takes it, in millivolts (1800, 3300, or 5000 // for 5 V I/O on the digital board v3r4; other pods refuse 5000 themselves). It accepts "3.3V", -// "1800mV", "3.3" (volts) or "3300" (a bare number above 5 is millivolts, as the pod's own commands -// take it). +// "1800mV" or "3.3" (a bare number is volts). func parseLAVoltage(s string) (int, error) { in := strings.TrimSpace(s) v, err := parseSI(in, "V") if err != nil { return 0, err } - if !strings.HasSuffix(strings.ToLower(in), "v") && v > 5 { - v /= 1000 // a bare 1800 or 3300 - } mv := int(math.Round(v * 1000)) if mv != 1800 && mv != 3300 && mv != 5000 { return 0, fmt.Errorf("LA voltage %q: the pod takes 1.8V or 3.3V (5V on the digital board v3r4)", in) @@ -119,27 +115,11 @@ func parseLAVoltage(s string) (int, error) { return mv, nil } -// sampleRateMHz resolves --sample-rate (any unit) and the older --sample-rate-mhz into MHz; 0 -// means neither was given. Both at once is a usage error. -func sampleRateMHz(cmd *cobra.Command, hz, mhz float64) (float64, error) { - if cmd.Flags().Changed("sample-rate") { - if cmd.Flags().Changed("sample-rate-mhz") { - return 0, usageErrorf("pass only one of --sample-rate or --sample-rate-mhz") - } - return hz / 1e6, nil - } - return mhz, nil -} - -// wholeUnits resolves a duration flag and its older integer flag (in unit) into whole units: -// the duration flag when set (it must be a whole number of units), else the integer flag. Both -// at once is a usage error. -func wholeUnits(cmd *cobra.Command, durFlag string, d time.Duration, intFlag string, n int, unit time.Duration) (int, error) { +// wholeUnits resolves a duration flag into whole units (0 when not set); it must be a whole +// number of them. +func wholeUnits(cmd *cobra.Command, durFlag string, d time.Duration, unit time.Duration) (int, error) { if !cmd.Flags().Changed(durFlag) { - return n, nil - } - if cmd.Flags().Changed(intFlag) { - return 0, usageErrorf("pass only one of --%s or --%s", durFlag, intFlag) + return 0, nil } if d < 0 || d%unit != 0 { return 0, usageErrorf("--%s %s: must be a whole number of %s", durFlag, d, unitName(unit)) diff --git a/cmd/benchpod-cli/units_test.go b/cmd/benchpod-cli/units_test.go index 70dfad2..bd885d9 100644 --- a/cmd/benchpod-cli/units_test.go +++ b/cmd/benchpod-cli/units_test.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "testing" ) @@ -43,57 +42,90 @@ func near(a, b float64) bool { } func TestParseLAVoltage(t *testing.T) { - for in, want := range map[string]int{"3.3V": 3300, "3.3v": 3300, "1.8V": 1800, "1800mV": 1800, "3.3": 3300, "1.8": 1800, "3300": 3300, "1800": 1800, - "5V": 5000, "5.0": 5000, "5000": 5000, "5000mV": 5000} { // 5 V: digital v3r4 (other pods refuse it) + for in, want := range map[string]int{"3.3V": 3300, "3.3v": 3300, "1.8V": 1800, "1800mV": 1800, "3.3": 3300, "1.8": 1800, + "5V": 5000, "5.0": 5000, "5000mV": 5000} { // 5 V: digital v3r4 (other pods refuse it) if got, err := parseLAVoltage(in); err != nil || got != want { t.Errorf("parseLAVoltage(%q) = %d, %v; want %d", in, got, err, want) } } - for _, in := range []string{"2.5", "1234", "4.9", "x", ""} { + // A bare number is volts: CLI 0.10 dropped "a number above 5 means mV". + for _, in := range []string{"2.5", "1234", "4.9", "x", "", "3300", "1800"} { if _, err := parseLAVoltage(in); err == nil { t.Errorf("parseLAVoltage(%q) accepted", in) } } } -// The SI-unit flags send exactly what the older unit-in-the-name flags send. -func TestSIFlagsMatchTheOldFlags(t *testing.T) { +// generate and la step send firmware 4.0's names and units (Hz, volts), from the SI flags. +func TestSIFlagsAndFirmware4Names(t *testing.T) { t.Setenv("BENCHPOD_CONNECTION", "") t.Setenv("BENCHPOD_TIMEOUT", "") addr, got := fakeLANPod(t, `{"status":"ok","data":null}`) - request := func(args ...string) map[string]any { + request := func(args ...string) string { t.Helper() if code := run(append(args, "--connection", addr)); code != exitOK { t.Fatalf("%v: exit %d", args, code) } - var req map[string]any - if err := json.Unmarshal([]byte(<-got), &req); err != nil { - t.Fatal(err) - } - return req + return <-got } - same := func(a, b map[string]any) { - t.Helper() - ja, _ := json.Marshal(a) - jb, _ := json.Marshal(b) - if string(ja) != string(jb) { - t.Fatalf("\n new %s\n old %s", ja, jb) - } + if req := request("generate", "--waveform", "sine", "--freq", "2kHz", "--duration", "2s", "--sample-rate", "10MHz", + "--path", "3v3", "--amplitude-v", "1", "--offset-v", "1.65"); req != `{"amplitude_v":1,"cmd":"generate","duration_ms":2000,`+ + `"freq_hz":2000,"offset_v":1.65,"path":"3v3","sample_rate_hz":10000000,"waveform":"sine"}` { + t.Fatalf("generate %s", req) + } + if req := request("generate", "--waveform", "square", "--amplitude-ma", "4", "--offset-ma", "12"); req != + `{"amplitude_ua":4000,"cmd":"generate","duration_ms":0,"freq_hz":1000,"offset_ua":12000,"waveform":"square"}` { + t.Fatalf("generate mA %s", req) + } + if req := request("la", "step", "--la", "6", "--steps", "3", "--delay", "50us"); req != `{"cmd":"la_step","delay_us":50,"la":6,"steps":3}` { + t.Fatalf("la step %s", req) + } + if req := request("measure", "--waveform", "sine", "--freq", "1kHz", "--sample-rate", "1MHz", "--samples", "4"); req != + `{"amplitude":127,"cmd":"measure","freq_hz":1000,"offset":128,"sample_rate_hz":1000000,"samples":4,"waveform":"sine"}` { + t.Fatalf("measure %s", req) } - same(request("generate", "--waveform", "sine", "--freq", "2kHz", "--duration", "2s", "--sample-rate", "10MHz"), - request("generate", "--waveform", "sine", "--freq", "2000", "--duration-ms", "2000", "--sample-rate-mhz", "10")) - same(request("la", "step", "--la", "6", "--steps", "3", "--delay", "50us"), - request("la", "step", "--la", "6", "--steps", "3", "--delay-us", "50")) + volts := []string{"--path", "3v3", "--amplitude-v", "1", "--offset-v", "1"} for _, args := range [][]string{ - {"generate", "--waveform", "sine", "--duration", "2s", "--duration-ms", "5"}, - {"generate", "--waveform", "sine", "--duration", "1500us"}, - {"generate", "--waveform", "sine", "--sample-rate", "fast"}, - {"generate", "--waveform", "sine", "--sample-rate", "1MHz", "--sample-rate-mhz", "1"}, + {"generate", "--waveform", "sine"}, // no volts or mA: the 8-bit levels are gone + {"generate", "--waveform", "sine", "--amplitude", "100"}, + append([]string{"generate", "--waveform", "sine", "--duration-ms", "5"}, volts...), + append([]string{"generate", "--waveform", "sine", "--duration", "1500us"}, volts...), + append([]string{"generate", "--waveform", "sine", "--sample-rate", "fast"}, volts...), + append([]string{"generate", "--waveform", "sine", "--sample-rate-mhz", "1"}, volts...), {"la", "step", "--la", "6", "--steps", "3", "--delay", "1500ns"}, + {"la", "step", "--la", "6", "--steps", "3", "--delay-us", "50"}, + {"capture", "--sample-rate-mhz", "1"}, } { if code := run(append(args, "--connection", addr)); code != exitUsage { t.Errorf("%v: exit %d, want %d", args, code, exitUsage) } } } + +// One name each: --out for output files, --format for formats, --addr for addresses. +func TestOneFlagName(t *testing.T) { + root := newRootCmd() + for _, c := range []struct { + path []string + has, gone string + }{ + {[]string{"capture"}, "format", "output"}, + {[]string{"measure"}, "format", "output"}, + {[]string{"test"}, "format", "output"}, + {[]string{"sensor", "export"}, "out", "output"}, + {[]string{"sensor", "start"}, "addr", "address"}, + {[]string{"flash-self"}, "addr", "address"}, + } { + cmd, _, err := root.Find(c.path) + if err != nil { + t.Fatal(err) + } + if cmd.Flags().Lookup(c.has) == nil || cmd.Flags().Lookup(c.gone) != nil { + t.Errorf("%v: want --%s and no --%s", c.path, c.has, c.gone) + } + } + if root.PersistentFlags().Lookup("out") == nil || root.PersistentFlags().Lookup("output-filename") != nil { + t.Error("global --out") + } +} diff --git a/cmd/benchpod-cli/usbbridge.go b/cmd/benchpod-cli/usbbridge.go index 19c2868..6e56b17 100644 --- a/cmd/benchpod-cli/usbbridge.go +++ b/cmd/benchpod-cli/usbbridge.go @@ -14,6 +14,7 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -118,7 +119,7 @@ func serveBridge(ctx context.Context, s *bridgeSession) bool { func runUSBBridge(g *globalFlags, port int, keep, watch bool) error { if port <= 0 || port > 65535 { - return fmt.Errorf("usb-bridge: --port %d is out of range", port) + return usageErrorf("usb-bridge: --port %d is out of range", port) } // Never the console (usbbridge_watch.go): the pod's USB network link only. return runUSBBridgeWatch(g, port, keep, watch) @@ -226,25 +227,25 @@ func newUSBReattachCmd(g *globalFlags) *cobra.Command { return &cobra.Command{ Use: "usb-reattach", Short: "Make the pod reconnect on USB, so this computer sets up its USB network adapter again", - Long: "Make the pod drop off the USB bus for half a second and connect again (USB console).\n" + + Long: "Make the pod drop off the USB bus for half a second and connect again (usb_reattach).\n" + "This computer then enumerates the console and the USB network adapter anew, as after\n" + "replugging the cable. macOS ignores a new network adapter while the screen is locked,\n" + "so run this after unlocking when the pod was plugged in or rebooted meanwhile.\n" + - "Needs firmware 3.9.0 or later.", + "The CLI sends it over the pod's USB network adapter when that is up, else over the\n" + + "pod's network address from its console status (or the --connection given); with\n" + + "neither, unplug the USB cable and plug it back in.", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("usb-reattach") + ctx, cancel, t, err := g.usbNetworkClient("usb-reattach", 10*time.Second) if err != nil { - return err - } - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(10*time.Second)) - if err != nil { - return err + return fmt.Errorf("%w (or unplug the USB cable and plug it back in)", err) } defer cancel() - defer console.Close() - if err := console.USBReattach(ctx); err != nil { - return fmt.Errorf("usb-reattach: %w", err) + if _, err := t.client.Command(ctx, map[string]any{"cmd": "usb_reattach"}); err != nil { + // Over the USB link itself the connection drops with the re-enumeration. + if _, refused := tcpclient.AsPodError(err); refused || !t.spec.IsNetwork() || !tcpclient.IsUSBLinkAddr(hostOf(t.spec.Addr)) { + return wifiError("usb-reattach", err) + } } fmt.Fprintln(os.Stderr, "The pod reconnected on USB; its network adapter (unless turned off with `benchpod usb-network off`) is back in a few seconds.") return nil diff --git a/cmd/benchpod-cli/usbbridge_service.go b/cmd/benchpod-cli/usbbridge_service.go index b1211f8..1138d29 100644 --- a/cmd/benchpod-cli/usbbridge_service.go +++ b/cmd/benchpod-cli/usbbridge_service.go @@ -280,7 +280,7 @@ func newUSBBridgeInstallCmd(g *globalFlags) *cobra.Command { Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { if port <= 0 || port > 65535 { - return fmt.Errorf("usb-bridge install: --port %d is out of range", port) + return usageErrorf("usb-bridge install: --port %d is out of range", port) } exe, err := benchpodExecutable() if err != nil { diff --git a/cmd/benchpod-cli/usbnet.go b/cmd/benchpod-cli/usbnet.go index 0235ca9..640dc4b 100644 --- a/cmd/benchpod-cli/usbnet.go +++ b/cmd/benchpod-cli/usbnet.go @@ -7,6 +7,7 @@ import ( "io" "net" "os" + "strings" "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" @@ -18,6 +19,12 @@ import ( // needs the network and is given a USB connection uses it; the console stays for the commands // that only the console runs and as the fallback. +// usbNetworkOffHint is how a user brings the pod's USB network adapter back, for the commands +// that run over it (JSON over USB) when it is off. +const usbNetworkOffHint = "Turn USB networking on with `benchpod usb-network on --connection usb` (the pod's console " + + "`usb-network on`); Wi-Fi set on the pod keeps it off: clear it with `benchpod clear-wifi` over the pod's network " + + "address, or `benchpod net-reset` over USB" + // usbNetProbeTimeout bounds the TCP check of the pod's address on the USB link. const usbNetProbeTimeout = 2 * time.Second @@ -70,9 +77,9 @@ func (g *globalFlags) usbNetAddr(device string) (string, error) { var why error switch { case !u.On && u.OffBySetting: - why = errors.New("USB networking is turned off on the pod (`benchpod usb-network on` over its USB console turns it back on)") + why = errors.New("USB networking is turned off on the pod (`benchpod usb-network on --connection usb`, the pod's console `usb-network on`, turns it back on)") case !u.On: - why = errors.New("USB networking is off because Wi-Fi is configured on the pod (`benchpod clear-wifi` turns it back on)") + why = errors.New("USB networking is off because Wi-Fi is configured on the pod (`benchpod clear-wifi` over its network address, or `benchpod net-reset` over USB, turns it back on)") case !u.Link: why = fmt.Errorf("the pod's USB network adapter (%s) is not up on this computer; "+ "macOS ignores a new adapter while the screen is locked: unlock and run `benchpod usb-reattach`", u.PodIP) @@ -174,6 +181,42 @@ func (g *globalFlags) networkTarget(cmd string) (ConnSpec, error) { if err != nil || !spec.IsSerial() { return spec, err } + return g.networkTargetFor(spec, cmd) +} + +// usbNetworkTarget is the pod's API for the commands that used to run on the USB console and now +// send JSON over the pod's USB network adapter (set-wifi, show-network, identity wipe, ...): an +// explicit network or embeddedci.com --connection is used as given; otherwise the pod on USB (a +// saved network default falls through to USB, as these commands always did), its USB network +// adapter, else its network address when that answers. +func (g *globalFlags) usbNetworkTarget(cmd string) (ConnSpec, error) { + if raw := strings.TrimSpace(g.connection); raw != "" { + if spec, err := parseTarget(raw); err == nil && !spec.IsSerial() { + return spec, nil + } + } + spec := ConnSpec{Kind: connSerial, Device: g.serialDevice(), Pod: g.usbPodName()} + return g.networkTargetFor(spec, cmd) +} + +// usbNetworkClient is podClient for usbNetworkTarget. +func (g *globalFlags) usbNetworkClient(cmd string, def time.Duration) (context.Context, context.CancelFunc, *podTarget, error) { + spec, err := g.usbNetworkTarget(cmd) + if err != nil { + return nil, func() {}, nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(def)) + cancel = withSignalCleanup(cancel, installSignalHandler(ctx, cancel)) + t, err := openPodTarget(ctx, spec) + if err != nil { + cancel() + return nil, func() {}, nil, fmt.Errorf("%s: %w", cmd, err) + } + return ctx, cancel, t, nil +} + +// networkTargetFor is networkTarget for a USB spec. +func (g *globalFlags) networkTargetFor(spec ConnSpec, cmd string) (ConnSpec, error) { if g.usbAddr != "" { return ConnSpec{Kind: connNetwork, Addr: g.usbAddr}, nil } diff --git a/cmd/benchpod-cli/usbnet_test.go b/cmd/benchpod-cli/usbnet_test.go index 6e29080..bedec60 100644 --- a/cmd/benchpod-cli/usbnet_test.go +++ b/cmd/benchpod-cli/usbnet_test.go @@ -111,14 +111,14 @@ func TestPreferredPodIPPicksTheUSBLink(t *testing.T) { func TestDescribeUSBWarnsAboutDefaultPower(t *testing.T) { ma := 500 - got := describeUSB(podUSB{Net: "on", Link: true, IP: "10.237.8.85", HostIP: "10.237.8.86", Source: "default", SourceMA: &ma}) + got := describeUSB(podUSB{Net: true, Link: true, IP: "10.237.8.85", HostIP: "10.237.8.86", Source: "default", SourceMA: &ma}) if !strings.Contains(got, "10.237.8.85") || !strings.Contains(got, "500 mA") || !strings.Contains(got, "1.5 A") { t.Fatalf("got %q", got) } - if got := describeUSB(podUSB{Net: "on", Source: "3.0A"}); strings.Contains(got, "500 mA") || !strings.Contains(got, "power 3.0A") { + if got := describeUSB(podUSB{Net: true, Source: "3.0A"}); strings.Contains(got, "500 mA") || !strings.Contains(got, "power 3.0A") { t.Fatalf("3.0A: %q", got) } - if got := describeUSB(podUSB{Net: "off"}); !strings.Contains(got, "Wi-Fi") { + if got := describeUSB(podUSB{Net: false}); !strings.Contains(got, "Wi-Fi") { t.Fatalf("off: %q", got) } } @@ -131,7 +131,7 @@ func TestDescribePowerDraw(t *testing.T) { TotalUA *int `json:"total_ua"` }{powerRail{OK: true, BusMV: 5012, CurrentUA: 231000}, &total} tp := &targetPower{} - tp.Efuse1.Enabled = 1 + tp.Efuse1.Enabled = true got := describePowerDraw(d, tp) for _, want := range []string{"internal 5 V rail 142 mA", "pod 231 mA", "total from USB 373 mA"} { if !strings.Contains(got, want) { diff --git a/cmd/benchpod-cli/usbnetwork.go b/cmd/benchpod-cli/usbnetwork.go index 408a961..d223d06 100644 --- a/cmd/benchpod-cli/usbnetwork.go +++ b/cmd/benchpod-cli/usbnetwork.go @@ -106,7 +106,7 @@ func runUSBNetwork(g *globalFlags, set string, out io.Writer) error { return errors.New(usbNetworkMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } @@ -118,7 +118,7 @@ func runUSBNetwork(g *globalFlags, set string, out io.Writer) error { func usbNetworkJSON(ctx context.Context, c podCommander, set string) (string, error) { req := map[string]any{"cmd": "usb_network"} if set != "" { - req["set"] = set + req["enabled"] = set == "on" } data, err := c.Command(ctx, req) if err != nil { @@ -128,12 +128,15 @@ func usbNetworkJSON(ctx context.Context, c podCommander, set string) (string, er return "", err } var rep struct { - Setting string `json:"setting"` + Enabled *bool `json:"enabled"` } - if err := json.Unmarshal(data, &rep); err != nil || rep.Setting == "" { + if err := json.Unmarshal(data, &rep); err != nil || rep.Enabled == nil { return "", fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(data))) } - return rep.Setting, nil + if *rep.Enabled { + return "on", nil + } + return "off", nil } func printUSBNetwork(out io.Writer, via, setting, set string) { diff --git a/cmd/benchpod-cli/usbnetwork_test.go b/cmd/benchpod-cli/usbnetwork_test.go index ee5febe..828282b 100644 --- a/cmd/benchpod-cli/usbnetwork_test.go +++ b/cmd/benchpod-cli/usbnetwork_test.go @@ -10,7 +10,7 @@ import ( // Over Ethernet/Wi-Fi the setting is read; changing it is refused before anything is sent. func TestUSBNetworkOnTheLANReadsOnly(t *testing.T) { - addr, got := fakeLANPod(t, `{"status":"ok","data":{"setting":"on"}}`) + addr, got := fakeLANPod(t, `{"status":"ok","data":{"enabled":true}}`) g := &globalFlags{connection: addr} var out bytes.Buffer if err := runUSBNetwork(g, "", &out); err != nil || !strings.Contains(out.String(), ": on") { @@ -27,7 +27,7 @@ func TestUSBNetworkOnTheLANReadsOnly(t *testing.T) { // Over USB, `off` goes over the pod's USB link itself (no console); the pod's reply is printed. func TestUSBNetworkOffOverTheUSBLink(t *testing.T) { - addr, got := fakeLANPod(t, `{"status":"ok","data":{"setting":"off"}}`) + addr, got := fakeLANPod(t, `{"status":"ok","data":{"enabled":false}}`) old := localUSBPod t.Cleanup(func() { localUSBPod = old }) localUSBPod = func(string) string { return addr } @@ -35,7 +35,7 @@ func TestUSBNetworkOffOverTheUSBLink(t *testing.T) { if err := runUSBNetwork(&globalFlags{connection: "usb"}, "off", &out); err != nil { t.Fatal(err) } - if req := <-got; !strings.Contains(req, `"set":"off"`) || !strings.Contains(req, `"usb_network"`) { + if req := <-got; !strings.Contains(req, `"enabled":false`) || !strings.Contains(req, `"usb_network"`) { t.Fatalf("request %s", req) } if !strings.Contains(out.String(), "now off") || !strings.Contains(out.String(), "usb-network on") { @@ -64,7 +64,7 @@ func TestParseUSBNetOffBySetting(t *testing.T) { if u.On || u.OffBySetting { t.Fatalf("wifi: %+v", u) } - if got := describeUSB(podUSB{Net: "off", OffReason: "setting"}); !strings.Contains(got, "usb-network on") { + if got := describeUSB(podUSB{Net: false, OffReason: "setting"}); !strings.Contains(got, "usb-network on") { t.Fatalf("status row %q", got) } } diff --git a/cmd/benchpod-cli/wifi.go b/cmd/benchpod-cli/wifi.go new file mode 100644 index 0000000..d701807 --- /dev/null +++ b/cmd/benchpod-cli/wifi.go @@ -0,0 +1,517 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" + "time" + + "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" + "github.com/spf13/cobra" +) + +// ── Wi-Fi over JSON ───────────────────────────────────────────────────────── +// +// set-wifi, show-network, scan-wifi and clear-wifi send the pod's JSON commands (wifi_set, +// wifi_status, wifi_scan, wifi_clear) over its USB network adapter (usbNetworkTarget): firmware +// 4.0 has no Wi-Fi commands on its console. Wi-Fi and USB networking are one or the other on the +// pod: wifi_set turns USB networking off (its reply still goes out over it), wifi_clear turns it +// back on. When no network reaches the pod at all, the console's `net-reset` (benchpod net-reset) +// forgets the Wi-Fi. + +// wifiState is the part of the pod's wifi_status reply the CLI reads. +type wifiState struct { + State string `json:"state"` + Configured bool `json:"configured"` + Connected bool `json:"connected"` + SSID string `json:"ssid"` + Via string `json:"via"` // "wifi-bridge" when a Wi-Fi bridge on the Ethernet port carries Wi-Fi + RSSI *int `json:"rssi_dbm"` + Bridge *struct { + Paired bool `json:"paired"` + Problem *string `json:"problem"` + RSSI *int `json:"rssi_dbm"` + } `json:"bridge"` +} + +func (s wifiState) viaBridge() bool { return s.Via == "wifi-bridge" } + +// rssi is the signal of the link that carries Wi-Fi ("" when not joined). +func (s wifiState) rssi() string { + r := s.RSSI + if s.viaBridge() && s.Bridge != nil { + r = s.Bridge.RSSI + } + if r == nil { + return "" + } + return strconv.Itoa(*r) + " dBm" +} + +// problem is what the pod sees wrong with its Wi-Fi bridge, "" if nothing. +func (s wifiState) problem() string { + if s.Bridge != nil && s.Bridge.Problem != nil { + return *s.Bridge.Problem + } + return "" +} + +// bridgeJoinFailure is why the bridge cannot join, "" while it is joining or has joined. +func (s wifiState) bridgeJoinFailure() string { + switch s.State { + case "auth-failed": + return "the Wi-Fi bridge could not join: wrong password (or the network refused it)" + case "no-ap": + return "the Wi-Fi bridge could not join: it does not see that network" + } + return "" +} + +// joined says the pod (or its bridge) is joined to ssid. +func (s wifiState) joined(ssid string) bool { + return (s.Connected || s.State == "connected") && strings.TrimSpace(s.SSID) == strings.TrimSpace(ssid) +} + +func readWifi(ctx context.Context, c podCommander) (wifiState, error) { + var st wifiState + raw, err := c.Command(ctx, map[string]any{"cmd": "wifi_status"}) + if err != nil { + return st, err + } + if err := json.Unmarshal(raw, &st); err != nil { + return st, fmt.Errorf("wifi_status: unexpected reply %s", strings.TrimSpace(string(raw))) + } + return st, nil +} + +// podIP is the pod's Ethernet (else Wi-Fi) address from its status, "" when it has none. +func podIP(ctx context.Context, c podCommander) string { + raw, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}) + if err != nil { + return "" + } + var st struct { + IP string `json:"ip"` + } + if json.Unmarshal(raw, &st) != nil { + return "" + } + return usableIP(st.IP) +} + +func usableIP(ip string) string { + ip = strings.TrimSpace(ip) + if p := net.ParseIP(ip); p == nil || p.IsUnspecified() { + return "" + } + return ip +} + +// ── set-wifi ───────────────────────────────────────────────────────────────── + +func newSetWifiCmd(g *globalFlags) *cobra.Command { + var ssid, password string + var passwordStdin, skipBlobs bool + cmd := &cobra.Command{ + Use: "set-wifi", + Short: "Save Wi-Fi credentials and join (over the pod's USB network adapter)", + Long: "Save Wi-Fi credentials on the pod and wait for it to join. The CLI sends them\n" + + "over the pod's USB network adapter (wifi_set). Wi-Fi and USB networking are one or\n" + + "the other on the pod: once the credentials are stored, USB networking turns off\n" + + "(`benchpod clear-wifi` over the pod's network address, or `benchpod net-reset`\n" + + "over USB, turns it back on). With a Wi-Fi bridge on the pod's Ethernet port the\n" + + "bridge keeps them and USB networking stays on.\n\n" + + "USB networking off: `benchpod usb-network on --connection usb` (the pod's\n" + + "console `usb-network on`).", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + if strings.TrimSpace(ssid) == "" { + return usageErrorf("--ssid is required") + } + pw, err := resolveWifiPassword(password, passwordStdin) + if err != nil { + return fmt.Errorf("set-wifi: %w", err) + } + _, err = runSetWifi(g, ssid, pw, skipBlobs) + return err + }, + } + cmd.Flags().StringVar(&ssid, "ssid", "", "Wi-Fi SSID (required)") + cmd.Flags().StringVar(&password, "password", "", "Wi-Fi password (insecure: visible in shell history); omit to be prompted") + cmd.Flags().BoolVar(&passwordStdin, "password-stdin", false, "read the Wi-Fi password from the first line of stdin") + cmd.Flags().BoolVar(&skipBlobs, "skip-blobs", false, "do not install a missing ESP32-C3 image first (not needed through a Wi-Fi bridge)") + return cmd +} + +// wifiJoinWait bounds how long set-wifi waits for the pod (or its bridge) to join; wifiJoinPoll is +// how often it asks. Variables for the tests. +var ( + wifiJoinWait = 45 * time.Second + wifiJoinPoll = 3 * time.Second +) + +// runSetWifi saves Wi-Fi credentials over the pod's network API and waits for the join, returning +// the pod's address when the join is confirmed ("" when it is not). Shared by set-wifi and setup. +func runSetWifi(g *globalFlags, ssid, pw string, skipBlobs bool) (string, error) { + ctx, cancel, t, err := g.usbNetworkClient("set-wifi", 90*time.Second) + if err != nil { + return "", err + } + defer cancel() + + before, err := readWifi(ctx, t.client) + if err != nil { + return "", wifiError("set-wifi", err) + } + // Wi-Fi runs on the ESP32-C3, whose image the pod keeps in its W25Q: a pod without it (fresh + // board, no network) can only get it over USB. + if !before.viaBridge() && !skipBlobs && t.spec.IsNetwork() { + if err := ensureEspBlob(ctx, t.spec.Addr); err != nil { + return "", fmt.Errorf("set-wifi: %w", err) + } + } + raw, err := t.client.Command(ctx, map[string]any{"cmd": "wifi_set", "ssid": ssid, "password": pw}) + if err != nil { + return "", wifiError("set-wifi", err) + } + var rep struct { + Via string `json:"via"` + } + _ = json.Unmarshal(raw, &rep) + bridge := before.viaBridge() || rep.Via == "wifi-bridge" + if bridge { + fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q on the pod's Wi-Fi bridge via %s; waiting for it to join...\n", ssid, t.label) + } else { + fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q via %s; waiting for the pod to join "+ + "(USB networking turns off now)...\n", ssid, t.label) + } + return waitWifiJoin(ctx, g, t, ssid, bridge) +} + +// waitWifiJoin follows the join: over the connection the credentials went over while it still +// works (a bridge, the pod's Ethernet, embeddedci.com), else over the address the pod's console +// status reports once it has one. +func waitWifiJoin(ctx context.Context, g *globalFlags, t *podTarget, ssid string, bridge bool) (string, error) { + deadline := time.Now().Add(wifiJoinWait) + var st wifiState + for { + var c podCommander = t.client + s, err := readWifi(ctx, c) + if err != nil && !bridge { + // The USB link went down with wifi_set: find the pod's new address on its console. + if ip := consolePodIP(g); ip != "" { + c = &tcpclient.Client{Addr: net.JoinHostPort(ip, wifiPodPort), DialTimeout: 2 * time.Second} + s, err = readWifi(ctx, c) + } + } + if err == nil { + st = s + if st.joined(ssid) { + ip := podIP(ctx, c) + if bridge { + fmt.Fprintf(os.Stderr, "The Wi-Fi bridge joined %q (rssi %s), pod ip=%s\n", ssid, valueOrDash(st.rssi()), valueOrDash(ip)) + } else { + fmt.Fprintf(os.Stderr, "Joined %q, ip=%s\n", ssid, valueOrDash(ip)) + } + return ip, nil + } + if why := st.bridgeJoinFailure(); bridge && strings.TrimSpace(st.SSID) == ssid && why != "" { + return "", fmt.Errorf("set-wifi: %s (the credentials are saved on the bridge; run set-wifi again to change them)", why) + } + } + if time.Now().After(deadline) || ctx.Err() != nil { + break + } + select { + case <-ctx.Done(): + case <-time.After(wifiJoinPoll): + } + } + fmt.Fprintf(os.Stderr, "Credentials saved; join not confirmed yet (state %s; run `benchpod show-network`).\n", valueOrDash(st.State)) + return "", nil +} + +// wifiPodPort is the port set-wifi reaches the pod on at its new address (tests change it). +var wifiPodPort = tcpclient.PlainPort + +// consolePodIP is the pod's network address from its USB console's status, "" when it has none +// (or no console answers). A variable so tests can replace it. +var consolePodIP = func(g *globalFlags) string { + pods, _, err := serialconsole.ProbeSerial(g.serialDevice(), 2*time.Second) + if err != nil { + return "" + } + name := g.usbPodName() + for _, p := range pods { + if name != "" && !strings.Contains(p.Status, name) { + continue + } + if p.Addressed() && !usbLinkNet.Contains(net.ParseIP(p.IP)) { + return p.IP + } + } + return "" +} + +// wifiError words a failed Wi-Fi command; a pod without built-in Wi-Fi or a bridge says so itself. +func wifiError(what string, err error) error { + if pe, ok := tcpclient.AsPodError(err); ok { + return refusedError(what, pe) + } + return fmt.Errorf("%s: %w", what, err) +} + +// ensureEspBlob installs the blobs from the pod's firmware release when its ESP32-C3 slot is +// empty or holds a different image, so set-wifi works on a pod that has never had a network. +func ensureEspBlob(ctx context.Context, addr string) error { + ctx, cancel := context.WithTimeout(ctx, blobsInstallTimeout) + defer cancel() + lan, err := openLAN(ctx, addr) + if err != nil { + return fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) + } + defer lan.s.Close() + target := lanBlobs{lan: lan, addr: addr} + slots, err := target.Blobs(ctx) + missing, err := espBlobMissing(slots, err) + if err != nil || !missing { + return err + } + fmt.Fprintln(os.Stderr, "set-wifi: the pod has no ESP32-C3 image for Wi-Fi yet; installing it over USB first") + return installBlobs(ctx, target, releaseBlobSource(target.Release(ctx)), false, nil) +} + +// espBlobMissing reads the pod's blob listing for set-wifi: whether the ESP32-C3 image needs +// installing. Firmware without blob slots keeps the image built in, which is fine; any other +// error reading the slots is reported, with --skip-blobs as the way past it. +func espBlobMissing(slots []serialconsole.BlobSlot, err error) (bool, error) { + if errors.Is(err, serialconsole.ErrNoBlobSlots) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) + } + for _, s := range slots { + if s.Name == "esp" && s.NeedsInstall() { + return true, nil + } + } + return false, nil +} + +// ── show-network ───────────────────────────────────────────────────────────── + +// newShowNetworkCmd reports the pod's network state. It is named for what it reports rather than +// for one of the interfaces it can report on: the IP is whichever address the pod is actually +// using, and the pod prefers its wired Ethernet lease, so on a cabled pod this prints an address +// and no SSID at all. +func newShowNetworkCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "show-network", + Short: "Show the pod's network details: IP, plus stored SSID/state/RSSI (over the pod's USB network adapter)", + Long: "Report the pod's network state (status and wifi_status, over the pod's USB\n" + + "network adapter, or the --connection given).\n\n" + + "The IP is whichever address the pod is actually using: it prefers the wired\n" + + "Ethernet lease over Wi-Fi, so a pod on a cable reports an address here with no\n" + + "SSID at all. The SSID/state/RSSI fields describe the optional Wi-Fi interface.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + ctx, cancel, t, err := g.usbNetworkClient("show-network", 15*time.Second) + if err != nil { + return err + } + defer cancel() + st, err := readWifi(ctx, t.client) + if err != nil { + return wifiError("show-network", err) + } + out, closeOut, err := resolveOutput(g.outputFilename) + if err != nil { + return fmt.Errorf("show-network: open output: %w", err) + } + defer closeOut() + printNetwork(out, podIP(ctx, t.client), st) + return nil + }, + } +} + +func printNetwork(out io.Writer, ip string, st wifiState) { + // IP first: it is the field that matters on any pod, and it is populated on a wired pod that + // has no SSID at all. + fmt.Fprintf(out, "IP: %s\n", valueOrDash(ip)) + fmt.Fprintf(out, "SSID: %s\n", valueOrDash(st.SSID)) + fmt.Fprintf(out, "State: %s\n", valueOrDash(st.State)) + fmt.Fprintf(out, "RSSI: %s\n", valueOrDash(st.rssi())) + if st.Via != "" { + fmt.Fprintf(out, "Via: %s\n", st.Via) + } + if p := st.problem(); p != "" { + fmt.Fprintf(out, "Problem: %s\n", p) + } +} + +// ── scan-wifi ──────────────────────────────────────────────────────────────── + +// wifiScanPoll is how often scan-wifi reads a running scan. +var wifiScanPoll = 500 * time.Millisecond + +type wifiNetwork struct { + SSID string `json:"ssid"` + RSSI int `json:"rssi"` + Channel int `json:"channel"` + Auth string `json:"auth"` +} + +// newScanWifiCmd lists the networks the pod's Wi-Fi sees, to pick the SSID for set-wifi. +func newScanWifiCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "scan-wifi", + Short: "List the Wi-Fi networks the pod sees (over the pod's USB network adapter)", + Long: "List the Wi-Fi networks the pod sees, strongest first, to pick the SSID for set-wifi\n" + + "(wifi_scan, over the pod's USB network adapter). The pod scans with its built-in\n" + + "Wi-Fi, or with a Wi-Fi bridge on its Ethernet port when one is plugged in. A scan\n" + + "takes a few seconds; a joined pod stays joined.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + // 45 s: a pod that is joining waits for the join to finish (up to 30 s) before it scans. + ctx, cancel, t, err := g.usbNetworkClient("scan-wifi", 45*time.Second) + if err != nil { + return err + } + defer cancel() + nets, truncated, err := scanWifi(ctx, t.client) + if err != nil { + return wifiError("scan-wifi", err) + } + out, closeOut, err := resolveOutput(g.outputFilename) + if err != nil { + return fmt.Errorf("scan-wifi: open output: %w", err) + } + defer closeOut() + fmt.Fprintf(out, "%-6s %-4s %-10s %s\n", "RSSI", "CH", "SECURITY", "SSID") + for _, n := range nets { + ssid := n.SSID + if ssid == "" { + ssid = "(hidden)" + } + fmt.Fprintf(out, "%-6d %-4d %-10s %s\n", n.RSSI, n.Channel, n.Auth, ssid) + } + msg := fmt.Sprintf("%d networks", len(nets)) + if truncated { + msg += " (weaker ones left out)" + } + fmt.Fprintln(os.Stderr, msg) + return nil + }, + } +} + +// scanWifi starts a scan and reads it until it is done. +func scanWifi(ctx context.Context, c podCommander) ([]wifiNetwork, bool, error) { + var rep struct { + State string `json:"state"` + ID int `json:"id"` + Networks []wifiNetwork `json:"networks"` + Truncated bool `json:"truncated"` + } + req := map[string]any{"cmd": "wifi_scan"} + for { + raw, err := c.Command(ctx, req) + if err != nil { + return nil, false, err + } + if err := json.Unmarshal(raw, &rep); err != nil { + return nil, false, fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) + } + if rep.State == "done" { + return rep.Networks, rep.Truncated, nil + } + req = map[string]any{"cmd": "wifi_scan", "id": rep.ID} + select { + case <-ctx.Done(): + return nil, false, ctx.Err() + case <-time.After(wifiScanPoll): + } + } +} + +// ── clear-wifi ─────────────────────────────────────────────────────────────── + +// clearWifiTimeout covers the reply; the pod erases the ESP32-C3's NVS after it. +const clearWifiTimeout = 60 * time.Second + +func newClearWifiCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "clear-wifi", + Short: "Erase the stored Wi-Fi credentials (Wi-Fi goes down at once)", + Long: "Erase the pod's stored Wi-Fi credentials (wifi_clear): Wi-Fi goes down and USB\n" + + "networking comes back on. The CLI sends it over the pod's network: its USB network\n" + + "adapter, else (USB networking is off while Wi-Fi is set) its network address, or\n" + + "the --connection given. When no network reaches the pod, `benchpod net-reset`\n" + + "does it over the USB console.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + ctx, cancel, t, err := g.usbNetworkClient("clear-wifi", clearWifiTimeout) + if err != nil { + return fmt.Errorf("%w (without a network, `benchpod net-reset` clears the Wi-Fi over the USB console)", err) + } + defer cancel() + if _, err := t.client.Command(ctx, map[string]any{"cmd": "wifi_clear"}); err != nil { + return wifiError("clear-wifi", err) + } + fmt.Fprintln(os.Stderr, "Erased the stored Wi-Fi credentials. Wi-Fi is off; no reboot needed. USB networking is on again.") + return nil + }, + } +} + +// ── net-reset ──────────────────────────────────────────────────────────────── + +func newNetResetCmd(g *globalFlags) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "net-reset", + Short: "Forget the Wi-Fi and reset Ethernet over the USB console, when no network reaches the pod", + Long: "Run the pod's console `net-reset` (firmware 4.0): the pod forgets its Wi-Fi\n" + + "credentials (its own flash and the ESP32-C3's, or the Wi-Fi bridge's), which turns\n" + + "USB networking back on, and puts Ethernet back to autonegotiation with a PHY reset\n" + + "and a new DHCP lease. The policies, the cloud settings and the device key stay.\n" + + "It is the way back to a pod that no network reaches; with a network, clear-wifi\n" + + "does the Wi-Fi part.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + if !yes && !confirmYes("This forgets the pod's Wi-Fi and resets its Ethernet link. Type 'yes' to continue: ") { + return errors.New("aborted") + } + device, err := g.usbDevice("net-reset") + if err != nil { + return err + } + console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(clearWifiTimeout)) + if err != nil { + return err + } + defer cancel() + defer console.Close() + lines, err := console.NetReset(ctx) + for _, ln := range lines { + fmt.Fprintf(os.Stderr, " %s\n", ln) + } + if err != nil { + return fmt.Errorf("net-reset: %w", err) + } + fmt.Fprintln(os.Stderr, "Wi-Fi forgotten and Ethernet reset; USB networking is on again.") + return nil + }, + } + cmd.Flags().BoolVar(&yes, "yes", false, "skip the confirmation prompt") + return cmd +} diff --git a/cmd/benchpod-cli/wifi_test.go b/cmd/benchpod-cli/wifi_test.go new file mode 100644 index 0000000..8440e21 --- /dev/null +++ b/cmd/benchpod-cli/wifi_test.go @@ -0,0 +1,247 @@ +package main + +import ( + "bufio" + "encoding/json" + "net" + "os" + "strings" + "sync" + "testing" + "time" +) + +// jsonPod is a pod's JSON API that answers every line of every connection with handle. +type jsonPod struct { + mu sync.Mutex + reqs []map[string]any + handle func(req map[string]any) string +} + +func startJSONPod(t *testing.T, handle func(req map[string]any) string) (*jsonPod, string) { + t.Helper() + p := &jsonPod{handle: handle} + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + r := bufio.NewReader(c) + for { + line, err := r.ReadString('\n') + if err != nil { + return + } + var req map[string]any + _ = json.Unmarshal([]byte(line), &req) + p.mu.Lock() + p.reqs = append(p.reqs, req) + p.mu.Unlock() + if _, err := c.Write([]byte(p.handle(req) + "\n")); err != nil { + return + } + } + }(conn) + } + }() + return p, ln.Addr().String() +} + +func (p *jsonPod) cmds() []string { + p.mu.Lock() + defer p.mu.Unlock() + var out []string + for _, r := range p.reqs { + c, _ := r["cmd"].(string) + out = append(out, c) + } + return out +} + +func (p *jsonPod) last(cmd string) map[string]any { + p.mu.Lock() + defer p.mu.Unlock() + for i := len(p.reqs) - 1; i >= 0; i-- { + if p.reqs[i]["cmd"] == cmd { + return p.reqs[i] + } + } + return nil +} + +func fastWifiJoin(t *testing.T) { + oldWait, oldPoll, oldScan, oldIP := wifiJoinWait, wifiJoinPoll, wifiScanPoll, consolePodIP + wifiJoinWait, wifiJoinPoll, wifiScanPoll = 2*time.Second, 20*time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { wifiJoinWait, wifiJoinPoll, wifiScanPoll, consolePodIP = oldWait, oldPoll, oldScan, oldIP }) + consolePodIP = func(*globalFlags) string { return "" } +} + +// set-wifi: wifi_set over the USB network adapter, then wifi_status until the pod joined. +func TestSetWifiOverJSON(t *testing.T) { + fastWifiJoin(t) + var mu sync.Mutex + joined := false + pod, addr := startJSONPod(t, func(req map[string]any) string { + mu.Lock() + defer mu.Unlock() + switch req["cmd"] { + case "wifi_status": + if joined { + return okReply(map[string]any{"state": "connected", "connected": true, "configured": true, "ssid": "lab", "rssi_dbm": -60}) + } + return okReply(map[string]any{"state": "disabled", "connected": false, "configured": false, "ssid": ""}) + case "blob_status": + return okReply(map[string]any{"blobs": []any{map[string]any{"name": "esp", "state": "ok", "present": true}}}) + case "wifi_set": + joined = true + return okReply(map[string]any{"ssid": "lab"}) + case "status": + return okReply(map[string]any{"ip": "192.168.1.77", "api": 2, "min_client_api": 2}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + g := &globalFlags{connection: "usb", usbAddr: addr} + var ip string + var err error + out := captureStderr(t, func() { ip, err = runSetWifi(g, "lab", "s3cret", false) }) + if err != nil || ip != "192.168.1.77" { + t.Fatalf("ip %q, err %v\n%s", ip, err, out) + } + if set := pod.last("wifi_set"); set["ssid"] != "lab" || set["password"] != "s3cret" { + t.Fatalf("wifi_set %v", set) + } + if got := strings.Join(pod.cmds(), ","); !strings.HasPrefix(got, "wifi_status,blob_status,wifi_set,wifi_status") { + t.Fatalf("requests %s", got) + } + if !strings.Contains(out, `Joined "lab", ip=192.168.1.77`) || strings.Contains(out, "s3cret") { + t.Fatalf("stderr:\n%s", out) + } +} + +// When the USB link goes down with wifi_set, set-wifi follows the join on the address the +// console's status reports. +func TestSetWifiFollowsTheJoinOnTheNewAddress(t *testing.T) { + fastWifiJoin(t) + var mu sync.Mutex + set := false + _, usbAddr := startJSONPod(t, func(req map[string]any) string { + mu.Lock() + defer mu.Unlock() + switch req["cmd"] { + case "wifi_status": + if set { + return "the USB link is gone" // not a reply: the read fails + } + return okReply(map[string]any{"state": "disabled"}) + case "wifi_set": + set = true + return okReply(map[string]any{"ssid": "lab"}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + _, wifiAddr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "connected", "connected": true, "ssid": "lab"}) + case "status": + return okReply(map[string]any{"ip": "127.0.0.1", "api": 2, "min_client_api": 2}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + g := &globalFlags{connection: "usb", usbAddr: usbAddr} + host, port, _ := net.SplitHostPort(wifiAddr) + oldPort := wifiPodPort + wifiPodPort = port + t.Cleanup(func() { wifiPodPort = oldPort }) + consolePodIP = func(*globalFlags) string { return host } + var ip string + var err error + captureStderr(t, func() { ip, err = runSetWifi(g, "lab", "", true) }) + if err != nil || ip != "127.0.0.1" { + t.Fatalf("ip %q, err %v", ip, err) + } +} + +// Through a Wi-Fi bridge: the bridge keeps the credentials; a wrong password is an error. +func TestSetWifiThroughABridge(t *testing.T) { + fastWifiJoin(t) + pod, addr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "auth-failed", "ssid": "lab", "via": "wifi-bridge", + "bridge": map[string]any{"paired": true, "problem": nil}}) + case "wifi_set": + return okReply(map[string]any{"ssid": "lab", "via": "wifi-bridge"}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + var err error + captureStderr(t, func() { _, err = runSetWifi(&globalFlags{connection: "usb", usbAddr: addr}, "lab", "bad", false) }) + if err == nil || !strings.Contains(err.Error(), "wrong password") { + t.Fatalf("err = %v", err) + } + for _, c := range pod.cmds() { + if c == "blob_status" { + t.Fatal("checked the ESP32-C3 image through a bridge") + } + } +} + +func TestShowNetworkScanAndClearWifi(t *testing.T) { + fastWifiJoin(t) + scans := 0 + pod, addr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "connected", "connected": true, "ssid": "lab", "rssi_dbm": -61}) + case "status": + return okReply(map[string]any{"ip": "192.168.1.77", "api": 2, "min_client_api": 2}) + case "wifi_scan": + scans++ + if scans < 3 { + return okReply(map[string]any{"state": "scanning", "id": 3}) + } + return okReply(map[string]any{"state": "done", "id": 3, "networks": []any{ + map[string]any{"ssid": "lab", "rssi": -48, "channel": 6, "auth": "wpa2/wpa3"}, + map[string]any{"ssid": "", "rssi": -80, "channel": 1, "auth": "open"}}}) + case "wifi_clear": + return okReply("cleared") + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + out := t.TempDir() + "/out.txt" + read := func() string { b, _ := os.ReadFile(out); return string(b) } + if code := run([]string{"show-network", "--connection", addr, "--out", out}); code != exitOK { + t.Fatalf("show-network: exit %d", code) + } + if got := read(); got != "IP: 192.168.1.77\nSSID: lab\nState: connected\nRSSI: -61 dBm\n" { + t.Fatalf("show-network:\n%s", got) + } + captureStderr(t, func() { + if code := run([]string{"scan-wifi", "--connection", addr, "--out", out}); code != exitOK { + t.Fatalf("scan-wifi: exit %d", code) + } + }) + if got := read(); !strings.Contains(got, "-48 6 wpa2/wpa3 lab\n") || !strings.Contains(got, "(hidden)") { + t.Fatalf("scan-wifi:\n%s", got) + } + if r := pod.last("wifi_scan"); r["id"] != float64(3) { + t.Fatalf("poll %v", r) + } + captureStderr(t, func() { + if code := run([]string{"clear-wifi", "--connection", addr}); code != exitOK { + t.Fatalf("clear-wifi: exit %d", code) + } + }) + if pod.last("wifi_clear") == nil { + t.Fatal("no wifi_clear") + } +} diff --git a/cmd/benchpod-cli/wiring.go b/cmd/benchpod-cli/wiring.go index a84db28..d8c37bb 100644 --- a/cmd/benchpod-cli/wiring.go +++ b/cmd/benchpod-cli/wiring.go @@ -11,7 +11,6 @@ import ( "context" "encoding/base64" "encoding/json" - "errors" "fmt" "io" "os" @@ -56,7 +55,7 @@ func wiringList(ctx context.Context, c podCommander) (*wiringListReply, error) { Profiles *json.RawMessage `json:"profiles"` } if json.Unmarshal(raw, &probe) != nil || probe.Profiles == nil { - return nil, errNoWiringStore // firmware that stores profiles always lists them + return nil, fmt.Errorf("wiring_list: unexpected reply %s", strings.TrimSpace(string(raw))) } var l wiringListReply if err := json.Unmarshal(raw, &l); err != nil { @@ -65,16 +64,9 @@ func wiringList(ctx context.Context, c podCommander) (*wiringListReply, error) { return &l, nil } -// errNoWiringStore: the pod's firmware stores no wiring profiles. -var errNoWiringStore = errors.New("this pod's firmware does not store wiring profiles; update it with `benchpod flash-self`") - -// wiringStoreList is wiringList, with an older firmware's BP0002 ("unknown cmd") as errNoWiringStore. +// wiringStoreList is wiringList (the pod keeps its wiring profiles itself). func wiringStoreList(ctx context.Context, c podCommander) (*wiringListReply, error) { - l, err := wiringList(ctx, c) - if isUnknownCommand(err) { - return nil, errNoWiringStore - } - return l, err + return wiringList(ctx, c) } // wiringGet reads one profile in pieces; a save meanwhile (the revision moves) starts over. @@ -450,29 +442,7 @@ func newExplainCmd() *cobra.Command { } // loadPodWiringFromPod reads the pod's own profile (--wiring-profile, else its default) for the -// flags a command leaves out. ok false: the pod's firmware stores no profiles, so the caller -// falls back to embeddedci.com. -// podStoresWiring says whether the pod behind g's connection keeps its wiring profiles itself -// (firmware 3.10.8+). Then nothing is saved to embeddedci.com on the side. A variable so tests can -// replace it. -var podStoresWiring = func(g *globalFlags) bool { - spec, err := g.resolveTarget() - if err != nil { - return false - } - if spec = g.preferUSBNetwork(spec, "wiring"); spec.IsSerial() { - return false - } - ctx, cancel := context.WithTimeout(context.Background(), wiringLookupTimeout) - defer cancel() - t, err := openPodTarget(ctx, spec) - if err != nil { - return false - } - _, err = wiringStoreList(ctx, t.client) - return err == nil -} - +// flags a command leaves out. ok false: no profile could be read (no network to the pod). func loadPodWiringFromPod(g *globalFlags, warn io.Writer) (*podWiring, bool) { spec, err := g.resolveTarget() if err != nil { diff --git a/internal/ci/config.go b/internal/ci/config.go index 4e2a47a..0983676 100644 --- a/internal/ci/config.go +++ b/internal/ci/config.go @@ -198,7 +198,7 @@ type Expect struct { Min *float64 Max *float64 Drift *float64 - // FailOnDrift: a change beyond Drift against the baseline fails the run (exit 3); nil = the + // FailOnDrift: a change beyond Drift against the baseline fails the run (exit 11); nil = the // file's gate decides. FailOnDrift *bool Line int @@ -326,7 +326,7 @@ func Parse(data []byte, path string, env func(string) (string, bool)) (*Config, case "gate": cfg.Gate = p.str(v, "gate") if cfg.Gate != "drift" && cfg.Gate != "none" { - p.errf(v.Line, "gate must be drift (a drift beyond its allowance against the baseline fails the run with exit 3) or none, got %q", cfg.Gate) + p.errf(v.Line, "gate must be drift (a drift beyond its allowance against the baseline fails the run with exit 11) or none, got %q", cfg.Gate) } case "timeout": if d, ok := p.duration(v, "timeout"); ok { diff --git a/internal/ci/results_test.go b/internal/ci/results_test.go index 43dbeb0..26c4048 100644 --- a/internal/ci/results_test.go +++ b/internal/ci/results_test.go @@ -23,11 +23,11 @@ func TestRunOutcomeAndExitCodes(t *testing.T) { }{ {true, Counts{Passed: 3}, false, Passed, 0}, {true, Counts{Passed: 3, Skipped: 2, XFailed: 1}, false, Passed, 0}, - {true, Counts{Passed: 3, Failed: 1}, false, Failed, 2}, - {true, Counts{Passed: 3}, true, Failed, 2}, - {true, Counts{Failed: 1, Error: 1}, false, Errored, 2}, - {false, Counts{Passed: 3}, false, Invalid, 4}, - {false, Counts{Error: 3}, false, Invalid, 4}, + {true, Counts{Passed: 3, Failed: 1}, false, Failed, 10}, + {true, Counts{Passed: 3}, true, Failed, 10}, + {true, Counts{Failed: 1, Error: 1}, false, Errored, 10}, + {false, Counts{Passed: 3}, false, Invalid, 12}, + {false, Counts{Error: 3}, false, Invalid, 12}, } for _, c := range cases { got := RunOutcome(c.valid, c.counts, c.required) diff --git a/internal/ci/run.go b/internal/ci/run.go index 5d9ba4b..191112f 100644 --- a/internal/ci/run.go +++ b/internal/ci/run.go @@ -415,13 +415,15 @@ func RunOutcome(valid bool, c Counts, requiredFailed bool) string { return Passed } -// Exit codes of `benchpod ci` (spec section 6). +// Exit codes of `benchpod ci`. They do not clash with the CLI's own table (0 to 7: usage 2, +// unreachable 5, update the CLI 6, update the pod 7 mean the same in ci); a run's results are 10 +// and up. const ( ExitPassed = 0 - ExitSetup = 1 // file, usage or setup error - ExitFailed = 2 // a test failed (or errored) - ExitRegression = 3 // the run passed, but a gated measurement drifted beyond its allowance against the baseline - ExitInvalid = 4 // the run cannot be trusted: require not met, pod or lease lost, pod busy + ExitSetup = 1 // file or setup error + ExitFailed = 10 // a test failed (or errored) + ExitRegression = 11 // the run passed, but a gated measurement drifted beyond its allowance against the baseline + ExitInvalid = 12 // the run cannot be trusted: require not met, pod or lease lost, pod busy ) // ExitCode is the exit code for a run outcome. diff --git a/internal/cloudpod/cloudpod.go b/internal/cloudpod/cloudpod.go index 3b50b18..cdd889e 100644 --- a/internal/cloudpod/cloudpod.go +++ b/internal/cloudpod/cloudpod.go @@ -32,6 +32,26 @@ type Client struct { // ByName: the credential is a cloud token (GitHub Actions), which reaches the pod by name on // the /api/cloud/devices routes instead of by id on the user's device routes. ByName bool + + probed bool // the pod's API level was checked (probeAPI) +} + +// probeAPI reads the pod's status once before its first other command and stops on an API +// level this CLI does not drive (tcpclient.CheckPodAPI), like the LAN client does. +func (c *Client) probeAPI(ctx context.Context, req map[string]any) error { + if c.probed || !tcpclient.APIProbe(req) { + return nil + } + _, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}) + var upd *tcpclient.UpdateRequiredError + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &upd) || errors.As(err, &old) { + return err + } + if err == nil { + c.probed = true + } + return nil // a failed probe: the command reports what is wrong } // Resolve finds the pod named name (or with that id) among the devices the credential can see. @@ -138,6 +158,9 @@ func (c *Client) Command(ctx context.Context, req map[string]any) (json.RawMessa timeout = maxTimeout } } + if err := c.probeAPI(ctx, req); err != nil { + return nil, err + } var resp *serverapi.CommandResponse var err error // The server passes the command on as it is, so it carries client_api and client like a LAN one. @@ -157,7 +180,7 @@ func (c *Client) Command(ctx context.Context, req map[string]any) (json.RawMessa } return nil, tcpclient.RefusalError(msg, resp.Code, resp.Args) } - if tcpclient.IsStatus(req) && !tcpclient.NewerPodAllowed() { + if tcpclient.IsStatus(req) && !tcpclient.AnyPodAPIAllowed() { if err := tcpclient.CheckPodAPI(resp.Data); err != nil { return nil, err } @@ -227,10 +250,12 @@ func (e *Error) Is(target error) bool { // one, so the CLI's exit code says busy (4) or refused (3) as it does on the LAN. func (e *Error) Unwrap() error { switch e.Code { - case "lease_held", "device_busy": - return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "busy"} + case "lease_held": + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "the pod is in use", Code: "BP0025"} + case "device_busy": + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "the pod is busy", Code: "BP0047"} case "forbidden_tier": - return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "forbidden: needs an organization owner or admin"} + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "needs an organization owner or admin", Code: "BP0045"} } return nil } diff --git a/internal/cloudpod/cloudpod_test.go b/internal/cloudpod/cloudpod_test.go index 8682539..ed27b08 100644 --- a/internal/cloudpod/cloudpod_test.go +++ b/internal/cloudpod/cloudpod_test.go @@ -53,7 +53,7 @@ func jsonError(w http.ResponseWriter, status int, msg, code string) { func TestResolveAndCommand(t *testing.T) { f := &fakeServer{reply: func(w http.ResponseWriter) { - _, _ = w.Write([]byte(`{"request_id":"r","device_id":"id-b","status":"ok","data":{"version":"3.8.0"}}`)) + _, _ = w.Write([]byte(`{"request_id":"r","device_id":"id-b","status":"ok","data":{"version":"4.0.0","api":2}}`)) }} api := f.start(t) c, err := Resolve(context.Background(), api, "ApiKey eci_test", "bench-b") @@ -72,7 +72,7 @@ func TestResolveAndCommand(t *testing.T) { if err != nil { t.Fatal(err) } - if string(data) != `{"version":"3.8.0"}` || f.command["cmd"] != "status" { + if string(data) != `{"version":"4.0.0","api":2}` || f.command["cmd"] != "status" { t.Errorf("data %s, sent %v", data, f.command) } if f.timeout < 15000 || f.timeout > 20000 { @@ -247,24 +247,36 @@ func TestCloudCommandCarriesTheClientFields(t *testing.T) { } } -// The status check and BP0030 work through embeddedci.com too. -func TestCloudNewerPodNeedsANewerCLI(t *testing.T) { +// The status check and BP0030 work through embeddedci.com too: a newer pod needs a newer CLI, a +// pod older than firmware 4.0 (api 1, or none) needs a firmware update. +func TestCloudPodAPILevels(t *testing.T) { for _, c := range []struct { cmd, reply string - bad bool + newer, old bool }{ - {"status", `{"status":"ok","data":{"version":"3.11.0","api":2}}`, true}, - {"status", `{"status":"ok","data":{"version":"3.10.13"}}`, false}, - {"status", `{"status":"ok","data":{"api":1}}`, false}, - {"ping", `{"status":"ok","data":{"api":2}}`, false}, - {"la", `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":2,"api":2}}`, true}, + {"status", `{"status":"ok","data":{"version":"5.0.0","api":3}}`, true, false}, + {"status", `{"status":"ok","data":{"version":"4.0.0","api":2,"min_client_api":2}}`, false, false}, + {"status", `{"status":"ok","data":{"version":"3.10.13"}}`, false, true}, + {"status", `{"status":"ok","data":{"api":1}}`, false, true}, + {"ping", `{"status":"ok","data":{"api":1}}`, false, false}, // no probe: tcpclient.SetAPIProbe is off + {"la", `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":3,"api":3}}`, true, false}, } { f := &fakeServer{reply: func(w http.ResponseWriter) { _, _ = w.Write([]byte(c.reply)) }} cl := &Client{API: f.start(t), Credential: "tok", DeviceID: "id-b", Name: "bench-b"} _, err := cl.Command(context.Background(), map[string]any{"cmd": c.cmd}) var upd *tcpclient.UpdateRequiredError - if got := errors.As(err, &upd); got != c.bad || (!c.bad && err != nil) { + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &upd) != c.newer || errors.As(err, &old) != c.old || (!c.newer && !c.old && err != nil) { t.Errorf("%s %s: err = %v", c.cmd, c.reply, err) } } + // With the probe on, the first other command reads status first. + tcpclient.SetAPIProbe(true) + defer tcpclient.SetAPIProbe(false) + f := &fakeServer{reply: func(w http.ResponseWriter) { _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"3.10.13"}}`)) }} + cl := &Client{API: f.start(t), Credential: "tok", DeviceID: "id-b", Name: "bench-b"} + var old *tcpclient.FirmwareTooOldError + if _, err := cl.Command(context.Background(), map[string]any{"cmd": "la_pins"}); !errors.As(err, &old) || f.command["cmd"] != "status" { + t.Fatalf("probe: err = %v, sent %v", err, f.command) + } } diff --git a/internal/errcatalog/errors.json b/internal/errcatalog/errors.json index 9549d8d..68567af 100644 --- a/internal/errcatalog/errors.json +++ b/internal/errcatalog/errors.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "1fdf57bcda663e4e263d034fc81e30b23d565347daafb03b09b5cd7d7e63a332", + "catalog_sha256": "ceaaf830950d2109f3322d4045471f1677c40d668f98ffa875c9343780b49769", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -467,8 +467,8 @@ "name": "client_too_old", "area": "protocol", "since": "next", - "message": "This client is too old for the pod's firmware: it needs client API {min_client_api} or newer (this client sent {client_api})", - "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. status, diag, ping and lease_release still work.", + "message": "Update the BenchPod SDK, MCP or CLI: this firmware needs client API {min_client_api} or newer (this client sent {client_api})", + "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. These still run for any client: ping, status, diag, identity_public, lease_release, ota_status, ota_begin, ota_data, ota_end, ota_commit, ota_abort, ota_selftest and blob_status, so a client can see the levels, let go of the pod, and update the pod's firmware and blobs or roll them back.", "args": { "client_api": "int", "min_client_api": "int", @@ -480,6 +480,814 @@ "mcp": "tell the user the BenchPod MCP server is too old for this pod's firmware; they can update it (run `uvx embeddedci-mcp@latest`, or pip install -U embeddedci-mcp; with the benchpod plugin, update the plugin), then reconnect", "web": "Reload the page to get the latest web app." } + }, + "BP0031": { + "name": "la_pin_in_use", + "area": "io", + "since": "next", + "message": "LA{la} is in use by {owner}", + "cause": "Each LA channel has one owner at a time: a GPIO, a UART, SWD, SPI or I2C session, a step train or an emulated sensor. {owner} holds LA{la}, so the pod refuses to give it to anything else until that owner lets it go. function is the owner's function (gpio, uart_tx, i2c_sda, ...), and instance the emulated sensor's name, empty for anything else.", + "args": { + "la": "int", + "owner": "str", + "function": "str", + "instance": "str" + }, + "fix": { + "sdk": "free LA{la} first: bp.release_gpio({la}) for a GPIO, close the UART, SPI or I2C session that uses it, wait for the flash or step train, or stop the emulated sensor (bp.sensors.stop(name)); bp.la_pins() shows each channel's owner", + "cli": "free LA{la} where it was taken (the web app, a test or an MCP session holds it), or stop an emulated sensor with `benchpod sensor stop `; `benchpod la pins` shows each channel's owner", + "mcp": "free LA{la} first: gpio_release(la=[{la}]) for a GPIO, uart_close, spi or i2c_close for a session, sensor_stop with the sensor's instance for an emulated sensor, or wait for a flash; la_pins shows each channel's owner", + "web": "LA{la} is in use by {owner}. Free it there first (the Pins pane shows each pin's owner)." + } + }, + "BP0032": { + "name": "la_pull_down_engaged", + "area": "io", + "since": "next", + "message": "LA{la} has its {ohms} pull-down on, which {function} cannot work with ({reason})", + "cause": "A pull-down holds the line low. An open-drain bus (I2C), an idle-high UART line or SWDIO needs the line to rest high, so the pod refuses to start {function} on LA{la} while its pull-down is on.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "switch the pull-down off with bp.set_pull({la}, \"off\"), or use another channel", + "cli": "switch the pull-down off with `benchpod la pull {la} off`, or use another channel", + "mcp": "call set_pull(las=[{la}], pull=\"off\"), or use another channel", + "web": "Switch off LA{la}'s pull-down in the Pins pane, or pick another pin." + } + }, + "BP0033": { + "name": "la_pull_down_conflict", + "area": "io", + "since": "next", + "message": "LA{la} is used by {function}, which cannot work with the {ohms} pull-down ({reason})", + "cause": "A pull-down holds the line low. {function} on LA{la} needs the line to rest high, so the pod refuses to switch the pull-down on under it.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "stop what uses LA{la} first (bp.la_pins() shows it), or pull another channel down", + "cli": "stop what uses LA{la} first (`benchpod la pins` shows it), or pull another channel down", + "mcp": "stop what uses LA{la} first (la_pins shows it), or pull another channel down", + "web": "LA{la} is in use by {function}. Stop it before you switch on the pull-down." + } + }, + "BP0034": { + "name": "la_dut_output", + "area": "io", + "since": "next", + "message": "LA{la} is wired to a DUT output, and {function} would drive against it", + "cause": "The wiring marks LA{la} as a pin the DUT drives (la_dir dut_output). Two push-pull outputs on one wire fight each other, which can damage either side, so the pod refuses to drive it. There is no override.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "use an open_drain GPIO on LA{la}, or fix the wiring (bp.la_dir) if LA{la} is not a DUT output", + "cli": "use an open-drain GPIO on LA{la}, or fix the pin's direction in the wiring profile if it is not a DUT output", + "mcp": "use gpio_mode(mode=\"open_drain\") on LA{la}, or fix the wiring with la_dir if LA{la} is not a DUT output", + "web": "LA{la} is wired to a DUT output. Use open drain, or fix the pin's direction in the wiring." + } + }, + "BP0035": { + "name": "la_driven_pin", + "area": "io", + "since": "next", + "message": "LA{la} is driven by {function}, so it cannot be marked as a DUT output", + "cause": "{function} drives LA{la} from the pod. Marking the pin as one the DUT drives would put two outputs on one wire, so the pod refuses until the pod's side stops driving it.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "stop what drives LA{la} first (bp.la_pins() shows it), then set its direction", + "cli": "stop what drives LA{la} first (`benchpod la pins` shows it), then set its direction", + "mcp": "stop what drives LA{la} first (la_pins shows it), then call la_dir again", + "web": "LA{la} is driven by {function}. Stop it before you mark the pin as a DUT output." + } + }, + "BP0036": { + "name": "la_not_gpio_output", + "area": "io", + "since": "next", + "message": "LA{la} is not a GPIO output (it is {function})", + "cause": "Writing a level or sending a gpio step needs the channel set up as a GPIO output or open drain first.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "make it an output first: bp.gpio({la}, \"output\") (or \"open_drain\")", + "cli": "make LA{la} a GPIO output first", + "mcp": "call gpio_mode(la=[{la}], mode=\"output\") (or \"open_drain\") first", + "web": "Set LA{la} to output in the Pins pane first." + } + }, + "BP0037": { + "name": "la_voltage_pins_in_use", + "area": "io", + "since": "next", + "message": "The I/O voltage cannot change while pins are in use: {pins}", + "cause": "Changing the I/O voltage under a running GPIO, UART, flash or sensor would put the wrong level on the DUT's pins, so the pod refuses until they are free.", + "args": { + "pins": "str" + }, + "fix": { + "sdk": "stop what uses those pins first (release the GPIOs, close the sessions, bp.sensors.stop()), then set the voltage", + "cli": "stop what uses those pins first, then set the voltage again", + "mcp": "stop what uses those pins first (gpio_release, uart_close, sensor_stop), then call set_la_voltage again", + "web": "Stop what uses those pins first, then change the I/O voltage." + } + }, + "BP0038": { + "name": "trigger_timeout", + "area": "capture", + "since": "next", + "message": "No {edge} edge on LA{la} within {timeout_ms} ms", + "cause": "A triggered capture waits for its trigger condition before it records. The DUT never made a {edge} edge on LA{la} in the time given, so the pod stopped waiting and recorded nothing.", + "args": { + "la": "int", + "edge": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger_timeout_ms", + "cli": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger timeout", + "mcp": "check the DUT drives LA{la} and the edge is right, or retry with a longer trigger timeout", + "web": "Nothing happened on LA{la} in time. Check the wiring and the edge, or wait longer." + } + }, + "BP0039": { + "name": "sensor_trigger_timeout", + "area": "capture", + "since": "next", + "message": "No I2C start on LA{la} (SDA of {instance}) within {timeout_ms} ms: the DUT did not use the I2C bus", + "cause": "A sensor bus capture with trigger \"start\" waits for the DUT's first I2C start condition on the emulated sensor's SDA. None came in time.", + "args": { + "la": "int", + "instance": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "make the DUT talk to the sensor during the capture (reset it, or start the capture first), or pass trigger=\"none\"", + "cli": "make the DUT talk to the sensor during the capture, or capture without the start trigger", + "mcp": "make the DUT talk to the sensor during the capture (reset_target), or call sensor_capture with trigger \"none\"", + "web": "The DUT did not talk to the sensor in time. Reset it during the capture, or capture without the trigger." + } + }, + "BP0040": { + "name": "lan_locked", + "area": "policy", + "since": "next", + "message": "The pod's LAN is locked: {cmd} needs the cloud or USB", + "cause": "The pod's LAN policy is locked, so commands that change settings, flash or update (tiers T2 and T3) only run from the cloud or over USB. Reads and tests still run on the LAN.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") for {cmd}, or open the LAN policy over USB", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud ('embeddedci:') for {cmd}; ask the user before opening the LAN policy", + "web": "The pod's LAN is locked. Use the pod from the cloud or over USB for this." + } + }, + "BP0041": { + "name": "policy_not_from_lan", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or the USB console", + "cause": "Policies that decide who may change the pod are only changed by someone with the pod's cloud account or its USB cable, never by anyone on the network.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "change {setting} from the cloud or the USB console", + "cli": "change {setting} over USB (`--connection usb`) or from the cloud", + "mcp": "tell the user {setting} is changed from the cloud or the USB console", + "web": "Change {setting} from the cloud or over the pod's USB console." + } + }, + "BP0042": { + "name": "setting_cloud_or_usb", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or over USB", + "cause": "Settings that decide what the pod trusts (LAN TLS, the cloud CA, the cloud proxy) are not changed from the network. TLS on port 8443 has no client authentication, so it does not count either.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") to change {setting}", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud to change {setting}", + "web": "Change {setting} from the cloud or over USB." + } + }, + "BP0043": { + "name": "setting_device_only", + "area": "policy", + "since": "next", + "message": "{setting} can only be changed on the device: the USB console, or over the USB link", + "cause": "This setting changes how the pod can be reached or updated, so it needs someone at the pod: its USB console or its USB network link. Neither the LAN nor the cloud may change it.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) to change {setting}", + "cli": "run this over USB with --connection usb", + "mcp": "connect over USB ('usb') to change {setting}, or ask the user to do it at the pod", + "web": "Change {setting} with the pod plugged in over USB." + } + }, + "BP0044": { + "name": "policy_loosen_usb_only", + "area": "policy", + "since": "next", + "message": "Only the USB console can loosen {setting} (now {now})", + "cause": "The cloud may make the pod stricter but never looser: a stolen cloud account must not be able to lower the pod's firmware signature policy.", + "args": { + "setting": "str", + "now": "str" + }, + "fix": { + "sdk": "loosen {setting} on the pod's USB console", + "cli": "loosen {setting} over USB with `benchpod policy` and --connection usb", + "mcp": "tell the user {setting} can only be loosened on the pod's USB console", + "web": "Loosen {setting} on the pod's USB console." + }, + "retired": "4.0.0", + "replaced_by": "BP0074" + }, + "BP0045": { + "name": "role_required", + "area": "policy", + "since": "next", + "message": "{cmd} needs an organization owner or admin", + "cause": "A cloud session runs commands up to the tier the server allows its user. {cmd} changes or updates the pod, which needs an owner or admin of the pod's organization.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use an API key or session of an organization owner or admin (API keys need the benchpod:admin scope)", + "cli": "sign in as an organization owner or admin; API keys need the benchpod:admin scope", + "mcp": "tell the user {cmd} needs an organization owner or admin (an API key with the benchpod:admin scope)", + "web": "Ask an owner or admin of your organization to do this." + } + }, + "BP0046": { + "name": "no_analog_front_end", + "area": "board", + "since": "next", + "message": "This BenchPod has no analog front end, so it cannot run {cmd}", + "cause": "The digital board has no DAC, ADC or analog outputs. The pod checks at boot; after fitting an analog add-on, restart it.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use a pod with an analog front end (bp.capabilities shows it), or leave out the analog step", + "cli": "use a pod with an analog front end", + "mcp": "this pod has no analog front end; skip the analog step or use another pod", + "web": "This pod has no analog front end." + } + }, + "BP0047": { + "name": "pod_busy", + "area": "busy", + "since": "next", + "message": "The pod is running another long command (a capture, measurement, upload or update)", + "cause": "Captures, measurements, waveform uploads and firmware updates share the pod's sample memory, so one runs at a time. Light commands (status, GPIO, ...) still run.", + "args": {}, + "fix": { + "sdk": "wait for the other command to finish, then try again", + "cli": "the pod is running another long command; try again when it ends", + "mcp": "wait for the other call to finish, then try again", + "web": "The pod is busy with another capture or upload. Try again when it ends." + } + }, + "BP0048": { + "name": "storage_bus_busy", + "area": "busy", + "since": "next", + "message": "The pod's storage bus is in use: {what}", + "cause": "The flash that holds settings, gateware and update images shares a bus with the sample memory. While {what}, the pod cannot write it.", + "args": { + "what": "str" + }, + "fix": { + "sdk": "try again when it ends", + "cli": "try again when it ends", + "mcp": "wait until it ends, then try again", + "web": "Try again when it ends." + } + }, + "BP0049": { + "name": "uart_session_open", + "area": "uart", + "since": "next", + "message": "A UART session is already open", + "cause": "The pod runs one UART at a time: the web app's Terminal, a test, an MCP session or a flash over the UART holds it.", + "args": {}, + "fix": { + "sdk": "close the open UART session first (session.close(), or leave its with block)", + "cli": "close the other UART session (the web app's Terminal, a test or an MCP session) first", + "mcp": "call uart_close first", + "web": "Close the open terminal session first." + } + }, + "BP0050": { + "name": "swd_session_open", + "area": "flash", + "since": "next", + "message": "An SWD session is already running", + "cause": "The pod runs one SWD session (a flash or a debug run) at a time.", + "args": {}, + "fix": { + "sdk": "wait for the running flash to finish, then try again", + "cli": "wait for the running flash to finish, then try again", + "mcp": "wait for the running flash to finish, then try again", + "web": "Wait for the running flash to finish." + } + }, + "BP0051": { + "name": "update_in_progress", + "area": "update", + "since": "next", + "message": "A {target} update from {holder} is in progress", + "cause": "The pod takes one update at a time, from one place. Another one is running.", + "args": { + "target": "str", + "holder": "str" + }, + "fix": { + "sdk": "wait for the other update to finish (or ota_abort it from where it runs), then try again", + "cli": "wait for the other update to finish, then try again", + "mcp": "tell the user another update is running and wait for it", + "web": "Another update is running. Wait for it to finish." + } + }, + "BP0052": { + "name": "cloud_command_busy", + "area": "busy", + "since": "next", + "message": "The pod is still running the previous cloud command", + "cause": "Over the cloud command channel the pod runs one command at a time. The server retries, so this is usually brief.", + "args": {}, + "fix": { + "sdk": "try again in a moment", + "cli": "try again in a moment", + "mcp": "retry in a moment", + "web": "Try again in a moment." + } + }, + "BP0053": { + "name": "reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply did not fit the pod's reply buffer", + "cause": "The command worked, but its answer is larger than the pod can send at once. Commands that can grow (la_pins) take a subset.", + "args": {}, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset); update the SDK if it keeps happening", + "cli": "ask for less at once; update the CLI if it keeps happening", + "mcp": "ask for fewer channels or less data per call", + "web": "Reload the page; if it keeps happening, update the pod's firmware." + } + }, + "BP0054": { + "name": "cloud_reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply is too large for the cloud channel ({bytes} bytes, limit {limit})", + "cause": "Cloud command replies travel in one frame of at most {limit} bytes. This one is {bytes}. Large data (captures) go through the cloud byte tunnel instead.", + "args": { + "bytes": "int", + "limit": "int" + }, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset), or connect over the LAN or USB", + "cli": "ask for less at once, or connect over the LAN or USB", + "mcp": "ask for fewer channels or less data per call", + "web": "Ask for less at once." + } + }, + "BP0055": { + "name": "sensor_instance_unknown", + "area": "sensors", + "since": "next", + "message": "The pod has no emulated sensor {instance}", + "cause": "The instance was never defined or started on this pod, was stopped, or the pod restarted.", + "args": { + "instance": "str" + }, + "fix": { + "sdk": "list the running sensors with bp.sensors.status(), or start {instance} first", + "cli": "list the running sensors with `benchpod sensor status`, or start {instance} first", + "mcp": "call sensor_status to list the running sensors, or sensor_start {instance} first", + "web": "{instance} is not running. Start it first." + } + }, + "BP0056": { + "name": "no_module_link", + "area": "board", + "since": "next", + "message": "This BenchPod has no module link, so it cannot run {cmd}", + "cause": "Only boards with a module header (digital v3r3) talk to an add-on module.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "skip the module step on this board", + "cli": "this board has no module link", + "mcp": "this pod has no module link; skip the module step", + "web": "This pod has no module link." + } + }, + "BP0057": { + "name": "image_switch_sensors_running", + "area": "sensors", + "since": "next", + "message": "The emulated sensors {sensors} need the emulation image; stop them before switching", + "cause": "I2C, SPI and UART sensors run in the emulation gateware image. Switching to another image would stop them mid-run, so the pod refuses.", + "args": { + "sensors": "str" + }, + "fix": { + "sdk": "stop them with bp.sensors.stop(), then switch the image", + "cli": "stop them with `benchpod sensor stop` first", + "mcp": "call sensor_stop (all) first, then fpga_image", + "web": "Stop the emulated sensors first." + } + }, + "BP0058": { + "name": "fpga_image_required", + "area": "firmware", + "since": "next", + "message": "{feature} is not in the running gateware image; it needs the {image} image", + "cause": "The pod's FPGA runs one of three images (loop, deep replay, emulation), and each has some features. {feature} is in the {image} image.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "switch with bp.fpga_image(FpgaImage.LOOP) (or DEEP_REPLAY for the deep image), then try again", + "cli": "switch with `benchpod sensor image {image}`, then try again", + "mcp": "call fpga_image(image=\"{image}\"), then try again", + "web": "Switch the FPGA image to {image} first." + } + }, + "BP0059": { + "name": "fpga_image_sensors_first", + "area": "sensors", + "since": "next", + "message": "{feature} is not in the emulation image the emulated sensors use; stop them, then switch to the {image} image", + "cause": "Emulated I2C, SPI and UART sensors run in the emulation gateware image, which has no room for {feature}. It needs the {image} image, and switching stops the sensors.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "bp.sensors.stop(), then bp.fpga_image(...) for the {image} image", + "cli": "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image {image}`", + "mcp": "call sensor_stop (all), then fpga_image(image=\"{image}\")", + "web": "Stop the emulated sensors, then switch to the {image} image." + } + }, + "BP0060": { + "name": "ota_unknown_target", + "area": "update", + "since": "next", + "message": "{target} is not an update target this firmware knows", + "cause": "The firmware on the pod is older than the tool, or the target name is wrong.", + "args": { + "target": "str" + }, + "fix": { + "sdk": "update the pod's firmware first (`benchpod flash-self`)", + "cli": "update the pod's firmware with `benchpod flash-self` first", + "mcp": "tell the user the pod's firmware does not know this update target; update the firmware first", + "web": "Update the pod's firmware first." + } + }, + "BP0061": { + "name": "i2c_needs_pullups", + "area": "i2c", + "since": "next", + "message": "I2C needs pull-ups: LA{la} has none switched on", + "cause": "I2C lines are open drain: something must pull them high. The pod can do it with its own pull-ups, or the board has its own.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "switch the pull-up on (bp.enable_pullup({la})), or pass pullups=\"external\" when the board has its own", + "cli": "pull LA{la} up with `benchpod la pull {la} up`, or pass --pullups external when the board has its own", + "mcp": "call set_pull(las=[{la}], pull=\"up\"), or pass pullups=\"external\" when the board has its own", + "web": "Switch on LA{la}'s pull-up, or say the board has its own." + } + }, + "BP0062": { + "name": "i2c_session_not_open", + "area": "i2c", + "since": "next", + "message": "No I2C session is open", + "cause": "I2C transactions run inside a session that i2c_start opens.", + "args": {}, + "fix": { + "sdk": "open one with bp.open_i2c() first", + "cli": "start the I2C master first", + "mcp": "call i2c_open first", + "web": "Open an I2C session first." + } + }, + "BP0063": { + "name": "i2c_engine_reset", + "area": "i2c", + "since": "next", + "message": "The I2C engine was reset, which ended the session", + "cause": "A gateware reload (an image switch, a recovery) resets the I2C engine, so the open session is gone.", + "args": {}, + "fix": { + "sdk": "open the session again with bp.open_i2c()", + "cli": "start the I2C command again", + "mcp": "call i2c_open again", + "web": "Open the I2C session again." + } + }, + "BP0064": { + "name": "loop_sweep_with_map", + "area": "dac", + "since": "next", + "message": "The sweep input cannot be combined with an input map on this gateware", + "cause": "The sweep spans the raw count range, not the mapped window, so most of each pass would sit at one end of the curve.", + "args": {}, + "fix": { + "sdk": "step the input with bp.loop_input() instead of the sweep", + "cli": "step the loop input instead of using the sweep", + "mcp": "step the input with loop_input instead", + "web": "Step the input instead of sweeping it." + } + }, + "BP0065": { + "name": "output_used_by_sensor", + "area": "sensors", + "since": "next", + "message": "The {output} output is played by the emulated sensor {instance}", + "cause": "An analog emulated sensor drives the pod's {output} output, so a DAC or current command would fight it.", + "args": { + "output": "str", + "instance": "str" + }, + "fix": { + "sdk": "stop it first with bp.sensors.stop(\"{instance}\")", + "cli": "stop it first with `benchpod sensor stop {instance}`", + "mcp": "call sensor_stop(instance=\"{instance}\") first", + "web": "Stop the emulated sensor {instance} first." + } + }, + "BP0066": { + "name": "step_busy", + "area": "io", + "since": "next", + "message": "A step pulse train is running", + "cause": "The pod runs one step train at a time.", + "args": {}, + "fix": { + "sdk": "wait for the step train to finish (or stop it), then try again", + "cli": "wait for the step train to finish, then try again", + "mcp": "wait for the la_step train to finish, then try again", + "web": "Wait for the step train to finish." + } + }, + "BP0067": { + "name": "samples_out_of_range", + "area": "capture", + "since": "next", + "message": "samples must be 1 to {max} for this capture", + "cause": "Each capture holds a fixed number of samples: the shallow ADC capture what fits the RAM buffer, the deep ones what fits their PSRAM region at the rate asked for. A deep ADC capture is capture_dual with la_samples 0.", + "args": { + "max": "int" + }, + "fix": { + "sdk": "ask for at most {max} samples, or use a deep capture (capture_dual) for more", + "cli": "ask for at most {max} samples", + "mcp": "ask for at most {max} samples, or use capture_correlated / a deep capture for more", + "web": "Capture at most {max} samples." + } + }, + "BP0068": { + "name": "la_rate_above_ceiling", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit: with ADC samples in the capture the raw LA runs at most {max_mhz} MS/s on this gateware, {fit_mhz} MS/s for {samples} samples", + "cause": "On gateware before v53 the raw LA runs at most {max_mhz} MS/s when the same capture records ADC samples: faster, the PSRAM writer starved the ADC. The pod refuses an explicit rate it cannot run instead of slowing it down. {fit_mhz} MS/s is the fastest rate that fits {samples} samples. Above 12 MS/s the LA records its changes instead.", + "args": { + "rate_mhz": "str", + "max_mhz": "str", + "fit_mhz": "str", + "samples": "int" + }, + "fix": { + "sdk": "ask for at most {max_mhz} MS/s ({fit_mhz} MS/s for {samples} samples), leave the rate out for the fastest that fits, or update the pod's gateware", + "cli": "ask for at most {max_mhz} MS/s, or leave the rate out for the fastest that fits", + "mcp": "retry with la_sample_rate_hz at most {fit_mhz} MHz in Hz (or leave it out for the fastest that fits)", + "web": "Pick {fit_mhz} MS/s or less, or leave the rate on automatic." + } + }, + "BP0069": { + "name": "la_rate_too_deep", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit {samples} samples: at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples", + "cause": "The raw LA samples into a burst buffer that drains to the PSRAM more slowly than the fastest rates. A capture deeper than the buffer holds at {rate_mhz} MS/s would drop samples, so the pod refuses it instead of slowing it down. Either way out works: fewer samples at this rate, or a lower rate for this depth.", + "args": { + "rate_mhz": "str", + "samples": "int", + "max_samples": "int", + "fit_mhz": "str" + }, + "fix": { + "sdk": "capture at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples (leave the rate out for the fastest that fits)", + "cli": "capture at most {max_samples} samples at {rate_mhz} MS/s, or ask for {fit_mhz} MS/s or less (or leave the rate out)", + "mcp": "retry with at most {max_samples} samples, or with the rate at most {fit_mhz} MS/s (or leave it out for the fastest that fits)", + "web": "Capture at most {max_samples} samples at {rate_mhz} MS/s, or pick {fit_mhz} MS/s or less." + } + }, + "BP0070": { + "name": "capture_dual_too_deep", + "area": "capture", + "since": "next", + "message": "capture_dual takes at most {la_max} LA and {adc_max} ADC samples", + "cause": "Each stream of a capture_dual has its own PSRAM region of a fixed size. A deeper LA-only capture fits la_capture, which takes up to {la_capture_max} LA samples.", + "args": { + "la_max": "int", + "adc_max": "int", + "la_capture_max": "int" + }, + "fix": { + "sdk": "ask for at most {la_max} LA and {adc_max} ADC samples, or use la_capture for up to {la_capture_max} LA samples", + "cli": "ask for at most {la_max} LA and {adc_max} ADC samples", + "mcp": "ask for at most {la_max} LA and {adc_max} ADC samples, or use capture_la for up to {la_capture_max} LA samples", + "web": "Capture at most {la_max} LA and {adc_max} ADC samples." + } + }, + "BP0071": { + "name": "capture_overflowed", + "area": "capture", + "since": "next", + "message": "The capture overflowed: the PSRAM could not keep up with LA {la_ksps} kS/s and ADC {adc_ksps} kS/s", + "cause": "The capture started, but its streams wrote to the PSRAM faster than it could take them, so samples were lost and the pod returns none.", + "args": { + "la_ksps": "int", + "adc_ksps": "int" + }, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or capture fewer samples", + "cli": "lower the LA or ADC rate, or capture fewer samples", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or fewer samples", + "web": "Lower the LA or ADC rate, or capture fewer samples." + } + }, + "BP0072": { + "name": "psram_too_small", + "area": "capture", + "since": "next", + "message": "The capture is too deep: LA, ADC and a loaded DAC waveform together exceed the 8 MB PSRAM", + "cause": "A capture_dual packs its LA region, its ADC region and any deep-replay waveform still loaded into the pod's 8 MB PSRAM, and refuses up front when they do not fit.", + "args": {}, + "fix": { + "sdk": "capture fewer LA or ADC samples, or free the replay waveform (bp.dac_stop()) first", + "cli": "capture fewer samples", + "mcp": "retry with fewer la_samples or adc_samples, or call dac_stop to free a loaded replay waveform", + "web": "Capture fewer samples, or stop the DAC replay first." + } + }, + "BP0073": { + "name": "psram_bandwidth", + "area": "capture", + "since": "next", + "message": "The combined sample rate is more than the PSRAM bus can take", + "cause": "The LA, the ADC and a running deep replay share one PSRAM bus. The pod adds up their sustained rates and refuses a capture that would overrun it, instead of losing samples.", + "args": {}, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or stop the DAC replay first", + "cli": "lower the LA or ADC rate", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or call dac_stop first", + "web": "Lower the LA or ADC rate, or stop the DAC replay first." + } + }, + "BP0074": { + "name": "signatures_always_required", + "area": "policy", + "since": "next", + "message": "{setting} cannot be set to {want}: this firmware installs only signed images", + "cause": "Firmware 4.0.0 and later take an update (firmware, gateware, the Wi-Fi chip's image) only with a good signature, on every path: the LAN, the USB network adapter and the cloud. No command loosens that. Dev builds also take images signed with the developer key. Firmware you built yourself goes in over USB DFU (`benchpod flash-self`), which needs the pod on a USB cable.", + "args": { + "setting": "str", + "want": "str" + }, + "fix": { + "sdk": "install a signed release, or install self-built firmware over USB DFU (`benchpod flash-self`)", + "cli": "install a signed release, or install self-built firmware over USB DFU with `benchpod flash-self` (without --network)", + "mcp": "tell the user the pod takes only signed images; self-built firmware goes in over USB DFU (`benchpod flash-self`)", + "web": "The pod takes only signed images. Install self-built firmware over USB with `benchpod flash-self`." + } + }, + "BP0075": { + "name": "lan_plaintext_off", + "area": "policy", + "since": "next", + "message": "The pod serves its JSON API on the LAN over TLS only (port 8443): plaintext port 8080 is off", + "cause": "Firmware 4.0.0 and later serve the JSON API over Ethernet and Wi-Fi on TLS port 8443 only. Plaintext port 8080 still answers on the USB network adapter, and from the LAN when SCPI is switched on, but only for SCPI there. Plaintext JSON on the LAN comes back only when it is switched on over USB or from the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod by its address without a port (the SDK uses TLS on 8443 and pins the pod's certificate), or over USB ('usb')", + "cli": "connect by the pod's address without a port (the CLI uses TLS on 8443), or with --connection usb", + "mcp": "connect to the pod's address without :8080 (TLS on 8443 is used), or to 'usb'", + "web": "Connect to the pod over TLS (port 8443) or USB." + } + }, + "BP0076": { + "name": "usb_host_over_usb", + "area": "usb", + "since": "next", + "message": "USB host mode cannot start over the pod's own USB link", + "cause": "While the pod hosts a board on its USB port it is off the computer's USB, so the connection that asked would drop before the answer arrives. USB host mode starts only over the network (LAN or Wi-Fi) or the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod over the network or the cloud (Client(host) or 'embeddedci:'), not 'usb', then start USB host mode again", + "cli": "connect to the pod over the network or the cloud (--connection or embeddedci:), not usb, then run the command again", + "mcp": "connect to the pod over the network or the cloud (connect with its host or 'embeddedci:'), not 'usb', then try again", + "web": "Connect to the pod over the network or the cloud to use USB host mode." + } + }, + "BP0077": { + "name": "usb_host_port_unavailable", + "area": "usb", + "since": "next", + "message": "This pod has no USB host port {port}", + "cause": "Only pods with a USB-A host port can host a board there. Every pod can host on its USB-C port, but only on a bench rig with an adapter cable that powers the pod and carries the data lines to the board under test.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "use port='usb_c' with a USB-C adapter rig, or a pod with the USB-A host port", + "cli": "use --port usb_c with a USB-C adapter rig, or a pod with the USB-A host port", + "mcp": "tell the user this pod has no USB-A host port; port 'usb_c' works only with a USB-C adapter rig", + "web": "This pod has no USB-A host port." + } + }, + "BP0078": { + "name": "usb_host_no_crystal", + "area": "usb", + "since": "next", + "message": "USB host mode needs the pod's crystal clock, which is not running", + "cause": "A USB host keeps the bus timing itself and needs a precise clock. The pod runs on its internal oscillator because the crystal did not start at boot.", + "args": {}, + "fix": { + "sdk": "power cycle the pod; if bp.status() still shows the internal clock, contact support", + "cli": "power cycle the pod; if `benchpod status` still shows the internal clock, contact support", + "mcp": "ask the user to power cycle the pod; if it keeps happening, the pod needs support", + "web": "Power cycle the pod. If this keeps happening, contact support." + } + }, + "BP0079": { + "name": "usb_host_other_port", + "area": "usb", + "since": "next", + "message": "USB host mode is already running on {port}", + "cause": "The pod hosts one port at a time. A start for the same port renews the timeout; another port needs a stop first.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "stop USB host mode first (enabled=False), then start it on the other port", + "cli": "stop USB host mode first, then start it on the other port", + "mcp": "stop USB host mode first, then start it on the other port", + "web": "Stop USB host mode first." + } + }, + "BP0080": { + "name": "dac_pinout_mismatch", + "area": "analog", + "since": "next", + "message": "{cmd} refused, the DAC is off: the digital board ({digital}) and the analog module ({module}) use different flat-cable pinouts", + "cause": "The flat cable between the two boards carries the DAC's clock and data. Digital board v3r4 and analog module 3.5 swapped those two lines, so a newer board paired with an older one would send the DAC scrambled data and its outputs could jump to any voltage. The pod refuses every command that drives the DAC and sends it nothing; everything else keeps working. The module's revision comes from its EEPROM, so a module that was never programmed counts as an older one.", + "args": { + "cmd": "str", + "digital": "str", + "module": "str" + }, + "fix": { + "sdk": "pair a digital v3r4 or later board with an analog module 3.5 or later (or both older), or, if the module's EEPROM revision is wrong, program the revision printed on its board and restart the pod", + "cli": "pair a digital v3r4 or later board with an analog module 3.5 or later (or both older); `benchpod status` shows both. If the module's revision is wrong, program the one printed on its board and restart the pod", + "mcp": "tell the user the digital board and the analog module do not belong together (status shows both revisions): a digital v3r4+ board needs an analog module 3.5+, and an older digital board an older module", + "web": "The digital board and the analog module do not belong together, so the analog outputs are off. A digital v3r4 or later board needs an analog module 3.5 or later." + } } } } diff --git a/internal/features/features.go b/internal/features/features.go index 6b748e2..375cb41 100644 --- a/internal/features/features.go +++ b/internal/features/features.go @@ -2,9 +2,9 @@ // (generated from features/features.toml), copied here by scripts/sync-feature-map.sh. It says // which firmware and gateware have which feature, so the CLI needs no network to decide. // -// Firmware after 3.10.10 answers {"cmd":"status","caps":false} with features_rev (the table -// revision it is built from), fpga_image and the hw facts instead of the caps list; older -// firmware ignores the argument and sends the list. Has handles both. +// The pod's status carries features_rev (the table revision it is built from), fpga_image and +// the hw facts; Has decides from them. Firmware 4.0 sends no caps list (CLI 0.10 dropped the +// caps fallback for firmware up to 3.10.10). package features import ( @@ -22,13 +22,12 @@ func StatusRequest() map[string]any { return map[string]any{"cmd": "status", "ca // Entry is one feature of the table. type Entry struct { - Rev int `json:"rev"` - Firmware string `json:"firmware"` - Gateware int `json:"gateware"` - Board string `json:"board"` - Requires []string `json:"requires"` - LegacyCaps string `json:"legacy_caps"` - Status string `json:"status"` + Rev int `json:"rev"` + Firmware string `json:"firmware"` + Gateware int `json:"gateware"` + Board string `json:"board"` + Requires []string `json:"requires"` + Status string `json:"status"` } // Fact is a hardware or runtime fact the pod still announces. @@ -71,7 +70,6 @@ func Lookup(name string) (Entry, bool) { } type status struct { - Caps []string `json:"caps"` FeaturesRev int `json:"features_rev"` Gateware int `json:"gateware"` FPGAImage string `json:"fpga_image"` @@ -80,8 +78,8 @@ type status struct { } // Has reports whether the pod whose status reply this is has the feature `name` (a table name, -// for example "spi_master", "sensors", "generate16"). With features_rev the table decides; -// without it the reply's caps list does (the entry's legacy name, else the name itself). +// for example "spi_master", "sensors"): the table decides from features_rev. A reply without +// features_rev (firmware before 3.10.11) has none. func Has(statusReply json.RawMessage, name string) (bool, error) { var st status if err := json.Unmarshal(statusReply, &st); err != nil { @@ -92,15 +90,6 @@ func Has(statusReply json.RawMessage, name string) (bool, error) { if st.FeaturesRev > 0 { return resolve(st, top, name), nil } - want := name - if e, ok := table.Features[name]; ok && e.LegacyCaps != "" { - want = e.LegacyCaps - } - for _, c := range st.Caps { - if strings.EqualFold(c, want) { - return true, nil - } - } return false, nil } diff --git a/internal/features/features.json b/internal/features/features.json index bbc5dbd..1b5ea18 100644 --- a/internal/features/features.json +++ b/internal/features/features.json @@ -1,10 +1,10 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 8, - "api": 1, - "min_client_api": 0, - "table_sha256": "02f6411c240dcbc0cedda72648ba8713eb498a9a878ecca7f9fc817a3da586b2", + "revision": 11, + "api": 2, + "min_client_api": 2, + "table_sha256": "ea8870a74cd198ed990eeec337ab4792870bb26185f2c5449c7a23bd8dc94b05", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -223,7 +223,7 @@ "board": "any", "legacy_caps": "capture_b64", "legacy_frame": "capture_b64", - "docs": "API.md#base64-samples-encb64" + "docs": "API.md#base64-samples-the-default" }, "blob_slots": { "rev": 1, @@ -237,7 +237,7 @@ "board": "any", "legacy_caps": "can", "legacy_frame": "can", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "ota_sig": { "rev": 1, @@ -347,7 +347,7 @@ "board": "any", "legacy_caps": "can_fd", "legacy_frame": "can_fd", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "la_dir": { "rev": 1, @@ -661,13 +661,13 @@ "rev": 3, "firmware": "3.10.12", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "la_pull_1v8": { "rev": 4, "firmware": "3.10.13", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "log_level": { "rev": 4, @@ -704,6 +704,66 @@ "firmware": "next", "board": "any", "docs": "API.md#client-compatibility" + }, + "lan_tls_default": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#lan_tls--the-lan-api-over-tls" + }, + "sig_always_required": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#sig_policy--which-firmware-and-blob-updates-the-pod-accepts" + }, + "generate_volts_only": { + "rev": 10, + "firmware": "next", + "board": "analog", + "docs": "API.md#generate--dac-waveform-output" + }, + "json_names_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#commands" + }, + "can_start_stop": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#can_start--bring-can-up" + }, + "la_step_pull_split": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#la_pull--la-pin-pull-resistors" + }, + "json_booleans_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#target_power--enabledisable-a-target-power-efuse" + }, + "console_recovery_json": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "usb-serial-interface.md#removed-in-firmware-400" + }, + "usb_host": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#usb_host--usb-host-mode" + }, + "dac_pinout_guard": { + "rev": 11, + "firmware": "next", + "board": "any", + "docs": "API.md#dac-pinout-on-the-flat-cable" } } } diff --git a/internal/features/features_test.go b/internal/features/features_test.go index ccd84d4..dcc1142 100644 --- a/internal/features/features_test.go +++ b/internal/features/features_test.go @@ -29,10 +29,8 @@ func TestHasFromTheTable(t *testing.T) { {`{"gateware":44,"features_rev":1}`, "spi_master", false}, {`{"gateware":56,"features_rev":1,"analog":false}`, "generate16", false}, {`{"gateware":56,"features_rev":1,"analog":false,"hw":[]}`, "wifi_scan", false}, - // older firmware: the caps list decides - {`{"caps":["sensors","spi_master"]}`, "spi_master", true}, - {`{"caps":["sensors"]}`, "generate16", false}, - {`{"caps":["signal"]}`, "signal_alias", true}, // the table's name for the old "signal" + // no features_rev (firmware up to 3.10.10): CLI 0.10 reads no caps list + {`{"caps":["sensors","spi_master"]}`, "spi_master", false}, } { got, err := Has(json.RawMessage(tc.status), tc.name) if err != nil || got != tc.want { diff --git a/internal/fwrefusals/fwrefusals.go b/internal/fwrefusals/fwrefusals.go deleted file mode 100644 index cf65cd1..0000000 --- a/internal/fwrefusals/fwrefusals.go +++ /dev/null @@ -1,172 +0,0 @@ -// Package fwrefusals holds the firmware refusal texts the CLI shows or matches on, copied from -// benchpod-firmware, for tests. Each entry keeps the C string literal as it appears in the -// firmware source and one rendering of it; Check verifies the literals against a firmware -// checkout, so a wording change in the firmware fails the CLI tests instead of silently breaking -// a hint or a retry. -package fwrefusals - -import ( - _ "embed" - "encoding/json" - "fmt" - "os" - "path/filepath" - "regexp" - "sort" - "strings" -) - -//go:embed refusals.json -var raw []byte - -// Refusal is one firmware text. -type Refusal struct { - ID string `json:"id"` - File string `json:"file"` // relative to the firmware repository root - Kind string `json:"kind"` // "json" (an error reply), "console", "console_upload" - Format string `json:"format"` // the C literal, escapes kept - Example string `json:"example"` // one rendering, without a trailing newline or prompt - // Removed is the firmware version that no longer sends this text ("3.9.0"), "" while current. - // Such a text stays pinned: the CLI still meets it on pods running older firmware. Check skips it. - Removed string `json:"removed,omitempty"` - // Pending names the firmware pull request that adds this text ("benchpod-firmware#49") while - // it is not on the firmware's main branch yet: Check then reports it as pending, not as a - // change. Drop the field once that PR is merged. - Pending string `json:"pending,omitempty"` -} - -type doc struct { - Refusals []Refusal `json:"refusals"` - Tiers map[string]string `json:"tiers"` -} - -func load() doc { - var d doc - if err := json.Unmarshal(raw, &d); err != nil { - panic(fmt.Sprintf("fwrefusals: %v", err)) - } - return d -} - -// All returns every refusal. -func All() []Refusal { return load().Refusals } - -// Example returns the example text of refusal id; it panics on an unknown id. -func Example(id string) string { - for _, r := range All() { - if r.ID == id { - return r.Example - } - } - panic("fwrefusals: unknown id " + id) -} - -// TierFile is the firmware file the tiers come from. -func TierFile() string { return load().Tiers["_file"] } - -// Tiers maps a command to its pinned tier name ("T0".."T3"). -func Tiers() map[string]string { - out := map[string]string{} - for k, v := range load().Tiers { - if !strings.HasPrefix(k, "_") { - out[k] = v - } - } - return out -} - -var cEscapes = strings.NewReplacer(`\"`, `"`, `\\`, `\`, `\r`, "\r", `\n`, "\n", `\t`, "\t") - -// Pattern turns a refusal's C format into a regexp that matches its example: printf verbs -// match any text, a trailing newline and console prompt are dropped. -func (r Refusal) Pattern() *regexp.Regexp { - text := strings.TrimRight(cEscapes.Replace(r.Format), "\r\n> ") - verb := regexp.MustCompile(`%[-+ #0]*[0-9]*(?:l|ll|z|h)?[sdiuxX]`) - var b strings.Builder - b.WriteString("^") - last := 0 - for _, loc := range verb.FindAllStringIndex(text, -1) { - b.WriteString(regexp.QuoteMeta(text[last:loc[0]])) - b.WriteString(".+") - last = loc[1] - } - b.WriteString(regexp.QuoteMeta(text[last:])) - b.WriteString("$") - return regexp.MustCompile(b.String()) -} - -// FirmwareDir returns a benchpod-firmware checkout to check against: $BENCHPOD_FIRMWARE_DIR, else -// a benchpod-firmware directory next to this repository. "" when there is none. -func FirmwareDir() string { - if d := os.Getenv("BENCHPOD_FIRMWARE_DIR"); d != "" { - return d - } - wd, err := os.Getwd() - if err != nil { - return "" - } - for dir := wd; ; { - cand := filepath.Join(filepath.Dir(dir), "benchpod-firmware") - if _, err := os.Stat(filepath.Join(cand, "stm32h563", "src")); err == nil { - if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { - return cand - } - } - parent := filepath.Dir(dir) - if parent == dir { - return "" - } - dir = parent - } -} - -// adjacent joins C string literals split over lines ("a " "b" -> "a b"). -var adjacent = regexp.MustCompile(`"\s*\n\s*"`) - -// Check returns one problem per refusal format or tier missing from the firmware at dir. -func Check(dir string) []string { - var problems []string - sources := map[string]string{} - read := func(file string) (string, error) { - if s, ok := sources[file]; ok { - return s, nil - } - b, err := os.ReadFile(filepath.Join(dir, file)) - if err != nil { - return "", err - } - s := adjacent.ReplaceAllString(string(b), "") - sources[file] = s - return s, nil - } - for _, r := range All() { - if r.Removed != "" { - continue // older firmware only: the current tree has dropped it - } - src, err := read(r.File) - if err != nil { - problems = append(problems, fmt.Sprintf("%s: %v", r.ID, err)) - continue - } - if !strings.Contains(src, `"`+r.Format+`"`) && r.Pending == "" { - problems = append(problems, fmt.Sprintf("%s: %q is no longer in %s", r.ID, r.Format, r.File)) - } - } - src, err := read(TierFile()) - if err != nil { - return append(problems, fmt.Sprintf("tiers: %v", err)) - } - tiers := Tiers() - cmds := make([]string, 0, len(tiers)) - for c := range tiers { - cmds = append(cmds, c) - } - sort.Strings(cmds) - for _, c := range cmds { - re := regexp.MustCompile(`\{\s*"` + regexp.QuoteMeta(c) + `"\s*,\s*CMD_TIER_` + tiers[c] + `\s*\}`) - if !re.MatchString(src) { - problems = append(problems, fmt.Sprintf("tier: %s is no longer %s in %s", c, tiers[c], TierFile())) - } - } - return problems -} diff --git a/internal/fwrefusals/fwrefusals_test.go b/internal/fwrefusals/fwrefusals_test.go deleted file mode 100644 index 3bff906..0000000 --- a/internal/fwrefusals/fwrefusals_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package fwrefusals - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -func TestEveryExampleMatchesItsFormat(t *testing.T) { - seen := map[string]bool{} - for _, r := range All() { - if seen[r.ID] { - t.Errorf("duplicate id %s", r.ID) - } - seen[r.ID] = true - if r.File == "" || r.Format == "" || r.Example == "" || r.Kind == "" { - t.Errorf("%s: incomplete entry %+v", r.ID, r) - } - if !r.Pattern().MatchString(r.Example) { - t.Errorf("%s: example %q does not match format %q (%s)", r.ID, r.Example, r.Format, r.Pattern()) - } - } - if len(Tiers()) == 0 || TierFile() == "" { - t.Fatal("no tiers pinned") - } -} - -// The firmware still has every pinned text. CI checks benchpod-firmware out and points -// BENCHPOD_FIRMWARE_DIR at it; locally a sibling checkout is used. A failure means the firmware's -// wording changed: update refusals.json and whatever in the CLI matches on that text. -func TestFirmwareStillSendsThePinnedTexts(t *testing.T) { - dir := FirmwareDir() - if dir == "" { - if os.Getenv("CI") != "" { - t.Fatal("no benchpod-firmware checkout: set BENCHPOD_FIRMWARE_DIR") - } - t.Skip("no benchpod-firmware checkout next to this repository (set BENCHPOD_FIRMWARE_DIR)") - } - for _, p := range Check(dir) { - t.Error(p) - } -} - -func TestCheckReportsAChangedText(t *testing.T) { - dir := t.TempDir() - write := func(rel, body string) { - path := filepath.Join(dir, rel) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { - t.Fatal(err) - } - } - // A firmware tree with every text as pinned, then one reworded. - files := map[string]*strings.Builder{} - for _, r := range All() { - if files[r.File] == nil { - files[r.File] = &strings.Builder{} - } - files[r.File].WriteString(`send_error(c, "` + r.Format + "\");\n") - } - tiers := &strings.Builder{} - for c, tier := range Tiers() { - tiers.WriteString(`{ "` + c + `", CMD_TIER_` + tier + " },\n") - } - files[TierFile()] = tiers - for f, b := range files { - write(f, b.String()) - } - if p := Check(dir); len(p) != 0 { - t.Fatalf("a matching tree reported %v", p) - } - lockedFile := "" - for _, r := range All() { - if r.ID == "lan_locked" { - lockedFile = r.File - } - } - write(lockedFile, strings.Replace(files[lockedFile].String(), "needs the cloud", "requires the cloud", 1)) - write(TierFile(), strings.Replace(tiers.String(), `"ota_begin", CMD_TIER_T3`, `"ota_begin", CMD_TIER_T2`, 1)) - p := Check(dir) - if len(p) != 2 || !strings.Contains(p[0], "lan_locked") || !strings.Contains(p[1], "ota_begin") { - t.Fatalf("problems = %v", p) - } -} - -func TestAdjacentLiteralsAreJoined(t *testing.T) { - src := "return x ? \"busy: a capture, upload or update is using the PSRAM bus; \"\n" + - " \"try again when it ends\" : NULL;\n" - if got := adjacent.ReplaceAllString(src, ""); !strings.Contains(got, `"`+ - "busy: a capture, upload or update is using the PSRAM bus; try again when it ends"+`"`) { - t.Fatalf("not joined: %q", got) - } -} diff --git a/internal/fwrefusals/refusals.json b/internal/fwrefusals/refusals.json deleted file mode 100644 index 7cc6c16..0000000 --- a/internal/fwrefusals/refusals.json +++ /dev/null @@ -1,126 +0,0 @@ -{ - "_comment": "Firmware refusal texts the CLI shows or matches on, copied from benchpod-firmware main (897f057; la voltage + pin conflict texts 6e31527). format is the C string literal exactly as it appears in the source (adjacent literals joined, escapes kept); example is one rendering of it. The CLI tests check every example against its format, that the CLI shows or classifies it as intended, and, when a benchpod-firmware checkout is available (CI checks it out; locally the sibling directory), that each format is still in its source file, so a firmware wording change fails here. tiers pins cmd_tier.c entries for commands the CLI sends.", - "refusals": [ - {"id": "lan_locked_v39", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "locked: %s needs the cloud or USB", - "example": "locked: cloud_set needs the cloud or USB"}, - {"id": "lan_locked", "file": "stm32h563/src/cmd_gate.c", "removed": "3.9.0", "kind": "json", - "format": "locked: %s needs the cloud or the USB console", - "example": "locked: cloud_set needs the cloud or the USB console"}, - {"id": "lease_busy", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "busy: a cloud job holds this pod (%s, %lu s left)", - "example": "busy: a cloud job holds this pod (ci-run-42, 37 s left)"}, - {"id": "tunnel_forbidden", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "forbidden: %s needs an organization owner or admin", - "example": "forbidden: ota_begin needs an organization owner or admin"}, - {"id": "heavy_busy", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "busy", - "example": "busy"}, - {"id": "psram_bus_busy", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "busy: a capture, upload or update is using the PSRAM bus; try again when it ends", - "example": "busy: a capture, upload or update is using the PSRAM bus; try again when it ends"}, - {"id": "swd_busy_spi_session", "file": "stm32h563/src/command_handler_dap.c", "kind": "json", - "format": "swd busy: an SPI session is using the engine ({\\\"cmd\\\":\\\"spi_stop\\\"})", - "example": "swd busy: an SPI session is using the engine ({\"cmd\":\"spi_stop\"})"}, - {"id": "swd_busy", "file": "stm32h563/src/command_handler_dap.c", "kind": "json", - "format": "swd busy", - "example": "swd busy"}, - {"id": "uart_busy", "file": "stm32h563/src/command_handler_uart.c", "kind": "json", - "format": "uart busy", - "example": "uart busy"}, - {"id": "la_voltage_unset", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "la voltage not set; set la_mv (1800 or 3300) in the active wiring profile, or call la_voltage (mv 1800 or 3300) first", - "example": "la voltage not set; set la_mv (1800 or 3300) in the active wiring profile, or call la_voltage (mv 1800 or 3300) first"}, - {"id": "la_voltage_unset_v3109", "file": "stm32h563/src/command_handler.c", "removed": "3.10.10", "kind": "json", - "format": "la voltage not set; set it with la_voltage (mv 1800 or 3300) first", - "example": "la voltage not set; set it with la_voltage (mv 1800 or 3300) first"}, - {"id": "pin_conflict", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "pin conflict: LA%u is in use by %s; %s", - "example": "pin conflict: LA4 is in use by gpio; release it with {\"cmd\":\"gpio\",\"la\":4,\"mode\":\"off\"}"}, - {"id": "pin_hint_gpio", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "release it with {\\\"cmd\\\":\\\"gpio\\\",\\\"la\\\":%u,\\\"mode\\\":\\\"off\\\"}", - "example": "release it with {\"cmd\":\"gpio\",\"la\":4,\"mode\":\"off\"}"}, - {"id": "pin_hint_uart", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the uart proxy first", - "example": "stop the uart proxy first"}, - {"id": "pin_hint_swd", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "end the SWD session first", - "example": "end the SWD session first"}, - {"id": "pin_hint_sensor", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the sensor emulation first ({\\\"cmd\\\":\\\"sensor_stop\\\",\\\"instance\\\":\\\"%s\\\"})", - "example": "stop the sensor emulation first ({\"cmd\":\"sensor_stop\",\"instance\":\"env\"})"}, - {"id": "pin_hint_step", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "wait for the step train to finish", - "example": "wait for the step train to finish"}, - {"id": "pin_hint_spi", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the SPI session first ({\\\"cmd\\\":\\\"spi_stop\\\"})", - "example": "stop the SPI session first ({\"cmd\":\"spi_stop\"})"}, - {"id": "unknown_cmd", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "unknown cmd", - "example": "unknown cmd"}, - {"id": "spi_busy", "file": "stm32h563/src/command_handler_spi.c", "kind": "json", - "format": "spi busy: send spi_stop first", - "example": "spi busy: send spi_stop first"}, - {"id": "swd_or_spi_busy", "file": "stm32h563/src/command_handler_spi.c", "kind": "json", - "format": "swd or spi busy: end the SWD session first", - "example": "swd or spi busy: end the SWD session first"}, - {"id": "unknown_target", "file": "stm32h563/src/command_handler_ota.c", "kind": "json", - "format": "unknown target", - "example": "unknown target"}, - {"id": "ota_owner_busy", "file": "stm32h563/src/ota.c", "kind": "json", - "format": "busy: %s update from %s is in progress", - "example": "busy: firmware update from the cloud is in progress"}, - {"id": "sig_policy_unknown", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: unknown policy", - "example": "sig_policy: unknown policy"}, - {"id": "sig_policy_from_lan", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: change it from the cloud or the USB console", - "example": "sig_policy: change it from the cloud or the USB console"}, - {"id": "sig_policy_loosen", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: only the USB console can loosen the policy (now %s)", - "example": "sig_policy: only the USB console can loosen the policy (now required)"}, - {"id": "lan_policy_unknown", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "lan_policy: unknown policy", - "example": "lan_policy: unknown policy"}, - {"id": "lan_policy_from_lan", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "lan_policy: change it from the cloud or the USB console", - "example": "lan_policy: change it from the cloud or the USB console"}, - {"id": "usb_network_not_device", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "usb_network: change it on the device (the USB console, or over the USB link)", - "example": "usb_network: change it on the device (the USB console, or over the USB link)"}, - {"id": "cloud_ca_from_lan_v39", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "%s: change it from the cloud or over USB", - "example": "cloud_ca: change it from the cloud or over USB"}, - {"id": "cloud_ca_from_lan", "file": "stm32h563/src/pod_policy.c", "removed": "3.9.0", "kind": "json", - "format": "%s: change it from the cloud or the USB console", - "example": "cloud_ca: change it from the cloud or the USB console"}, - {"id": "cloud_proxy_from_lan_v39", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "%s: change it from the cloud or over USB", - "example": "cloud_proxy: change it from the cloud or over USB"}, - {"id": "cloud_proxy_from_lan", "file": "stm32h563/src/pod_policy.c", "removed": "3.9.0", "kind": "json", - "format": "%s: change it from the cloud or the USB console", - "example": "cloud_proxy: change it from the cloud or the USB console"}, - {"id": "console_unknown_command", "file": "stm32h563/src/console.c", "kind": "console", - "format": " unknown command '%s' (try 'help')\\r\\n", - "example": " unknown command 'cloud-ca' (try 'help')"}, - {"id": "console_upload_busy", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data busy\\r\\n> ", - "example": "upload-data busy"}, - {"id": "console_upload_retry_crc", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data retry crc\\r\\n> ", - "example": "upload-data retry crc"}, - {"id": "console_upload_ok", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data ok %lu\\r\\n> ", - "example": "upload-data ok 4096"}, - {"id": "console_upload_end_busy", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-end error %s\\r\\n", - "example": "upload-end error busy: firmware update from the cloud is in progress"} - ], - "tiers": { - "_file": "stm32h563/src/cmd_tier.c", - "cloud_set": "T2", "cloud_clear": "T2", - "ota_begin": "T3", "ota_data": "T3", "ota_end": "T3", "ota_commit": "T3", "ota_abort": "T3", - "cloud_ca": "T0", "cloud_proxy": "T0", "sig_policy": "T0", "lan_policy": "T0", - "status": "T0", "dap_start": "T1", "spi_start": "T1", "spi_flash": "T1" - } -} diff --git a/internal/sensors/commands.go b/internal/sensors/commands.go index f92d0bf..f6102c8 100644 --- a/internal/sensors/commands.go +++ b/internal/sensors/commands.go @@ -200,7 +200,7 @@ func Values(pairs []string) (map[string]any, error) { } // HasCapability reports whether the pod whose status reply this is has cap (features.Has: the -// features table when the reply has features_rev, else its caps list). +// features table, from the reply's features_rev). func HasCapability(status json.RawMessage, cap string) bool { ok, err := features.Has(status, cap) return err == nil && ok diff --git a/internal/sensors/sensors_test.go b/internal/sensors/sensors_test.go index fced3bb..e10c6c2 100644 --- a/internal/sensors/sensors_test.go +++ b/internal/sensors/sensors_test.go @@ -222,7 +222,7 @@ func TestPinsAddressesAndValues(t *testing.T) { if _, err := Values([]string{"t=hot"}); err == nil { t.Fatal("hot accepted") } - if !HasCapability(json.RawMessage(`{"caps":["dac","sensors"]}`), "sensors") || HasCapability(json.RawMessage(`{"caps":["dac"]}`), "sensors") { + if !HasCapability(json.RawMessage(`{"features_rev":11,"gateware":60}`), "sensors") || HasCapability(json.RawMessage(`{"caps":["dac","sensors"]}`), "sensors") { t.Fatal("caps") } } diff --git a/internal/serialconsole/cloudcfg.go b/internal/serialconsole/cloudcfg.go deleted file mode 100644 index 77dfed4..0000000 --- a/internal/serialconsole/cloudcfg.go +++ /dev/null @@ -1,268 +0,0 @@ -package serialconsole - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// The pod's company CA certificate and HTTP proxy over the console (firmware -// docs/design/cloud-hardening.md, section 3): -// -// ca -> ca (one line per certificate) | ca none -// ca-clear -> ca-clear ok | ca-clear error -// proxy -> proxy auth|noauth | proxy none -// proxy-set [user pw] -> proxy auth|noauth | proxy error -// proxy-clear -> proxy none -// -// Any command may also answer " error ". The CA itself is uploaded with the regular -// upload path (Upload with target "ca"). Older firmware answers "unknown command". - -// ErrUnknownCommand is older firmware's answer to a console command it does not have. It is the -// same value as ErrPolicyUnsupported, so either name matches with errors.Is. -var ErrUnknownCommand = ErrPolicyUnsupported - -// ConsoleLineMax is the longest command line the firmware's line editor takes (CONSOLE_LINE_MAX -// is 128 including the terminating NUL). -const ConsoleLineMax = 127 - -// CommandError is the pod refusing a console command (" error "). It is the CLI's one -// refusal type, tcpclient.PodError, with Cmd set. -type CommandError = tcpclient.PodError - -// CACert is one certificate of the pod's company CA, as the pod reports it. -type CACert struct { - Subject string `json:"subject"` - SHA256 string `json:"sha256"` // hex SHA-256 of the DER certificate -} - -// ProxyConfig is the pod's HTTP proxy. Addr is "" when no proxy is set. -type ProxyConfig struct { - Addr string // host:port - Auth bool // a user and password are stored (the pod never reports the password) -} - -// CloudCA lists the company CA certificates the pod holds (none: an empty list). -func (c *Console) CloudCA(ctx context.Context) ([]CACert, error) { - out, err := c.cfgCommand(ctx, "ca", "ca", "", parseCAComplete) - if err != nil { - return nil, err - } - certs, err := parseCA(out) - if errors.Is(err, errNoCAReply) { - return nil, fmt.Errorf("ca: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } - return certs, err -} - -// CloudCAClear removes the pod's company CA. -func (c *Console) CloudCAClear(ctx context.Context) error { - out, err := c.cfgCommand(ctx, "ca-clear", "ca-clear", "", func(s string) bool { - _, ok := lastReply(s, "ca-clear", "ca-clear") - return ok - }) - if err != nil { - return err - } - rest, ok := lastReply(out, "ca-clear", "ca-clear") - if !ok { - return fmt.Errorf("ca-clear: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } - if why, isErr := replyError(rest); isErr { - return &CommandError{Cmd: "ca-clear", Reason: why} - } - return nil -} - -// CloudProxy reports the pod's HTTP proxy. -func (c *Console) CloudProxy(ctx context.Context) (ProxyConfig, error) { - return c.proxyCommand(ctx, "proxy", "proxy", "") -} - -// CloudProxyClear removes the pod's HTTP proxy and returns what the pod reports afterwards. -func (c *Console) CloudProxyClear(ctx context.Context) (ProxyConfig, error) { - return c.proxyCommand(ctx, "proxy-clear", "proxy-clear", "") -} - -// CloudProxySet sets the pod's HTTP proxy to addr (host:port), with a user and password when -// user is not empty. The password never reaches a log line or an error message. -func (c *Console) CloudProxySet(ctx context.Context, addr, user, password string) (ProxyConfig, error) { - addr = strings.TrimSpace(addr) - if addr == "" || strings.ContainsAny(addr, " \t\r\n") { - return ProxyConfig{}, fmt.Errorf("proxy-set: bad address %q", addr) - } - if (user == "") != (password == "") { - return ProxyConfig{}, errors.New("proxy-set: pass both a user and a password, or neither") - } - if strings.ContainsAny(user, " \t\r\n") || strings.ContainsAny(password, " \t\r\n") { - return ProxyConfig{}, errors.New("proxy-set: the USB console cannot carry a user or password with spaces; set it over the LAN") - } - line, display := "proxy-set "+addr, "proxy-set "+addr - if user != "" { - line += " " + user + " " + password - display += " " + user + " ***" - } - if len(line) > ConsoleLineMax { - return ProxyConfig{}, fmt.Errorf("proxy-set: the command is %d characters, the USB console takes %d; use a shorter host, user or password, or set it over the LAN", - len(line), ConsoleLineMax) - } - return c.proxyCommand(ctx, line, display, password) -} - -func (c *Console) proxyCommand(ctx context.Context, line, display, secret string) (ProxyConfig, error) { - cmd := strings.Fields(line)[0] - done := func(s string) bool { - _, ok := proxyReply(s, cmd, line) - return ok - } - out, err := c.cfgCommand(ctx, line, display, secret, done) - if err != nil { - return ProxyConfig{}, err - } - rest, ok := proxyReply(out, cmd, line) - if !ok { - return ProxyConfig{}, fmt.Errorf("%s: no reply from the pod (got: %q)", cmd, maskPassword(tail([]byte(out), 200), secret)) - } - if why, isErr := replyError(rest); isErr { - return ProxyConfig{}, &CommandError{Cmd: cmd, Reason: maskPassword(why, secret)} - } - f := strings.Fields(rest) - if f[0] == "none" { - return ProxyConfig{}, nil - } - p := ProxyConfig{Addr: f[0]} - if len(f) > 1 { - p.Auth = f[1] == "auth" - } - return p, nil -} - -// proxyReply is the pod's answer to a proxy command: a "proxy ..." line, or " error ...". -func proxyReply(raw, cmd, line string) (string, bool) { - if cmd != "proxy" { - if rest, ok := lastReply(raw, cmd, line); ok { - if _, isErr := replyError(rest); isErr { - return rest, true - } - } - } - return lastReply(raw, "proxy", line) -} - -// cfgCommand sends line (shown as display, with secret masked) and reads until complete reports -// the reply is in (or the prompt and a short grace passed). An "unknown command" answer is -// ErrUnknownCommand. -func (c *Console) cfgCommand(ctx context.Context, line, display, secret string, complete func(string) bool) (string, error) { - cmd := strings.Fields(line)[0] - unknownOrDone := func(s string) bool { return strings.Contains(s, "unknown command") || complete(s) } - out, err := c.sendCommandUntil(ctx, line, display, secret, unknownOrDone) - if strings.Contains(out, "unknown command") { - return "", ErrUnknownCommand - } - if err != nil && !complete(out) { - return "", fmt.Errorf("%s: %w", cmd, err) - } - return out, nil -} - -// consoleLines splits raw console output into trimmed lines, dropping prompts and backspaces. -func consoleLines(raw string) []string { - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - var lines []string - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - if ln != "" { - lines = append(lines, ln) - } - } - return lines -} - -// lastReply returns what follows " " on the last line that starts with it, skipping the -// first copy of the echoed command line. -func lastReply(raw, word, line string) (string, bool) { - echoSeen := false - var rest string - found := false - for _, ln := range consoleLines(raw) { - if !echoSeen && ln == line { - echoSeen = true - continue - } - if strings.HasPrefix(ln, word+" ") { - rest, found = strings.TrimSpace(ln[len(word)+1:]), true - } - } - return rest, found && rest != "" -} - -// replyError reports whether a reply is "error ", and the why. -func replyError(rest string) (string, bool) { - if rest != "error" && !strings.HasPrefix(rest, "error ") { - return "", false - } - why := strings.TrimSpace(strings.TrimPrefix(rest, "error")) - if why == "" { - why = "refused" - } - return why, true -} - -// parseCAComplete reports whether the reply to `ca` is in: "ca none", an error, or at least one -// certificate line. More certificate lines may follow; the prompt ends the read. -func parseCAComplete(raw string) bool { - _, err := parseCA(raw) - return err == nil || !errors.Is(err, errNoCAReply) -} - -var errNoCAReply = errors.New("no ca reply yet") - -// parseCA reads "ca " lines (the subject may hold spaces; the hash is the -// last field), "ca none", or "ca error ". -func parseCA(raw string) ([]CACert, error) { - var certs []CACert - none := false - for _, ln := range consoleLines(raw) { - rest, ok := strings.CutPrefix(ln, "ca ") - if !ok { - continue - } - rest = strings.TrimSpace(rest) - if why, isErr := replyError(rest); isErr { - return nil, &CommandError{Cmd: "ca", Reason: why} - } - if rest == "none" { - none = true - continue - } - i := strings.LastIndexAny(rest, " \t") - if i < 0 { - continue - } - sha := strings.ToLower(rest[i+1:]) - if !isHex64(sha) { - continue - } - certs = append(certs, CACert{Subject: strings.TrimSpace(rest[:i]), SHA256: sha}) - } - if len(certs) == 0 && !none { - return nil, errNoCAReply - } - return certs, nil -} - -func isHex64(s string) bool { - if len(s) != 64 { - return false - } - for _, r := range s { - if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') { - return false - } - } - return true -} diff --git a/internal/serialconsole/cloudcfg_test.go b/internal/serialconsole/cloudcfg_test.go deleted file mode 100644 index 2e033d0..0000000 --- a/internal/serialconsole/cloudcfg_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package serialconsole - -import ( - "bytes" - "context" - "errors" - "fmt" - "strings" - "testing" -) - -const ( - shaA = "8f2a6e0a3c5b0f1e9d7c6b5a4938271605f4e3d2c1b0a9988776655443322110" - shaB = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" -) - -// cfgPod answers ca, ca-clear, proxy, proxy-set and proxy-clear like the firmware's console: -// the line is echoed, a log line may interleave, then the reply and the prompt. old makes it -// answer like firmware without the commands. -type cfgPod struct { - certs []CACert - proxy string - auth bool - old bool - failNext string // the next ca-clear or proxy-set answers " error " - lines []string -} - -func (p *cfgPod) console() *Console { - fc := &fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.lines = append(p.lines, line) - out.WriteString(line + "\r\n") - out.WriteString("[cloud] reconnect in 5 s\r\n") - f := strings.Fields(line) - switch { - case p.old: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case f[0] == "ca": - if len(p.certs) == 0 { - out.WriteString("ca none\r\n") - } - for _, c := range p.certs { - fmt.Fprintf(out, "ca %s %s\r\n", c.Subject, c.SHA256) - } - case f[0] == "ca-clear" && p.failNext != "": - fmt.Fprintf(out, "ca-clear error %s\r\n", p.failNext) - p.failNext = "" - case f[0] == "ca-clear": - p.certs = nil - out.WriteString("ca-clear ok\r\n") - case f[0] == "proxy-set" && p.failNext != "": - fmt.Fprintf(out, "proxy error %s\r\n", p.failNext) - p.failNext = "" - case f[0] == "proxy-set": - p.proxy, p.auth = f[1], len(f) == 4 - fallthrough - case f[0] == "proxy": - if p.proxy == "" { - out.WriteString("proxy none\r\n") - } else if p.auth { - fmt.Fprintf(out, "proxy %s auth\r\n", p.proxy) - } else { - fmt.Fprintf(out, "proxy %s noauth\r\n", p.proxy) - } - case f[0] == "proxy-clear": - p.proxy, p.auth = "", false - out.WriteString("proxy none\r\n") - } - out.WriteString("> ") - }} - return newConsole(fc) -} - -func TestCloudCAShowAndClear(t *testing.T) { - pod := &cfgPod{certs: []CACert{{"CN=Acme Root CA, O=Acme Corp", shaA}, {"CN=Acme Issuing CA 2", shaB}}} - c := pod.console() - - certs, err := c.CloudCA(testContext(t)) - if err != nil { - t.Fatalf("ca: %v", err) - } - if len(certs) != 2 || certs[0] != pod.certs[0] || certs[1] != pod.certs[1] { - t.Fatalf("ca = %+v", certs) - } - - if err := c.CloudCAClear(testContext(t)); err != nil { - t.Fatalf("ca-clear: %v", err) - } - certs, err = c.CloudCA(testContext(t)) - if err != nil || len(certs) != 0 { - t.Fatalf("ca after clear = %+v, %v", certs, err) - } - - pod.failNext = "w25q write failed" - err = c.CloudCAClear(testContext(t)) - var ce *CommandError - if !errors.As(err, &ce) || ce.Reason != "w25q write failed" { - t.Fatalf("ca-clear refusal = %v", err) - } -} - -func TestCloudProxySetShowClear(t *testing.T) { - pod := &cfgPod{} - c := pod.console() - var logs bytes.Buffer - c.logf = func(format string, a ...any) { fmt.Fprintf(&logs, format+"\n", a...) } - - p, err := c.CloudProxy(testContext(t)) - if err != nil || p.Addr != "" { - t.Fatalf("proxy = %+v, %v", p, err) - } - p, err = c.CloudProxySet(testContext(t), "proxy.corp:3128", "alice", "s3cret") - if err != nil || p.Addr != "proxy.corp:3128" || !p.Auth { - t.Fatalf("proxy-set = %+v, %v", p, err) - } - if got := pod.lines[len(pod.lines)-1]; got != "proxy-set proxy.corp:3128 alice s3cret" { - t.Fatalf("sent %q", got) - } - if strings.Contains(logs.String(), "s3cret") { - t.Fatalf("the password reached the log:\n%s", logs.String()) - } - p, err = c.CloudProxySet(testContext(t), "10.0.0.1:8080", "", "") - if err != nil || p.Addr != "10.0.0.1:8080" || p.Auth { - t.Fatalf("proxy-set noauth = %+v, %v", p, err) - } - p, err = c.CloudProxyClear(testContext(t)) - if err != nil || p.Addr != "" { - t.Fatalf("proxy-clear = %+v, %v", p, err) - } - - pod.failNext = "cannot resolve host" - _, err = c.CloudProxySet(testContext(t), "nowhere:1", "", "") - var ce *CommandError - if !errors.As(err, &ce) || ce.Cmd != "proxy-set" || ce.Reason != "cannot resolve host" { - t.Fatalf("proxy-set refusal = %v", err) - } -} - -func TestCloudProxySetLocalChecks(t *testing.T) { - pod := &cfgPod{} - c := pod.console() - for _, tc := range []struct{ addr, user, pass, want string }{ - {"a b:1", "", "", "bad address"}, - {"p:1", "u", "", "both a user and a password"}, - {"p:1", "u", "pa ss", "spaces"}, - {"p:1", "u", strings.Repeat("x", 120), "the USB console takes 127"}, - } { - _, err := c.CloudProxySet(context.Background(), tc.addr, tc.user, tc.pass) - if err == nil || !strings.Contains(err.Error(), tc.want) { - t.Errorf("%+v: err = %v, want %q", tc, err, tc.want) - } - if err != nil && tc.pass != "" && strings.Contains(err.Error(), tc.pass) { - t.Errorf("the password is in the error: %v", err) - } - } - if len(pod.lines) != 0 { - t.Fatalf("a refused value reached the pod: %v", pod.lines) - } -} - -func TestCloudConfigOldFirmware(t *testing.T) { - c := (&cfgPod{old: true}).console() - if _, err := c.CloudCA(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("ca: %v", err) - } - if err := c.CloudCAClear(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("ca-clear: %v", err) - } - if _, err := c.CloudProxy(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("proxy: %v", err) - } - if _, err := c.CloudProxySet(testContext(t), "p:1", "u", "pw"); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("proxy-set: %v", err) - } -} - -func TestParseCA(t *testing.T) { - raw := "ca\r\n[log] x\r\nca CN=Root With Spaces " + strings.ToUpper(shaA) + "\r\nca garbage\r\n> " - certs, err := parseCA(raw) - if err != nil || len(certs) != 1 || certs[0].Subject != "CN=Root With Spaces" || certs[0].SHA256 != shaA { - t.Fatalf("parseCA = %+v, %v", certs, err) - } - if _, err := parseCA("ca\r\n> "); !errors.Is(err, errNoCAReply) { - t.Fatalf("echo only: %v", err) - } - var ce *CommandError - if _, err := parseCA("ca\r\nca error w25q read failed\r\n> "); !errors.As(err, &ce) || ce.Reason != "w25q read failed" { - t.Fatalf("error reply: %v", err) - } -} - -func TestUploadCATarget(t *testing.T) { - sim := newPodUploadSim() - c := newConsole(sim) - pem := []byte("-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n") - if err := c.Upload(context.Background(), "ca", pem, 0, nil); err != nil { - t.Fatalf("upload ca: %v", err) - } - if !bytes.Equal(sim.committed["ca"], pem) { - t.Fatalf("committed %q", sim.committed["ca"]) - } - for _, cmd := range sim.commands { - if strings.HasPrefix(cmd, "upload-sig") { - t.Fatalf("a CA upload sent %q", cmd) - } - } -} diff --git a/internal/serialconsole/identity.go b/internal/serialconsole/identity.go index 71468c6..2a6046c 100644 --- a/internal/serialconsole/identity.go +++ b/internal/serialconsole/identity.go @@ -88,38 +88,6 @@ func parseIdentityState(reply string) (IdentityState, error) { return IdentityState{ShortID: f[0], PublicKey: f[1]}, nil } -// IdentityWipe erases the pod's device key and makes a new one, confirming with token (the -// current short id, or "unknown"). It returns the new short id. -func (c *Console) IdentityWipe(ctx context.Context, token string) (string, error) { - token = strings.TrimSpace(token) - if token == "" || strings.ContainsAny(token, " \t\r\n") { - return "", fmt.Errorf("identity-wipe: bad confirmation token %q", token) - } - line := "identity-wipe " + token - complete := func(acc string) bool { - _, _, err := parseConsoleReply(acc, "identity-wipe", line) - return !errors.Is(err, errNoConsoleReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - reply, refused, perr := parseConsoleReply(out, "identity-wipe", line) - switch { - case perr == nil && refused: - return "", &IdentityError{Cmd: "identity-wipe", Reason: reply} - case perr == nil: - f := strings.Fields(reply) - if len(f) < 2 || f[0] != "ok" { - return "", fmt.Errorf("identity-wipe: unexpected reply %q", reply) - } - return f[1], nil - case !errors.Is(perr, errNoConsoleReply): - return "", perr - case err != nil: - return "", fmt.Errorf("identity-wipe: %w", err) - default: - return "", fmt.Errorf("identity-wipe: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } -} - var errNoConsoleReply = errors.New("no reply yet") // parseConsoleReply finds " " in raw console output, skipping the line editor's echo diff --git a/internal/serialconsole/identity_test.go b/internal/serialconsole/identity_test.go index cd981b3..b5fe57f 100644 --- a/internal/serialconsole/identity_test.go +++ b/internal/serialconsole/identity_test.go @@ -64,35 +64,9 @@ func TestIdentityShow(t *testing.T) { } } -func TestIdentityWipe(t *testing.T) { - pod := &identityPod{problem: "unknown identity record", newID: "ed6313"} - c, fc := pod.console() - if _, err := c.IdentityWipe(testContext(t), "a1b2c3"); err == nil { - t.Fatal("a wrong token was accepted") - } else { - var ie *IdentityError - if !errors.As(err, &ie) || !strings.Contains(ie.Reason, "identity-wipe unknown") { - t.Fatalf("err = %v", err) - } - } - id, err := c.IdentityWipe(testContext(t), "unknown") - if err != nil || id != "ed6313" { - t.Fatalf("wipe = %q, %v", id, err) - } - if got := fc.written.String(); got != "identity-wipe a1b2c3\nidentity-wipe unknown\n" { - t.Fatalf("written = %q", got) - } - if _, err := c.IdentityWipe(testContext(t), "two words"); err == nil { - t.Fatal("a token with a space was sent") - } -} - func TestIdentityOldFirmware(t *testing.T) { c, _ := (&identityPod{old: true}).console() if _, err := c.Identity(testContext(t)); !errors.Is(err, ErrIdentityUnsupported) { t.Fatalf("identity err = %v", err) } - if _, err := c.IdentityWipe(testContext(t), "unknown"); !errors.Is(err, ErrIdentityUnsupported) { - t.Fatalf("wipe err = %v", err) - } } diff --git a/internal/serialconsole/lavoltage.go b/internal/serialconsole/lavoltage.go deleted file mode 100644 index 8578c8e..0000000 --- a/internal/serialconsole/lavoltage.go +++ /dev/null @@ -1,75 +0,0 @@ -package serialconsole - -import ( - "context" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -// The LA bank voltage over the console (firmware console.c, "la-voltage"): -// -// la-voltage -> LA VCCIO = 3300 mV (st=1) | LA VCCIO = UNSET (st=0) -// la-voltage 1800|3300 -> LA VCCIO = 1800 mV (st=0) -// | 1.8 V needs a v3 pod; this board is ... -// | la voltage can't change while pins are in use: ... -// | usage: la-voltage <1800|3300> - -var laVCCIOLine = regexp.MustCompile(`LA VCCIO = (UNSET|\d+ mV)`) - -// laVoltageRefusals start the console's refusal lines. -var laVoltageRefusals = []string{"1.8 V needs", "la voltage ", "usage: la-voltage"} - -var errNoLAVoltageReply = errors.New("no la-voltage reply yet") - -// LAVoltage sets the LA bank voltage to mv (1800 or 3300), or only reads it when mv is 0, and -// returns the selection the pod reports afterwards in millivolts (0: not set yet). -func (c *Console) LAVoltage(ctx context.Context, mv int) (int, error) { - line := "la-voltage" - if mv != 0 { - line += " " + strconv.Itoa(mv) - } - complete := func(acc string) bool { - _, err := parseLAVoltageReply(acc) - return !errors.Is(err, errNoLAVoltageReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - got, perr := parseLAVoltageReply(out) - if perr == nil || !errors.Is(perr, errNoLAVoltageReply) { - return got, perr - } - if err != nil { - return 0, err - } - return 0, fmt.Errorf("la-voltage: no reply from the pod (got: %q)", tail([]byte(out), 200)) -} - -// parseLAVoltageReply finds the reply in raw console output; log lines interleave freely. -func parseLAVoltageReply(raw string) (int, error) { - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - if strings.Contains(ln, movedLine) { - return 0, ErrMovedToNetwork - } - if strings.Contains(ln, "unknown command") { - return 0, ErrUnknownCommand - } - if m := laVCCIOLine.FindStringSubmatch(ln); m != nil { - if m[1] == "UNSET" { - return 0, nil - } - n, _ := strconv.Atoi(strings.TrimSuffix(m[1], " mV")) - return n, nil - } - for _, p := range laVoltageRefusals { - if strings.HasPrefix(ln, p) { - return 0, &CommandError{Cmd: "la-voltage", Reason: ln} - } - } - } - return 0, errNoLAVoltageReply -} diff --git a/internal/serialconsole/lavoltage_test.go b/internal/serialconsole/lavoltage_test.go deleted file mode 100644 index c2feb2f..0000000 --- a/internal/serialconsole/lavoltage_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package serialconsole - -import ( - "bytes" - "errors" - "fmt" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// laVoltagePod answers la-voltage like the firmware's console (console.c). -type laVoltagePod struct { - mv int - v2 bool // a v2 board: no 1.8 V - inUse string // pins in use: a change is refused - old bool - moved bool // firmware 3.9.0+: la-voltage moved to the JSON API - writes []string -} - -func (p *laVoltagePod) console() *Console { - return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.writes = append(p.writes, line) - out.WriteString(line + "\r\n[net] dhcp renew\r\n") - f := strings.Fields(line) - switch { - case p.old: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case p.moved: - fmt.Fprintf(out, "%s: moved to the network API (JSON la_voltage) in firmware 3.9.0; update the benchpod CLI to 0.6.0 or later (or embeddedci to 2.12.0), which uses it over USB\r\n", f[0]) - case len(f) == 1 && p.mv == 0: - out.WriteString(" LA VCCIO = UNSET (st=0)\r\n") - case len(f) == 1: - fmt.Fprintf(out, " LA VCCIO = %d mV (st=1)\r\n", p.mv) - case p.inUse != "" && f[1] != fmt.Sprint(p.mv): - fmt.Fprintf(out, " la voltage can't change while pins are in use: %s; stop them first\r\n", p.inUse) - case f[1] == "1800" && p.v2: - out.WriteString(" 1.8 V needs a v3 pod; this board is v2 (its TPS2116 has no 1.8 V setting)\r\n") - case f[1] == "1800" || f[1] == "3300": - fmt.Sscan(f[1], &p.mv) - fmt.Fprintf(out, " LA VCCIO = %d mV (st=1)\r\n", p.mv) - default: - out.WriteString(" usage: la-voltage <1800|3300>\r\n") - } - out.WriteString("> ") - }}) -} - -func TestLAVoltageShowAndSet(t *testing.T) { - pod := &laVoltagePod{} - c := pod.console() - if mv, err := c.LAVoltage(testContext(t), 0); err != nil || mv != 0 { - t.Fatalf("unset = %d, %v", mv, err) - } - if mv, err := c.LAVoltage(testContext(t), 3300); err != nil || mv != 3300 || pod.mv != 3300 { - t.Fatalf("set = %d, %v", mv, err) - } - if mv, err := c.LAVoltage(testContext(t), 0); err != nil || mv != 3300 { - t.Fatalf("show = %d, %v", mv, err) - } - if got := strings.Join(pod.writes, "|"); got != "la-voltage|la-voltage 3300|la-voltage" { - t.Fatalf("writes = %s", got) - } -} - -func TestLAVoltageRefusals(t *testing.T) { - for _, pod := range []*laVoltagePod{ - {mv: 3300, v2: true}, - {mv: 3300, inUse: "LA3 (uart_rx), LA4 (uart_tx)"}, - } { - _, err := pod.console().LAVoltage(testContext(t), 1800) - pe, ok := tcpclient.AsPodError(err) - if !ok || pe.Cmd != "la-voltage" || pe.Reason == "" || strings.HasPrefix(pe.Reason, " ") { - t.Fatalf("err = %#v", err) - } - } - _, err := (&laVoltagePod{old: true}).console().LAVoltage(testContext(t), 0) - if !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("old firmware: %v", err) - } -} - -// Firmware 3.9.0 answers la-voltage with the moved line; firmware before it runs the command. -func TestLAVoltageAcrossFirmwareGenerations(t *testing.T) { - _, err := (&laVoltagePod{moved: true}).console().LAVoltage(testContext(t), 3300) - if !errors.Is(err, ErrMovedToNetwork) { - t.Fatalf("3.9.0 console: err = %v, want ErrMovedToNetwork", err) - } - got, err := (&laVoltagePod{}).console().LAVoltage(testContext(t), 3300) - if err != nil || got != 3300 { - t.Fatalf("older firmware: %d, %v", got, err) - } -} diff --git a/internal/serialconsole/netreset.go b/internal/serialconsole/netreset.go new file mode 100644 index 0000000..8e1b188 --- /dev/null +++ b/internal/serialconsole/netreset.go @@ -0,0 +1,40 @@ +package serialconsole + +import ( + "context" + "errors" + "strings" +) + +// ErrNoNetReset is a console without `net-reset`: firmware before 4.0. +var ErrNoNetReset = errors.New("the pod's console has no net-reset (it needs firmware 4.0: `benchpod flash-self`)") + +// NetReset runs the console's `net-reset` (firmware 4.0): the pod forgets its Wi-Fi credentials +// (its flash and the ESP32-C3's NVS, or the Wi-Fi bridge's), which turns USB networking back on, +// and puts Ethernet back to autonegotiation with a PHY reset and a new DHCP lease. It returns +// the pod's `net-reset ...` lines: first the Ethernet one, then the Wi-Fi outcome. +func (c *Console) NetReset(ctx context.Context) ([]string, error) { + done := func(acc string) bool { + return strings.Contains(acc, "net-reset wifi") || strings.Contains(acc, "net-reset error") + } + out, err := c.sendCommandUntil(ctx, "net-reset", "net-reset", "", done) + var lines []string + for _, ln := range consoleLines(out) { + ln = strings.TrimSpace(ln) + if strings.HasPrefix(ln, "net-reset ") { + lines = append(lines, ln) + } + } + if strings.Contains(strings.ToLower(out), "unknown command") { + return nil, ErrNoNetReset + } + for _, ln := range lines { + if why, ok := strings.CutPrefix(ln, "net-reset error "); ok { + return lines, &CommandError{Cmd: "net-reset", Reason: why} + } + } + if err != nil { + return lines, err + } + return lines, nil +} diff --git a/internal/serialconsole/netreset_test.go b/internal/serialconsole/netreset_test.go new file mode 100644 index 0000000..5f1f57a --- /dev/null +++ b/internal/serialconsole/netreset_test.go @@ -0,0 +1,35 @@ +package serialconsole + +import ( + "bytes" + "errors" + "reflect" + "testing" +) + +func netResetConsole(reply string) *Console { + return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { + out.WriteString(line + "\r\n") + out.WriteString("[eth] link down\r\n") + out.WriteString(reply) + out.WriteString("> ") + }}) +} + +func TestNetReset(t *testing.T) { + c := netResetConsole("net-reset eth autonegotiation, link and DHCP again\r\n" + + "net-reset wifi cleared (pod flash and the ESP32-C3's NVS)\r\n") + lines, err := c.NetReset(testContext(t)) + want := []string{"net-reset eth autonegotiation, link and DHCP again", "net-reset wifi cleared (pod flash and the ESP32-C3's NVS)"} + if err != nil || !reflect.DeepEqual(lines, want) { + t.Fatalf("lines %q, err %v", lines, err) + } + c = netResetConsole(" unknown command 'net-reset' (try 'help')\r\n") + if _, err := c.NetReset(testContext(t)); !errors.Is(err, ErrNoNetReset) { + t.Fatalf("old firmware: %v", err) + } + c = netResetConsole("net-reset error busy: a capture is running\r\n") + if _, err := c.NetReset(testContext(t)); err == nil || err.Error() != "net-reset: busy: a capture is running" { + t.Fatalf("refusal: %v", err) + } +} diff --git a/internal/serialconsole/power_test.go b/internal/serialconsole/power_test.go deleted file mode 100644 index a0a7a6d..0000000 --- a/internal/serialconsole/power_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package serialconsole - -import ( - "bytes" - "errors" - "fmt" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// powerPod answers `power` like the firmware's console (console.c). -type powerPod struct { - old bool - moved bool // firmware 3.9.0+: power moved to the JSON API - on [3]bool - writes []string -} - -func (p *powerPod) console() *Console { - return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.writes = append(p.writes, line) - out.WriteString(line + "\r\n[net] dhcp renew\r\n") - f := strings.Fields(line) - switch { - case p.moved: - fmt.Fprintf(out, "%s: moved to the network API (JSON target_power) in firmware 3.9.0; update the benchpod CLI to 0.6.0 or later (or embeddedci to 2.12.0), which uses it over USB\r\n", f[0]) - case p.old || f[0] != "power" || len(f) < 3: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case f[1] != "1" && f[1] != "2": - out.WriteString(" bad eFuse index\r\n") - default: - var e int - fmt.Sscan(f[1], &e) - p.on[e] = f[2] == "on" - state := "OFF" - if p.on[e] { - state = "ON" - } - fmt.Fprintf(out, " eFuse%d %s\r\n", e, state) - } - out.WriteString("> ") - }}) -} - -func TestTargetPowerOnOff(t *testing.T) { - pod := &powerPod{} - c := pod.console() - if err := c.TargetPower(testContext(t), 1, true); err != nil || !pod.on[1] { - t.Fatalf("on: %v (on=%v)", err, pod.on[1]) - } - if err := c.TargetPower(testContext(t), 1, false); err != nil || pod.on[1] { - t.Fatalf("off: %v (on=%v)", err, pod.on[1]) - } - if got := strings.Join(pod.writes, "|"); got != "power 1 on|power 1 off" { - t.Fatalf("writes = %s", got) - } -} - -func TestTargetPowerRefusals(t *testing.T) { - err := (&powerPod{}).console().TargetPower(testContext(t), 3, true) - if pe, ok := tcpclient.AsPodError(err); !ok || pe.Cmd != "power" || pe.Reason != "bad eFuse index" { - t.Fatalf("bad index: %#v", err) - } - // A console without the command must fail, not pass for a powered target. - err = (&powerPod{old: true}).console().TargetPower(testContext(t), 1, true) - if !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("old firmware: %v", err) - } -} - -func TestTargetPowerAcrossFirmwareGenerations(t *testing.T) { - if err := (&powerPod{moved: true}).console().TargetPower(testContext(t), 1, true); !errors.Is(err, ErrMovedToNetwork) { - t.Fatalf("3.9.0 console: err = %v, want ErrMovedToNetwork", err) - } - if err := (&powerPod{}).console().TargetPower(testContext(t), 1, true); err != nil { - t.Fatalf("older firmware: %v", err) - } -} diff --git a/internal/serialconsole/refusals_test.go b/internal/serialconsole/refusals_test.go deleted file mode 100644 index a11a0f9..0000000 --- a/internal/serialconsole/refusals_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package serialconsole - -import ( - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" -) - -// The console upload replies the CLI waits for start with a word it recognizes, and the console's -// unknown-command line still says "unknown command" (how the CLI spots old firmware). -func TestConsoleRepliesTheCLIRecognizes(t *testing.T) { - for _, r := range fwrefusals.All() { - switch r.Kind { - case "console_upload": - cmd, rest, _ := strings.Cut(r.Example, " ") - word := strings.Fields(rest)[0] - if !strings.HasPrefix(cmd, "upload-") || !uploadReplyWords[word] { - t.Errorf("%s: %q: reply word %q is not one awaitReply accepts", r.ID, r.Example, word) - } - case "console": - if !strings.Contains(r.Example, "unknown command") { - t.Errorf("%s: %q no longer says unknown command", r.ID, r.Example) - } - } - } -} diff --git a/internal/serialconsole/replies.go b/internal/serialconsole/replies.go new file mode 100644 index 0000000..1eab578 --- /dev/null +++ b/internal/serialconsole/replies.go @@ -0,0 +1,59 @@ +package serialconsole + +import ( + "strings" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" +) + +// ErrUnknownCommand is older firmware's answer to a console command it does not have. It is the +// same value as ErrPolicyUnsupported, so either name matches with errors.Is. +var ErrUnknownCommand = ErrPolicyUnsupported + +// CommandError is the pod refusing a console command (" error "). It is the CLI's one +// refusal type, tcpclient.PodError, with Cmd set. +type CommandError = tcpclient.PodError + +// consoleLines splits raw console output into trimmed lines, dropping prompts and backspaces. +func consoleLines(raw string) []string { + s := strings.ReplaceAll(raw, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + var lines []string + for _, ln := range strings.Split(s, "\n") { + ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) + if ln != "" { + lines = append(lines, ln) + } + } + return lines +} + +// lastReply returns what follows " " on the last line that starts with it, skipping the +// first copy of the echoed command line. +func lastReply(raw, word, line string) (string, bool) { + echoSeen := false + var rest string + found := false + for _, ln := range consoleLines(raw) { + if !echoSeen && ln == line { + echoSeen = true + continue + } + if strings.HasPrefix(ln, word+" ") { + rest, found = strings.TrimSpace(ln[len(word)+1:]), true + } + } + return rest, found && rest != "" +} + +// replyError reports whether a reply is "error ", and the why. +func replyError(rest string) (string, bool) { + if rest != "error" && !strings.HasPrefix(rest, "error ") { + return "", false + } + why := strings.TrimSpace(strings.TrimPrefix(rest, "error")) + if why == "" { + why = "refused" + } + return why, true +} diff --git a/internal/serialconsole/serialconsole.go b/internal/serialconsole/serialconsole.go index 22b63de..c0a708b 100644 --- a/internal/serialconsole/serialconsole.go +++ b/internal/serialconsole/serialconsole.go @@ -20,7 +20,6 @@ import ( "path/filepath" "sort" "strings" - "sync" "time" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" @@ -90,11 +89,6 @@ const perReadTimeout = 250 * time.Millisecond // exactly this; any "ERROR:"/"usage:" line before it is a handshake failure. const dapReadySentinel = "dap ready" -// dapFlushDelay gives the final leave frame time to reach the firmware over USB -// before the port is closed, so the probe is disarmed promptly rather than only -// by the firmware's 60s inactivity watchdog. -const dapFlushDelay = 50 * time.Millisecond - // errPortVanished is returned by sendCommand when the port reaches EOF before a // prompt. For most commands that is a failure; for Bootsel it is the expected // success signal (the device reboots into the UF2 bootloader and the CDC-ACM @@ -553,55 +547,8 @@ func (c *Console) sendCommandWait(ctx context.Context, line, display, secret str } } -// TargetPower enables (on) or disables a target power eFuse over the console -// (firmware console.c: `power <1|2> `, which answers "eFuse1 ON", -// "eFuse1 OFF" or "bad eFuse index"). efuse is 1 (internal 5V) or 2 (external). -// Anything but the matching eFuse line is reported as an error, so a console -// that does not know the command can no longer pass for a powered target. -func (c *Console) TargetPower(ctx context.Context, efuse int, on bool) error { - state, want := "off", "OFF" - if on { - state, want = "on", "ON" - } - line := fmt.Sprintf("power %d %s", efuse, state) - complete := func(acc string) bool { - return !errors.Is(parsePowerReply(acc, efuse, want), errNoPowerReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - perr := parsePowerReply(out, efuse, want) - if !errors.Is(perr, errNoPowerReply) { - return perr - } - if err != nil { - return err - } - return fmt.Errorf("power: no reply from the pod (got: %q)", tail([]byte(out), 200)) -} - var errNoPowerReply = errors.New("no power reply yet") -// parsePowerReply finds the `power` reply in raw console output; log lines -// interleave freely. -func parsePowerReply(raw string, efuse int, want string) error { - ok := fmt.Sprintf("eFuse%d %s", efuse, want) - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - switch { - case strings.Contains(ln, movedLine): - return ErrMovedToNetwork - case strings.Contains(ln, "unknown command"): - return ErrUnknownCommand - case ln == ok: - return nil - case strings.HasPrefix(ln, "bad eFuse"), strings.HasPrefix(ln, "ERROR:"): - return &CommandError{Cmd: "power", Reason: ln} - } - } - return errNoPowerReply -} - // Status runs the firmware's `status` console command and returns its output as // presentable text (the console prints human-readable lines, not JSON). The // echoed command and the trailing prompt are stripped; interleaved async log @@ -679,70 +626,6 @@ func (c *Console) Dfu(ctx context.Context) error { return errors.New("device did not acknowledge dfu (RP2350 pods use `bootsel` instead)") } -// DAPStart enters the firmware's length-framed CMSIS-DAP probe mode over the -// console. It sends `dap-start `, then reads console -// lines until the firmware prints the `dap ready` sentinel; any `ERROR:`/`usage:` -// line before it is a handshake failure. On success the port is switched to -// blocking reads and an io.ReadWriteCloser carrying the raw framed DAP stream is -// returned — ready to hand to openocd.BridgeDAP. Its Close sends a zero-length -// frame to disarm the probe and return the console to its prompt, mirroring how -// closing the TCP connection returns the pod to a safe state. The firmware's 60s -// inactivity watchdog is the backstop if Close never runs. -// -// swclk/swdio are LA pin numbers (1-14); the caller is responsible for -// parsing/validating them (see parseLAPin in the CLI). Target reset is not a -// parameter: since pod rev3 nRESET is the pod's own pin on J1 pin 22, driven by -// the firmware behind CMSIS-DAP SWJ_PINS. -// -// If the firmware never reports "dap ready" before ctx expires (or emits an -// error line), no connection is returned and the error carries the full console -// transcript captured during the handshake, so the caller can show what the pod -// actually said instead of launching OpenOCD against a link that isn't armed. -func (c *Console) DAPStart(ctx context.Context, swclk, swdio int) (io.ReadWriteCloser, error) { - cmd := fmt.Sprintf("dap-start %d %d", swclk, swdio) - if err := c.writeLine(cmd); err != nil { - return nil, fmt.Errorf("write dap-start: %w", err) - } - if rt, ok := c.rw.(readTimeoutSetter); ok { - _ = rt.SetReadTimeout(perReadTimeout) - } - - // Accumulate every line so a handshake failure can report the firmware's - // actual output rather than just the last partial read. - var transcript strings.Builder - record := func(line string) { - transcript.WriteString(line) - transcript.WriteByte('\n') - } - - for { - line, err := c.readLine(ctx) - if err != nil { - if line != "" { - record(line) - } - return nil, fmt.Errorf("dap-start: pod never reported %q (%w)%s", - dapReadySentinel, err, transcriptSuffix(transcript.String())) - } - record(line) - trimmed := strings.TrimSpace(line) - switch { - case trimmed == dapReadySentinel: - // Raw DAP mode is open for the whole flash session, which can outlast - // any per-read timeout — switch to blocking reads so the bridge's - // pumps block until data/close rather than spinning. - if rt, ok := c.rw.(readTimeoutSetter); ok { - _ = rt.SetReadTimeout(serial.NoTimeout) - } - return &dapConn{rw: c.rw}, nil - case strings.HasPrefix(trimmed, "ERROR:"), strings.HasPrefix(trimmed, "usage:"): - return nil, fmt.Errorf("dap-start rejected by firmware: %s%s", - trimmed, transcriptSuffix(transcript.String())) - } - // Otherwise: the command echo or an async log line — keep reading. - } -} - // transcriptSuffix formats captured console output for a handshake error, // returning "" when there is nothing to show. func transcriptSuffix(t string) string { @@ -782,86 +665,6 @@ func (c *Console) readLine(ctx context.Context) (string, error) { } } -// dapConn is the raw framed CMSIS-DAP stream returned by DAPStart. Read/Write -// pass straight through to the serial port; Close (idempotent) sends a -// zero-length frame to disarm the probe, then closes the port. It deliberately -// does NOT read after the leave frame: openocd.BridgeDAP closes this connection -// while its own pump goroutine is still reading the same port, so a concurrent -// read here would race it. Closing the port unblocks that goroutine, and the -// leave frame (with the 60s watchdog as a backstop) is enough to leave the -// firmware in a safe state. -type dapConn struct { - rw io.ReadWriteCloser - closeOnce sync.Once - closeErr error -} - -func (s *dapConn) Read(p []byte) (int, error) { return s.rw.Read(p) } -func (s *dapConn) Write(p []byte) (int, error) { return s.rw.Write(p) } - -func (s *dapConn) Close() error { - s.closeOnce.Do(func() { - if _, err := s.rw.Write([]byte{0x00, 0x00}); err == nil { - // Let the zero-length leave frame flush over USB before dropping the port. - time.Sleep(dapFlushDelay) - } - s.closeErr = s.rw.Close() - }) - return s.closeErr -} - -// quoteArg double-quotes an argument for the firmware shell. Embedded double -// quotes are not currently supported by the firmware parser, so we reject them -// with a clear error rather than guess at an escaping scheme. -func quoteArg(s string) (string, error) { - if strings.Contains(s, `"`) { - return "", errors.New(`value may not contain a double-quote (") character`) - } - return `"` + s + `"`, nil -} - -// maskPassword replaces occurrences of the cleartext password in captured -// output with "***" so it is never logged. No-op for empty passwords. -func maskPassword(out, password string) string { - if password == "" { - return out - } - return strings.ReplaceAll(out, password, "***") -} - -// parseIPAfter returns the value of an "ip=" token appearing after the -// given marker in s, or "" if none is found. -func parseIPAfter(s, marker string) string { - i := strings.Index(s, marker) - if i < 0 { - return "" - } - rest := s[i+len(marker):] - j := strings.Index(rest, "ip=") - if j < 0 { - return "" - } - return firstToken(rest[j+len("ip="):]) -} - -// fieldValue scans s line-by-line for a "