diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index 07036a5..34c7d09 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -6,8 +6,13 @@ agent to load the board's own profile by name and shows one consistent example, the process-node bench's `process-node-stm32` profile (UART RX on LA3, I2C SCL on LA1 and SDA on LA2, the alarm on LA5). It used to mix that bench's I2C pins with the default pins' UART RX (LA5). -- `set_wiring`'s `profile` description lists the `pulls` key (the LA channels whose pull - resistor `power_on` switches on). +- `set_wiring`'s `profile` description lists the `pulls` key: a map of LA channel to `up` / + `down`, or a list of channels that pull their own direction. +- `set_pull(las, pull="up" | "down" | "off")`: pull by direction; the pod picks the resistor. + `enabled` still works (true = each channel's own direction). Channels 1-14; a direction a + channel can't pull is refused (BP0024, BP0023 without a resistor). +- `pull_status` lists all 14 channels with `state` (up, down, off) and `supported` directions; + `la_pins` (and the gpio tools' pins) add `pull_dirs`. ## 3.0.2 diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index e00bb46..ae92aa5 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -239,7 +239,7 @@ description, ranges and enums, so an agent sees more than this table. ### I2C master The pod as an I2C master on two LA pins (gateware v55+), to read and write registers of a chip on -the DUT's board. The bus needs pull-ups: the pod's on LA1-LA6 (`set_pull` first, LA voltage 3.3), or +the DUT's board. The bus needs pull-ups: the pod's on LA1-LA6 (`set_pull(pull="up")` first, LA voltage 3.3), or the board's with `pullups="external"`. | Tool | Purpose | Parameters | @@ -293,8 +293,8 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI' | Tool | Purpose | Parameters | | --- | --- | --- | -| `set_pull` | Engage or release the bias resistors: LA1-LA6 pull up, LA7/LA8 pull down. | **`las`**, **`enabled`** | -| `pull_status` | State, direction and value of the bias resistor on LA1-LA8. | none | +| `set_pull` | Pull LA channels `up` or `down`, or switch their resistor `off`; the pod picks the value. Today LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none; another direction is refused (BP0024, BP0023). `enabled` is the older on/off form. | **`las`**, `pull`, `enabled` | +| `pull_status` | Every LA channel's pull resistor: state (`up`, `down` or `off`), the directions it supports and its value. | none | | `lan_tls` | The pod's LAN API over TLS (firmware 3.9.3+): port 8443, the HTTPS-only setting and the certificate's sha256 (what clients pin). Turning HTTPS-only off and regenerating need a TLS, USB or cloud connection. | `https_only`, `regenerate` | | `usb_network` | Read the pod's USB network setting (firmware 3.9.0+), or turn the adapter off over the USB link. Only the device changes it; turning it back on is `benchpod usb-network on` on the USB console. | `set=off` | @@ -445,7 +445,7 @@ capture tools' summaries, `la_timing` and `decode_la` instead. the user for the board's (1.8 or 3.3), set it in the profile (set_wiring with la_mv 1800 or 3300, then save_wiring) or call set_la_voltage` and `PinConflictError: uart_proxy_start: pin conflict: LA4 is in use by gpio; release it with gpio_release(la=[4])`. The other pin owners point to `uart_close` and - `sensor_stop`; a pull conflict to `set_pull(las=[7], enabled=false)`. + `sensor_stop`; a pull conflict to `set_pull(las=[7], pull="off")`. - **Capabilities.** `connect` and `status` report what the pod can do as flags, so an agent can check before it calls a tool: for example `la_pins`, `capture_trigger`, `power_profile`, `nrst_pin`, `can`, `calibrate`, `cal_dmm`, `current_out`, `pod_current`, `sensors` and `analog` (false on the diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py index 29a80f1..c0c592d 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/guide.py @@ -23,9 +23,9 @@ Typical flows: - Flash and boot: flash(file) then power_cycle_and_capture(until_regex) — with a wiring profile that is all; otherwise pass swclk, swdio, target, nreset and rx, tx. - SPI flash (a 25-series chip on four LA pins, wiring spi_sclk/spi_mosi/spi_miso/spi_cs): spi_flash_info to see it answers, then spi_flash_program(file, addr); hold_reset=true keeps the DUT off the bus. spi_transfer talks to any other SPI device. -- I2C master (gateware v55+): set_pull([sda, scl], true), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions (firmware 3.10.4+), so this is on by default. +- I2C master (gateware v55+): set_pull([sda, scl], pull="up"), i2c_open, then i2c_transfer(addr, write_hex, read) or i2c_scan; i2c_close. capture_la(send={...}) runs one I2C, SPI or gpio transaction right after the capture arms and triggers on it. la_dir marks DUT outputs so the pod never drives against them; connect and set_wiring send the wiring profile's directions (firmware 3.10.4+), so this is on by default. - Interactive console: uart_open, power_on, uart_read(until_regex), uart_write, uart_close. -- Emulate sensors (I2C, SPI, UART, analog; firmware with the 'sensors' capability): the pod plays a sensor from a definition. sensor_library lists ready ones (bme280, bmp280, sht4x, mpu6050, gps_nmea, ...) and sensor_show gives one's YAML and params. For I2C, set_pull([sda, scl], true) on LA1-LA6 (LA7/LA8 pull DOWN) first. sensor_start(definition=, pins={sda, scl} | {tx} | ...), then sensor_set(instance, values) changes readings, sensor_stimulus_load + sensor_stimulus_start play values over time, sensor_fault injects a fault, sensor_status shows bus activity, sensor_capture waits for the DUT's next transaction on an I2C sensor's bus and decodes it, sensor_stop ends it. A part the library lacks: read sensor_format, write a definition from the datasheet, check it with sensor_validate, then sensor_start it. A GPS module is gps_nmea on pins={tx: }. +- Emulate sensors (I2C, SPI, UART, analog; firmware with the 'sensors' capability): the pod plays a sensor from a definition. sensor_library lists ready ones (bme280, bmp280, sht4x, mpu6050, gps_nmea, ...) and sensor_show gives one's YAML and params. For I2C, set_pull([sda, scl], pull="up") on LA1-LA6 (LA7/LA8 pull down only) first. sensor_start(definition=, pins={sda, scl} | {tx} | ...), then sensor_set(instance, values) changes readings, sensor_stimulus_load + sensor_stimulus_start play values over time, sensor_fault injects a fault, sensor_status shows bus activity, sensor_capture waits for the DUT's next transaction on an I2C sensor's bus and decodes it, sensor_stop ends it. A part the library lacks: read sensor_format, write a definition from the datasheet, check it with sensor_validate, then sensor_start it. A GPS module is gps_nmea on pins={tx: }. - Analog: dac_output (DC), generate (sine/square/sawtooth) and replay drive the DAC and route its path; adc_read gives one calibrated value, capture_adc a waveform summary; dac_stop ends any DAC output. - 4-20 mA input: adc_read(source='current_in') reads terminal J8 and returns current in amps (0.004 to 0.020 for a live loop) next to the voltage across the 249 ohm sense resistor. calibration shows whether the pod has calibrated its ADC offset there. If not, analog readings can be off by up to about 50 mV: ask the user to disconnect J8, then calibrate (once per pod, stored on the pod; on firmware 3.9.3+ it corrects every ADC source). - 4-20 mA output: current_out(current) holds a loop current on terminal J9, in amps (0.012 is 12 mA), and returns the current actually held and the range. It needs an external floating loop supply on J9 and cannot go below about 4 mA or above about 20 mA. It shares the DAC with the voltage outputs and switches them off; dac_stop does not return the loop to 4 mA, current_out(0.004) does. The loop must float: nothing in it may touch pod ground, also not through a target that shares a ground with the pod (SWD, UART). Ask the user how J9 is wired first, and never suggest wiring J9 straight into J8. generate, replay and replay_waveform take dac_path='current_out' to play a waveform as a current (levels in amps); capture_adc(source='current_in') summarises the loop current in amps. @@ -63,9 +63,10 @@ ALARM (DUT output) LA5 signal "ALARM" Target power internal 5 V (efuse 1) efuse=1 (external: efuse=2) -Bias resistors (3V3-referenced, so unavailable while the LA bank is at 1.8 V): - LA1, LA2 4.7k pull-up LA3, LA4 2.2k pull-up LA5, LA6 10k pull-up - LA7, LA8 10k pull-DOWN LA9-LA14 none +Pull resistors: set_pull(las, pull="up"|"down"|"off"); the pod picks the value. Today's boards +(pull_status shows each channel's supported directions; 3V3-referenced, so off at a 1.8 V LA bank): + LA1, LA2 4.7k up LA3, LA4 2.2k up LA5, LA6 10k up + LA7, LA8 10k down only LA9-LA14 none LA I/O bank: 1.8 V or 3.3 V, matching the DUT's I/O voltage: the wiring profile's la_mv (set_la_voltage overrides it for a session). diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py index 3dc3709..29eab2c 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/models.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/models.py @@ -217,7 +217,10 @@ class LaPinResult(BaseModel): "swd_dio, i2c_sda, i2c_scl, step, step_dir, spi_*, sensor_*, or i2cm_sda/i2cm_scl (i2c_open).")) gpio: Optional[str] = Field(None, description="GPIO mode when function is gpio: input, output or open_drain.") level: Optional[int] = Field(None, description="Commanded level of a GPIO output / open-drain channel.") - pull: Optional[str] = Field(None, description="Bias direction: up, down, or null on LA9-LA14.") + pull: Optional[str] = Field(None, description=( + "The way its pull resistor pulls when on: up or down; null without one (LA9-LA14 today).")) + pull_dirs: Optional[List[str]] = Field(None, description=( + "Every direction set_pull can pull it: [up], [down], [up, down] or [].")) pull_ohms: Optional[str] = None pull_on: bool = False in_use: bool = Field(description="A function other than none owns the channel.") @@ -532,8 +535,13 @@ class I2cRegsResult(BaseModel): class PullChannel(BaseModel): la: int + #: What the channel does now: up, down or off. + state: str + #: The directions it can pull (empty: no pull resistor). + supported: List[str] enabled: bool - direction: str + #: The way it pulls when on; None without a resistor. + direction: Optional[str] ohms: str available: bool diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index 137310e..5372c1f 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -94,7 +94,7 @@ "LA channel 1-14, or a name from the wiring profile — a signal ('READY') or a role " "('uart_rx', 'i2c_sda', 'swd_swclk'). Call `wiring` to see the names. The gpio_* tools also " "take expander pins ('EXT1') once one is attached (expansion)."))] -BiasPin = Annotated[int, Field(ge=1, le=8)] +PullPin = Annotated[int, Field(ge=1, le=14)] EfuseRail = Annotated[Literal[1, 2], Field(description="Target-power rail: internal 5 V (efuse 1) or external (efuse 2).")] WiredEfuse = Annotated[Optional[Literal[1, 2]], Field(description=( "Target-power rail: internal 5 V (efuse 1) or external (efuse 2). Omit for the wiring profile's rail."))] @@ -192,9 +192,10 @@ def isa(name: str) -> bool: (re.compile(r"send i2c_stop first"), "call i2c_close first"), (re.compile(r"send i2c_start first"), "call i2c_open first"), (re.compile(r"i2c_start again"), "call i2c_open again"), - (re.compile(r'\{"cmd":"la","la":(\d+),"pullup":"on"\}'), r"set_pull(las=[\1], enabled=true)"), + (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup":"on|pull":"up)"\}'), r'set_pull(las=[\1], pull="up")'), + (re.compile(r'\{"cmd":"la","la":(\d+),"pull":"down"\}'), r'set_pull(las=[\1], pull="down")'), (re.compile(r'pass "pullups":"external"'), 'pass pullups="external"'), - (re.compile(r'\{"cmd":"la","la":(\d+),"pullup":"off"\}'), r"set_pull(las=[\1], enabled=false)"), + (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup|pull)":"off"\}'), r'set_pull(las=[\1], pull="off")'), (re.compile(r'\{"cmd":"gpio","la":(\d+),"mode":"output"\}'), r'gpio_mode(la=[\1], mode="output")'), (re.compile(r'\{"cmd":"fpga_image","image":0\}'), 'fpga_image(image="loop")'), (re.compile(r'\{"cmd":"dac_loop_input"\}'), "loop_input"), @@ -573,8 +574,9 @@ async def set_wiring( profile: Annotated[Dict[str, Any], Field(description=( "The profile as a JSON object (schema version 2): la_mv, efuse, uart_rx/uart_tx/uart_baud, " "i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals " - "[{name, la, direction, active_low, description}], pulls (the LA channels whose pull resistor " - "power_on switches on, e.g. [1, 2]; LA1-LA8 have one, the others it switches off; left out: " + "[{name, la, direction, active_low, description}], pulls (the pull resistors power_on switches " + "on, the others off: {\"1\": \"up\", \"2\": \"up\", \"8\": \"down\"}, or a list of channels " + "that pull their own way, e.g. [1, 2]; today LA1-LA6 pull up, LA7/LA8 down; left out: " "power_on leaves the pulls as they are). What it leaves out is undefined (not " "wired); a pin set to null is not wired. {\"version\": 1} objects fill in the old default pins."))], save: Annotated[bool, Field(description=( @@ -956,7 +958,7 @@ async def i2c_open( scl: Annotated[Optional[LaRef], Field(description="SCL channel; omit for the profile's i2c_scl.")] = None, hz: Annotated[int, Field(ge=10_000, le=1_000_000, description="SCL rate.")] = 100_000, pullups: Annotated[Literal["pod", "external"], Field(description=( - "pod: LA1-LA6 with the pod's pull-ups on (set_pull first, LA voltage 3.3); " + "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today, LA voltage 3.3); " "external: the board has its own."))] = "pod", ) -> m.I2cSessionResult: """Make the pod an I2C master on two LA pins (gateware v55+), replacing any open session. @@ -1415,7 +1417,7 @@ async def sensor_library(version: LibraryVersion = None) -> m.SensorLibraryResul """The sensor library: ready definitions the pod can emulate (name, kind, label) and the version in use. Sensor flow: sensor_library -> sensor_show(name) for its params -> set_la_voltage and, for I2C, - set_pull on SDA/SCL -> sensor_start(definition=name, pins) -> sensor_set / sensor_fault / + set_pull(pull="up") on SDA/SCL -> sensor_start(definition=name, pins) -> sensor_set / sensor_fault / sensor_stimulus_load + sensor_stimulus_start -> sensor_status, sensor_regs -> sensor_stop. No library entry for the part? Write a definition from its datasheet (sensor_format) and pass the YAML to sensor_validate, then sensor_start. Needs no pod. @@ -1490,7 +1492,7 @@ async def sensor_start( ) -> m.SensorStarted: """Make the pod play a sensor for the DUT: upload the definition (library name or your own YAML/JSON) and start it on pins. - Set the LA voltage first, and the pull-ups for I2C (set_pull on sda and scl, LA1-LA6). + Set the LA voltage first, and the pull-ups for I2C (set_pull([sda, scl], pull="up"), LA1-LA6). Starting an instance name that runs replaces it. Up to 4 I2C sensors (several may share one bus at different addresses), 1 SPI, 1 UART and 2 analog sensors (one per output) run at once. I2C/SPI/UART sensors load the pod's emulation FPGA image if another runs (image_loaded in the @@ -1607,25 +1609,62 @@ def op() -> m.I2cCaptureResult: return await _call(op) -# -- bias resistors --------------------------------------------------------------------- +# -- pull resistors --------------------------------------------------------------------- def _pull(state: Any) -> m.PullChannel: - return m.PullChannel(la=state.la, enabled=state.enabled, direction=state.direction, + # embeddedci before 3.0.3 has no state / supported on PullState + direction = state.direction + supported = getattr(state, "supported", None) + if supported is None: + supported = (direction,) if direction in ("up", "down") else () + return m.PullChannel(la=state.la, state=getattr(state, "state", direction if state.enabled else "off"), + supported=list(supported), enabled=state.enabled, direction=direction, ohms=state.ohms, available=state.available) +def _sdk_pulls_by_direction(pod: Any) -> bool: + """The SDK takes set_pull(la, "up" | "down" | "off") (embeddedci 3.0.3+).""" + return "pull" in inspect.signature(type(pod).set_pull).parameters + + +def _set_pull_old_sdk(pod: Any, la: int, want: Any) -> Any: + """set_pull on embeddedci before 3.0.3, which only knows on/off: a direction is checked here, + so "up" never engages LA7's pull-down.""" + from embeddedci.benchpod.constants import PULLDOWN_CHANNELS, PULLUP_CHANNELS + + if want in ("up", "down"): + ok = PULLUP_CHANNELS if want == "up" else PULLDOWN_CHANNELS + if la not in ok: + raise ValueError(f"LA{la} can't pull {want} on this board; upgrade embeddedci for the full " + "message (pull_status shows each channel's direction)") + want = True + elif want == "off": + want = False + return pod.set_pull(la, bool(want)) + + @mcp.tool(annotations=_ann("Set pull resistors", idempotent=True)) async def set_pull( - las: Annotated[List[BiasPin], Field(min_length=1, max_length=8, description="LA channels (1-8).")], - enabled: bool, + las: Annotated[List[PullPin], Field(min_length=1, max_length=14, description="LA channels (1-14).")], + pull: Annotated[Optional[Literal["up", "down", "off"]], Field(description=( + "The direction: up, down or off. The pod picks the resistor (ohms in the result). A channel " + "pulls only the ways its resistor allows (pull_status: supported); today LA1-LA6 pull up, " + "LA7/LA8 down, LA9-LA14 have none, and the pod refuses the rest (BP0024, BP0023)."))] = None, + enabled: Annotated[Optional[bool], Field(description=( + "Older form, use pull: true engages each channel's own direction, false is off."))] = None, ) -> m.PullStatusResult: - """Engage or release the fixed bias resistors: LA1-LA6 pull UP (I2C lines), LA7/LA8 pull DOWN. + """Pull LA channels up or down, or switch their pull resistor off. For an I2C bus pull SDA and + SCL up. The resistors are 3V3-referenced, so the pod refuses to engage them with the LA bank at + 1.8 V.""" + if pull is None and enabled is None: + raise ValueError('set_pull needs pull: "up", "down" or "off"') + want: Any = pull if pull is not None else bool(enabled) - The resistors are 3V3-referenced, so the pod refuses to engage them with the LA bank at 1.8 V. - """ def op() -> m.PullStatusResult: pod = SESSION.require() - return m.PullStatusResult(channels=[_pull(pod.set_pull(la, enabled)) for la in las]) + if _sdk_pulls_by_direction(pod): + return m.PullStatusResult(channels=[_pull(pod.set_pull(la, want)) for la in las]) + return m.PullStatusResult(channels=[_pull(_set_pull_old_sdk(pod, la, want)) for la in las]) return await _call(op) @@ -1683,10 +1722,12 @@ def op() -> m.LanTlsResult: @mcp.tool(annotations=_ann("Pull resistor status", read_only=True)) async def pull_status() -> m.PullStatusResult: - """State, direction and value of the bias resistor on LA1-LA8.""" + """Every LA channel's pull resistor: state (up, down or off), the directions it supports + (empty without a resistor) and its value.""" def op() -> m.PullStatusResult: pod = SESSION.require() - return m.PullStatusResult(channels=[_pull(pod.pull_state(la)) for la in range(1, 9)]) + las = range(1, 15) if _sdk_pulls_by_direction(pod) else range(1, 9) + return m.PullStatusResult(channels=[_pull(pod.pull_state(la)) for la in las]) return await _call(op) diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py index 9bb22d9..3519b6a 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/summaries.py @@ -12,6 +12,11 @@ from embeddedci.benchpod import Capture, LaCapture, PowerProfile, Trigger, Wiring from embeddedci.benchpod.constants import PULL_OHMS, PULLDOWN_CHANNELS +try: # embeddedci 3.0.3+: the board's pull table (directions per channel) + from embeddedci.benchpod.constants import PULL_TABLE +except ImportError: # pragma: no cover - the mcp-min-sdk job + PULL_TABLE = {} + from . import models as m _V_DIGITS = 5 @@ -113,6 +118,9 @@ def send_summary(r: Any) -> Optional[m.SendResultModel]: # -- wiring, pins and power ------------------------------------------------------------ def _bias(la: int) -> Optional[str]: + hw = PULL_TABLE.get(la) + if hw: + return f"{hw.ohms} {'/'.join(hw.dirs)}" ohms = PULL_OHMS.get(la) return None if not ohms else f"{ohms} {'down' if la in PULLDOWN_CHANNELS else 'up'}" @@ -139,6 +147,8 @@ def pin_state(pin: Any) -> m.LaPinResult: """One :class:`~embeddedci.benchpod.LaPinState` as a tool result row.""" return m.LaPinResult(la=pin.la, function=pin.function, gpio=pin.gpio, level=pin.level, pull=pin.pull, pull_ohms=pin.pull_ohms, pull_on=pin.pull_on, + pull_dirs=(list(pin.pull_dirs) if hasattr(pin, "pull_dirs") + else ([pin.pull] if pin.pull else [])), in_use=pin.in_use, dir=pin.dir, warnings=pin.warnings or None) diff --git a/packages/embeddedci-mcp/tests/test_bus_master_tools.py b/packages/embeddedci-mcp/tests/test_bus_master_tools.py index 3a7b1ca..e24a32c 100644 --- a/packages/embeddedci-mcp/tests/test_bus_master_tools.py +++ b/packages/embeddedci-mcp/tests/test_bus_master_tools.py @@ -45,7 +45,7 @@ def test_i2c_refusals_name_the_tools(): assert _mcp_refusal_text("no I2C session: send i2c_start first").endswith("call i2c_open first") text = _mcp_refusal_text('I2C needs pull-ups: switch on LA1\'s with {"cmd":"la","la":1,"pullup":"on"}, ' 'or pass "pullups":"external"') - assert "set_pull(las=[1], enabled=true)" in text and 'pullups="external"' in text + assert 'set_pull(las=[1], pull="up")' in text and 'pullups="external"' in text def test_la_dir_sets_lists_and_follows_the_wiring(connected): diff --git a/packages/embeddedci-mcp/tests/test_e2e_mcp.py b/packages/embeddedci-mcp/tests/test_e2e_mcp.py index da39e40..cce45ff 100644 --- a/packages/embeddedci-mcp/tests/test_e2e_mcp.py +++ b/packages/embeddedci-mcp/tests/test_e2e_mcp.py @@ -89,7 +89,8 @@ def test_status_and_typed_state(connected): assert [w for w in connected["warnings"] if "default USB power" not in w] == [] assert "internal" in call("power_status") channels = call("pull_status")["channels"] - assert [c["direction"] for c in channels] == ["up"] * 6 + ["down"] * 2 + assert [c["direction"] for c in channels] == ["up"] * 6 + ["down"] * 2 + [None] * 6 + assert [c["supported"] for c in channels] == [["up"]] * 6 + [["down"]] * 2 + [[]] * 6 def test_analog_round_trip(connected): diff --git a/packages/embeddedci-mcp/tests/test_gpio_tools.py b/packages/embeddedci-mcp/tests/test_gpio_tools.py index 432bd05..9fc721e 100644 --- a/packages/embeddedci-mcp/tests/test_gpio_tools.py +++ b/packages/embeddedci-mcp/tests/test_gpio_tools.py @@ -20,7 +20,7 @@ def test_la_pins_reports_every_channel_with_levels(connected): result = call("la_pins") assert [p["la"] for p in result["pins"]] == list(range(1, 15)) assert _pin(result, 1) == {"la": 1, "function": "none", "gpio": None, "level": None, - "pull": "up", "pull_ohms": "4.7k", "pull_on": False, "in_use": False, + "pull": "up", "pull_dirs": ["up"], "pull_ohms": "4.7k", "pull_on": False, "in_use": False, "dir": None, "warnings": None} assert _pin(result, 7)["pull"] == "down" and _pin(result, 12)["pull"] is None assert _pin(result, 14)["pull"] is None @@ -53,7 +53,7 @@ def test_gpio_mode_claims_channels_in_one_command(connected): result = call("gpio_mode", la=[3, 4], mode="output", level=1) assert [p["la"] for p in result["pins"]] == [3, 4] assert result["pins"][0] == {"la": 3, "function": "gpio", "gpio": "output", "level": 1, - "pull": "up", "pull_ohms": "2.2k", "pull_on": False, "in_use": True, + "pull": "up", "pull_dirs": ["up"], "pull_ohms": "2.2k", "pull_on": False, "in_use": True, "dir": None, "warnings": None} assert connected.requests[-1] == {"cmd": "gpio", "la": [3, 4], "mode": "output", "level": 1} diff --git a/packages/embeddedci-mcp/tests/test_refusals.py b/packages/embeddedci-mcp/tests/test_refusals.py index 6e53d4f..f338f4d 100644 --- a/packages/embeddedci-mcp/tests/test_refusals.py +++ b/packages/embeddedci-mcp/tests/test_refusals.py @@ -122,7 +122,7 @@ def test_pull_conflict_names_set_pull(connected): with pytest.raises(ToolError) as info: call("gpio_pulse", la=3, width=0.001, count=5) assert "PullConflictError: la: pull conflict: LA7" in str(info.value) - assert str(info.value).endswith("disable it with set_pull(las=[7], enabled=false) or use another channel") + assert str(info.value).endswith('disable it with set_pull(las=[7], pull="off") or use another channel') def test_efuse_rails_are_named_the_same_everywhere(): diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index 207600a..1b3f96e 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -579,12 +579,28 @@ def test_sensor_tools_refuse_old_firmware(connected): def test_pulls(connected): - res = call("set_pull", las=[7], enabled=True) - assert res["channels"][0]["direction"] == "down" + res = call("set_pull", las=[7], enabled=True) # the older form still works + assert res["channels"][0]["direction"] == "down" and res["channels"][0]["state"] == "down" + res = call("set_pull", las=[1, 2], pull="up") + assert [c["state"] for c in res["channels"]] == ["up", "up"] + assert res["channels"][0]["supported"] == ["up"] and res["channels"][0]["ohms"] == "4.7k" + assert call("set_pull", las=[7], pull="off")["channels"][0]["state"] == "off" status = call("pull_status") - assert [c["la"] for c in status["channels"]] == list(range(1, 9)) - with pytest.raises(ToolError): - call("set_pull", las=[9], enabled=True) + new_sdk = "pull" in inspect.signature(BenchPod.set_pull).parameters + if not new_sdk: # embeddedci before 3.0.3 (the mcp-min-sdk job): LA1-LA8, checked here + assert [c["la"] for c in status["channels"]] == list(range(1, 9)) + with pytest.raises(ToolError, match="LA7 can't pull up"): + call("set_pull", las=[7], pull="up") + return + assert [c["la"] for c in status["channels"]] == list(range(1, 15)) + assert status["channels"][8] == {"la": 9, "state": "off", "supported": [], "enabled": False, + "direction": None, "ohms": "", "available": True} + with pytest.raises(ToolError, match="BP0023"): + call("set_pull", las=[9], pull="up") + with pytest.raises(ToolError, match="LA7 supports pull-down only on this board"): + call("set_pull", las=[7], pull="up") + with pytest.raises(ToolError, match="needs pull"): + call("set_pull", las=[1]) # -- analog + captures ----------------------------------------------------------------- diff --git a/packages/embeddedci-mcp/tests/tools_surface.json b/packages/embeddedci-mcp/tests/tools_surface.json index 0b42ea4..060daf5 100644 --- a/packages/embeddedci-mcp/tests/tools_surface.json +++ b/packages/embeddedci-mcp/tests/tools_surface.json @@ -2854,7 +2854,7 @@ }, "pullups": { "default": "pod", - "description": "pod: LA1-LA6 with the pod's pull-ups on (set_pull first, LA voltage 3.3); external: the board has its own.", + "description": "pod: channels with the pod's pull-up on (set_pull(pull=\"up\") first, LA1-LA6 today, LA voltage 3.3); external: the board has its own.", "enum": [ "pod", "external" @@ -4898,25 +4898,51 @@ "input": { "properties": { "enabled": { - "title": "Enabled", - "type": "boolean" + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Older form, use pull: true engages each channel's own direction, false is off.", + "title": "Enabled" }, "las": { - "description": "LA channels (1-8).", + "description": "LA channels (1-14).", "items": { - "maximum": 8, + "maximum": 14, "minimum": 1, "type": "integer" }, - "maxItems": 8, + "maxItems": 14, "minItems": 1, "title": "Las", "type": "array" + }, + "pull": { + "anyOf": [ + { + "enum": [ + "up", + "down", + "off" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The direction: up, down or off. The pod picks the resistor (ohms in the result). A channel pulls only the ways its resistor allows (pull_status: supported); today LA1-LA6 pull up, LA7/LA8 down, LA9-LA14 have none, and the pod refuses the rest (BP0024, BP0023).", + "title": "Pull" } }, "required": [ - "las", - "enabled" + "las" ], "title": "set_pullArguments", "type": "object" @@ -4934,7 +4960,7 @@ "properties": { "profile": { "additionalProperties": true, - "description": "The profile as a JSON object (schema version 2): la_mv, efuse, uart_rx/uart_tx/uart_baud, i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals [{name, la, direction, active_low, description}], pulls (the LA channels whose pull resistor power_on switches on, e.g. [1, 2]; LA1-LA8 have one, the others it switches off; left out: power_on leaves the pulls as they are). What it leaves out is undefined (not wired); a pin set to null is not wired. {\"version\": 1} objects fill in the old default pins.", + "description": "The profile as a JSON object (schema version 2): la_mv, efuse, uart_rx/uart_tx/uart_baud, i2c_sda/i2c_scl/i2c_addr, swd_swclk/swd_swdio/swd_nreset/swd_target, spi_*, and signals [{name, la, direction, active_low, description}], pulls (the pull resistors power_on switches on, the others off: {\"1\": \"up\", \"2\": \"up\", \"8\": \"down\"}, or a list of channels that pull their own way, e.g. [1, 2]; today LA1-LA6 pull up, LA7/LA8 down; left out: power_on leaves the pulls as they are). What it leaves out is undefined (not wired); a pin set to null is not wired. {\"version\": 1} objects fill in the old default pins.", "title": "Profile", "type": "object" }, diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 054eb6b..cde384b 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -6,6 +6,22 @@ `Wiring.preset()`), and `wiring.DEFAULT_PINS` is its values: they are the pins the pod used to assume, not the wiring of a particular bench. The old names `"embeddedci-reference"` and `REFERENCE_BENCH` still work. The values are unchanged, so version 1 profiles mean what they did. +- **Pull resistors by direction:** `BenchPod.set_pull(la, "up" | "down" | "off")` (None is off) + returns a `PullState` with `state`, `supported` (the directions the channel can pull) and `ohms`; + the pod picks the resistor. `enable_pullup` / `disable_pullup` / `enable_pulldown` / + `disable_pulldown` stay as shortcuts. `set_pull(la, True/False)` and `enabled=` still work + (deprecated: True pulls the channel's own direction). A direction the channel can't pull raises + `PullDirectionError` (code `BP0024`, also a `ValueError`), up/down on a channel without a resistor + `BP0023`. Firmware with the `la_pull_dir` feature gets `pull`; older firmware gets `pullup` and the + SDK checks the direction itself. `pull_state` and `enabled_pulls` cover LA1-LA14. +- **Wiring `pulls` map:** `Wiring.pulls` also takes `{"1": "up", "8": "down"}`; the list of channels + stays valid and means each channel's own direction. `Wiring.pull_directions()` gives either as + the map, and `power_on` applies it. `to_dict()` writes the list whenever every pull is its + channel's own direction, so older readers keep taking it. +- `LaPinState.pull_dirs`: every direction the channel's pull resistor can pull. +- The board's pull resistors are one table, `constants.PULL_TABLE` (`PullHw`: dirs, default, + ohms); `PULL_OHMS`, `PULLUP_CHANNELS` and `PULLDOWN_CHANNELS` come from it. +- Error catalog and features table synced from benchpod-firmware (BP0023, BP0024, `la_pull_dir`). ## 3.0.2 diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index bb3e123..3a72d5a 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -34,7 +34,7 @@ No pin numbers: the SWD channels, the UART pair, the baud and the power rail com **Contents:** [Install](#install) · [Quick start](#quick-start) · [API conventions](#api-conventions-and-stability) · [pytest plugin](#pytest-plugin) · [Power and reset](#power-reset-and-power-monitoring) · [Flashing](#flashing) · [UART](#uart) · -[Bias resistors](#la-bias-resistors) · [Emulated sensors](#emulated-sensors) · +[Pull resistors](#la-pull-resistors) · [Emulated sensors](#emulated-sensors) · [Analog paths](#analog-paths-dc-output-and-single-readings) · [Captures](#captures) · [DAC](#dac-generator-replay-and-faults) · [Control loop](#in-fabric-dac-control-loop) · [CAN](#can) · [AI Vision](#ai-vision-board) · [Cloud](#cloud-embeddedcidevice-name) · [Build reporting](#build-reporting) · @@ -641,7 +641,9 @@ cloud device's single profile on embeddedci.com, and raises over the LAN or USB. **Power-on applies the profile.** `bp.power_on()` (or `bp.power_on(wiring_profile="k66")`) sets the profile's I/O voltage when the pod has none or another one, sets its pull resistors, then switches the profile's rail on and records on the pod which profile powered the board (`target_status`). -`Wiring.pulls` lists the LA channels whose pull resistor is on (`{"pulls": [1, 2]}` in the JSON): +`Wiring.pulls` says which pull resistors are on, as a map of channel to direction +(`{"pulls": {"1": "up", "2": "up", "8": "down"}}` in the JSON) or as a list of channels that pull +their own direction (`{"pulls": [1, 2]}`); `Wiring.pull_directions()` gives either as the map. `power_on` switches exactly those on and the others off. They work at 3.3 V only, so at 1.8 V nothing is sent, and a profile without `pulls` (`None`) leaves them as they are. It never changes the I/O voltage under a board that is already powered: that raises, and `bp.set_la_voltage()` does it if you @@ -1040,30 +1042,45 @@ with bp.open_uart(rx=PIN5, tx=PIN4, de=PIN9, baud=19200, parity="even", `de` needs gateware v58 (`bp.supports("uart_de")`); older pods raise `UnsupportedFeatureError` before anything is sent. The USB console has no DE. -## LA bias resistors +## LA pull resistors -Eight LA channels carry a fixed, switchable bias resistor. They are referenced to 3V3, so the pod -won't engage one while the LA bank is at 1.8 V (`PullState.available` is false). +You name the direction, `"up"`, `"down"` or `"off"`; the pod picks the resistor and reports its +value. Which channels have one and which way each can pull depends on the board, and +`PullState.supported` says it per channel. On today's boards each resistor pulls one way only: -| Channels | Resistor | Value | +| Channels | Pulls | Value | |---|---|---| -| LA1, LA2 | pull-up | 4.7k | -| LA3, LA4 | pull-up | 2.2k | -| LA5, LA6 | pull-up | 10k | -| LA7, LA8 | pull-**down** | 10k | +| LA1, LA2 | up | 4.7k | +| LA3, LA4 | up | 2.2k | +| LA5, LA6 | up | 10k | +| LA7, LA8 | **down** | 10k | | LA9–LA14 | none | — | +The resistors are referenced to 3V3, so the pod won't engage one while the LA bank is at 1.8 V +(`PullState.available` is false). + ```python from embeddedci.benchpod import PIN1, PIN2, PIN7 -bp.enable_pullup(PIN1, PIN2) # LA1-LA6 only: ValueError on LA7/LA8 -bp.enable_pulldown(PIN7) # LA7/LA8 only -print(bp.pull_state(PIN1)) # PullState(la=1, enabled=True, direction='up', ohms='4.7k', available=True) -print(bp.enabled_pulls()) # [1, 2, 7] -bp.set_pull(PIN7, False) # either direction -bp.disable_pullup(PIN1, PIN2) +bp.set_pull(PIN1, "up") # PullState(la=1, enabled=True, direction='up', ohms='4.7k', supported=('up',), ...) +bp.set_pull(PIN7, "down") +bp.set_pull(PIN7, "off") # None is off too; "off" works on every channel +print(bp.pull_state(PIN1).state) # 'up' ('up', 'down' or 'off') +print(bp.enabled_pulls()) # [1] +bp.enable_pullup(PIN1, PIN2) # shortcuts: set_pull(la, "up") ... +bp.enable_pulldown(PIN7) # ... and set_pull(la, "down") +bp.disable_pullup(PIN1, PIN2) # off, on a channel that pulls up ``` +A direction the channel can't pull raises `PullDirectionError` (a `FirmwareError` and a +`ValueError`) with code `BP0024`, "LA7 supports pull-down only on this board", and `"up"` or `"down"` +on a channel without a resistor raises it with `BP0023`. `.la`, `.want` and `.have` name the channel +and the directions. `set_pull(la, True)` / `set_pull(la, False)` (or `enabled=`) still work but are +deprecated: True pulls the channel's own direction. + +Firmware before the `la_pull_dir` feature (`bp.supports("la_pull_dir")`) only takes on/off; the SDK +then sends that and checks the direction itself, so the calls above work on every pod. + An open-drain bus such as I2C must sit on LA1–LA6. ## GPIO on the LA pins @@ -1110,7 +1127,7 @@ The other owners point to `bp.sensors.stop("")`, closing the session f `bp.open_uart()` or `bp.open_spi()`, or waiting for a flash or step train to finish. The pod's own text, with its raw protocol command, stays in `exc.firmware_message`. -`bp.la_pins()` lists every channel's `LaPinState` (`function`, `gpio` mode, `level`, `pull`, `pull_on`), +`bp.la_pins()` lists every channel's `LaPinState` (`function`, `gpio` mode, `level`, `pull`, `pull_on`, `pull_dirs`), and `bp.configure_gpio(channels, mode)` is the same group claim as `gpio_pins()` returning those states. Captures observe every channel whatever its function. GPIO channels stay GPIO — also across disconnects — until released (the pytest `benchpod` fixture releases them at session start and end), @@ -2247,6 +2264,7 @@ Invalid arguments raise `ValueError` before anything is sent. Everything else ra | `DirectionConflictError` | a push-pull driver on a pin `la_dir` marks as a DUT output (a `FirmwareError`) | `la` | | `I2CNackError` | an I2C device did not acknowledge (`I2CMaster.write`, `read`, `write_read`, `read_reg`, `write_reg`) | `addr`, `nack_at` | | `PullConflictError` | an engaged bias resistor can't work with the channel's function (a `FirmwareError`) | `la` | +| `PullDirectionError` | the channel can't pull that way (BP0024) or has no pull resistor (BP0023); also a `ValueError` | `la`, `want`, `have` | | `TriggerTimeout` | a triggered capture's condition never happened (a `FirmwareError`) | `la`, `edge` | | `CanTimeout` | `CanBus.expect` timed out | `frames` | @@ -2313,7 +2331,7 @@ few built from other shapes); `to_dict()` goes the other way where a type is sen | `LanTls` | `lan_tls`, `set_lan_tls_https_only`, `regenerate_lan_tls`, `set_lan_tls_cert` | `port`, `https_only`, `sessions`, `origin` (`generated`/`user`), `key`, `subject`, `san`, `not_after`, `sha256` (what clients pin), `error` (no certificate) | | `UsbCcStatus` | `usb_cc` | `orientation`, `advertised`, `advertised_current` (A), `cc1_voltage`, `cc2_voltage` (V) | | `PullState` | `pull_state`, `set_pull` | `la`, `enabled`, `direction`, `ohms`, `available` | -| `LaPinState` | `la_pins`, `configure_gpio`, `la_dir` | `la`, `function`, `gpio`, `level`, `pull`, `pull_ohms`, `pull_on`, `dir`, `warn`, `warnings`, `in_use` | +| `LaPinState` | `la_pins`, `configure_gpio`, `la_dir` | `la`, `function`, `gpio`, `level`, `pull`, `pull_ohms`, `pull_on`, `pull_dirs`, `dir`, `warn`, `warnings`, `in_use` | | `GpioPin` (class) | `gpio`, `gpio_pins`, `signal` | `name`, `configure()`, `set(level)`, `high()`, `low()`, `activate()`, `deactivate()`, `is_active()`, `read()`, `wait_for(level, *, timeout)`, `pulse(width, *, count=1)`, `state()`, `release()` | | `ExtPin` (class) | `gpio`, `gpio_pins`, `signal` on an EXT pin | a `GpioPin` with `ext`, `pin`; `la` is `None`; `pulse()` raises `ExpansionError` | | `FlashResult` | `flash` | `ok`, `returncode`, `stdout`, `stderr`, `target_unreachable`, `stalled`, `artifact` (the uploaded build, for `flash(build=...)`) | diff --git a/packages/embeddedci/src/embeddedci/benchpod/__init__.py b/packages/embeddedci/src/embeddedci/benchpod/__init__.py index 6e1fba6..2f3c906 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/__init__.py +++ b/packages/embeddedci/src/embeddedci/benchpod/__init__.py @@ -110,6 +110,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin PodLeasedError, PodLockedError, PullConflictError, + PullDirectionError, TargetUnreachableError, TlsPinMismatchError, TransportError, @@ -356,6 +357,7 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin "CanTimeout", "PinConflictError", "PullConflictError", + "PullDirectionError", "DirectionConflictError", "TriggerTimeout", "UnsupportedFeatureError", diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 99c2a17..ee435a6 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -72,9 +72,10 @@ LA_STEP_MAX_STEPS, LA_STEP_MIN_DELAY_US, LA_VOLTAGES, - PULLDOWN_CHANNELS, - PULLUP_CHANNELS, + PULL_DIRECTIONS, + PULL_TABLE, REPLAY_MAPPINGS, + PullDirection, WAVESHAPES, AdcGainSource, AdcRange, @@ -99,8 +100,8 @@ coerce_pin, ) from .connection import resolve_connection -from .errors import (BenchPodError, FirmwareError, UnsupportedFeatureError, classify_firmware_error, - status_too_large) +from .errors import (BenchPodError, FirmwareError, PullDirectionError, UnsupportedFeatureError, + classify_firmware_error, firmware_error, status_too_large) from .flash import FlashResult from .gpio import LA_DIRS, ExtPin, GpioPin, LaPinState from .lease import DEFAULT_LEASE_TTL, DEFAULT_LEASE_WAIT, DeviceLease @@ -229,6 +230,16 @@ def _check_level(level: Any) -> int: } +class _NoPull: + """set_pull's "pull not given" (``enabled=`` is the older keyword); a stable repr for the docs.""" + + def __repr__(self) -> str: + return "" + + +_NO_PULL = _NoPull() + + def _one_or_many(las: List[int]) -> Any: return las[0] if len(las) == 1 else las @@ -1097,10 +1108,11 @@ def _apply_profile_pulls(self, w: Wiring) -> None: volts = w.la_voltage if w.la_voltage is not None else self.get_la_voltage().voltage if volts is None or abs(volts - 3.3) > 0.05: return - for la in PULLUP_CHANNELS + PULLDOWN_CHANNELS: - self.set_pull(la, la in w.pulls) - _log.info("power_on: pull resistors on LA%s from the wiring profile", - ", LA".join(str(x) for x in w.pulls) if w.pulls else " none") + wanted = w.pull_directions() + for la in PULL_TABLE: + self.set_pull(la, wanted.get(la, "off")) + _log.info("power_on: pull resistors from the wiring profile: %s", + ", ".join(f"LA{la} {d}" for la, d in sorted(wanted.items())) or "none") def _rail_on(self, rail: int) -> bool: try: @@ -1473,56 +1485,125 @@ def _flash_local(self, *, swclk: int, swdio: int, nreset: bool, target: str, fil timeout=timeout, connect_attempts=connect_attempts, ) - # -- LA bias resistors (LA1-8) ------------------------------------------ - # LA1-LA6 carry a pull-UP, LA7/LA8 a pull-DOWN (see constants.PULL_OHMS). The resistors are - # 3V3-referenced, so the pod refuses to engage one while the LA bank is at 1.8 V. + # -- LA pull resistors ------------------------------------------------------- + # The host names a direction ("up", "down", "off"); the pod picks the resistor and reports its + # value. Which channels have one and which way each can pull depends on the board: on today's + # boards LA1-LA6 pull up, LA7/LA8 down and LA9-LA14 have none (constants.PULL_TABLE). The + # resistors are 3V3-referenced, so the pod refuses to engage one while the LA bank is at 1.8 V. + + def _pull_dir_api(self) -> bool: + """The pod takes ``pull: up|down|off`` (feature ``la_pull_dir``); older firmware only + ``pullup: on|off``, on today's boards.""" + try: + return self.supports("la_pull_dir") + except BenchPodError: + return False @staticmethod - def _bias_channel(la: Union[Pin, int], allowed: Sequence[int], kind: str) -> int: + def _pull_want(la: int, pull: Union[str, bool, None]) -> str: + """``pull`` as "up" / "down" / "off". True (deprecated) is the channel's own direction.""" + if pull is None or pull is False: + return "off" + if pull is True: + hw = PULL_TABLE.get(la) + return hw.default if hw else "up" + want = str(pull).strip().lower() + if want == "none": + want = "off" + check_choice(want, PULL_DIRECTIONS, "pull") + return want + + @staticmethod + def _pull_refusal(la: int, want: str, supported: Tuple[str, ...]) -> PullDirectionError: + """The pod's own refusal (BP0023 / BP0024), for what the SDK refuses before asking.""" + if not supported: + return firmware_error(f"LA{la} has no pull resistor on this board", cmd="la", + code="BP0023", values={"la": la}) # type: ignore[return-value] + have = supported[0] + return firmware_error(f"LA{la} supports pull-{have} only on this board", cmd="la", + code="BP0024", values={"la": la, "want": want, "have": have}) # type: ignore[return-value] + + def set_pull(self, la: Union[Pin, int], pull: Union[PullDirection, bool, None, object] = _NO_PULL, *, + enabled: Optional[bool] = None) -> PullState: + """Pull LA ``la`` ``"up"``, ``"down"`` or ``"off"`` (``None`` is off too) and return its + :class:`PullState`. + + The pod picks the resistor; :attr:`PullState.ohms` says which. A direction the channel's + resistor can't pull raises :class:`~embeddedci.benchpod.errors.PullDirectionError` (BP0024, + "LA7 supports pull-down only on this board"), and ``"up"``/``"down"`` on a channel without + one too (BP0023). ``"off"`` is fine on every channel. + + ``set_pull(la, True)`` / ``set_pull(la, False)`` (and ``enabled=``) still work + (deprecated): True engages the channel's own direction (up on LA1-LA6, down on LA7/LA8), + False is off. + """ + if pull is _NO_PULL: + if enabled is None: + raise TypeError('set_pull() needs pull: "up", "down" or "off"') + pull = bool(enabled) la_i = coerce_pin(la, "la") - if la_i not in allowed: - if la_i in PULLDOWN_CHANNELS and kind == "pull-up": - raise ValueError(f"LA{la_i} has a pull-DOWN, not a pull-up; use enable_pulldown") - if la_i in PULLUP_CHANNELS and kind == "pull-down": - raise ValueError(f"LA{la_i} has a pull-UP, not a pull-down; use enable_pullup") - raise ValueError(f"LA{la_i} has no {kind} (bias resistors exist on LA1-LA8 only)") - return la_i - - def set_pull(self, la: Union[Pin, int], enabled: bool) -> PullState: - """Engage or release LA ``la``'s fixed bias resistor, whichever way it pulls (LA1-LA8).""" - la_i = self._bias_channel(la, PULLUP_CHANNELS + PULLDOWN_CHANNELS, "bias resistor") - reply = self.command({"cmd": "la", "la": la_i, "pullup": "on" if enabled else "off"}) + want = self._pull_want(la_i, pull) # type: ignore[arg-type] + if self._pull_dir_api(): + with _classified_errors(): + reply = self.command({"cmd": "la", "la": la_i, "pull": want}) + return PullState.from_reply(reply, la_i) + # Older firmware: only pullup on/off, which engages the channel's one direction. Check the + # direction here, so "up" never engages LA7's pull-down. + hw = PULL_TABLE.get(la_i) + if want != "off" and (not hw or want not in hw.dirs): + raise self._pull_refusal(la_i, want, hw.dirs if hw else ()) + if not hw: + return PullState.none(la_i) + with _classified_errors(): + reply = self.command({"cmd": "la", "la": la_i, "pullup": "off" if want == "off" else "on"}) return PullState.from_reply(reply, la_i) def pull_state(self, la: Union[Pin, int]) -> PullState: - """Read LA ``la``'s bias resistor: engaged, direction, value (LA1-LA8).""" - la_i = self._bias_channel(la, PULLUP_CHANNELS + PULLDOWN_CHANNELS, "bias resistor") - return PullState.from_reply(self.command({"cmd": "la", "la": la_i}), la_i) + """Read LA ``la``'s pull resistor: engaged, direction, value, supported directions.""" + la_i = coerce_pin(la, "la") + if la_i not in PULL_TABLE and not self._pull_dir_api(): + return PullState.none(la_i) # older firmware refuses the query on LA9-LA14 + with _classified_errors(): + return PullState.from_reply(self.command({"cmd": "la", "la": la_i}), la_i) def enabled_pulls(self) -> List[int]: - """The LA channels whose bias resistor is currently engaged.""" + """The LA channels whose pull resistor is currently engaged (either direction).""" mask = int(_dict(self.command({"cmd": "la"})).get("la_pullup_mask", 0) or 0) - return [la for la in range(1, 9) if mask >> (la - 1) & 1] + return [la for la in range(1, 15) if mask >> (la - 1) & 1] def enable_pullup(self, *las: Union[Pin, int]) -> None: - """Engage the pull-up on LA channels from LA1-LA6 — e.g. an open-drain I2C bus's SDA/SCL.""" + """Pull LA channels up, e.g. an open-drain I2C bus's SDA/SCL (LA1-LA6 on today's boards). + Same as ``set_pull(la, "up")``.""" for la in las: - self.set_pull(self._bias_channel(la, PULLUP_CHANNELS, "pull-up"), True) + self.set_pull(la, "up") def disable_pullup(self, *las: Union[Pin, int]) -> None: - """Release the pull-up on LA channels from LA1-LA6.""" + """Release a pull-up. Same as ``set_pull(la, "off")`` on a channel that pulls up.""" for la in las: - self.set_pull(self._bias_channel(la, PULLUP_CHANNELS, "pull-up"), False) + self._release_pull(la, "up") def enable_pulldown(self, *las: Union[Pin, int]) -> None: - """Engage the pull-down on LA7 and/or LA8.""" + """Pull LA channels down (LA7/LA8 on today's boards). Same as ``set_pull(la, "down")``.""" for la in las: - self.set_pull(self._bias_channel(la, PULLDOWN_CHANNELS, "pull-down"), True) + self.set_pull(la, "down") def disable_pulldown(self, *las: Union[Pin, int]) -> None: - """Release the pull-down on LA7 and/or LA8.""" + """Release a pull-down. Same as ``set_pull(la, "off")`` on a channel that pulls down.""" for la in las: - self.set_pull(self._bias_channel(la, PULLDOWN_CHANNELS, "pull-down"), False) + self._release_pull(la, "down") + + def _release_pull(self, la: Union[Pin, int], kind: str) -> None: + """Switch the pull off, refusing a channel that can't pull ``kind`` at all (so a typo + like disable_pullup(7) is not silently a no-op).""" + la_i = coerce_pin(la, "la") + if self._pull_dir_api(): + supported = self.pull_state(la_i).supported + else: + hw = PULL_TABLE.get(la_i) + supported = hw.dirs if hw else () + if kind not in supported: + raise self._pull_refusal(la_i, kind, supported) + self.set_pull(la_i, "off") # -- emulated sensors --------------------------------------------------------- diff --git a/packages/embeddedci/src/embeddedci/benchpod/constants.py b/packages/embeddedci/src/embeddedci/benchpod/constants.py index 9804163..d0476cf 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/constants.py +++ b/packages/embeddedci/src/embeddedci/benchpod/constants.py @@ -18,7 +18,7 @@ from __future__ import annotations from enum import Enum, IntEnum -from typing import Dict, Literal, Sequence, Tuple, Union, get_args +from typing import Dict, Literal, NamedTuple, Sequence, Tuple, Union, get_args from .errors import BenchPodError @@ -158,14 +158,36 @@ class Pin(IntEnum): #: LA I/O-bank voltages the pod supports (volts). 1.8 V needs a rev3 pod. LA_VOLTAGES: Tuple[float, ...] = (1.8, 3.3) -#: Fixed bias network per LA channel (LA1..LA8). LA1-LA6 pull UP to +3V3, LA7/LA8 pull -#: DOWN; LA9-LA14 have none. Source of truth: firmware ``i2c_bus.c``. -PULL_OHMS: Dict[int, str] = { - 1: "4.7k", 2: "4.7k", 3: "2.2k", 4: "2.2k", - 5: "10k", 6: "10k", 7: "10k", 8: "10k", +#: Pull directions a host asks for (``BenchPod.set_pull``). The pod picks the resistor value. +PullDirection = Literal["up", "down", "off"] +PULL_DIRECTIONS: Tuple[str, ...] = ("up", "down", "off") + + +class PullHw(NamedTuple): + """One LA channel's pull resistor on a board: the directions it can pull, the one + ``set_pull(la, True)`` (and firmware's older ``pullup:on``) engages, and its value.""" + + dirs: Tuple[str, ...] + default: str + ohms: str + + +#: Pull resistors per LA channel on today's boards (every v3 board): LA1-LA6 pull UP, LA7/LA8 +#: pull DOWN, LA9-LA14 have none. The firmware has the same table (``la_pins.c``) and reports it +#: per channel (``la_pins`` ``dirs``); the SDK only uses this one for firmware that does not +#: (before the ``la_pull_dir`` feature). A board revision with other resistors gets its own table. +PULL_TABLE_V3: Dict[int, PullHw] = { + 1: PullHw(("up",), "up", "4.7k"), 2: PullHw(("up",), "up", "4.7k"), + 3: PullHw(("up",), "up", "2.2k"), 4: PullHw(("up",), "up", "2.2k"), + 5: PullHw(("up",), "up", "10k"), 6: PullHw(("up",), "up", "10k"), + 7: PullHw(("down",), "down", "10k"), 8: PullHw(("down",), "down", "10k"), } -PULLUP_CHANNELS: Tuple[int, ...] = (1, 2, 3, 4, 5, 6) -PULLDOWN_CHANNELS: Tuple[int, ...] = (7, 8) +PULL_TABLE: Dict[int, PullHw] = PULL_TABLE_V3 + +#: Derived from :data:`PULL_TABLE`, kept for existing callers. +PULL_OHMS: Dict[int, str] = {la: hw.ohms for la, hw in PULL_TABLE.items()} +PULLUP_CHANNELS: Tuple[int, ...] = tuple(la for la, hw in PULL_TABLE.items() if "up" in hw.dirs) +PULLDOWN_CHANNELS: Tuple[int, ...] = tuple(la for la, hw in PULL_TABLE.items() if "down" in hw.dirs) # LA step trains (``la_step``, ``GpioPin.pulse``): the gateware counts steps and the half-period in # 16-bit counters, so the pod refuses more steps or a longer half-period. diff --git a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json index 3c32dc9..abf69cd 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json +++ b/packages/embeddedci/src/embeddedci/benchpod/error_catalog.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "e3f0e5ef3292ec9d3791bfb0e1de5b44f67b907385745b09286e1c2076a0b90f", + "catalog_sha256": "ef24d36dfee6afedccb095b4bf9c71b907bddc65233b3e0a35a5dfdc7bcff521", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -249,6 +249,137 @@ "mcp": "call dac_stop (after checking with the user) or wait for the capture to finish, then save again", "web": "Stop the generator or wait for the capture to finish, then save." } + }, + "BP0017": { + "name": "gateware_too_old", + "area": "firmware", + "since": "next", + "message": "{feature} needs gateware v{min} or later", + "cause": "The pod's FPGA image is older than the feature. Firmware updates bring the matching gateware with them.", + "args": { + "feature": "str", + "min": "int" + }, + "fix": { + "sdk": "update the pod's firmware (`benchpod flash-self`, or the firmware update in the web app)", + "cli": "update the pod's firmware with `benchpod flash-self`", + "mcp": "tell the user the pod's firmware is too old for {feature}; they can update it with `benchpod flash-self` or in the web app", + "web": "Update the pod's firmware on its Settings tab." + } + }, + "BP0018": { + "name": "uart_same_pin", + "area": "uart", + "since": "next", + "message": "UART rx and tx are both LA{la}; a one-wire UART needs half_duplex", + "cause": "A normal UART drives its TX pin all the time, so it cannot share the pin with RX. In half duplex the pod only pulls the line low and lets the pull-up hold it high, so both sides can talk on one wire.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "pass half_duplex=True for a one-wire UART, or put rx and tx on two LA channels", + "cli": "add --half-duplex for a one-wire UART, or put rx and tx on two LA channels", + "mcp": "set half_duplex=true for a one-wire UART, or use two LA channels for rx and tx", + "web": "Turn on half duplex for a one-wire UART, or pick two different pins." + } + }, + "BP0019": { + "name": "uart_half_duplex_two_pins", + "area": "uart", + "since": "next", + "message": "half_duplex runs on one pin, but rx is LA{rx} and tx is LA{tx}", + "cause": "In half duplex the pod sends and receives on the same wire, so rx and tx name the same LA channel.", + "args": { + "rx": "int", + "tx": "int" + }, + "fix": { + "sdk": "give the same LA channel for rx and tx, or leave half_duplex off", + "cli": "give the same LA channel for rx and tx, or leave --half-duplex off", + "mcp": "give the same LA channel for rx and tx, or set half_duplex=false", + "web": "Pick the same pin for RX and TX, or turn half duplex off." + } + }, + "BP0020": { + "name": "uart_entry_no_reset_pin", + "area": "uart", + "since": "next", + "message": "The UART entry sequence needs the pod's reset pin, which this board does not have", + "cause": "The entry sequence holds the target in reset with the pod's own reset pin while it holds TX low. Pods before v3 have no reset pin.", + "args": {}, + "fix": { + "sdk": "use a v3 pod, or open the UART without entry and reset the target yourself", + "cli": "use a v3 pod, or open the UART without --entry and reset the target yourself", + "mcp": "open the UART without entry; this pod cannot reset the target", + "web": "This pod cannot reset the target. Open the UART without the entry sequence." + } + }, + "BP0021": { + "name": "uart_entry_invalid", + "area": "uart", + "since": "next", + "message": "The UART entry option {arg} is out of range (0 to {max})", + "cause": "The entry sequence times are milliseconds, each up to a limit, and the first bytes are at most a few dozen hex bytes.", + "args": { + "arg": "str", + "max": "int" + }, + "fix": { + "sdk": "pass {arg} between 0 and {max}", + "cli": "pass {arg} between 0 and {max}", + "mcp": "pass {arg} between 0 and {max}", + "web": "Set {arg} between 0 and {max}." + } + }, + "BP0022": { + "name": "uart_de_pin", + "area": "uart", + "since": "next", + "message": "The UART's DE pin LA{la} is also its rx or tx", + "cause": "DE switches an RS-485 transceiver between sending and listening, so it is a wire of its own, from an LA channel to the transceiver's DE and /RE pins.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "give de the LA channel wired to the transceiver's DE and /RE, not rx or tx", + "cli": "give --de the LA channel wired to the transceiver's DE and /RE, not rx or tx", + "mcp": "set de to the LA channel wired to the transceiver's DE and /RE, not rx or tx", + "web": "Pick the pin wired to the transceiver's DE and /RE, not the RX or TX pin." + } + }, + "BP0023": { + "name": "la_no_pull", + "area": "io", + "since": "next", + "message": "LA{la} has no pull resistor on this board", + "cause": "Only some LA channels have a pull resistor the pod can switch, and which ones depends on the board. la_pins lists each channel's pull and the directions it supports.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "pick a channel with a pull resistor (bp.la_pins() shows them), or add one on the board", + "cli": "pick a channel with a pull resistor (`benchpod la pins` shows them), or add one on the board", + "mcp": "pick a channel with a pull resistor (la_pins or pull_status shows them), or add one on the board", + "web": "This pin has no pull resistor. Pick a pin that has one, or add one on the board." + } + }, + "BP0024": { + "name": "la_pull_direction", + "area": "io", + "since": "next", + "message": "LA{la} supports pull-{have} only on this board", + "cause": "The pull resistor on LA{la} is wired one way on this board, so it cannot pull {want}. Which way each channel pulls depends on the board; la_pins lists it.", + "args": { + "la": "int", + "want": "str", + "have": "str" + }, + "fix": { + "sdk": "use bp.set_pull({la}, \"{have}\"), or pick a channel that pulls {want} (bp.la_pins() shows them)", + "cli": "use `benchpod la pull {la} {have}`, or pick a channel that pulls {want} (`benchpod la pins` shows them)", + "mcp": "call set_pull(las=[{la}], pull=\"{have}\"), or pick a channel that pulls {want} (pull_status shows them)", + "web": "LA{la} can only pull {have} on this board. Pick a pin that pulls {want}." + } } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/errors.py b/packages/embeddedci/src/embeddedci/benchpod/errors.py index ad5dd56..7fc9f41 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/errors.py +++ b/packages/embeddedci/src/embeddedci/benchpod/errors.py @@ -189,6 +189,20 @@ def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0) -> N self.la = la +class PullDirectionError(FirmwareError, ValueError): + """The channel can't pull the way asked: it has no pull resistor (``BP0023``), or its resistor + pulls the other way on this board (``BP0024``, "LA7 supports pull-down only on this board"). + ``la`` is the channel, ``want`` the direction asked for, ``have`` the one it supports ("" when + it has none). Also a :class:`ValueError`, which the SDK raised for this before the pod did.""" + + def __init__(self, message: str, *, cmd: Optional[str] = None, la: int = 0, want: str = "", + have: str = "") -> None: + super().__init__(message, cmd=cmd) + self.la = la + self.want = want + self.have = have + + class DirectionConflictError(FirmwareError): """The pod refused to drive a pin that :meth:`BenchPod.la_dir ` marks as wired to a DUT output (a push-pull GPIO output, @@ -327,11 +341,12 @@ def status_too_large(message: str, cmd: Optional[str] = "status") -> bool: "i2c busy: close the I2C session from bp.open_i2c() first"), (re.compile(r"send i2c_start first"), "open one with bp.open_i2c() first"), (re.compile(r"i2c_start again"), "open it again with bp.open_i2c()"), - (re.compile(r'switch on LA(\d+)\'s with \{"cmd":"la","la":\d+,"pullup":"on"\}'), + (re.compile(r'switch on LA(\d+)\'s with \{"cmd":"la","la":\d+,"(?:pullup":"on|pull":"up)"\}'), r"switch on LA\1's with bp.enable_pullup(\1)"), - (re.compile(r'\{"cmd":"la","la":(\d+),"pullup":"on"\}'), r"bp.enable_pullup(\1)"), + (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup":"on|pull":"up)"\}'), r"bp.enable_pullup(\1)"), + (re.compile(r'\{"cmd":"la","la":(\d+),"pull":"down"\}'), r'bp.set_pull(\1, "down")'), (re.compile(r'pass "pullups":"external"'), 'pass pullups="external"'), - (re.compile(r'\{"cmd":"la","la":(\d+),"pullup":"off"\}'), r"bp.set_pull(\1, False)"), + (re.compile(r'\{"cmd":"la","la":(\d+),"(?:pullup|pull)":"off"\}'), r'bp.set_pull(\1, "off")'), (re.compile(r'\{"cmd":"gpio","la":(\d+),"mode":"output"\}'), r'bp.gpio(\1, "output")'), (re.compile(r'\{"cmd":"fpga_image","image":([012])\}'), r"bp.fpga_image(\1)"), (re.compile(r'\{"cmd":"dac_loop_input"\}'), "bp.loop_input()"), @@ -450,5 +465,10 @@ def firmware_error(message: str, *, cmd: Optional[str] = None, code: str = "", exc = FirmwareError(message, cmd=cmd) if code == "BP0002": # unknown command: the firmware lacks the feature exc = UnsupportedFeatureError(message, cmd=cmd, feature=cmd or "") + elif code in ("BP0023", "BP0024"): # no pull resistor / the other direction only + v = dict(values or {}) + la = v.get("la", 0) + exc = PullDirectionError(message, cmd=cmd, la=int(la) if str(la).isdigit() else 0, + want=str(v.get("want", "")), have=str(v.get("have", ""))) exc = classify_firmware_error(exc) return _attach_code(exc, code or "", values) diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json index da21413..b816f48 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json +++ b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json @@ -1,8 +1,8 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 2, - "table_sha256": "22265d477544ffd24beee7ee1aa64a6ab64f9112196af7419e08b2f04e1e2f56", + "revision": 3, + "table_sha256": "e85098f7edfacd900d95465c08e08295d5bee3cb82a7e8b3759fedbd13d5adbd", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -114,6 +114,11 @@ "firmware": "3.10.10", "gateware": 56, "date": "2026-11-17" + }, + { + "firmware": "3.10.11", + "gateware": 58, + "date": "2026-11-18" } ], "features": { @@ -441,7 +446,7 @@ }, "uart_hd": { "rev": 1, - "firmware": "next", + "firmware": "3.10.11", "gateware": 57, "board": "any", "docs": "API.md#uart_proxy_start--transparent-uart-bridge" @@ -632,10 +637,16 @@ }, "uart_de": { "rev": 2, - "firmware": "next", + "firmware": "3.10.11", "gateware": 58, "board": "any", "docs": "API.md#uart_proxy_start--transparent-uart-bridge" + }, + "la_pull_dir": { + "rev": 3, + "firmware": "next", + "board": "any", + "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/gpio.py b/packages/embeddedci/src/embeddedci/benchpod/gpio.py index 80a6258..137b9e0 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/gpio.py +++ b/packages/embeddedci/src/embeddedci/benchpod/gpio.py @@ -18,7 +18,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple if TYPE_CHECKING: # pragma: no cover from .client import BenchPod @@ -46,7 +46,8 @@ class LaPinState: gpio: Optional[str] = None #: The commanded level of a GPIO output or open-drain pin. level: Optional[int] = None - #: ``"up"``, ``"down"`` or ``None`` (LA9-LA14 have no bias resistor). + #: The way the pull resistor pulls when on: ``"up"``, ``"down"`` or ``None`` (no resistor: + #: LA9-LA14 on today's boards). pull: Optional[str] = None pull_ohms: Optional[str] = None pull_on: bool = False @@ -57,6 +58,10 @@ class LaPinState: #: output) and :data:`WARN_UNPOWERED_DUT` (target power is off while the pin is driven high or #: pulled up). :attr:`warnings` spells them out. warn: int = 0 + #: Every direction the pull resistor can pull (``set_pull``): ``("up",)``, ``("down",)``, + #: ``("up", "down")`` or ``()``. Firmware before ``la_pull_dir`` does not say; it is then + #: ``(pull,)``. + pull_dirs: Tuple[str, ...] = () raw: Dict[str, Any] = field(default_factory=dict, compare=False, repr=False) @property @@ -85,7 +90,10 @@ def from_reply(cls, entry: Any) -> "LaPinState": return cls(la=int(e.get("la", 0) or 0), function=str(e.get("function") or "none"), gpio=e.get("gpio") or None, level=None if level is None else int(level), pull=pull.get("dir"), pull_ohms=pull.get("ohms"), pull_on=bool(pull.get("on", False)), - dir=e.get("dir") or None, warn=int(e.get("warn") or 0), raw=dict(e)) + dir=e.get("dir") or None, warn=int(e.get("warn") or 0), + pull_dirs=(tuple(str(d) for d in pull["dirs"]) if isinstance(pull.get("dirs"), list) + else ((str(pull["dir"]),) if pull.get("dir") else ())), + raw=dict(e)) class GpioPin: diff --git a/packages/embeddedci/src/embeddedci/benchpod/header.py b/packages/embeddedci/src/embeddedci/benchpod/header.py index 840d3a9..60cc6fe 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/header.py +++ b/packages/embeddedci/src/embeddedci/benchpod/header.py @@ -15,7 +15,7 @@ from typing import Any, Dict, List, Mapping, Optional, Tuple -from .constants import PULL_OHMS, PULLDOWN_CHANNELS +from .constants import PULL_OHMS from .wiring import ROLE_KEYS, Wiring HEADERS: Tuple[str, ...] = ("j1", "front") @@ -76,9 +76,10 @@ def _uses(w: Wiring, la: int) -> List[Tuple[str, str]]: def _pull(w: Wiring, la: int) -> Optional[str]: ohms = PULL_OHMS.get(la) - if not ohms or not w.pulls or la not in w.pulls: + d = w.pull_directions().get(la) + if not ohms or not d: return None - return f"pull-{'down' if la in PULLDOWN_CHANNELS else 'up'} {ohms} on" + return f"pull-{d} {ohms} on" def _cell(w: Wiring, n: int, name: str) -> str: diff --git a/packages/embeddedci/src/embeddedci/benchpod/state.py b/packages/embeddedci/src/embeddedci/benchpod/state.py index bdf4d36..03abd00 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/state.py +++ b/packages/embeddedci/src/embeddedci/benchpod/state.py @@ -9,7 +9,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import Any, Dict, List, Mapping, Optional +from typing import Any, Dict, List, Mapping, Optional, Tuple from .constants import Efuse, coerce_efuse @@ -181,29 +181,55 @@ def from_reply(cls, reply: Any) -> "UsbCcStatus": @dataclass(frozen=True) class PullState: - """The fixed bias resistor on one LA channel (LA1-LA8).""" + """The pull resistor on one LA channel: what it does now and what it can do.""" la: int - #: The resistor is engaged. + #: The resistor is engaged (``state`` is ``"up"`` or ``"down"``). enabled: bool - #: ``"up"`` (LA1-LA6) or ``"down"`` (LA7/LA8). - direction: str - #: Nominal resistance, e.g. ``"4.7k"``. + #: The way the resistor pulls when engaged: ``"up"`` or ``"down"``; ``None`` on a channel + #: without one. On today's boards LA1-LA6 pull up, LA7/LA8 down. + direction: Optional[str] + #: The resistor's value, e.g. ``"4.7k"`` (``""`` without one). Reported, never chosen: on + #: boards with several values the firmware picks one from the pin's function. ohms: str #: A pull can be engaged right now (the resistors are 3V3-referenced, so not at 1.8 V). available: bool = True + #: Every direction the channel can pull: ``("up",)``, ``("down",)``, ``("up", "down")`` or ``()``. + supported: Tuple[str, ...] = () raw: Dict[str, Any] = _raw() + @property + def state(self) -> str: + """What the channel does now: ``"up"``, ``"down"`` or ``"off"``.""" + return (self.direction or "off") if self.enabled else "off" + + @classmethod + def none(cls, la: int, raw: Optional[Dict[str, Any]] = None) -> "PullState": + """A channel without a pull resistor.""" + return cls(la=la, enabled=False, direction=None, ohms="", supported=(), raw=dict(raw or {})) + @classmethod def from_reply(cls, reply: Any, la: int) -> "PullState": - from .constants import PULL_OHMS, PULLDOWN_CHANNELS + """From the pod's ``la`` reply. Firmware before ``la_pull_dir`` sends no ``state`` or + ``dirs``; the board table (:data:`~embeddedci.benchpod.constants.PULL_TABLE`) fills them.""" + from .constants import PULL_TABLE d = _d(reply) - default_dir = "down" if la in PULLDOWN_CHANNELS else "up" - return cls(la=int(d.get("la", la)), enabled=bool(d.get("pullup", 0)), - direction=str(d.get("pull", default_dir)), - ohms=str(d.get("ohms", PULL_OHMS.get(la, ""))), - available=bool(d.get("pullups_available", 1)), raw=d) + la = int(d.get("la", la)) + hw = PULL_TABLE.get(la) + dirs = d.get("dirs") + supported = (tuple(str(x) for x in dirs) if isinstance(dirs, list) + else (hw.dirs if hw else ())) + pull = d.get("pull") + direction: Optional[str] = (str(pull) if pull in ("up", "down") + else (hw.default if hw and pull is None else None)) + state = d.get("state") + enabled = (state in ("up", "down")) if isinstance(state, str) else bool(d.get("pullup", 0)) + if isinstance(state, str) and state in ("up", "down"): + direction = state + return cls(la=la, enabled=enabled, direction=direction, + ohms=str(d.get("ohms", hw.ohms if hw else "") or ""), + available=bool(d.get("pullups_available", 1)), supported=supported, raw=d) @dataclass(frozen=True) diff --git a/packages/embeddedci/src/embeddedci/benchpod/wiring.py b/packages/embeddedci/src/embeddedci/benchpod/wiring.py index 7657bad..dcd80ab 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/wiring.py +++ b/packages/embeddedci/src/embeddedci/benchpod/wiring.py @@ -24,7 +24,7 @@ from pathlib import Path from typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple, Union -from .constants import PULL_OHMS, PULLDOWN_CHANNELS, PULLUP_CHANNELS +from .constants import PULL_TABLE, PULLDOWN_CHANNELS, PULLUP_CHANNELS PULL_CHANNELS = PULLUP_CHANNELS + PULLDOWN_CHANNELS @@ -70,6 +70,17 @@ _PASSTHROUGH_PREFIXES = ("loop_input_", "loop_output_", "expansion") +def _channels(las: Tuple[int, ...]) -> str: + """``(1, 2, 3, 7, 8)`` -> ``"1..3, 7..8"``.""" + runs: List[List[int]] = [] + for la in sorted(las): + if runs and la == runs[-1][-1] + 1: + runs[-1].append(la) + else: + runs.append([la]) + return ", ".join(f"{r[0]}..{r[-1]}" if len(r) > 1 else str(r[0]) for r in runs) + + def _is_int(value: Any) -> bool: return isinstance(value, int) and not isinstance(value, bool) @@ -148,10 +159,12 @@ class Wiring: #: The DUT direction of a role or signal where its default is wrong: role key or signal name #: -> ``dut_input``, ``dut_output`` or ``bidir`` (see :meth:`pin_dut_dirs`). dut_dirs: Mapping[str, str] = field(default_factory=dict) - #: The LA channels whose pull resistor is on (LA1-LA8 have one each: LA1-LA6 pull up, LA7-LA8 - #: pull down). :meth:`BenchPod.power_on` switches exactly these on and the others off before - #: the rail goes on. ``None``: the profile leaves the pull resistors as they are. - pulls: Optional[Tuple[int, ...]] = None + #: The pull resistors :meth:`BenchPod.power_on` switches on (the others off) before the rail + #: goes on: a map of LA channel -> ``"up"`` or ``"down"`` (``{1: "up", 2: "up"}``), or a list + #: of channels (``[1, 2]``), which pull their own direction (up on LA1-LA6, down on LA7/LA8 on + #: today's boards). ``None``: the profile leaves the pull resistors as they are. + #: :meth:`pull_directions` gives either form as the map. + pulls: Optional[Union[Tuple[int, ...], Mapping[int, str]]] = None def __post_init__(self) -> None: object.__setattr__(self, "signals", tuple(self.signals)) @@ -160,6 +173,11 @@ def __post_init__(self) -> None: if all(_is_int(x) for x in pulls): pulls = tuple(sorted(set(pulls))) object.__setattr__(self, "pulls", pulls) + elif isinstance(self.pulls, Mapping): + # JSON keys are strings ("1"); keep anything else as it is for validate() to name + m = {(int(k) if isinstance(k, str) and k.strip().isdigit() else k): + (v.strip().lower() if isinstance(v, str) else v) for k, v in self.pulls.items()} + object.__setattr__(self, "pulls", dict(sorted(m.items(), key=lambda kv: str(kv[0]).zfill(3)))) if isinstance(self.dut_dirs, Mapping): object.__setattr__(self, "dut_dirs", dict(self.dut_dirs)) object.__setattr__(self, "extra", dict(self.extra)) @@ -275,7 +293,14 @@ def to_dict(self) -> Dict[str, Any]: out[f.name] = getattr(self, f.name) out["signals"] = [s.to_dict() for s in self.signals] out["dut_dirs"] = dict(self.dut_dirs) - if self.pulls is not None: + if isinstance(self.pulls, Mapping): + # the list whenever every pull is its channel's own direction: every reader takes it + dirs = self.pull_directions() + if dirs and all(PULL_TABLE.get(la) and PULL_TABLE[la].default == d for la, d in dirs.items()): + out["pulls"] = sorted(dirs) + else: + out["pulls"] = {str(la): d for la, d in self.pulls.items()} + elif self.pulls is not None: out["pulls"] = list(self.pulls) out.update(self.extra) return out @@ -349,19 +374,34 @@ def warnings(self) -> List[str]: la = getattr(self, key) if _is_int(la) and la >= 9: out.append(f"{key} is on LA{la}, which has no pod pull-up; the bus needs external pull-ups") - elif la in PULLDOWN_CHANNELS and self._pull_may_be_on(la): - out.append(f"{key} is on LA{la}, which has a 10k pull-down; keep it disabled on an " - "open-drain bus") - if self.uart_rx in PULLDOWN_CHANNELS and self._pull_may_be_on(self.uart_rx): + elif _is_int(la) and self._pull_may_be(la, "down"): + out.append(f"{key} is on LA{la}, which has a {PULL_TABLE[la].ohms} pull-down; keep it " + "disabled on an open-drain bus") + if _is_int(self.uart_rx) and self._pull_may_be(self.uart_rx, "down"): out.append(f"uart_rx is on LA{self.uart_rx}, which has a pull-down; the UART idles high, " "so keep the pull disabled") if self.la_mv == 1800 and self.pulls: out.append("pulls: the pull resistors work at 3.3 V only; at 1.8 V they stay off") return out - def _pull_may_be_on(self, la: int) -> bool: - """Is LA ``la``'s pull resistor on with this profile, or may it be (``pulls`` None)?""" - return self.pulls is None or la in self.pulls + def pull_directions(self) -> Dict[int, str]: + """The pulls :meth:`BenchPod.power_on` switches on: LA channel -> ``"up"`` / ``"down"``. A + list of channels gives each channel's own direction; ``pulls`` None gives ``{}``.""" + if isinstance(self.pulls, Mapping): + return {int(la): str(d) for la, d in self.pulls.items()} + out: Dict[int, str] = {} + for la in self.pulls or (): + hw = PULL_TABLE.get(la) if _is_int(la) else None + if hw: + out[int(la)] = hw.default + return out + + def _pull_may_be(self, la: int, direction: str) -> bool: + """Does LA ``la`` pull ``direction`` with this profile, or may it (``pulls`` None)?""" + if self.pulls is None: + hw = PULL_TABLE.get(la) + return bool(hw and direction in hw.dirs) + return self.pull_directions().get(la) == direction def describe(self) -> str: """A readable pin table: channel, what is wired to it, its bias resistor and its DUT @@ -372,8 +412,8 @@ def describe(self) -> str: rail = f"eFuse {self.efuse}" if self.efuse is not None else "not set" lines = [f"LA I/O {io}, target power {rail}"] for la in range(1, 15): - pull = PULL_OHMS.get(la) - bias = (f"{pull} pull-{'down' if la in PULLDOWN_CHANNELS else 'up'}" if pull else "no pull") + hw = PULL_TABLE.get(la) + bias = f"{hw.ohms} pull-{'/'.join(hw.dirs)}" if hw else "no pull" line = f"LA{la:<3} {pins.get(la, '-'):<12} {bias:<16} {dirs.get(la, '')}" lines.append(line.rstrip()) return "\n".join(lines + [f"warning: {w}" for w in self.warnings()]) @@ -430,13 +470,25 @@ def _errors(self) -> List[str]: errs.append(f"signals[{i}].active_low must be true or false") if not isinstance(s.description, str) or len(s.description) > 120: errs.append(f"signals[{i}].description must be a string of at most 120 characters") - if self.pulls is not None: + if isinstance(self.pulls, Mapping): + for la, d in self.pulls.items(): + hw = PULL_TABLE.get(la) if _is_int(la) else None + if not hw: + errs.append(f"pulls.{la}: must be an LA channel with a pull resistor " + f"({_channels(PULL_CHANNELS)}), got {la!r}") + elif d not in ("up", "down"): + errs.append(f"pulls.{la}: must be \"up\" or \"down\", got {d!r}") + elif d not in hw.dirs: + errs.append(f"pulls.{la}: LA{la} supports pull-{hw.default} only on this board") + elif self.pulls is not None: if not isinstance(self.pulls, (list, tuple)): - errs.append("pulls must be a list of the LA channels whose pull resistor is on, e.g. [1, 2]") + errs.append("pulls must be a map of LA channel -> \"up\" or \"down\" " + "(e.g. {\"1\": \"up\"}) or a list of channels (e.g. [1, 2])") else: for i, la in enumerate(self.pulls): if not (_is_int(la) and la in PULL_CHANNELS): - errs.append(f"pulls[{i}] must be an LA channel with a pull resistor (1..8), got {la!r}") + errs.append(f"pulls[{i}] must be an LA channel with a pull resistor " + f"({_channels(PULL_CHANNELS)}), got {la!r}") if not isinstance(self.dut_dirs, Mapping): errs.append("dut_dirs must be an object of role or signal name -> direction") else: diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 531ca6f..bedbab5 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -179,7 +179,7 @@ "set_lan_tls_cert": "(self, cert_pem: 'Union[str, bytes]', key_pem: 'Union[str, bytes]') -> \"'LanTls'\"", "set_lan_tls_https_only": "(self, on: 'bool') -> \"'LanTls'\"", "set_module_id": "(self, serial: 'str', rev: 'str', module_type: 'str' = 'analog', *, replace: 'bool' = False) -> 'ModuleInfo'", - "set_pull": "(self, la: 'Union[Pin, int]', enabled: 'bool') -> 'PullState'", + "set_pull": "(self, la: 'Union[Pin, int]', pull: 'Union[PullDirection, bool, None, object]' = , *, enabled: 'Optional[bool]' = None) -> 'PullState'", "set_reset": "(self, asserted: 'bool') -> 'ResetState'", "signal": "(self, name: 'str') -> 'GpioPin'", "spi_flash": "(self, image: \"Union[bytes, str, 'os.PathLike[str]']\", addr: 'int' = 0, *, erase: 'bool' = True, verify: 'bool' = True, hold_reset: 'bool' = False, sck: 'Union[Pin, int, str, None]' = None, mosi: 'Union[Pin, int, str, None]' = None, miso: 'Union[Pin, int, str, None]' = None, cs: 'Union[Pin, int, str, None]' = None, hz: 'int' = 6000000, mode: 'int' = 0, progress: 'Optional[_spi.Progress]' = None) -> '_spi.SpiFlashResult'", @@ -724,6 +724,7 @@ "pull_on", "dir", "warn", + "pull_dirs", "raw" ], "from_reply": "(cls, entry: 'Any') -> \"'LaPinState'\"", @@ -940,6 +941,9 @@ "PullConflictError": { "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, la: 'int' = 0) -> 'None'" }, + "PullDirectionError": { + "__init__": "(self, message: 'str', *, cmd: 'Optional[str]' = None, la: 'int' = 0, want: 'str' = '', have: 'str' = '') -> 'None'" + }, "PullState": { "__fields__": [ "la", @@ -947,9 +951,12 @@ "direction", "ohms", "available", + "supported", "raw" ], - "from_reply": "(cls, reply: 'Any', la: 'int') -> \"'PullState'\"" + "from_reply": "(cls, reply: 'Any', la: 'int') -> \"'PullState'\"", + "none": "(cls, la: 'int', raw: 'Optional[Dict[str, Any]]' = None) -> \"'PullState'\"", + "state": "property" }, "RailPower": { "__fields__": [ @@ -1289,6 +1296,7 @@ "pin_dut_dirs": "(self) -> 'Dict[int, str]'", "pins": "(self) -> 'Dict[int, str]'", "preset": "(cls, name: 'str' = 'embeddedci-default') -> \"'Wiring'\"", + "pull_directions": "(self) -> 'Dict[int, str]'", "signal": "(self, name: 'str') -> 'Signal'", "to_dict": "(self) -> 'Dict[str, Any]'", "undefined": "(cls) -> \"'Wiring'\"", @@ -1407,6 +1415,7 @@ "PowerProfileSession", "PowerStatus", "PullConflictError", + "PullDirectionError", "PullState", "RailPower", "ReplayHandle", diff --git a/packages/embeddedci/tests/e2e/test_e2e_gpio.py b/packages/embeddedci/tests/e2e/test_e2e_gpio.py index e58d150..c15e128 100644 --- a/packages/embeddedci/tests/e2e/test_e2e_gpio.py +++ b/packages/embeddedci/tests/e2e/test_e2e_gpio.py @@ -18,6 +18,7 @@ from embeddedci.benchpod import ( PinConflictError, PullConflictError, + PullDirectionError, Signal, Trigger, TriggerTimeout, @@ -99,6 +100,46 @@ def test_pull_down_conflicts_with_open_drain_both_ways(gpio_pod, bench): gpio_pod.disable_pulldown(ch) +@FREE_PULL_LA +@FREE_PULLDOWN_LA +@FREE_LA +def test_pull_by_direction(gpio_pod, bench): + """set_pull(la, "up" | "down" | "off"): the line follows, the other direction is refused with + BP0024, a channel without a resistor with BP0023. Firmware with la_pull_dir answers itself; + older firmware gets pullup on/off and the SDK refuses the same way.""" + up, down, bare = bench.free_pull_la, bench.free_pulldown_la, bench.free_la[0] + new_fw = gpio_pod.supports("la_pull_dir") + try: + st = gpio_pod.set_pull(up, "up") + assert st.state == "up" and st.supported == ("up",) and st.ohms + assert gpio_pod.gpio(up, "input").read() == 1 + gpio_pod.release_gpio(up) + st = gpio_pod.set_pull(down, "down") + assert st.state == "down" and st.supported == ("down",) + assert gpio_pod.gpio(down, "input").read() == 0 + gpio_pod.release_gpio(down) + if new_fw: + assert gpio_pod.pull_state(up).raw.get("dirs") == ["up"] + for la, want, have in ((down, "up", "down"), (up, "down", "up")): + with pytest.raises(PullDirectionError) as ei: + gpio_pod.set_pull(la, want) + assert (ei.value.code, ei.value.la, ei.value.want, ei.value.have) == ("BP0024", la, want, have) + assert f"LA{la} supports pull-{have} only on this board" in str(ei.value) + with pytest.raises(PullDirectionError) as ei: + gpio_pod.set_pull(bare, "up") + assert ei.value.code == "BP0023" and ei.value.la == bare + assert gpio_pod.set_pull(bare, "off").supported == () + assert gpio_pod.pull_state(bare).state == "off" + assert sorted(gpio_pod.enabled_pulls()) == sorted([up, down]) + assert gpio_pod.set_pull(down, True).state == "down" # the deprecated on/off form + assert gpio_pod.set_pull(down, False).state == "off" + finally: + gpio_pod.release_gpio(up, down) + gpio_pod.set_pull(up, "off") + gpio_pod.set_pull(down, "off") + assert up not in gpio_pod.enabled_pulls() and down not in gpio_pod.enabled_pulls() + + @FREE_LA def test_uart_is_refused_on_a_gpio_pin_until_released(gpio_pod, bench): rx, tx = bench.free_la diff --git a/packages/embeddedci/tests/test_client_v2.py b/packages/embeddedci/tests/test_client_v2.py index e0ff57d..6580f16 100644 --- a/packages/embeddedci/tests/test_client_v2.py +++ b/packages/embeddedci/tests/test_client_v2.py @@ -205,11 +205,12 @@ def test_pullups_and_pulldowns_are_not_interchangeable(): bp, t = _bp({"la": lambda req: {"la": req.get("la"), "pullup": 1, "ohms": "10k", "pull": "down" if req.get("la") in (7, 8) else "up", "pullups_available": 1}}) - with pytest.raises(ValueError, match="pull-DOWN"): + # firmware without la_pull_dir: the SDK checks the direction itself, like the pod would + with pytest.raises(ValueError, match="LA7 supports pull-down only"): bp.enable_pullup(7) - with pytest.raises(ValueError, match="pull-UP"): + with pytest.raises(ValueError, match="LA2 supports pull-up only"): bp.enable_pulldown(2) - with pytest.raises(ValueError, match="LA1-LA8"): + with pytest.raises(ValueError, match="LA9 has no pull resistor"): bp.enable_pullup(9) assert t.commands == [] bp.enable_pullup(1, 2) diff --git a/packages/embeddedci/tests/test_pull_direction.py b/packages/embeddedci/tests/test_pull_direction.py new file mode 100644 index 0000000..5fa2453 --- /dev/null +++ b/packages/embeddedci/tests/test_pull_direction.py @@ -0,0 +1,196 @@ +"""Pull resistors by direction (``set_pull(la, "up"|"down"|"off")``, firmware feature +``la_pull_dir``): what the SDK sends to new firmware, the ``pullup`` fallback for older firmware, +the refusals (BP0023 / BP0024) and the wiring profile's ``pulls`` map (firmware +command_handler_pins.c handle_la, la_pins.c s_pulls_v3).""" + +from __future__ import annotations + +from typing import Any, Dict, List + +import pytest + +from embeddedci.benchpod import BenchPod, PullDirectionError, PullState, Wiring +from embeddedci.benchpod.constants import PULL_TABLE +from embeddedci.benchpod.errors import firmware_error + + +class Pod: + """A pod with today's resistors. ``features_rev`` 3 has la_pull_dir (takes ``pull``), 2 does not + (takes ``pullup`` only and refuses a query on LA9-LA14, as firmware 3.10.11 does).""" + + def __init__(self, features_rev: int) -> None: + self.features_rev = features_rev + self.on: Dict[int, bool] = {} + self.sent: List[Dict[str, Any]] = [] + + def status(self) -> Dict[str, Any]: + return {"board": "stm32h563", "adc_bits": 16, "version": "3.10.11", "la_voltage": 3.3, + "features_rev": self.features_rev, "gateware": 58, "fpga_image": "deep", + "hw": ["nrst_pin"]} + + def ping(self) -> Any: + return "pong" + + def close(self) -> None: + pass + + def command(self, req: dict) -> Any: + if req.get("cmd") == "status": + return self.status() + assert req["cmd"] == "la", req + self.sent.append(req) + if "la" not in req: + mask = sum(1 << (la - 1) for la, on in self.on.items() if on) + return {"la_pullup_mask": mask, "pullups_available": 1} + la = req["la"] + hw = PULL_TABLE.get(la) + if self.features_rev < 3: + if "pull" in req: + raise AssertionError("old firmware got pull") + if not hw: + raise firmware_error("no pull-up on this la", cmd="la") + if "pullup" in req: + self.on[la] = req["pullup"] == "on" + return {"la": la, "pullup": int(self.on.get(la, False)), "ohms": hw.ohms, "pull": hw.default, + "pullups_available": 1} + want = req.get("pull") + if want is None and "pullup" in req: + want = (hw.default if hw else "none") if req["pullup"] == "on" else "off" + if want in ("up", "down", "none") and not hw: + raise firmware_error(f"LA{la} has no pull resistor on this board", cmd="la", code="BP0023", + values={"la": la}) + if want in ("up", "down") and want not in hw.dirs: + raise firmware_error(f"LA{la} supports pull-{hw.default} only on this board", cmd="la", + code="BP0024", values={"la": la, "want": want, "have": hw.default}) + if want is not None and hw: + self.on[la] = want != "off" + on = self.on.get(la, False) + return {"la": la, "pullup": int(on), "ohms": hw.ohms if hw else "", + "pull": hw.default if hw else "none", "state": (hw.default if on else "off") if hw else "off", + "dirs": list(hw.dirs) if hw else [], "pullups_available": 1} + + +def _bp(features_rev: int = 3) -> "tuple[BenchPod, Pod]": + pod = Pod(features_rev) + return BenchPod(transport=pod, lease=False, wiring={"version": 2}), pod + + +def test_new_firmware_gets_the_direction(): + bp, pod = _bp(3) + assert bp.supports("la_pull_dir") + st = bp.set_pull(1, "up") + assert pod.sent[-1] == {"cmd": "la", "la": 1, "pull": "up"} + assert isinstance(st, PullState) + assert st.enabled and st.state == "up" and st.direction == "up" and st.supported == ("up",) + assert st.ohms == "4.7k" + st = bp.set_pull(7, "down") + assert pod.sent[-1] == {"cmd": "la", "la": 7, "pull": "down"} and st.state == "down" + for off in ("off", None, False): + st = bp.set_pull(7, off) + assert pod.sent[-1] == {"cmd": "la", "la": 7, "pull": "off"} and st.state == "off" + assert not st.enabled and st.direction == "down" + assert bp.enabled_pulls() == [1] + + +def test_new_firmware_refusals_carry_the_code(): + bp, pod = _bp(3) + with pytest.raises(PullDirectionError) as e: + bp.set_pull(7, "up") + assert e.value.code == "BP0024" and e.value.la == 7 and e.value.want == "up" and e.value.have == "down" + assert "LA7 supports pull-down only on this board" in str(e.value) + assert isinstance(e.value, ValueError) + with pytest.raises(PullDirectionError) as e: + bp.set_pull(9, "down") + assert e.value.code == "BP0023" and e.value.la == 9 + # off is fine everywhere; a query on LA9 answers + assert bp.set_pull(9, "off").supported == () + st = bp.pull_state(12) + assert st.direction is None and st.ohms == "" and st.state == "off" + + +def test_true_false_and_enabled_still_work(): + bp, pod = _bp(3) + assert bp.set_pull(8, True).state == "down" # True = the channel's own direction + assert pod.sent[-1] == {"cmd": "la", "la": 8, "pull": "down"} + assert bp.set_pull(2, enabled=True).state == "up" + assert bp.set_pull(2, enabled=False).state == "off" + with pytest.raises(TypeError, match="needs pull"): + bp.set_pull(2) + with pytest.raises(ValueError, match="pull"): + bp.set_pull(2, "sideways") # type: ignore[arg-type] + + +def test_shortcuts(): + bp, pod = _bp(3) + bp.enable_pullup(1, 2) + bp.enable_pulldown(8) + assert [r.get("pull") for r in pod.sent] == ["up", "up", "down"] + with pytest.raises(PullDirectionError, match="LA8 supports pull-down only"): + bp.disable_pullup(8) + with pytest.raises(PullDirectionError, match="LA3 supports pull-up only"): + bp.disable_pulldown(3) + bp.disable_pulldown(8) + assert pod.sent[-1] == {"cmd": "la", "la": 8, "pull": "off"} + with pytest.raises(PullDirectionError, match="LA7 supports pull-down only"): + bp.enable_pullup(7) + + +def test_old_firmware_falls_back_to_pullup(): + bp, pod = _bp(2) + assert not bp.supports("la_pull_dir") + st = bp.set_pull(3, "up") + assert pod.sent[-1] == {"cmd": "la", "la": 3, "pullup": "on"} + assert st.state == "up" and st.supported == ("up",) and st.ohms == "2.2k" + st = bp.set_pull(3, "off") + assert pod.sent[-1] == {"cmd": "la", "la": 3, "pullup": "off"} and st.state == "off" + bp.set_pull(7, "down") + assert pod.sent[-1] == {"cmd": "la", "la": 7, "pullup": "on"} + n = len(pod.sent) + # the SDK refuses what the old firmware would do wrong (pullup:on on LA7 pulls DOWN) + with pytest.raises(PullDirectionError) as e: + bp.set_pull(7, "up") + assert e.value.code == "BP0024" and e.value.have == "down" + with pytest.raises(PullDirectionError) as e: + bp.set_pull(10, "up") + assert e.value.code == "BP0023" + # LA9-LA14: answered here, old firmware refuses the query + assert bp.set_pull(10, "off").supported == () + assert bp.pull_state(10).state == "off" + assert len(pod.sent) == n + + +def test_wiring_pulls_map_and_list(): + w = Wiring.from_dict({"version": 2, "pulls": {"1": "up", "2": "UP", "7": "down"}}) + assert w.pulls == {1: "up", 2: "up", 7: "down"} + assert w.pull_directions() == {1: "up", 2: "up", 7: "down"} + # every pull is its channel's own direction: written as the list, which older readers take + assert w.to_dict()["pulls"] == [1, 2, 7] + assert Wiring.from_dict(w.to_dict()).pull_directions() == w.pull_directions() + # an empty map stays a map (it switches every pull off, like []) + assert Wiring.from_dict({"version": 2, "pulls": {}}).to_dict()["pulls"] == {} + lst = Wiring.from_dict({"version": 2, "pulls": [8, 1]}) + assert lst.pulls == (1, 8) and lst.pull_directions() == {1: "up", 8: "down"} + assert lst.to_dict()["pulls"] == [1, 8] + for bad, msg in (({"7": "up"}, "LA7 supports pull-down only"), ({"9": "up"}, "pulls.9"), + ({"1": "sideways"}, '"up" or "down"'), ("1", "map of LA channel")): + with pytest.raises(ValueError, match=msg): + Wiring.from_dict({"version": 2, "pulls": bad}) + + +def test_la_pins_reports_the_directions(): + from embeddedci.benchpod.gpio import LaPinState + + new = LaPinState.from_reply({"la": 1, "function": "none", "pull": {"dir": "up", "ohms": "4.7k", "on": False, + "dirs": ["up"]}}) + assert new.pull_dirs == ("up",) + old = LaPinState.from_reply({"la": 7, "function": "none", "pull": {"dir": "down", "ohms": "10k", "on": True}}) + assert old.pull_dirs == ("down",) and old.pull_on + assert LaPinState.from_reply({"la": 9, "function": "none", "pull": None}).pull_dirs == () + + +def test_power_on_applies_the_map(): + bp, pod = _bp(3) + w = Wiring.from_dict({"version": 2, "la_mv": 3300, "pulls": {"2": "up", "8": "down"}}) + bp._apply_profile_pulls(w) + sent = {r["la"]: r["pull"] for r in pod.sent} + assert sent == {1: "off", 2: "up", 3: "off", 4: "off", 5: "off", 6: "off", 7: "off", 8: "down"} diff --git a/packages/embeddedci/tests/test_refusal_errors.py b/packages/embeddedci/tests/test_refusal_errors.py index 3b8660f..532d5a9 100644 --- a/packages/embeddedci/tests/test_refusal_errors.py +++ b/packages/embeddedci/tests/test_refusal_errors.py @@ -179,7 +179,7 @@ def test_pull_conflict_names_set_pull(): 'idles high); disable it with {"cmd":"la","la":7,"pullup":"off"} or use another channel') err = firmware_error(fw, cmd="uart_proxy_start") assert type(err) is PullConflictError and err.la == 7 - assert str(err).endswith("disable it with bp.set_pull(7, False) or use another channel") + assert str(err).endswith('disable it with bp.set_pull(7, "off") or use another channel') assert err.firmware_message == fw