Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/embeddedci-mcp/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## 3.0.2

- `wiring` returns `board_header` and `header_map`: the profile on the pod's real I/O header as
text (each pin in its place, then what to connect to it), for showing the user how to wire the
board.
- Needs embeddedci 3.0.2. `uart_open`, `capture_uart` and `power_cycle_and_capture` take the
frame from the wiring profile (`uart_parity`, `uart_stop_bits`) when `parity` / `stop_bits` are
omitted; `uart_open` reports the frame it used.
Expand Down
2 changes: 1 addition & 1 deletion packages/embeddedci-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ description, ranges and enums, so an agent sees more than this table.

| Tool | Purpose | Parameters |
| --- | --- | --- |
| `wiring` | Which DUT signal is on which LA channel, plus the I/O voltage, power rail, UART baud and SWD target; the profiles stored on the pod and `unsaved_changes` (what this connection changed that is not stored). What a profile does not set is undefined. | none |
| `wiring` | Which DUT signal is on which LA channel, plus the I/O voltage, power rail, UART baud and SWD target; the profiles stored on the pod and `unsaved_changes` (what this connection changed that is not stored); `board_header` and `header_map`, the profile on the pod's real I/O header as text (each pin in its place, then what to connect to it). What a profile does not set is undefined. | none |
| `set_wiring` | Replace the wiring profile for this connection only (version 2: what it leaves out is undefined); `save=true`, or the server's `--wiring-autosave`, also stores it on the pod. Autosave never stores a change of the I/O voltage, rail or SWD target. Also sends the profile's pin directions to the pod (`la_dir`, firmware 3.10.4+). | **`profile`**, `save=false` |
| `save_wiring` | Store this connection's profile (or `profile`) on the pod, under `name` or the profile it was loaded from. Saving the loaded profile refuses with `BP0009` when someone else saved it meanwhile. Never changes the pod's default. | `name`, `profile` |
| `load_wiring` | Switch this connection to a profile stored on the pod (omit `name`: the pod's default). Nothing on the pod changes. | `name` |
Expand Down
7 changes: 7 additions & 0 deletions packages/embeddedci-mcp/src/embeddedci_mcp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,13 @@ class WiringResult(BaseModel):
directions: Optional[str] = Field(None, description=(
"'sent' when the pod has the profile's pin directions (la_dir: sent on connect and by "
"set_wiring), else 'not sent: <why>' (older firmware, or a DUT output pin driven right now)."))
board_header: Optional[str] = Field(None, description=(
"The pod's I/O header: 'j1' (2x11 pin headers, one-piece boards up to v3-r2) or 'front' "
"(2x13 connector on the front of digital v3r3 and later); null when the pod cannot tell."))
header_map: Optional[str] = Field(None, description=(
"The profile on that header as text: each header pin in its physical place, then what to "
"connect to each pin on the user's board. Show it to the user when they ask how to wire the "
"board; both headers when board_header is null."))


# -- LA pin ownership + GPIO -------------------------------------------------------
Expand Down
15 changes: 14 additions & 1 deletion packages/embeddedci-mcp/src/embeddedci_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@
Wiring,
i2c,
)

try: # embeddedci 3.0.2+: the profile on the pod's header as text
from embeddedci.benchpod import header_map
except ImportError: # pragma: no cover - older SDK: wiring leaves board_header/header_map null
header_map = None # type: ignore[assignment]

