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
13 changes: 13 additions & 0 deletions packages/embeddedci-mcp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog — `embeddedci-mcp`

## 4.0.2

Not released yet. Needs embeddedci 4.0.2.

- **`decode_la` decodes USB** full and low speed: `protocol="usb"`, `dp`, `dm`, `speed`
(`auto`, `full`, `low`). `items` are transactions, `transfers` the control transfers (an
enumeration as a list), with `speed`, `errors` and `sof_count`. `benchpod://capture/decode`
carries the packets, transactions and transfers.
- **`decode_la` decodes Modbus RTU, CAN / CAN FD, PWM, 1-Wire and SMBus/PMBus:** new
arguments `tx` (Modbus two-line tap), `can`, `bitrate`, `data_bitrate`, `sample_point`,
`channels` and `servo` (PWM), `onewire`, `pec`. `items` has one line per frame, transaction or channel;
`errors` counts the bad ones. `benchpod://capture/decode` carries the full results.

## 4.0.1

For BenchPod firmware 4.0.1; needs embeddedci 4.0.1.
Expand Down
4 changes: 2 additions & 2 deletions packages/embeddedci-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ version the SDK pins (0.1.0, bundled) unless `BENCHPOD_SENSOR_LIBRARY`, the CLI'
| `capture_adc` | Capture the ADC: calibrated statistics, dominant frequency and a min/max envelope; `clipped_samples` counts samples past the range's full scale. `oversample` converts at 400 kS/s and averages down to `sample_rate_hz` for lower noise, about 5 s at most. | `samples=4096`, `sample_rate_hz`, `source`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `range`, `oversample` |
| `capture_la` | Capture all 14 LA channels: levels, edge count, first edge and frequency per channel. Up to 48 MS/s on gateware v50+. `send` (gateware v55+) runs one transaction right after the capture arms: `{"bus":"i2c","addr":118,"write_hex":"d0","read":1}` (the `i2c_open` session, else one from the wiring), `{"bus":"spi","tx_hex":"9f00"}` (SPI pins from the wiring) or `{"bus":"gpio","la":6,"level":0}` (a GPIO output); without `trigger_la` it triggers on SDA or CS falling or the pin's edge, and the result's `send` has the reply. | `samples=4096`, `sample_rate_hz`, `stop_dac_after_s`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `trigger_pre_samples=0`, `send` |
| `capture_correlated` | ADC and LA from one hardware trigger, on one timebase. | `adc_samples=4096`, `adc_sample_rate_hz`, `la_samples=4096`, `la_sample_rate_hz`, `stop_dac_after_s`, `points=200`, `trigger_la`, `trigger_edge=rising`, `trigger_timeout_s=10`, `source` |
| `decode_la` | Decode I2C, UART or SPI from the last LA capture (or a new one). | **`protocol`**, `sda`, `scl`, `rx`, `baud`, `sclk`, `mosi`, `miso`, `cs`, `mode=0`, `capture=last`, `samples=16384`, `sample_rate_hz=1000000`, `max_items=200` |
| `decode_la` | Decode I2C, UART, SPI, USB, Modbus RTU, CAN / CAN FD, PWM, 1-Wire, SMBus or PMBus from the last LA capture (or a new one). USB (full speed at 48 MS/s, low speed from 6 MS/s) returns transactions as `items` and the control transfers as `transfers`: an enumeration as a list. CAN needs 6 samples per data bit. | **`protocol`**, `sda`, `scl`, `rx`, `baud`, `sclk`, `mosi`, `miso`, `cs`, `mode=0`, `dp`, `dm`, `speed=auto`, `tx`, `can`, `bitrate`, `data_bitrate`, `sample_point`, `channels`, `servo=false`, `onewire`, `pec=auto`, `capture=last`, `samples=16384`, `sample_rate_hz=1000000`, `max_items=200` |
| `la_timing` | Edge timestamps, pulse widths, frequency, duty cycle and channel-to-channel delay from the last capture. | **`la`**, `edge=rising`, `to_la`, `to_edge=rising`, `after=0`, `max_edges=100` |

