From 73c813f81aef1d2af4caf7cd76b041d74834749d Mon Sep 17 00:00:00 2001 From: thetooler Date: Sat, 24 Oct 2026 13:41:12 +0800 Subject: [PATCH 1/2] feat: add a TCP transport so the SDK can drive a simulated firmware The SDK is a thin protocol layer, so pointing it at a socket is enough to run the same script against a simulated arm -- as long as the bytes are identical. - transport_tcp.py: TcpTransport with the same contract as SerialTransport (port string kept verbatim for connect() idempotency, half frames survive a timeout, timeout=0 means take what has arrived, a failed write raises so _CartPending still drops its token, peer close is a link failure instead of a silent timeout); - arm.py: three-way dispatch in connect() -- injected factory first, then a tcp:// or host:port target, then SerialTransport unchanged. Deliberately not a make_transport() factory: tests/conftest.py injects by replacing the SerialTransport attribute, and a factory hides that point (344 errors). - is_tcp_target() in transport.py, so serial callers pay nothing. --- src/litearm/arm.py | 13 +- src/litearm/transport.py | 16 +++ src/litearm/transport_tcp.py | 255 +++++++++++++++++++++++++++++++++++ tests/test_transport_tcp.py | 217 +++++++++++++++++++++++++++++ 4 files changed, 499 insertions(+), 2 deletions(-) create mode 100644 src/litearm/transport_tcp.py create mode 100644 tests/test_transport_tcp.py diff --git a/src/litearm/arm.py b/src/litearm/arm.py index 046c9bd..65be883 100644 --- a/src/litearm/arm.py +++ b/src/litearm/arm.py @@ -47,7 +47,7 @@ from litearm.log import ArmLog from litearm.model import ModelParams from litearm.params import JointParams -from litearm.transport import SerialTransport, find_cdc_port +from litearm.transport import SerialTransport, find_cdc_port, is_tcp_target __all__ = ["Arm", "Msg", "main", "MIN_FW", "FIRMWARE_PREFIX"] @@ -931,7 +931,16 @@ def connect(self, port: Optional[str] = None) -> "Arm": raise TransportError("未找到 STM32 CDC (VID:PID 1d50:606f), 请用 --port 指定") # 唯一的传输构造点(`reconnect()` = `close()` + 本函数,故也走这里)。 # 注入了工厂就用工厂 —— 离线 (`testing.FakeTransport`) 与真机走同一条会话装配路径。 - self._tr = (self._transport_factory or SerialTransport)(p) + if self._transport_factory is not None: + self._tr = self._transport_factory(p) + elif is_tcp_target(p): + # 远端/仿真: 帧与串口完全相同, 只是载体是 socket (见 transport_tcp)。 + # ⚠ 刻意**不**把串口分支也塞进一个总工厂: 那会挡掉 + # `tests/conftest.py` 替换 `SerialTransport` 的注入点。 + from litearm.transport_tcp import TcpTransport + self._tr = TcpTransport(p) + else: + self._tr = SerialTransport(p) self._a = _Ack(self) #: fork 守卫的落章点 —— 本会话属于**这个**进程 (见 `ForkedSessionError`)。 #: 位置: 会话对象一建好就落, 早于下面那句握手写帧, 也早于读线程起。 diff --git a/src/litearm/transport.py b/src/litearm/transport.py index a5f694f..95cda24 100644 --- a/src/litearm/transport.py +++ b/src/litearm/transport.py @@ -370,6 +370,22 @@ def _read_chunk(self, end: float): raise TransportError(f"读失败: {e}") from e +def is_tcp_target(port: object) -> bool: + """`port` 是不是一个"要走 TCP 的远端目标"(`tcp://` / `sim://` / 裸 `host:port`)。 + + 判定与误判防护在 :func:`litearm.transport_tcp.is_tcp_url`; 这里只是薄委托, + **不在本模块再实现一遍** (两份判定必然漂)。 + + 为什么本模块需要知道这件事、而不是干脆提供一个 `make_transport()` 总工厂: + `Arm.connect()` 的串口分支必须**仍然直接引用 `SerialTransport` 这个名字** —— + 离线测试与 `litearm-server --dry-run` 都靠替换那个属性来注入假传输 + (`tests/conftest.py` 的 `fake_transport_factory`)。总工厂会把那个注入点挡掉。 + 所以分流的形状是"TCP 例外走新路, 其余原路不动", 而不是"所有传输过一道工厂"。 + """ + from litearm.transport_tcp import is_tcp_url + return is_tcp_url(port) + + def _now() -> float: import time return time.monotonic() diff --git a/src/litearm/transport_tcp.py b/src/litearm/transport_tcp.py new file mode 100644 index 0000000..7903e40 --- /dev/null +++ b/src/litearm/transport_tcp.py @@ -0,0 +1,255 @@ +"""TCP 传输 —— 与串口**同一套帧**, 只是载体从 USB CDC 换成 socket。 + +用途只有一个: 把 `litearm-python` 接到一个"固件替身"上 (仿真的 MuJoCo 后端, 或任何 +在别处实现了本协议的东西), 命令行与真机逐字节相同 —— 于是同一份采集/策略脚本 +不用改一行, 只是把端口从 `/dev/ttyACM0` 换成 `tcp://127.0.0.1:5601`。 + +**它不是"另一个后端"**: 帧的语义、时序假设、错误分类全部与 :mod:`litearm.transport` +一致。下面每一条都是 :class:`~litearm.transport.SerialTransport` 的契约照抄, 因为它们 +是 `Arm` 层的承重假设, 不是串口特有的实现细节: + +* :attr:`port` **原样保存 URL 字符串** —— `Arm.connect()` 的幂等比较读的就是它 + (`arm.py` 里 `port == getattr(self._tr, "port", None)`)。存成 `(host, port)` 元组会让 + 重复 `connect()` 每次都被判成"换了目标", 把在途笛卡尔记账与零重力保活推倒重来。 +* :meth:`read_frame` 超时返回 ``None``, **半帧留在缓冲里**不丢; 且 + ``timeout=0`` 是"有就给我", 不是"一个字节都不碰" (否则 `Arm.poll_cart()` 恒 ``None``)。 +* :meth:`write_frame` 的**写失败必须抛** :class:`~litearm.errors.TransportError` —— + `_CartPending` 靠"抛了 ⟹ 整帧未送达"这条不变量摘 token, 破了就是**假成功**。 +* :meth:`close` 幂等; 对端关闭 (recv 得到 ``b""``) 要**报链路断**, 不能静默返回 ``None`` + —— 否则上层只能靠超时发现, 归因会指向"固件不理我"。 + +⚠ 零依赖: 只用标准库 ``socket``/``select``。本包的唯一依赖仍是 pyserial。 +""" +from __future__ import annotations + +import select +import socket +import threading +import time +from typing import Optional, Tuple + +from litearm import _protocol as P +from litearm.errors import TransportError + +#: 残缺帧 (SOF 起算但未收齐) 最多等多久。与 `transport._PARTIAL_MAX_S` 同值同理由: +#: 噪声里凑出的假帧头永远收不齐, 不设上限就会把后面的真帧永久挡住。 +_PARTIAL_MAX_S = 0.25 + +#: 读超时之后那段"非阻塞补读"的时间上限 (秒)。照抄 `transport._NONBLOCK_EXTRA_S`: +#: `timeout=0` 时要把**已经到达**的字节读进来, 但数据持续到达时不能变成无界循环。 +_NONBLOCK_EXTRA_S = 0.02 + +#: 一次 recv 的字节数。串口那边按 `in_waiting` 要, socket 这边一次给多少都行 —— +#: 装配循环本来就按"来多少字节都可能"写的。 +_RECV_MAX = 4096 + +#: 连接超时。真机上是 `serial.Serial()` 打开设备, 这边是 TCP 三次握手。 +_CONNECT_TIMEOUT_S = 2.0 + +#: 写超时 —— **必须有界**。`emergency_stop()` 必须永远可达 (见 SerialTransport 的同名注释)。 +_WRITE_TIMEOUT_S = 0.5 + +_SCHEMES = ("tcp://", "sim://") + + +def is_tcp_url(port: object) -> bool: + """`port` 是不是一个"要走 TCP 的目标"。 + + 认三种写法: `tcp://host:port`、`sim://host:port`、以及裸的 `host:port` + (只含一个冒号、冒号后是纯数字、不含路径分隔符 —— 这样 `/dev/ttyACM0` + 与 `COM3` 都不会被误判)。 + """ + if not isinstance(port, str) or not port: + return False + if port.startswith(_SCHEMES): + return True + if "/" in port or "\\" in port or port.count(":") != 1: + return False + host, _, portnum = port.partition(":") + if not host or not portnum.isdigit(): + return False + # ⚠ 必须查范围: 光看 isdigit 会把 "host:70000" 判成 TCP 目标, 然后在 + # connect 时以一个和"端口写错"毫不相干的错误炸掉。 + return 0 < int(portnum) < 65536 + + +def parse_tcp_url(port: str) -> Tuple[str, int]: + """`tcp://host:port` / `host:port` -> `(host, port)`。非法时抛 ValueError。""" + s = port + for scheme in _SCHEMES: + if s.startswith(scheme): + s = s[len(scheme):] + break + host, sep, portnum = s.rpartition(":") + if not sep or not host: + raise ValueError(f"TCP 目标应形如 tcp://host:port (收到 {port!r})") + try: + n = int(portnum) + except ValueError: + raise ValueError(f"端口号不是整数: {portnum!r} (来自 {port!r})") from None + if not 0 < n < 65536: + raise ValueError(f"端口号越界: {n} (来自 {port!r})") + return host, n + + +class TcpTransport: + """帧读写传输 (TCP 版)。接口与行为契约见模块 docstring。 + + **读写各一把锁, 读写之间不互斥** —— 与 :class:`~litearm.transport.SerialTransport` + 同结构: 读者互斥 `_buf`/`_partial_since`, 写者互斥"一帧的字节原子交给 socket"; + 读写之间并发本来就安全, 而用单把锁罩住会让一次阻塞读把保活写拖过 0.1s 看门狗窗口。 + """ + + TEXT_LOG_MAX = 2048 + + def __init__(self, port: str, timeout: float = 0.2, + connect_timeout: float = _CONNECT_TIMEOUT_S): + self.port = port # ⚠ 原样保存, 见模块 docstring + self.timeout = timeout + host, portnum = parse_tcp_url(port) if isinstance(port, str) else (None, None) + if host is None: + raise TransportError(f"不是合法的 TCP 目标: {port!r}") + try: + self._sock = socket.create_connection((host, portnum), + timeout=connect_timeout) + except OSError as e: + raise TransportError(f"连接 {port} 失败: {e}") from e + try: + self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass # 无 Nagle 更好; 设不上不致命 + self._sock.settimeout(None) # 一律用 select 控阻塞, 不用 socket 超时 + self._buf = bytearray() + self._partial_since: Optional[float] = None + self._text = bytearray() + self._rlock = threading.RLock() + self._wlock = threading.RLock() + self._closed = False + self._peer_closed = False + self.flush_failures = 0 # 与串口同名同义 (socket 无 flush, 恒 0) + + # -- 状态 --------------------------------------------------------------- + @property + def text_log(self) -> str: + """最近被跳过的非帧字节 —— 与串口同语义 (开机签名在那边靠它解析)。""" + with self._rlock: + return bytes(self._text).decode("utf-8", errors="replace") + + @property + def is_open(self) -> bool: + if self._closed: + return False + try: + return not self._peer_closed + except Exception: # noqa: BLE001 + return False + + def close(self) -> None: + """幂等关闭。**先 shutdown 再 close** —— 只 close 会让对端读到一个 + 半关闭的连接而继续写, 从这里看就是"关了还在收"。""" + with self._rlock, self._wlock: + if self._closed: + return + self._closed = True + try: + self._sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + self._sock.close() + except OSError: + pass + + # -- 写 ----------------------------------------------------------------- + def write_frame(self, cmd: int, payload: bytes = b"") -> None: + """写一帧。失败**必须抛** `TransportError` (整帧未送达的判据, 见模块 docstring)。""" + frame = P.pack_frame(cmd, payload) + with self._wlock: + if self._closed or self._peer_closed: + raise TransportError(f"写失败: {self.port} 已关闭") + try: + self._sock.settimeout(_WRITE_TIMEOUT_S) + self._sock.sendall(frame) + except OSError as e: + raise TransportError(f"写失败: {e}") from e + finally: + try: + self._sock.settimeout(None) + except OSError: + pass + + # -- 读 ----------------------------------------------------------------- + def read_frame(self, timeout: Optional[float] = None) -> Optional[Tuple[int, bytes]]: + """读一帧; 超时返回 None。跳过噪声字节, 丢弃 CRC 坏帧 (与串口逐字同义)。""" + end = time.monotonic() + (self.timeout if timeout is None else timeout) + with self._rlock: + return self._read_frame_locked(end) + + def _read_frame_locked(self, end: float) -> Optional[Tuple[int, bytes]]: + nb_end: Optional[float] = None + while True: + while self._buf: + if self._buf[0] != P.SOF: + self._note_text(self._buf[0]) + del self._buf[0] + continue + if len(self._buf) < 3: + break + ln = self._buf[2] + total = 3 + ln + 2 + if len(self._buf) < total: + break + got = P.unpack_frame(bytes(self._buf[:total])) + if got is not None: + del self._buf[:total] + self._partial_since = None + return got + del self._buf[0] + now = time.monotonic() + if self._buf and self._buf[0] == P.SOF: + if self._partial_since is None: + self._partial_since = now + elif now - self._partial_since > _PARTIAL_MAX_S: + del self._buf[0] + self._partial_since = None + continue + else: + self._partial_since = None + if now >= end: + # 窗口用尽, 但仍要把**已经到达**的字节读进来 (timeout=0 的语义) + if nb_end is None: + nb_end = now + _NONBLOCK_EXTRA_S + elif now > nb_end: + return None + chunk = self._recv(0.0) + if chunk: + self._buf += chunk + continue + return None + chunk = self._recv(end - now) + if chunk: + self._buf += chunk + + def _recv(self, wait: float) -> Optional[bytes]: + """等至多 `wait` 秒取一块。对端关闭时抛 `TransportError` (链路断, 不静默)。""" + if self._closed: + raise TransportError("读失败: 链路已关闭") + try: + ready, _, _ = select.select([self._sock], [], [], max(wait, 0.0)) + except (OSError, ValueError) as e: + raise TransportError(f"读失败: {e}") from e + if not ready: + return None + try: + data = self._sock.recv(_RECV_MAX) + except OSError as e: + raise TransportError(f"读失败: {e}") from e + if not data: + self._peer_closed = True + raise TransportError(f"读失败: {self.port} 对端关闭了连接") + return data + + def _note_text(self, byte: int) -> None: + self._text.append(byte) + if len(self._text) > self.TEXT_LOG_MAX: + del self._text[:len(self._text) - self.TEXT_LOG_MAX] diff --git a/tests/test_transport_tcp.py b/tests/test_transport_tcp.py new file mode 100644 index 0000000..7be581f --- /dev/null +++ b/tests/test_transport_tcp.py @@ -0,0 +1,217 @@ +"""TCP 传输 —— 契约与串口逐条对齐 (见 `litearm/transport_tcp.py` 模块 docstring)。 + +这些用例**不依赖**任何仿真后端: 一个本地 socket 假装成固件, 只验传输层本身。 +""" +from __future__ import annotations + +import contextlib +import socket +import threading +import time + +import pytest + +from litearm import _protocol as P +from litearm import transport as tr_mod +from litearm.errors import TransportError +from litearm.transport import is_tcp_target +from litearm.transport_tcp import TcpTransport, is_tcp_url, parse_tcp_url + + +@contextlib.contextmanager +def fake_firmware(): + """起一个只监听 127.0.0.1 的"固件", 返回 (url, 服务端 socket)。""" + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + port = srv.getsockname()[1] + accepted = {} + + def _accept(): + conn, _ = srv.accept() + accepted["conn"] = conn + + th = threading.Thread(target=_accept, daemon=True) + th.start() + try: + yield f"tcp://127.0.0.1:{port}", accepted + finally: + th.join(timeout=2.0) + for s in (accepted.get("conn"), srv): + if s is not None: + try: + s.close() + except OSError: + pass + + +def _conn(box, timeout=2.0): + """等服务端 accept 落地, 返回那条连接 (构造 TcpTransport 是异步完成的)。""" + end = time.time() + timeout + while "conn" not in box and time.time() < end: + time.sleep(0.005) + assert "conn" in box, "服务端没接受连接" + return box["conn"] + + +# --------------------------------------------------------------------------- # +# 端口字符串的判定 +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize("port", ["tcp://127.0.0.1:5601", "sim://localhost:9000", + "127.0.0.1:5601", "host:1"]) +def test_tcp_urls_are_recognized(port): + assert is_tcp_url(port) is True + + +@pytest.mark.parametrize("port", ["/dev/ttyACM0", "COM3", "fake", "", None, 42, + "C:\\Users\\x", "host:abc", "host:70000", ":5601"]) +def test_non_tcp_ports_are_not_misdetected(port): + assert is_tcp_url(port) is False, f"{port!r} 不应被判成 TCP" + + +def test_parse_rejects_bad_urls(): + for bad in ("tcp://noport", "tcp://:123", "tcp://h:notanumber", "tcp://h:99999"): + with pytest.raises(ValueError): + parse_tcp_url(bad) + + +def test_parse_accepts_scheme_less_form(): + assert parse_tcp_url("127.0.0.1:5601") == ("127.0.0.1", 5601) + assert parse_tcp_url("sim://localhost:7") == ("localhost", 7) + + +# --------------------------------------------------------------------------- # +# 收发契约 +# --------------------------------------------------------------------------- # +def test_roundtrip_write_then_read(): + with fake_firmware() as (url, accepted): + tr = TcpTransport(url, timeout=0.5) + try: + tr.write_frame(P.CMD_GET_STATUS) + _conn(accepted).settimeout(2.0) + data = _conn(accepted).recv(64) + assert P.unpack_frame(data) == (P.CMD_GET_STATUS, b"") + _conn(accepted).sendall(P.pack_frame(P.RSP_FIRMWARE, b"Litearm1.10.0-7J")) + got = tr.read_frame(timeout=2.0) + assert got == (P.RSP_FIRMWARE, b"Litearm1.10.0-7J") + finally: + tr.close() + + +def test_port_is_kept_verbatim_for_connect_idempotency(): + """`Arm.connect()` 的幂等判据读的是 `transport.port`, 必须是原样的 URL。""" + with fake_firmware() as (url, accepted): + tr = TcpTransport(url) + try: + assert tr.port == url + assert isinstance(tr.port, str) + finally: + tr.close() + + +def test_half_frame_survives_a_timeout(): + """半帧超时**不丢**: 下一次读要能接着把它装配出来 (串口的同名契约)。""" + with fake_firmware() as (url, accepted): + tr = TcpTransport(url, timeout=0.05) + try: + frame = P.pack_frame(P.RSP_TCP, P.pack_f32s([0.1, 0.2, 0.3, 0.0, 0.0, 0.0])) + conn = _conn(accepted) + conn.sendall(frame[:6]) + assert tr.read_frame(timeout=0.15) is None, "半帧不该装配成功" + conn.sendall(frame[6:]) + got = tr.read_frame(timeout=1.0) + assert got is not None and got[0] == P.RSP_TCP + finally: + tr.close() + + +def test_timeout_zero_returns_what_already_arrived(): + """`timeout=0` 是"有就给我" —— `Arm.poll_cart()` 靠它。""" + with fake_firmware() as (url, accepted): + tr = TcpTransport(url, timeout=0.2) + try: + _conn(accepted).sendall(P.pack_frame(P.RSP_ACK, bytes([P.CMD_ENABLE]))) + time.sleep(0.05) # 让字节真的到达内核缓冲 + got = tr.read_frame(0) + assert got == (P.RSP_ACK, bytes([P.CMD_ENABLE])) + finally: + tr.close() + + +def test_noise_bytes_go_to_text_log(): + with fake_firmware() as (url, accepted): + tr = TcpTransport(url, timeout=0.2) + try: + _conn(accepted).sendall(b"[litearm-usbcdc] ready (normal)") + assert tr.read_frame(timeout=0.2) is None + assert "ready" in tr.text_log + finally: + tr.close() + + +def test_peer_close_raises_instead_of_silently_timing_out(): + """对端关闭必须**报链路断**: 静默超时会把归因指向"固件不理我"。""" + with fake_firmware() as (url, accepted): + tr = TcpTransport(url, timeout=0.5) + try: + _conn(accepted).close() + with pytest.raises(TransportError): + for _ in range(50): + tr.read_frame(timeout=0.05) + finally: + tr.close() + + +def test_write_after_close_raises_transport_error(): + with fake_firmware() as (url, accepted): + tr = TcpTransport(url) + tr.close() + with pytest.raises(TransportError): + tr.write_frame(P.CMD_GET_STATUS) + assert tr.is_open is False + tr.close() # 幂等 + + +def test_connect_failure_is_a_transport_error(): + """端口没人监听时, 必须是本包的 TransportError (调用方按它做分支)。""" + with pytest.raises(TransportError): + TcpTransport("tcp://127.0.0.1:1", connect_timeout=0.5) + + +# --------------------------------------------------------------------------- # +# 分发 (Arm.connect 的分支) +# --------------------------------------------------------------------------- # +def test_is_tcp_target_delegates_to_the_same_rules(): + assert is_tcp_target("tcp://127.0.0.1:5601") is True + assert is_tcp_target("127.0.0.1:5601") is True + assert is_tcp_target("/dev/ttyACM0") is False + assert is_tcp_target("fake") is False + + +def test_arm_keeps_using_serial_transport_for_non_tcp_ports(monkeypatch): + """串口分支必须**仍然直接引用 `arm.SerialTransport`** —— 那是离线测试与 + `litearm-server --dry-run` 的注入点 (tests/conftest.py 靠替换它注桩)。 + """ + from litearm import arm as arm_mod + from litearm.testing import FakeTransport + + made = [] + + def factory(port): + made.append(port) + return FakeTransport() + + monkeypatch.setattr(arm_mod, "SerialTransport", factory) + arm_mod.Arm(port="fake").connect().close() + assert made == ["fake"], "非 TCP 端口没有走 SerialTransport 注入点" + + +def test_arm_routes_a_tcp_url_to_the_tcp_transport(monkeypatch): + from litearm import arm as arm_mod + + monkeypatch.setattr(arm_mod, "SerialTransport", + lambda *a, **k: pytest.fail("TCP 目标不该去开串口")) + with pytest.raises(TransportError): + # 端口没人监听 -> 传输层报 TransportError, 但**不是**串口路径 + arm_mod.Arm(port="tcp://127.0.0.1:1").connect() From 01c68036b2110e636cbcd8d64a94cb60892c45d7 Mon Sep 17 00:00:00 2001 From: thetooler Date: Wed, 28 Oct 2026 11:28:17 +0800 Subject: [PATCH 2/2] docs: show how to point the SDK at a simulated firmware over tcp:// The transport landed with code and tests only, so the only way to discover that `port` takes a network target was to read `transport_tcp.py`. Document the three accepted spellings, that auto-discovery does not apply, and the two failure modes (unreachable endpoint / peer closed), plus what a simulated arm can and cannot validate in the examples. --- README.md | 44 ++++++++++++++++++++++++++++++++++++++++ README.zh-CN.md | 38 ++++++++++++++++++++++++++++++++++ examples/README.md | 26 +++++++++++++++++++++++- examples/README.zh-CN.md | 21 +++++++++++++++++++ examples/_common.py | 5 ++++- 5 files changed, 132 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b4053d9..d705ab6 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ from there. `Arm().connect()` is the only entry point. Every session carries a read thread, so **you must `close()` it** — `with` does that for you. Pass `port` to pick the serial port; leave it out and the SDK auto-discovers it (VID:PID `1d50:606f`). The SDK **reads no environment variables**. +`port` also takes a network target — see [Over TCP](#over-tcp). Every `arm` below refers to that connected session object; the snippets show only the steps that section is about. @@ -130,6 +131,46 @@ print(arm.n) # joint count arm.close() # disconnect (a with block does this for you) ``` +#### Over TCP + +`port` also accepts a network target, so the same script drives a firmware stand-in — a +MuJoCo-backed simulation, or anything else that speaks this protocol — with nothing changed +below the connection call: + +```text +pa.Arm(port="tcp://127.0.0.1:5601").connect() +``` + +Three spellings are accepted: `tcp://host:port`, `sim://host:port`, and a bare `host:port` +(exactly one colon, digits after it). A serial path is never mistaken for one: + +```python +from litearm.transport import is_tcp_target + +is_tcp_target("tcp://127.0.0.1:5601") # True +is_tcp_target("127.0.0.1:5601") # True — bare host:port +is_tcp_target("sim://127.0.0.1:5601") # True +is_tcp_target("/dev/ttyACM0") # False — still serial +is_tcp_target("COM5") # False +``` + +This is **not a second backend**: the frames, their timing assumptions and the error classes are +the serial ones — only the carrier changes, from USB CDC to a socket — so every `Arm` method +behaves identically. What does differ: + +- **auto-discovery does not apply.** It enumerates USB CDC (`1d50:606f`) only, and with no arm + plugged in `Arm().connect()` raises. Name the network target explicitly. +- Nothing extra to install: stdlib `socket` / `select` only, so `pyserial` stays the sole + dependency. +- An unreachable endpoint fails inside `connect()` with `TransportError` (2 s connect timeout), + and a peer that closes the socket also raises `TransportError` — the link does not sit there + looking idle until some unrelated timeout fires. +- The target string is kept verbatim, so `connect()` on a live session remains a no-op instead + of re-targeting it. + +`connect()` picks the carrier in this order: an injected `transport_factory`, then a +TCP-looking target, then `SerialTransport`. + ### Joint motion All three need `enable()` first: `movej` is a single shot (the firmware plans the S-curve and @@ -319,6 +360,9 @@ litearm-python fw # version string + axis count litearm-python tcp # current pose + frame rate litearm-python movej -0.1 0 0 0 0 0 0 --speed 0.3 litearm-python home + +# the same commands against a simulated firmware over TCP +litearm-python --port tcp://127.0.0.1:5601 status ``` `status` / `fw` / `tcp` are read-only; the rest really drive the arm. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5c1d912..c283dfd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -98,6 +98,7 @@ with pa.Arm().connect() as arm: `Arm().connect()` 是唯一入口。每个会话背后有一条读线程,**用完必须 `close()`**,`with` 会自动关。 串口由 `port` 参数指定,不传则自动发现(VID:PID `1d50:606f`)。SDK **不读任何环境变量**。 +`port` 也可以是网络目标,见[走 TCP](#走-tcp)。 下面各节的 `arm` 都指这个已连好的会话对象,片段只写该节要讲的那几步。 @@ -112,6 +113,40 @@ print(arm.n) # 关节数 arm.close() # 断开(用 with 会自动调) ``` +#### 走 TCP + +`port` 也可以填**网络目标** —— 同一份脚本就能驱动一个"固件替身"(MuJoCo 后端仿真,或任何 +按本协议实现的对方),连接那一行以下一个字都不用改: + +```text +pa.Arm(port="tcp://127.0.0.1:5601").connect() +``` + +认三种写法:`tcp://host:port`、`sim://host:port`、以及裸的 `host:port`(只有一个冒号、 +冒号后是纯数字)。串口路径不会被误判: + +```python +from litearm.transport import is_tcp_target + +is_tcp_target("tcp://127.0.0.1:5601") # True +is_tcp_target("127.0.0.1:5601") # True —— 裸 host:port +is_tcp_target("/dev/ttyACM0") # False —— 仍走串口 +is_tcp_target("COM5") # False +``` + +它**不是"另一个后端"**:帧格式、时序假设、错误分类全部与串口那套一致,只是载体从 USB CDC +换成了 socket —— 所以 `Arm` 的每个方法行为都相同。有区别的只有这几条: + +- **自动发现不适用。** 它只枚举 USB CDC(`1d50:606f`),没插臂时 `Arm().connect()` 直接抛 + `TransportError`。网络目标必须显式写出来。 +- 不用多装任何东西:只用标准库 `socket` / `select`,`pyserial` 仍是唯一依赖。 +- 目标不可达时在 `connect()` 里抛 `TransportError`(连接超时 2 s);对端关掉 socket 也抛 + `TransportError` —— 不会让链路"看起来只是没数据",等到别处的超时才归因错。 +- 目标串原样保存,所以已连上的会话再 `connect()` 仍是空操作,不会被判成"换了目标"而把在途 + 记账与保活推倒重来。 + +`connect()` 选载体的顺序:注入的 `transport_factory` > 像 TCP 的目标 > `SerialTransport`。 + ### 关节运动 三个入口都要先 `enable()`:`movej` 单发(固件规划 S 曲线、自己走完), @@ -296,6 +331,9 @@ litearm-python fw # 版本串 + 轴数 litearm-python tcp # 当前位姿 + 帧率 litearm-python movej -0.1 0 0 0 0 0 0 --speed 0.3 litearm-python home + +# 对着 TCP 仿真固件跑同一套命令 +litearm-python --port tcp://127.0.0.1:5601 status ``` `status` / `fw` / `tcp` 只读,其余会真的驱动机械臂。 diff --git a/examples/README.md b/examples/README.md index 3f72f90..0abab7d 100644 --- a/examples/README.md +++ b/examples/README.md @@ -14,7 +14,8 @@ explicit `--go`, so nothing moves by accident. `/dev/ttyACM*`. Port priority: `--port` > the `LITEARM_PORT` environment variable > auto-discovery -(`1d50:606f`). +(`1d50:606f`). `--port` and `LITEARM_PORT` also take a network target — see +[Against a simulated firmware](#against-a-simulated-firmware-over-tcp). ## Running @@ -42,6 +43,29 @@ python examples\01_hello.py On Windows, `LITEARM_PORT` pins a port such as `COM5`. +## Against a simulated firmware over TCP + +Every example runs unchanged against a firmware stand-in that speaks the same protocol over a +socket — a MuJoCo-backed simulation, for instance. Hand it the target instead of a device path: + +```bash +python3 examples/01_hello.py --port tcp://127.0.0.1:5601 +LITEARM_PORT=tcp://127.0.0.1:5601 ./run_example.sh 06_cartesian.py --go +``` + +`tcp://host:port`, `sim://host:port` and a bare `host:port` all work; a device path such as +`/dev/ttyACM0` or `COM5` is never mistaken for one. Auto-discovery is **skipped** for a network +target — it enumerates USB CDC only — so the target must always be spelled out. + +Read-only-by-default and the `--go` gate hold here too, and poses / speeds mean the same thing. +What does not carry over is anything that depends on the real arm's mechanics. `01` / `02` / `06` +are still a genuine end-to-end test of the command plumbing, but a simulation agrees with itself: +none of it tells you whether your workspace, joint limits or cycle times are achievable on +hardware, and `07_vel_jitter_trace.py` measures the timing of whatever is on the other end rather +than the USB link. `09_payload_identify.py` is meaningless there — it measures the mass your load +adds to the arm, and a simulated arm has no load to add. `08_tcp_offset.py` is fine: the offset +solve is host-side. + ## The examples | Example | What it shows | Needs `--go` | diff --git a/examples/README.zh-CN.md b/examples/README.zh-CN.md index 5c66401..8e7466b 100644 --- a/examples/README.zh-CN.md +++ b/examples/README.zh-CN.md @@ -11,6 +11,7 @@ litearm-python SDK 的可运行样例,一个脚本一项功能。每个都能 3. 串口可被独占——关掉其它占着 `/dev/ttyACM*` 的进程。 端口优先级:`--port` > 环境变量 `LITEARM_PORT` > 自动发现(`1d50:606f`)。 +`--port` 与 `LITEARM_PORT` 也可以填网络目标 —— 见[对着 TCP 仿真固件跑](#对着-tcp-仿真固件跑)。 ## 运行 @@ -38,6 +39,26 @@ python examples\01_hello.py Windows 上 `LITEARM_PORT` 可以锁定 `COM5` 这类端口。 +## 对着 TCP 仿真固件跑 + +所有样例都能原样跑在"固件替身"上 —— 对方用同一套协议、只是载体换成 socket,例如 MuJoCo +后端仿真。把目标写在端口的位置上即可: + +```bash +python3 examples/01_hello.py --port tcp://127.0.0.1:5601 +LITEARM_PORT=tcp://127.0.0.1:5601 ./run_example.sh 06_cartesian.py --go +``` + +`tcp://host:port`、`sim://host:port`、裸的 `host:port` 都认;`/dev/ttyACM0` / `COM5` 这类 +设备路径不会被误判。网络目标**不走自动发现**(自动发现只枚举 USB CDC),必须显式写出来。 + +「默认只读 + 要 `--go` 才动」在这里同样成立,位姿与速度的含义也没变。**不成立**的是任何 +依赖真机机械特性的判断:`01` / `02` / `06` 仍是对命令链路的一次真端到端验证,但仿真自己 +跟自己一致 —— 它不会告诉你工作空间、关节限位、节拍在实物上是否可行; +`07_vel_jitter_trace.py` 量到的是对端的时序,不是 USB 链路。 +`09_payload_identify.py` 在仿真上没有意义:它量的是负载给臂额外加的质量,而仿真的臂没有 +负载可加。`08_tcp_offset.py` 没问题,偏移是在宿主侧解出来的。 + ## 样例列表 | 样例 | 演示什么 | 需要 `--go` | diff --git a/examples/_common.py b/examples/_common.py index c93c2eb..218dc39 100644 --- a/examples/_common.py +++ b/examples/_common.py @@ -18,7 +18,8 @@ def parser(desc="", go_help=GO_HELP): ap = argparse.ArgumentParser(description=desc) - ap.add_argument("--port", default=None, help="串口 (默认自动找 1d50:606f)") + ap.add_argument("--port", default=None, + help="串口, 或 TCP 目标 tcp://host:port (默认自动找 1d50:606f)") ap.add_argument("--go", action="store_true", help=go_help) ap.add_argument("--speed", type=float, default=0.3, help="move 速度倍率 0~1") return ap @@ -32,6 +33,8 @@ def make_arm(args): """连接并校验固件版本约定 (Litearm<主.次.修>-{7J|1J} ≥1.5.0)。 端口优先级: --port > 环境变量 LITEARM_PORT > 自动发现 (1d50:606f)。 + 前两者可以是串口, 也可以是 TCP 目标 (tcp://host:port) —— 后者连着仿真固件, + 此时不会走自动发现 (它只枚举 USB CDC), 必须显式指定。 """ port = args.port or os.environ.get("LITEARM_PORT") or None return pa.Arm(port=port).connect()