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
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ with pa.Arm().connect() as arm:

`Arm().connect()` 是唯一入口。每个会话背后有一条读线程,**用完必须 `close()`**,`with` 会自动关。
串口由 `port` 参数指定,不传则自动发现(VID:PID `1d50:606f`)。SDK **不读任何环境变量**。
`port` 也可以是网络目标,见[走 TCP](#走-tcp)。

下面各节的 `arm` 都指这个已连好的会话对象,片段只写该节要讲的那几步。

Expand All @@ -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 曲线、自己走完),
Expand Down Expand Up @@ -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` 只读,其余会真的驱动机械臂。
Expand Down
26 changes: 25 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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` |
Expand Down
21 changes: 21 additions & 0 deletions examples/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ litearm-python SDK 的可运行样例,一个脚本一项功能。每个都能
3. 串口可被独占——关掉其它占着 `/dev/ttyACM*` 的进程。

端口优先级:`--port` > 环境变量 `LITEARM_PORT` > 自动发现(`1d50:606f`)。
`--port` 与 `LITEARM_PORT` 也可以填网络目标 —— 见[对着 TCP 仿真固件跑](#对着-tcp-仿真固件跑)。

## 运行

Expand Down Expand Up @@ -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` |
Expand Down
5 changes: 4 additions & 1 deletion examples/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
13 changes: 11 additions & 2 deletions src/litearm/arm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down Expand Up @@ -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`)。
#: 位置: 会话对象一建好就落, 早于下面那句握手写帧, 也早于读线程起。
Expand Down
16 changes: 16 additions & 0 deletions src/litearm/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading
Loading