### DAC
Expand Down Expand Up @@ -423,7 +423,7 @@ in an app (the BenchPod desktop app's capture view), three more give the last ca
|---|---|
| `benchpod://capture/la` | The last `capture_la` / `capture_correlated` as run-length `edges`, `[sample index, 14-bit word]` from sample 0, plus `sample_rate_hz`, `count`, `pre_samples`, `seq`, `correlated`. |
| `benchpod://capture/adc` | The last `capture_adc` / `capture_correlated`: `samples` in volts (or mA for `current_in`), `unit`, `sample_rate_hz`, `source`, `seq`, `correlated`. |
| `benchpod://capture/decode` | The last `decode_la`: `protocol`, `channels`, and I2C `transactions` with timed segments, or UART / SPI `frames` with `start_us` / `end_us`; `seq` is the capture it decoded. |
| `benchpod://capture/decode` | The last `decode_la`: `protocol`, `channels`, and I2C `transactions` with timed segments, UART / SPI / Modbus / CAN `frames` with `start_us` / `end_us`, USB `packets`, `transactions` and `transfers`, 1-Wire and SMBus `transactions`, or PWM `channels`; `seq` is the capture it decoded. |

Each is `{"seq": 0}` before the first capture. `seq` numbers the captures, and `correlated` says
the LA and ADC captures share one timebase. They can be megabytes: an agent should read the
Expand Down
2 changes: 1 addition & 1 deletion packages/embeddedci-mcp/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ classifiers = [
dependencies = [
# cloud: the embeddedci:<device> destination; discovery: connect("discover") over mDNS;
# analysis: dominant frequency in capture summaries; yaml: sensor definitions an agent writes.
"embeddedci[cloud,discovery,analysis,yaml]>=4.0.1,<5",
"embeddedci[cloud,discovery,analysis,yaml]>=4.0.2,<5",
"mcp>=1.12,<2",
"anyio>=4",
"pydantic>=2.7",
Expand Down
2 changes: 1 addition & 1 deletion packages/embeddedci-mcp/src/embeddedci_mcp/guide.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
- 4-20 mA input: adc_read(source='current_in') reads terminal J8 and returns current in amps (0.004 to 0.020 for a live loop) next to the voltage across the sense resistor (249 ohm; from analog module v3r5 100 ohm behind a 30 mA limiter, read in the low range by default, so a reading stuck near 28.5 to 31.5 mA is the limiter). calibration shows whether the pod has calibrated its ADC offset there. If not, analog readings can be off by up to about 50 mV: ask the user to disconnect J8, then calibrate (once per pod, stored on the pod; it corrects every ADC source).
- 4-20 mA output: current_out(current) holds a loop current on terminal J9, in amps (0.012 is 12 mA), and returns the current actually held and the range. It needs an external floating loop supply on J9 and cannot go below about 4 mA or above about 20 mA. It shares the DAC with the voltage outputs and switches them off; dac_stop does not return the loop to 4 mA, current_out(0.004) does. The loop must float: nothing in it may touch pod ground, also not through a target that shares a ground with the pod (SWD, UART). Ask the user how J9 is wired first, and never suggest wiring J9 straight into J8. generate and replay take dac_path='current_out' to play a waveform as a current (levels in amps); capture_adc(source='current_in') summarises the loop current in amps.
- Gateware images: the FPGA runs either the 'loop' image (control_loop) or the 'deep_replay' image (replays longer than 2048 samples). control_loop and replay switch automatically (~3 s; switched_image in the result says so). A switch resets the FPGA and stops any DAC output, UART session or sensor emulation, so start those after it. fpga_image switches explicitly. I2C/SPI/UART sensors run on a third, emulation image that sensor_start loads by itself (control_loop and deep replays are unavailable while it runs).
- Logic: capture_la, then decode_la (i2c/uart/spi) re-decodes that capture without re-capturing, and la_timing measures edge times, pulse widths, frequency and the delay between two channels (e.g. trigger pin to result pin).
- Logic: capture_la, then decode_la (i2c/uart/spi/usb/modbus/can/pwm/onewire/smbus/pmbus; usb full speed needs a 48 MS/s capture) re-decodes that capture without re-capturing, and la_timing measures edge times, pulse widths, frequency and the delay between two channels (e.g. trigger pin to result pin).
- Triggers: capture_adc, capture_la and capture_correlated take trigger_la (+ trigger_edge rising/falling/high/low, trigger_timeout seconds) to start on an event rather than immediately, so t = 0 is that edge. Without the trigger firing the tool fails with "TriggerTimeout: ...".
- Power profiles: measure_power(duration) reports the DUT's average/minimum/peak current, voltage, energy and charge over a window, with an optional trace (points). To profile across other tool calls, bracket them with power_profile_start and power_profile_stop.
- CAN: can_open (mode 'internal' self-tests a lone pod), can_write, can_read, can_respond, can_close.
Expand Down
6 changes: 6 additions & 0 deletions packages/embeddedci-mcp/src/embeddedci_mcp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,12 @@ class DecodeResult(BaseModel):
items: List[str]
truncated: bool
text: Optional[str] = Field(None, description="UART only: the decoded bytes as text.")
speed: Optional[str] = Field(None, description="USB only: full or low.")
transfers: Optional[List[str]] = Field(None, description=(
"USB only: one line per control transfer (request, status, descriptor read back)."))
errors: Optional[int] = Field(None, description=(
"USB, Modbus, CAN, 1-Wire, SMBus/PMBus: packets, frames or transactions with an error."))
sof_count: Optional[int] = Field(None, description="USB only: start-of-frame packets (left out of items).")


# -- DAC ------------------------------------------------------------------------------
Expand Down
153 changes: 146 additions & 7 deletions packages/embeddedci-mcp/src/embeddedci_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2367,16 +2367,41 @@ async def decode_la(
miso: Optional[LaPin] = None,
cs: Optional[LaPin] = None,
mode: Literal[0, 1, 2, 3] = 0,
dp: Annotated[Optional[LaPin], Field(description="usb: the channel on D+.")] = None,
dm: Annotated[Optional[LaPin], Field(description="usb: the channel on D-.")] = None,
speed: Annotated[Literal["auto", "full", "low"], Field(description=(
"usb: full (12 Mbit/s), low (1.5 Mbit/s) or auto (from the idle state)."))] = "auto",
tx: Annotated[Optional[LaPin], Field(description=(
"modbus: the other direction on a two-line tap (rx alone for an RS-485 receive output)."))] = None,
can: Annotated[Optional[LaPin], Field(description="can: the transceiver's RXD (or the controller's TX/RX).")] = None,
bitrate: Annotated[Optional[float], Field(gt=0, le=5_000_000, description="can: nominal bit rate, bit/s.")] = None,
data_bitrate: Annotated[Optional[float], Field(gt=0, le=12_000_000, description=(
"can: CAN FD data bit rate, bit/s (left out: the nominal rate)."))] = None,
sample_point: Annotated[Optional[float], Field(gt=0, lt=1, description=(
"can: where a bit is read, as a fraction of it (default 0.75)."))] = None,
channels: Annotated[Optional[List[LaPin]], Field(description="pwm: the channels to measure.")] = None,
servo: Annotated[bool, Field(description="pwm: also read the high pulses as servo positions (1 ms = 0 %, 2 ms = 100 %).")] = False,
onewire: Annotated[Optional[LaPin], Field(description="onewire: the bus line.")] = None,
pec: Annotated[Literal["auto", "on", "off"], Field(description=(
"smbus/pmbus: auto = a trailing byte that matches is a PEC; on = every transaction ends in one."))] = "auto",
capture: Annotated[Literal["last", "new"], Field(description=(
"last = decode the previous capture_la; new = capture first (needs samples/sample_rate_hz)."))] = "last",
samples: Samples = 16384,
sample_rate_hz: Annotated[float, Field(gt=0, le=50_000_000)] = 1_000_000,
max_items: Annotated[int, Field(ge=1, le=5000)] = 200,
) -> m.DecodeResult:
"""Decode I2C (sda, scl), UART (rx, baud) or SPI (sclk + mosi/miso/cs, mode) from LA data.

Sample at least ~10x the bit rate. Decoding the last capture again with other channels is free.
"""Decode I2C (sda, scl), UART (rx, baud), SPI (sclk + mosi/miso/cs, mode), USB (dp, dm,
speed), Modbus RTU (rx, baud, tx), CAN/CAN FD (can, bitrate, data_bitrate), PWM (channels),
1-Wire (onewire) or SMBus/PMBus (sda, scl, pec) from LA data.

Sample at least ~10x the bit rate; USB full speed needs a 48 MS/s capture, low speed 6 MS/s;
CAN 6 samples per data bit; 1-Wire 1 MS/s (4 MS/s in overdrive).
USB items are transactions (token, data, handshake; repeated NAKs merged), transfers the
control transfers with the SETUP request and descriptors decoded (an enumeration).
Decoding the last capture again with other channels is free.
"""
channels_arg = channels or []

def op() -> m.DecodeResult:
pod = SESSION.require()
if protocol == "i2c" and (sda is None or scl is None):
Expand All @@ -2385,21 +2410,61 @@ def op() -> m.DecodeResult:
raise ValueError("uart needs rx and baud")
if protocol == "spi" and sclk is None:
raise ValueError("spi needs sclk")
if protocol == "usb" and (dp is None or dm is None):
raise ValueError("usb needs dp and dm")
if protocol == "modbus" and (rx is None or baud is None):
raise ValueError("modbus needs rx and baud")
if protocol == "can" and (can is None or bitrate is None):
raise ValueError("can needs can (the channel) and bitrate")
if protocol == "pwm" and not channels_arg:
raise ValueError("pwm needs channels")
if protocol == "onewire" and onewire is None:
raise ValueError("onewire needs onewire (the channel)")
if protocol in ("smbus", "pmbus") and (sda is None or scl is None):
raise ValueError(f"{protocol} needs sda and scl")
if protocol == "usb":
try:
from embeddedci.benchpod import usb_decode
except ImportError:
raise ValueError("usb decode needs embeddedci 4.0.2 or later: pip install -U embeddedci") from None
la = SESSION.last_la
if capture == "new" or la is None:
la = pod.capture_la(samples, sample_rate_hz=sample_rate_hz)
SESSION.last_la = la
channels = {k: v for k, v in (("sda", sda), ("scl", scl), ("rx", rx), ("baud", baud),
("sclk", sclk), ("mosi", mosi), ("miso", miso), ("cs", cs))
("sclk", sclk), ("mosi", mosi), ("miso", miso), ("cs", cs),
("dp", dp), ("dm", dm), ("tx", tx), ("can", can),
("bitrate", bitrate), ("data_bitrate", data_bitrate),
("sample_point", sample_point), ("onewire", onewire))
if v is not None}
if protocol == "pwm":
channels["channels"] = list(channels_arg)
channels["servo"] = servo
if protocol in ("smbus", "pmbus"):
channels["pec"] = pec
if protocol == "spi":
channels["mode"] = mode
if protocol == "usb":
channels["speed"] = speed
frames = pod.decode(la, protocol, **channels)
try:
SESSION.last_decode = _decode_view(la, protocol, channels, frames)
except Exception: # the capture view's copy never fails the decode itself
SESSION.last_decode = None
text = None
if protocol == "usb":
items = usb_decode.format_transactions(frames)
transfers = usb_decode.format_transfers(frames)
return m.DecodeResult(protocol=protocol, count=len(items), items=items[:max_items],
truncated=len(items) > max_items, speed=frames.speed,
transfers=transfers[:max_items], errors=frames.error_count,
sof_count=frames.sof_count)
if protocol in _LA_FORMATTERS:
items = _LA_FORMATTERS[protocol](frames)
n = len(frames.channels) if protocol == "pwm" else len(frames)
errors = 0 if protocol == "pwm" else sum(1 for f in frames if not f.ok)
return m.DecodeResult(protocol=protocol, count=n, items=items[:max_items],
truncated=len(items) > max_items, errors=errors)
if protocol == "i2c":
items = i2c.format_transactions(frames).splitlines()
elif protocol == "uart":
Expand All @@ -2414,6 +2479,72 @@ def op() -> m.DecodeResult:
return await _call(op)


def _t(us: float) -> str:
return f"{us / 1e6:.6f}s"


def _fmt_modbus(frames) -> List[str]:
return [f"{_t(f.start_us)} {f.role} addr {f.addr} {f.summary}" + ("" if f.ok else f" error={f.error}")
for f in frames]


def _fmt_can(frames) -> List[str]:
out = []
for f in frames:
kind = "" if f.kind == "data" else f" {f.kind}"
fd = (" FD" + (" BRS" if f.brs else "")) if f.fd else ""
out.append(f"{_t(f.start_us)} {f.id_hex}{kind}{fd} [{f.len}] {f.data_hex}".rstrip()
+ ("" if f.ok else f" error={f.error}"))
return out


def _fmt_pwm(res) -> List[str]:
out = []
for c in res.channels:
if not c.count:
out.append(f"LA{c.channel}: no full period (level {c.level})")
continue
line = (f"LA{c.channel}: {c.count} periods, {c.freq_hz.mean:.6g} Hz ({c.freq_hz.min:.6g}-{c.freq_hz.max:.6g}), "
f"duty {100 * c.duty.mean:.2f} % ({100 * c.duty.min:.2f}-{100 * c.duty.max:.2f}), "
f"high {c.high_us.mean:.4g} us, jitter {c.jitter_us:.3g} us")
if c.glitches:
line += f", {c.glitches} glitches"
if c.servo:
line += f", servo {c.servo.pulse_ms.mean:.3f} ms ({c.servo.position_pct.mean:.1f} %)"
out.append(line)
return out


def _fmt_onewire(tx) -> List[str]:
out = []
for t in tx:
parts = [_t(t.start_us), "reset" if t.reset else "(no reset)"]
if t.reset:
parts.append("presence" if t.presence else "no presence")
if t.overdrive:
parts.append("overdrive")
parts += [p for p in (t.rom_command_name, t.rom, t.function, t.detail) if p]
if t.bytes_hex:
parts.append(f"[{t.bytes_hex}]")
out.append(" ".join(parts) + ("" if t.ok else f" error={t.error}"))
return out


def _fmt_smbus(tx) -> List[str]:
out = []
for t in tx:
cmd = t.command_name or (f"cmd 0x{t.command:02X}" if t.command is not None else "")
parts = [p for p in (_t(t.start_us), t.addr_hex, t.kind, cmd, t.data_hex, t.value) if p]
if t.pec != "none":
parts.append(f"PEC {t.pec}")
out.append(" ".join(parts) + ("" if t.ok else f" error={t.error}"))
return out


_LA_FORMATTERS = {"modbus": _fmt_modbus, "can": _fmt_can, "pwm": _fmt_pwm, "onewire": _fmt_onewire,
"smbus": _fmt_smbus, "pmbus": _fmt_smbus}


def _pulse_stats(widths: List[float]) -> m.PulseStats:
if not widths:
return m.PulseStats(count=0)
Expand Down Expand Up @@ -3006,7 +3137,13 @@ def _decode_view(la: Any, protocol: str, channels: Dict[str, Any], frames: Any)
frames (the EmbeddedCI web app's decode result)."""
view: Dict[str, Any] = {"seq": SESSION.la_seq, "protocol": protocol,
"channels": {k: v for k, v in channels.items()}}
if protocol == "i2c":
if protocol in ("usb", "pwm"):
view.update({k: v for k, v in frames.as_dict().items() if k != "protocol"})
elif protocol in ("modbus", "can"):
view["frames"] = [f.as_dict() for f in frames]
elif protocol in ("onewire", "smbus", "pmbus"):
view["transactions"] = [t.as_dict() for t in frames]
elif protocol == "i2c":
view["transactions"] = i2c.timed_transactions(la.words, channels["sda"], channels["scl"],
la.sample_rate_hz)
else:
Expand Down Expand Up @@ -3063,8 +3200,10 @@ def capture_adc_resource() -> str:

@mcp.resource("benchpod://capture/decode", name="capture_decode_data", mime_type="application/json",
title="Last decode, with timing",
description=("The last decode_la in full: I2C transactions with timed segments, or UART / "
"SPI frames, for drawing on the capture. seq is the capture it decoded."))
description=("The last decode_la in full: I2C transactions with timed segments, UART / "
"SPI / Modbus / CAN frames, USB packets, transactions and transfers, 1-Wire and "
"SMBus transactions, or PWM channels, for drawing on the capture. seq is the "
"capture it decoded."))
def capture_decode_resource() -> str:
return json.dumps(SESSION.last_decode or {"seq": 0}, separators=(",", ":"))

Expand Down
Loading