from embeddedci.benchpod import decode as sdk_decode
from embeddedci.benchpod.capabilities import Capabilities
from embeddedci.benchpod.client import API_BASE_ENV, API_KEY_ENV
Expand Down Expand Up @@ -542,14 +548,21 @@ async def wiring() -> m.WiringResult:
Returns the profile this connection uses (normally a profile stored on the pod: profile_name,
the pod's default unless connect named another): a 14-row pin table, the named signals, the
power rail, the UART baud and the SWD target, warnings about risky wiring, the pod's stored
profiles and unsaved_changes (what set_wiring changed that is not stored yet). Every tool whose
profiles and unsaved_changes (what set_wiring changed that is not stored yet), and header_map:
the profile on the pod's real I/O header as text, to show the user how to wire their board. Every tool whose
channel, baud, rail or SWD arguments are omitted takes them from this profile; what the profile
does not set is undefined, and a tool that needs it says so: ask the user, never guess a pin.
"""
def op() -> m.WiringResult:
pod = SESSION.require()
result = wiring_summary(pod.wiring)
result.directions = pod.pin_directions_status
if header_map is not None and hasattr(pod, "board_header"):
try:
result.board_header = pod.board_header()
except Exception: # noqa: BLE001 - the pin map is extra: a pod that cannot say gets both headers
result.board_header = None
result.header_map = header_map(pod.wiring, result.board_header)
return _pod_wiring_state(pod, result)

return await _call(op)
Expand Down
16 changes: 16 additions & 0 deletions packages/embeddedci-mcp/tests/test_wiring_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,19 @@ def test_set_wiring_takes_back_what_wiring_returned(connected):
result = call("set_wiring", profile={**profile, "swd_target": "target/stm32f4x.cfg"})
assert result["swd_target"] == "target/stm32f4x.cfg"
assert SESSION.require().wiring.extra["loop_output_max_v"] == 3.3


def test_wiring_draws_the_profile_on_the_pods_header(connected, monkeypatch):
from embeddedci_mcp import server
if server.header_map is None:
pytest.skip("embeddedci < 3.0.2 has no header_map")
_set()
pod = SESSION.require()
monkeypatch.setattr(type(pod), "board_header", lambda self: "front")
result = call("wiring")
assert result["board_header"] == "front"
assert result["header_map"].startswith("Front connector (2x13)")
assert "pin 7 (LA7, UART RX) -> board TX" in result["header_map"]
monkeypatch.setattr(type(pod), "board_header", lambda self: None)
result = call("wiring")
assert result["board_header"] is None and "both are shown" in result["header_map"]
5 changes: 5 additions & 0 deletions packages/embeddedci/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## 3.0.2

- **The profile on the pod's header:** `BenchPod.board_header()` says which I/O header the pod has
(`"j1"`, the 2x11 pin headers up to v3-r2, or `"front"`, the 2x13 front connector of digital v3r3
and later; asked once per connection with the read-only `module` command), and
`header_map(wiring, header)` writes the profile on it as text: every pin in its place, then what
to connect to it.
- **UART frame in the wiring profile:** `Wiring.uart_parity` (`"none"`, `"even"`, `"odd"`) and
`Wiring.uart_stop_bits` (1, 2), next to `uart_baud`. `open_uart`, `capture_uart` and
`power_cycle_and_capture` take them from the profile when `parity` / `stop_bits` are omitted
Expand Down
13 changes: 13 additions & 0 deletions packages/embeddedci/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,19 @@ A file holds the same JSON object the pod stores:
`bp.signal(name)` returns a GPIO handle for a signal (see [GPIO on the LA pins](#gpio-on-the-la-pins));
channel arguments accept a role or signal name too (`bp.open_uart(rx="uart_rx", tx=4)`).

**The profile on the pod's header.** `bp.board_header()` says which I/O header the pod has:
`"j1"` (the 2x11 pin headers of the one-piece boards up to v3-r2) or `"front"` (the 2x13 connector
on the front of digital v3r3 and later), None when the pod cannot tell. `header_map(wiring, header)`
writes the profile on that header as text: every pin in its physical place, then what to connect
to each pin on your board (header None writes both headers). The web and desktop apps draw the same
thing from the Pins pane's Visualize button.

```python
from embeddedci.benchpod import header_map

print(header_map(bp.wiring, bp.board_header()))
```

## Power, reset and power monitoring

```python
Expand Down
2 changes: 2 additions & 0 deletions packages/embeddedci/src/embeddedci/benchpod/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,13 @@ def test_boots(benchpod_target, firmware): # fixtures from the pytest plugin
from .motor_emulator import BatteryModel, EmulatorCalibration, MotorEmulator
from .waveforms import Waveform, WaveformLibrary
from .wiring import Signal, Wiring
from .header import header_map

__all__ = [
"BenchPod",
# wiring profile
"Wiring",
"header_map",
"Signal",
# LA pin modes + GPIO
"GpioPin",
Expand Down
27 changes: 27 additions & 0 deletions packages/embeddedci/src/embeddedci/benchpod/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1805,6 +1805,33 @@ def calibrate_adc_gain(self, source: AdcGainSource, *, range: AdcRange = "normal

# -- The analog module (two-board BenchPod, digital v3r3) -------------------

def board_header(self) -> Optional[str]:
"""Which I/O header this pod has: ``"front"`` (the 2x13 connector on the front of digital
v3r3 and later) or ``"j1"`` (the 2x11 pin headers of the one-piece boards up to v3-r2);
None when the pod cannot tell. Asked once per connection: the read-only ``module`` command
(it answers on a module-link board and refuses on the others, over the cloud too), else the
status. :func:`~embeddedci.benchpod.header.header_map` writes the wiring on it."""
cached = getattr(self, "_board_header", False)
if cached is not False:
return cached
from .header import header_from_status

header: Optional[str] = None
try:
self.command({"cmd": "module"})
header = "front"
except UnsupportedFeatureError:
header = None
except BenchPodError as e:
header = "j1" if "no module link" in str(e).lower() else None
if header is None:
try:
header = header_from_status(self.status())
except BenchPodError:
header = None
self._board_header = header
return header

def module(self) -> ModuleInfo:
"""The analog module and its EEPROM: identity, revision, serial and stored calibration.

Expand Down
142 changes: 142 additions & 0 deletions packages/embeddedci/src/embeddedci/benchpod/header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""The pod's I/O header, pin by pin, with a wiring profile on it.

Two headers exist:

* ``"j1"``: the 2x11 J1 of the one-piece boards up to v3-r2, seen from above: pin 1 (the square
pad) at the bottom right, at the ADC/DAC end; even pins along the board edge.
* ``"front"``: the 2x13 right-angle connector on the front of digital v3r3 and later, seen facing
the front of the enclosure: pin 1 at the top right, odd pins along the top.

:func:`header_map` writes a profile on a header as plain text (for a terminal, a log or an AI
agent); the web and desktop apps draw the same thing (their Pins pane's Visualize button).
"""

from __future__ import annotations

from typing import Any, Dict, List, Mapping, Optional, Tuple

from .constants import PULL_OHMS, PULLDOWN_CHANNELS
from .wiring import ROLE_KEYS, Wiring

HEADERS: Tuple[str, ...] = ("j1", "front")

_COMMON: List[Tuple[int, str]] = [(n, f"LA{n}") for n in range(1, 15)] + [
(15, "GND"), (16, "GND"), (17, "+3V3"), (18, "+1V8"), (19, "CAN+"), (20, "CAN-"),
(21, "LA_REF"), (22, "NRST_CONTROL"),
]

#: Every pin of each header, pin 1 first: ``(pin number, name)``.
HEADER_PINS: Dict[str, List[Tuple[int, str]]] = {
"j1": _COMMON,
"front": _COMMON + [(n, "GND") for n in (23, 24, 25, 26)],
}

_ROLE_LABELS = {
"uart_rx": "UART RX", "uart_tx": "UART TX", "i2c_sda": "I2C SDA", "i2c_scl": "I2C SCL",
"swd_swclk": "SWCLK", "swd_swdio": "SWDIO", "spi_sclk": "SPI SCLK", "spi_mosi": "SPI MOSI",
"spi_miso": "SPI MISO", "spi_cs": "SPI CS",
}
_ROLE_CONNECT = {
"uart_rx": "board TX", "uart_tx": "board RX", "i2c_sda": "SDA", "i2c_scl": "SCL",
"swd_swclk": "SWCLK", "swd_swdio": "SWDIO", "spi_sclk": "SCLK", "spi_mosi": "MOSI (board SDI)",
"spi_miso": "MISO (board SDO)", "spi_cs": "CS",
}
_SIGNAL_USE = {"input": "the pod reads it", "output": "the pod drives it", "open_drain": "open drain",
"bidir": "open drain"}


def header_from_status(status: Optional[Mapping[str, Any]]) -> Optional[str]:
"""The header from a status reply: ``module`` in the full status means digital v3r3 or later
(``"front"``); board_rev v2 or v3r2 is a one-piece board (``"j1"``). None when it cannot tell
(the cloud's short status, or board_rev "v3", which both kinds report)."""
if not status:
return None
if status.get("module") is not None:
return "front"
if status.get("board_rev") in ("v2", "v3r2"):
return "j1"
return None


def _is_la(name: str) -> bool:
return name.startswith("LA") and name[2:].isdigit()


def _uses(w: Wiring, la: int) -> List[Tuple[str, str]]:
"""``(label, connect to)`` for everything the profile puts on an LA channel."""
out: List[Tuple[str, str]] = []
for key in ROLE_KEYS:
if getattr(w, key) == la:
out.append((_ROLE_LABELS.get(key, key), _ROLE_CONNECT.get(key, key)))
for s in w.signals:
if s.la == la:
out.append((s.name, f"{s.name} ({_SIGNAL_USE.get(s.direction, 'the pod reads it')})"))
return out


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:
return None
return f"pull-{'down' if la in PULLDOWN_CHANNELS else 'up'} {ohms} on"


def _cell(w: Wiring, n: int, name: str) -> str:
"""'3 LA3 UART RX' / '22 NRST_CONTROL DUT reset' / '9 LA9 -'."""
if _is_la(name):
uses = _uses(w, n)
return f"{n} {name} " + (" / ".join(u for u, _ in uses) if uses else "-")
if name == "NRST_CONTROL" and w.swd_nreset:
return f"{n} {name} DUT reset"
return f"{n} {name}"


def connections(w: Wiring, header: str = "j1") -> List[Dict[str, Any]]:
"""What to connect, one entry per used header pin plus ground:
``[{"pin": 3, "name": "LA3", "used_for": "UART RX", "connect": "board TX", "pull": "pull-up 2.2k on"}, ...]``."""
out: List[Dict[str, Any]] = []
for n, name in HEADER_PINS[header]:
if _is_la(name):
uses = _uses(w, n)
if uses:
out.append({"pin": n, "name": name, "used_for": " / ".join(u for u, _ in uses),
"connect": " / ".join(c for _, c in uses), "pull": _pull(w, n)})
elif name == "NRST_CONTROL" and w.swd_nreset:
out.append({"pin": n, "name": name, "used_for": "Reset", "connect": "board NRST", "pull": None})
gnd = [n for n, name in HEADER_PINS[header] if name == "GND"]
out.append({"pin": gnd, "name": "GND", "used_for": "Ground", "connect": "board GND (any one)", "pull": None})
return out


def header_map(w: Wiring, header: Optional[str] = None) -> str:
"""The profile on the pod's header as plain text: the pins in their physical places, then what
to connect to each. ``header`` is ``"j1"`` or ``"front"`` (:meth:`BenchPod.board_header`);
None writes both (the pod did not say which it has)."""
if header is None:
return ("The pod did not say which header it has; both are shown.\n\n"
+ header_map(w, "j1") + "\n\n" + header_map(w, "front"))
if header not in HEADERS:
raise ValueError(f"header must be one of {', '.join(HEADERS)}")
names = dict(HEADER_PINS[header])
lines: List[str] = []
if header == "j1":
lines.append("Pin headers J1 (2x11), looking down at the pod: pin 1 (square pad) at the bottom right, "
"the ADC/DAC end at the bottom, even pins along the board edge on the left.")
rows = [(_cell(w, p + 1, names[p + 1]), _cell(w, p, names[p])) for p in range(21, 0, -2)]
width = max(len(left) for left, _ in rows)
lines.append(f" {'board edge side'.ljust(width)} | other side")
lines += [f" {left.ljust(width)} | {right}" for left, right in rows]
else:
lines.append("Front connector (2x13), facing the front of the pod: pin 1 (square pad) at the top "
"right, odd pins on the top row.")
cols = [(_cell(w, p, names[p]), _cell(w, p + 1, names[p + 1])) for p in range(25, 0, -2)]
width = max(len(top) for top, _ in cols)
lines.append(f" column {'top row'.ljust(width)} | bottom row")
lines += [f" {i + 1:>2} {top.ljust(width)} | {bottom}" for i, (top, bottom) in enumerate(cols)]
lines.append(" (column 1 is the left end as you face the pod)")
lines.append("Connect:")
for c in connections(w, header):
pin = ", ".join(str(n) for n in c["pin"]) if isinstance(c["pin"], list) else str(c["pin"])
pull = f" [{c['pull']}]" if c["pull"] else ""
lines.append(f" pin {pin} ({c['name']}, {c['used_for']}) -> {c['connect']}{pull}")
return "\n".join(lines)
3 changes: 3 additions & 0 deletions packages/embeddedci/tests/api_surface.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"adc_read": "(self, source: 'AdcSource' = 'ext', *, range: 'Optional[AdcRange]' = None) -> 'AdcReading'",
"analog_path": "(self, path: 'AnalogPath', *, range: 'Optional[AdcRange]' = None) -> 'AnalogPathState'",
"apply_pin_directions": "(self, wiring: 'Optional[Wiring]' = None) -> 'List[LaPinState]'",
"board_header": "(self) -> 'Optional[str]'",
"calibrate": "(self, source: 'CalibrateSource' = 'current_in') -> 'Calibration'",
"calibrate_adc_gain": "(self, source: 'AdcGainSource', *, range: 'AdcRange' = 'normal') -> 'Calibration'",
"calibrate_dac": "(self, path: 'DacCalPath', points: 'Sequence[Tuple[int, float]]') -> 'Calibration'",
Expand Down Expand Up @@ -1457,6 +1458,7 @@
"encode_curve_b64url",
"expansion_chip",
"forget_lan_tls",
"header_map",
"i2c",
"input_percent_to_code",
"load_definition",
Expand All @@ -1480,6 +1482,7 @@
"encode_curve_b64url": "(codes: 'Sequence[int]') -> 'str'",
"expansion_chip": "(name: 'str') -> 'ExpansionChip'",
"forget_lan_tls": "(host: 'str', port: 'int' = 8080) -> 'bool'",
"header_map": "(w: 'Wiring', header: 'Optional[str]' = None) -> 'str'",
"i2c": "module",
"input_percent_to_code": "(percent: 'float') -> 'int'",
"load_definition": "(source: 'DefinitionSource', *, library: \"Optional['SensorLibrary']\" = None, base_dir: \"Union[str, 'os.PathLike[str]', None]\" = None) -> 'Dict[str, Any]'",
Expand Down
Loading