diff --git a/packages/embeddedci-mcp/CHANGELOG.md b/packages/embeddedci-mcp/CHANGELOG.md index 1db37db..ab00338 100644 --- a/packages/embeddedci-mcp/CHANGELOG.md +++ b/packages/embeddedci-mcp/CHANGELOG.md @@ -8,6 +8,8 @@ - `uart_open` and `capture_uart` take `half_duplex` (a one-wire UART on `rx`) and `entry` (`reset_ms`, `tx_low`, `hold_ms`, `idle_ms`, `data_hex`: a boot-mode entry the pod times before the session). Needs gateware v57. +- `uart_open` and `capture_uart` take `de` and `de_active_low`: the pod drives an RS-485 + transceiver's DE on that LA channel while it sends. Needs gateware v58. - Pod features come from the SDK's copy of the firmware's features table for firmware after 3.10.10 (embeddedci 3.0.2); older firmware is read as before. diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index 8dd8178..0fc6700 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -253,9 +253,9 @@ the board's with `pullups="external"`. | Tool | Purpose | Parameters | | --- | --- | --- | -| `capture_uart` | Record the DUT's UART for a window, or until a regex matches. | **`duration`**, `rx`, `tx`, `baud`, `until_regex`, `parity`, `stop_bits`, `half_duplex`, `entry` | +| `capture_uart` | Record the DUT's UART for a window, or until a regex matches. | **`duration`**, `rx`, `tx`, `baud`, `until_regex`, `parity`, `stop_bits`, `half_duplex`, `entry`, `de`, `de_active_low` | | `power_cycle_and_capture` | Power-cycle the target and capture UART across the boot. | `rx`, `tx`, `efuse`, `delay=1`, `duration=4`, `baud`, `until_regex`, `off_settle=0.3`, `parity`, `stop_bits` | -| `uart_open` | Start buffering the DUT's UART in the background. The frame is the profile's (`uart_parity`, `uart_stop_bits`; 8N1 unless set) unless `parity` (`none`/`even`/`odd`) or `stop_bits` (1/2) say otherwise; anything but 8N1 needs firmware 3.10.8+. `half_duplex` runs it on one wire (`rx`; `tx` defaults to it) and `entry` (`reset_ms`, `tx_low`, `hold_ms`, `idle_ms`, `data_hex`) runs a pod-timed boot-mode entry first: reset with TX held low, release, the first bytes (gateware v57, for boot-ROM pins such as RL78 TOOL0). | `rx`, `tx`, `baud`, `parity`, `stop_bits`, `half_duplex`, `entry` | +| `uart_open` | Start buffering the DUT's UART in the background. The frame is the profile's (`uart_parity`, `uart_stop_bits`; 8N1 unless set) unless `parity` (`none`/`even`/`odd`) or `stop_bits` (1/2) say otherwise; anything but 8N1 needs firmware 3.10.8+. `half_duplex` runs it on one wire (`rx`; `tx` defaults to it) and `entry` (`reset_ms`, `tx_low`, `hold_ms`, `idle_ms`, `data_hex`) runs a pod-timed boot-mode entry first: reset with TX held low, release, the first bytes (gateware v57, for boot-ROM pins such as RL78 TOOL0). | `rx`, `tx`, `baud`, `parity`, `stop_bits`, `half_duplex`, `entry`, `de`, `de_active_low` | | `uart_write` | Send text to the DUT through the open UART session. | **`text`**, `line_ending=lf` | | `uart_read` | Return output received since the last read, optionally waiting for a match. | `until_regex`, `timeout=2` | | `uart_close` | Stop the background UART session. | none | diff --git a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py index f58400c..cf80980 100644 --- a/packages/embeddedci-mcp/src/embeddedci_mcp/server.py +++ b/packages/embeddedci-mcp/src/embeddedci_mcp/server.py @@ -1165,6 +1165,22 @@ def _uart_frame(pod: Any, method: str, parity: Optional[str], stop_bits: Optiona return {k: v for k, v in (("parity", parity), ("stop_bits", stop_bits)) if v is not None} +UartDe = Annotated[Optional[LaRef], Field(description=( + "LA channel (or wiring name) wired to an RS-485 transceiver's DE + /RE. The pod drives it high " + "while it sends and low otherwise, so the transceiver listens whenever the pod is not " + "sending and a fast device's reply is heard. Needs gateware v58. Omit for a plain UART."))] +UartDeActiveLow = Annotated[bool, Field(description="Drive DE low while sending (an active-low enable).")] + + +def _uart_de(pod: Any, method: str, de: Any, de_active_low: bool) -> Dict[str, Any]: + """The RS-485 DE keyword arguments for an SDK UART call: none when unused.""" + if de is None: + return {} + if "de" not in inspect.signature(getattr(type(pod), method)).parameters: + raise ValueError("UART de needs a newer embeddedci SDK; upgrade embeddedci") + return {"de": de, "de_active_low": True} if de_active_low else {"de": de} + + def _uart_line(pod: Any, method: str, half_duplex: bool, entry: Optional[UartEntryArg]) -> Dict[str, Any]: """The one-wire and boot-mode entry keyword arguments for an SDK UART call: none when unused, so an older SDK still works; refused when the SDK predates them.""" @@ -1191,6 +1207,8 @@ async def capture_uart( stop_bits: UartStopBits = None, half_duplex: UartHalfDuplex = False, entry: UartEntryOpt = None, + de: UartDe = None, + de_active_low: UartDeActiveLow = False, ctx: Context = None, # type: ignore[assignment] ) -> m.UartCaptureResult: """Record the DUT's UART output for a fixed window (or until until_regex matches). @@ -1199,6 +1217,7 @@ async def capture_uart( the profile says otherwise). half_duplex runs it on one wire, and entry runs a pod-timed boot-mode entry first (reset with TX low, release, first bytes). + de: the pod switches an RS-485 transceiver's DE on that LA channel while it sends. """ pattern = _compile(until_regex) @@ -1206,7 +1225,8 @@ def op() -> m.UartCaptureResult: pod = SESSION.require() return _uart_result(pod.capture_uart(rx=rx, tx=tx, baud=baud, duration=duration, until=pattern, **_uart_frame(pod, "capture_uart", parity, stop_bits), - **_uart_line(pod, "capture_uart", half_duplex, entry))) + **_uart_line(pod, "capture_uart", half_duplex, entry), + **_uart_de(pod, "capture_uart", de, de_active_low))) return await _call_reporting(ctx, "capturing UART", op) @@ -1250,6 +1270,8 @@ async def uart_open( stop_bits: UartStopBits = None, half_duplex: UartHalfDuplex = False, entry: UartEntryOpt = None, + de: UartDe = None, + de_active_low: UartDeActiveLow = False, ) -> m.UartSessionResult: """Start buffering the DUT's UART in the background (replacing any open session). @@ -1260,7 +1282,8 @@ async def uart_open( (Modbus RTU) an external RS-485 transceiver in between. A channel used as GPIO must be released first (gpio_release). half_duplex runs the session on one wire (rx; tx defaults to it), and entry runs a pod-timed boot-mode entry before it starts (reset with TX held low, release, the - first bytes), for boot-ROM programming such as RL78 TOOL0. + first bytes), for boot-ROM programming such as RL78 TOOL0. de puts an RS-485 transceiver's + DE on an LA channel the pod switches itself while it sends. """ def op() -> m.UartSessionResult: pod = SESSION.require() @@ -1269,6 +1292,7 @@ def op() -> m.UartSessionResult: rate = int(pod.wiring.uart_baud if baud is None else baud) frame = _uart_frame(pod, "open_uart", parity, stop_bits) line = _uart_line(pod, "open_uart", half_duplex, entry) + line.update(_uart_de(pod, "open_uart", de, de_active_low)) SESSION.close_uart() SESSION.uart = pod.open_uart(rx=rx_i, tx=tx_i, baud=rate, **frame, **line) SESSION.uart_port = (rx_i, tx_i, rate) diff --git a/packages/embeddedci-mcp/tests/conftest.py b/packages/embeddedci-mcp/tests/conftest.py index 69fef63..4a91eae 100644 --- a/packages/embeddedci-mcp/tests/conftest.py +++ b/packages/embeddedci-mcp/tests/conftest.py @@ -103,6 +103,7 @@ def __init__(self) -> None: self.power_efuse = 1 self.uart_frames: List[Tuple[str, int]] = [] # (parity, stop_bits) per uart_proxy_start self.uart_lines: List[Tuple[int, int, bool, Any]] = [] # (rx, tx, half_duplex, entry) + self.uart_des: List[Tuple[Any, bool]] = [] # (de, de_active_low) #: The bin-averaged trace a power_profile reply carries (µA / mV, µs since the start). self.power_samples: Dict[str, Any] = { "t_us": [0, 250_000, 500_000, 750_000], @@ -133,8 +134,10 @@ def dap_start(self, swclk: int, swdio: int): return FakeRawLink() def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", stop_bits: int = 1, - half_duplex: bool = False, entry: Any = None): + half_duplex: bool = False, entry: Any = None, de: Any = None, + de_active_low: bool = False): self.uart_frames.append((parity, stop_bits)) + self.uart_des.append((de, de_active_low)) self.uart_lines.append((rx, tx, half_duplex, entry)) for la, fn in list(self.function.items()): # a new proxy replaces the previous one if fn in ("uart_rx", "uart_tx", "uart_hd"): diff --git a/packages/embeddedci-mcp/tests/test_tools.py b/packages/embeddedci-mcp/tests/test_tools.py index f54d60b..207600a 100644 --- a/packages/embeddedci-mcp/tests/test_tools.py +++ b/packages/embeddedci-mcp/tests/test_tools.py @@ -469,6 +469,26 @@ def test_uart_half_duplex_and_entry(connected): call("uart_close") +def test_uart_de(connected): + if "de" not in inspect.signature(BenchPod.open_uart).parameters: + # The minimum SDK (mcp-min-sdk) predates the argument: the tool says to upgrade it. + with pytest.raises(ToolError, match="newer embeddedci SDK"): + call("uart_open", rx=5, tx=4, de=9) + return + # the pod's RS-485 DE needs the uart_de feature (gateware v58) + with pytest.raises(ToolError, match="gateware v58"): + call("uart_open", rx=5, tx=4, de=9) + connected.caps.append("uart_de") + SESSION.require().refresh_capabilities() + call("uart_open", rx=5, tx=4, de=9) + assert connected.uart_des[-1] == (9, False) + call("capture_uart", rx=5, tx=4, duration=0.2, de=9, de_active_low=True) + assert connected.uart_des[-1] == (9, True) + call("uart_open", rx=5, tx=4) + assert connected.uart_des[-1] == (None, False) + call("uart_close") + + # -- I2C sensor + pulls ---------------------------------------------------------------- def test_sensor_library_tools_need_no_pod(): diff --git a/packages/embeddedci-mcp/tests/tools_surface.json b/packages/embeddedci-mcp/tests/tools_surface.json index 4d3d4f8..c0f7712 100644 --- a/packages/embeddedci-mcp/tests/tools_surface.json +++ b/packages/embeddedci-mcp/tests/tools_surface.json @@ -1125,6 +1125,35 @@ "description": "UART baud rate; omit for the wiring profile's uart_baud.", "title": "Baud" }, + "de": { + "anyOf": [ + { + "anyOf": [ + { + "maximum": 14, + "minimum": 1, + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "LA channel 1-14, or a name from the wiring profile \u2014 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)." + }, + { + "type": "null" + } + ], + "default": null, + "description": "LA channel (or wiring name) wired to an RS-485 transceiver's DE + /RE. The pod drives it high while it sends and low otherwise, so the transceiver listens whenever the pod is not sending and a fast device's reply is heard. Needs gateware v58. Omit for a plain UART.", + "title": "De" + }, + "de_active_low": { + "default": false, + "description": "Drive DE low while sending (an active-low enable).", + "title": "De Active Low", + "type": "boolean" + }, "duration": { "description": "Capture window in seconds.", "exclusiveMinimum": 0, @@ -5588,6 +5617,35 @@ "description": "UART baud rate; omit for the wiring profile's uart_baud.", "title": "Baud" }, + "de": { + "anyOf": [ + { + "anyOf": [ + { + "maximum": 14, + "minimum": 1, + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "LA channel 1-14, or a name from the wiring profile \u2014 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)." + }, + { + "type": "null" + } + ], + "default": null, + "description": "LA channel (or wiring name) wired to an RS-485 transceiver's DE + /RE. The pod drives it high while it sends and low otherwise, so the transceiver listens whenever the pod is not sending and a fast device's reply is heard. Needs gateware v58. Omit for a plain UART.", + "title": "De" + }, + "de_active_low": { + "default": false, + "description": "Drive DE low while sending (an active-low enable).", + "title": "De Active Low", + "type": "boolean" + }, "entry": { "anyOf": [ { diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 49ad102..7b3c041 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -13,6 +13,11 @@ (rx and tx on one LA pin; the pod only pulls the line low and does not read back its own bytes) and `entry=UartEntry(...)`, a reset with TX held low, its release and the first bytes, all timed on the pod. Needs gateware v57 (capability `uart_hd`); the entry also needs the reset pin. +- **RS-485 direction driven by the pod:** `open_uart` and `capture_uart` take `de=` (the LA channel + on a transceiver's DE + /RE) and `de_active_low=`. The pod switches DE itself, from before the + first start bit to the end of the last stop bit, so a device that answers within a millisecond + is heard (DE switched from the host with GPIO calls drops about 25 ms after the request over + LAN). Needs gateware v58 (feature `uart_de`, features table revision 2). - **Features from the firmware's features table:** the SDK ships benchpod-firmware's `features/features.json` (`embeddedci.benchpod.feature_map`) and reads the pod's status with diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index 1b77e1f..4a14aeb 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -1006,6 +1006,23 @@ character, so `uart.read().encode("latin-1")` gives the bytes back unchanged, an sent as is. For the adapter wiring and a Modbus RTU test through a transceiver, see [5 V logic and RS-485](https://www.embeddedci.com/docs/benchpod-targets/5v-rs485). +**RS-485 direction (DE).** A half-duplex RS-485 transceiver sends while its DE (tied to /RE) is +high and listens while it is low. `de=` names the LA channel wired to DE, and the pod switches it +itself: high from before the first start bit of what it sends to the end of the last stop bit, low +otherwise. Nothing on the host times it, so a device that answers within a millisecond is still +heard (switching DE with `gpio` calls from the host takes tens of milliseconds over the network, +and the reply of a fast device is lost meanwhile). `de_active_low=True` inverts it: + +```python +with bp.open_uart(rx=PIN5, tx=PIN4, de=PIN9, baud=19200, parity="even", + encoding="latin-1") as uart: + uart.write(request) # DE goes high and low with the bytes + reply = uart.read(timeout=0.2) +``` + +`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 Eight LA channels carry a fixed, switchable bias resistor. They are referenced to 3V3, so the pod diff --git a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py index 7c17958..b544d4f 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/capabilities.py +++ b/packages/embeddedci/src/embeddedci/benchpod/capabilities.py @@ -205,6 +205,9 @@ class Capabilities: #: boot-mode entry (``entry``, with ``nrst_pin``) (gateware v57+): :meth:`BenchPod.open_uart` #: / :meth:`BenchPod.capture_uart` ``half_duplex``, ``entry``. uart_hd: bool = False + #: ``uart_de``: the UART proxy drives an RS-485 transceiver's DE (gateware v58+): + #: :meth:`BenchPod.open_uart` / :meth:`BenchPod.capture_uart` ``de``, ``de_active_low``. + uart_de: bool = False #: The running gateware version (``status`` ``gateware``); 0 when not reported. gateware: int = 0 #: The features-table revision the pod's firmware is built from (``status`` with @@ -382,6 +385,7 @@ def from_status(cls, status: Mapping[str, Any]) -> "Capabilities": ("spi_stream", "spi_stream"), ("uart_frame", "uart_frame"), ("uart_hd", "uart_hd"), + ("uart_de", "uart_de"), ("calibrate", "calibrate"), ("cal_dmm", "cal_dmm"), ("current_out", "current_out"), diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 11ca356..79082e1 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -1969,6 +1969,8 @@ def capture_uart( stop_bits: Optional[int] = None, half_duplex: bool = False, entry: Optional[_uart.UartEntry] = None, + de: Union[Pin, int, str, None] = None, + de_active_low: bool = False, ) -> _uart.UartCapture: """Capture the DUT's UART output for ``duration`` seconds. @@ -1980,12 +1982,13 @@ def capture_uart( """ if duration <= 0: raise ValueError(f"duration must be > 0 seconds, got {duration!r}") - link = self._uart_link(rx, tx, baud, parity, stop_bits, half_duplex, entry) + link = self._uart_link(rx, tx, baud, parity, stop_bits, half_duplex, entry, de, de_active_low) return _uart.capture(link, duration=duration, until=until) def _uart_link(self, rx: Any, tx: Any, baud: Optional[int], parity: Optional[str] = None, stop_bits: Optional[int] = None, half_duplex: bool = False, - entry: Optional[_uart.UartEntry] = None) -> Any: + entry: Optional[_uart.UartEntry] = None, + de: Any = None, de_active_low: bool = False) -> Any: if parity is not None and parity not in ("none", "even", "odd"): raise ValueError(f"parity must be 'none', 'even' or 'odd', got {parity!r}") if stop_bits is not None and (isinstance(stop_bits, bool) or stop_bits not in (1, 2)): @@ -2011,6 +2014,12 @@ def _uart_link(self, rx: Any, tx: Any, baud: Optional[int], parity: Optional[str f"UART half_duplex and entry need gateware v57 (capability uart_hd; this pod " f"runs firmware {fw}): update the pod's firmware", feature="uart_hd", firmware_version=self.capabilities.firmware_version) + if de is not None and not self.supports("uart_de"): + fw = self.capabilities.firmware_version or "unknown" + raise UnsupportedFeatureError( + f"UART de (RS-485 direction) needs gateware v58 (feature uart_de; this pod runs " + f"firmware {fw}): update the pod's firmware", + feature="uart_de", firmware_version=self.capabilities.firmware_version) if entry is not None and not self.supports("nrst_pin"): raise UnsupportedFeatureError( "UART entry needs the pod's reset pin, which this board does not have (v3 boards " @@ -2033,6 +2042,13 @@ def _uart_link(self, rx: Any, tx: Any, baud: Optional[int], parity: Optional[str kw["half_duplex"] = True if entry is not None: kw["entry"] = entry + if de is not None: + de_i = self._wired(de, "uart_de") + if de_i in (rx_i, tx_i): + raise ValueError(f"de needs a pin of its own: LA{de_i} is the UART's rx or tx") + kw["de"] = de_i + if de_active_low: + kw["de_active_low"] = True with _classified_errors(): return self._transport.uart_proxy_start(rx_i, tx_i, b, **kw) @@ -2078,6 +2094,8 @@ def open_uart( encoding: str = "utf-8", half_duplex: bool = False, entry: Optional[_uart.UartEntry] = None, + de: Union[Pin, int, str, None] = None, + de_active_low: bool = False, ) -> _uart.UartSession: """Open an event-based UART session (a background reader buffers the DUT's output). @@ -2124,12 +2142,22 @@ def open_uart( with bp.open_uart(rx=3, half_duplex=True, entry=entry, encoding="latin-1") as uart: uart.write(...) - Both need gateware v57 (capability ``uart_hd``); ``entry`` also needs the pod's reset pin + ``de`` is the LA channel on an RS-485 transceiver's DE (tied to /RE): the pod drives it + itself, high from before the first start bit of what it sends to the end of the last stop + bit, low otherwise, so the transceiver listens whenever the pod is not sending and a fast + device's reply is not lost (switching DE from the host takes tens of milliseconds). + ``de_active_low`` inverts it. Needs gateware v58 (feature ``uart_de``):: + + with bp.open_uart(rx=5, tx=4, de=9, baud=19200, parity="even", + encoding="latin-1") as uart: + uart.write(request) # no DE handling on the host + + ``half_duplex`` and ``entry`` need gateware v57 (capability ``uart_hd``); ``entry`` also needs the pod's reset pin (capability ``nrst_pin``). Older pods are refused with :class:`~embeddedci.benchpod.errors.UnsupportedFeatureError` before anything is sent. """ codecs.lookup(encoding) # an unknown encoding fails here, before the proxy starts - link = self._uart_link(rx, tx, baud, parity, stop_bits, half_duplex, entry) + link = self._uart_link(rx, tx, baud, parity, stop_bits, half_duplex, entry, de, de_active_low) return _uart.UartSession(link, max_buffer=max_buffer, encoding=encoding) # -- SPI master / SPI flash ------------------------------------------------ diff --git a/packages/embeddedci/src/embeddedci/benchpod/feature_map.json b/packages/embeddedci/src/embeddedci/benchpod/feature_map.json index 7872b35..da21413 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": 1, - "table_sha256": "5b64c07e36263d775a2f06d20833db87023055edced5958ee4bc5d17aa29855f", + "revision": 2, + "table_sha256": "22265d477544ffd24beee7ee1aa64a6ab64f9112196af7419e08b2f04e1e2f56", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -629,6 +629,13 @@ "board": "any", "legacy_frame": "serial", "status": "retired" + }, + "uart_de": { + "rev": 2, + "firmware": "next", + "gateware": 58, + "board": "any", + "docs": "API.md#uart_proxy_start--transparent-uart-bridge" } } } diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/base.py b/packages/embeddedci/src/embeddedci/benchpod/transport/base.py index b209dd3..2bf92a2 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/base.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/base.py @@ -99,7 +99,8 @@ def dap_start(self, swclk: int, swdio: int, packet_size: Optional[int] = None, @abstractmethod def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", stop_bits: int = 1, half_duplex: bool = False, - entry: Any = None) -> RawLink: + entry: Any = None, de: Optional[int] = None, + de_active_low: bool = False) -> RawLink: """Enter transparent UART-proxy mode and return the raw byte link. ``rx``/``tx`` are LA channels: ``rx`` is sampled (wire the DUT's TX @@ -107,7 +108,8 @@ def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", ``"even"``, ``"odd"``) and ``stop_bits`` (1, 2) set the frame format; only 8N1 is sent as before (older firmware knows nothing else). ``half_duplex`` (one wire, ``rx == tx``) and ``entry`` (a :class:`~embeddedci.benchpod.uart.UartEntry`) are - sent only when set (gateware v57). The returned + sent only when set (gateware v57), like ``de`` (an RS-485 transceiver's DE on that LA + channel, driven by the pod) and ``de_active_low`` (gateware v58). The returned link carries raw bytes; ``close()`` leaves the proxy. """ diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py index 000ee72..f2fdc9d 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/serial.py @@ -616,7 +616,12 @@ def dap_start(self, swclk: int, swdio: int, packet_size: Optional[int] = None, def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", stop_bits: int = 1, half_duplex: bool = False, - entry: Any = None) -> RawLink: + entry: Any = None, de: Optional[int] = None, + de_active_low: bool = False) -> RawLink: + if de is not None: + raise UnsupportedFeatureError( + "UART de needs the network, the USB network or the cloud: the USB console's " + "uart-proxy has no DE", feature="uart_de") if half_duplex or entry is not None: raise UnsupportedFeatureError( "UART half_duplex and entry need the network, the USB network or the cloud: the " diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index f3bbf44..92fb9c3 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -457,7 +457,8 @@ def dap_start(self, swclk: int, swdio: int, packet_size: Optional[int] = None, def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", stop_bits: int = 1, half_duplex: bool = False, - entry: Any = None) -> RawLink: + entry: Any = None, de: Optional[int] = None, + de_active_low: bool = False) -> RawLink: req: dict = {"cmd": "uart_proxy_start", "rx": rx, "tx": tx, "baud": baud} # Only a non-8N1 frame adds the fields (firmware 3.10.8+ / gateware v56 take them). if parity != "none": @@ -469,6 +470,11 @@ def uart_proxy_start(self, rx: int, tx: int, baud: int, parity: str = "none", req["half_duplex"] = True if entry is not None: req["entry"] = entry.to_request() + # RS-485 DE driven by the pod (gateware v58), only when asked for. + if de is not None: + req["de"] = de + if de_active_low: + req["de_active_low"] = True return self._raw_handshake(req, "uart_proxy_start", "uart") def close(self) -> None: diff --git a/packages/embeddedci/tests/api_surface.json b/packages/embeddedci/tests/api_surface.json index 4eefcbc..2ee7906 100644 --- a/packages/embeddedci/tests/api_surface.json +++ b/packages/embeddedci/tests/api_surface.json @@ -110,7 +110,7 @@ "capture_adc": "(self, samples: 'int' = 4096, *, sample_rate_hz: 'Optional[float]' = None, source: 'Optional[AdcSource]' = None, trigger: 'Optional[Trigger]' = None, trigger_timeout: 'float' = 10.0, range: 'Optional[AdcRange]' = None, oversample: 'bool' = False) -> 'Capture'", "capture_correlated": "(self, *, adc_samples: 'int' = 4096, adc_sample_rate_hz: 'Optional[float]' = None, la_samples: 'int' = 4096, la_sample_rate_hz: 'Optional[float]' = None, stop_dac_after: 'Optional[float]' = None, trigger: 'Optional[Trigger]' = None, trigger_timeout: 'float' = 10.0, source: 'Optional[AdcSource]' = None) -> 'CorrelatedCapture'", "capture_la": "(self, samples: 'int' = 4096, *, sample_rate_hz: 'Optional[float]' = None, stop_dac_after: 'Optional[float]' = None, trigger: 'Optional[Trigger]' = None, trigger_timeout: 'float' = 10.0, send: 'Optional[_i2c_master.Send]' = None) -> 'LaCapture'", - "capture_uart": "(self, *, rx: 'Union[Pin, int, str, None]' = None, tx: 'Union[Pin, int, str, None]' = None, baud: 'Optional[int]' = None, duration: 'float', until: 'Optional[_uart.Until]' = None, parity: 'Optional[str]' = None, stop_bits: 'Optional[int]' = None, half_duplex: 'bool' = False, entry: 'Optional[_uart.UartEntry]' = None) -> '_uart.UartCapture'", + "capture_uart": "(self, *, rx: 'Union[Pin, int, str, None]' = None, tx: 'Union[Pin, int, str, None]' = None, baud: 'Optional[int]' = None, duration: 'float', until: 'Optional[_uart.Until]' = None, parity: 'Optional[str]' = None, stop_bits: 'Optional[int]' = None, half_duplex: 'bool' = False, entry: 'Optional[_uart.UartEntry]' = None, de: 'Union[Pin, int, str, None]' = None, de_active_low: 'bool' = False) -> '_uart.UartCapture'", "clear_calibration": "(self, part: 'Optional[CalibrationPart]' = None) -> 'Calibration'", "close": "(self) -> 'None'", "command": "(self, req: 'Dict[str, Any]') -> 'Any'", @@ -150,7 +150,7 @@ "open_i2c": "(self, sda: 'Union[Pin, int, str, None]' = None, scl: 'Union[Pin, int, str, None]' = None, *, hz: 'int' = 100000, pullups: 'str' = 'pod') -> '_i2c_master.I2CMaster'", "open_motor_emulator": "(self, *, 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, programn: 'Union[Pin, int, str, None]' = None, done: 'Union[Pin, int, str, None]' = None, hz: 'int' = 6000000, calibration: 'Optional[_motor_emulator.EmulatorCalibration]' = None) -> '_motor_emulator.MotorEmulator'", "open_spi": "(self, *, 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' = 1000000, mode: 'int' = 0) -> '_spi.SpiSession'", - "open_uart": "(self, *, rx: 'Union[Pin, int, str, None]' = None, tx: 'Union[Pin, int, str, None]' = None, baud: 'Optional[int]' = None, max_buffer: 'int' = 1048576, parity: 'Optional[str]' = None, stop_bits: 'Optional[int]' = None, encoding: 'str' = 'utf-8', half_duplex: 'bool' = False, entry: 'Optional[_uart.UartEntry]' = None) -> '_uart.UartSession'", + "open_uart": "(self, *, rx: 'Union[Pin, int, str, None]' = None, tx: 'Union[Pin, int, str, None]' = None, baud: 'Optional[int]' = None, max_buffer: 'int' = 1048576, parity: 'Optional[str]' = None, stop_bits: 'Optional[int]' = None, encoding: 'str' = 'utf-8', half_duplex: 'bool' = False, entry: 'Optional[_uart.UartEntry]' = None, de: 'Union[Pin, int, str, None]' = None, de_active_low: 'bool' = False) -> '_uart.UartSession'", "pin_directions": "(self, wiring: 'Optional[Wiring]' = None) -> 'Dict[int, str]'", "pin_levels": "(self) -> 'Dict[int, int]'", "ping": "(self) -> 'Any'", @@ -317,6 +317,7 @@ "spi_stream", "uart_frame", "uart_hd", + "uart_de", "gateware", "features_rev", "features", diff --git a/packages/embeddedci/tests/test_uart_de.py b/packages/embeddedci/tests/test_uart_de.py new file mode 100644 index 0000000..57ec999 --- /dev/null +++ b/packages/embeddedci/tests/test_uart_de.py @@ -0,0 +1,102 @@ +"""RS-485 DE driven by the pod (``open_uart(de=...)``, gateware v58, feature ``uart_de``): refused +before anything is sent on pods without it, checked, and sent by the TCP transport only when +asked for (firmware command_handler_uart.c uart_proxy_start).""" + +from __future__ import annotations + +from typing import Any, Dict, List + +import pytest + +from embeddedci.benchpod import BenchPod, UnsupportedFeatureError +from embeddedci.benchpod.transport.tcp import TcpTransport + +from test_uart_frame import _serve_once + + +class TablePod: + """A pod after 3.10.10: status carries features_rev and the running gateware, no caps list.""" + + def __init__(self, features_rev: int, gateware: int) -> None: + self.features_rev = features_rev + self.gateware = gateware + self.starts: 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": self.gateware, "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() + raise AssertionError(f"unexpected command {req}") + + def uart_proxy_start(self, rx: int, tx: int, baud: int, **kw: Any) -> Any: + self.starts.append({"rx": rx, "tx": tx, "baud": baud, **kw}) + return object() + + +def _bp(features_rev: int = 2, gateware: int = 58) -> "tuple[BenchPod, TablePod]": + pod = TablePod(features_rev, gateware) + return BenchPod(transport=pod, lease=False, wiring={"version": 2}), pod + + +def test_de_reaches_the_transport(): + bp, pod = _bp() + assert bp.supports("uart_de") + bp._uart_link(5, 4, 19200, "even", 1, de=9) + bp._uart_link(5, 4, 9600, de=6, de_active_low=True) + assert pod.starts == [ + {"rx": 5, "tx": 4, "baud": 19200, "parity": "even", "stop_bits": 1, "de": 9}, + {"rx": 5, "tx": 4, "baud": 9600, "de": 6, "de_active_low": True}, + ] + + +def test_without_de_nothing_changes(): + bp, pod = _bp() + bp._uart_link(5, 4, 19200) + assert pod.starts == [{"rx": 5, "tx": 4, "baud": 19200}] + + +@pytest.mark.parametrize("features_rev,gateware", [(1, 58), (2, 57)]) +def test_old_pods_are_refused_before_anything_is_sent(features_rev, gateware): + bp, pod = _bp(features_rev, gateware) + assert not bp.supports("uart_de") + with pytest.raises(UnsupportedFeatureError) as info: + bp.open_uart(rx=5, tx=4, de=9) + assert info.value.feature == "uart_de" and "gateware v58" in str(info.value) + with pytest.raises(UnsupportedFeatureError): + bp.capture_uart(rx=5, tx=4, duration=0.1, de=9) + assert pod.starts == [] + + +@pytest.mark.parametrize("de", [5, 4]) +def test_de_needs_its_own_pin(de): + bp, pod = _bp() + with pytest.raises(ValueError, match="pin of its own"): + bp._uart_link(5, 4, 19200, de=de) + assert pod.starts == [] + + +def test_tcp_sends_de_only_when_set(): + seen: List[dict] = [] + srv, addr = _serve_once(seen) + try: + t = TcpTransport(addr, timeout=2) + t.uart_proxy_start(5, 4, 19200).close() + t.uart_proxy_start(5, 4, 19200, parity="even", de=9).close() + t.uart_proxy_start(5, 4, 19200, de=9, de_active_low=True).close() + finally: + srv.close() + assert seen == [ + {"cmd": "uart_proxy_start", "rx": 5, "tx": 4, "baud": 19200}, + {"cmd": "uart_proxy_start", "rx": 5, "tx": 4, "baud": 19200, "parity": "even", "de": 9}, + {"cmd": "uart_proxy_start", "rx": 5, "tx": 4, "baud": 19200, "de": 9, "de_active_low": True}, + ]