by Drew Owens
Open-source 15-DoF XL330 biped goose robot with Spine molecule PCB, 3D-printed chassis, and Isaac Lab to MuJoCo sim-to-real RL stack
main
Drew Owens
Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack
e843249
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
"""Binary Spine UART framing (COBS + CRC-16) and Unix-domain-socket JSON-RPC."""
from __future__ import annotations
import json
import os
import select
import socket
import struct
import threading
from pathlib import Path
from typing import Any, Callable, Dict
from goosectl.config import TOTAL_DOF
HOST_FRAME_MAGIC: int = 0xA5
HOST_FRAME_HEADER_STRUCT = struct.Struct("<BBHH") # magic, msg_type, seq, payload_len
HOST_FRAME_CRC_STRUCT = struct.Struct("<H")
HOST_MSG_TELEMETRY: int = 0x01
HOST_MSG_CMD_JOINTS: int = 0x02
HOST_MSG_CMD_ESTOP: int = 0x03
HOST_MSG_PING: int = 0x04
HOST_MSG_PONG: int = 0x84
SPINE_STATUS_TORQUE_ENABLED: int = 1 << 0
SPINE_STATUS_WATCHDOG_TRIPPED: int = 1 << 1
SPINE_STATUS_ESTOP_LATCHED: int = 1 << 2
SPINE_STATUS_UNDERVOLT_FAULT: int = 1 << 3
SPINE_STATUS_OVERCURRENT_FAULT: int = 1 << 4
SPINE_STATUS_DXL_BUS_OK: int = 1 << 5
SPINE_STATUS_TORSO_IMU_OK: int = 1 << 6
SPINE_STATUS_HEAD_I2C_OK: int = 1 << 7
HOST_CMD_FLAG_TORQUE_ENABLE: int = 1 << 0
HOST_CMD_FLAG_ESTOP: int = 1 << 1
HOST_CMD_FLAG_CLEAR_FAULTS: int = 1 << 2
HOST_CMD_FLAG_LED_OVERRIDE: int = 1 << 3
# Exact binary layout matching mg_telemetry_payload_t (194 bytes) in firmware/include/host_frame.h
TELEMETRY_PAYLOAD_STRUCT = struct.Struct("<IHHHhh3h3h3h3hH64B15h15h15h")
CMD_JOINTS_PAYLOAD_STRUCT = struct.Struct("<H15h3B3B")
assert TELEMETRY_PAYLOAD_STRUCT.size == 194, f"Expected 194B, got {TELEMETRY_PAYLOAD_STRUCT.size}"
assert CMD_JOINTS_PAYLOAD_STRUCT.size == 38, f"Expected 38B, got {CMD_JOINTS_PAYLOAD_STRUCT.size}"
def _build_dxl_crc_table() -> tuple[int, ...]:
table = []
for i in range(256):
crc = i << 8
for _ in range(8):
if crc & 0x8000:
crc = ((crc << 1) ^ 0x8005) & 0xFFFF
else:
crc = (crc << 1) & 0xFFFF
table.append(crc)
return tuple(table)
_DXL_CRC_TABLE = _build_dxl_crc_table()
def dxl_crc16(data: bytes, crc_accum: int = 0x0000) -> int:
"""Compute Dynamixel Protocol 2.0 CRC-16 (poly 0x8005, non-reflected)."""
for b in data:
idx = ((crc_accum >> 8) ^ b) & 0xFF
crc_accum = ((crc_accum << 8) ^ _DXL_CRC_TABLE[idx]) & 0xFFFF
return crc_accum
def cobs_encode(data: bytes) -> bytes:
"""Consistent Overhead Byte Stuffing matching firmware/src/host_frame.c."""
out = bytearray([0])
code_idx = 0
code = 1
n = len(data)
for i, b in enumerate(data):
if b == 0:
out[code_idx] = code
code = 1
code_idx = len(out)
out.append(0)
else:
out.append(b)
code += 1
if code == 0xFF and (i + 1) < n:
out[code_idx] = code
code = 1
code_idx = len(out)
out.append(0)
out[code_idx] = code
return bytes(out)
def cobs_decode(encoded: bytes) -> bytes:
"""Decode COBS body (without trailing 0x00 delimiter) matching host_frame.c."""
if not encoded:
raise ValueError("Empty COBS buffer")
out = bytearray()
idx = 0
n = len(encoded)
while idx < n:
code = encoded[idx]
idx += 1
if code == 0:
raise ValueError("Unexpected zero byte inside COBS payload")
copy_len = code - 1
if idx + copy_len > n:
raise ValueError("Truncated COBS block")
out.extend(encoded[idx : idx + copy_len])
idx += copy_len
if code < 0xFF and idx < n:
out.append(0)
return bytes(out)
def host_frame_pack(msg_type: int, seq: int, payload: bytes = b"") -> bytes:
"""Pack [magic, msg_type, seq, len, payload, crc16] into 0x00-terminated COBS frame."""
header = HOST_FRAME_HEADER_STRUCT.pack(HOST_FRAME_MAGIC, msg_type & 0xFF, seq & 0xFFFF, len(payload))
body = header + payload
crc = dxl_crc16(body, 0x0000)
raw = body + HOST_FRAME_CRC_STRUCT.pack(crc)
return cobs_encode(raw) + b"\x00"
def host_frame_unpack(wire_frame: bytes) -> tuple[int, int, bytes]:
"""Unpack a COBS wire frame and verify magic + CRC-16. Returns (msg_type, seq, payload)."""
if wire_frame.endswith(b"\x00"):
wire_frame = wire_frame[:-1]
raw = cobs_decode(wire_frame)
if len(raw) < HOST_FRAME_HEADER_STRUCT.size + HOST_FRAME_CRC_STRUCT.size:
raise ValueError("Decoded frame shorter than header + CRC")
magic, msg_type, seq, payload_len = HOST_FRAME_HEADER_STRUCT.unpack_from(raw, 0)
if magic != HOST_FRAME_MAGIC:
raise ValueError(f"Invalid frame magic 0x{magic:02X}")
expected_len = HOST_FRAME_HEADER_STRUCT.size + payload_len + HOST_FRAME_CRC_STRUCT.size
if len(raw) != expected_len:
raise ValueError(f"Frame length mismatch: {len(raw)} vs {expected_len}")
(rx_crc,) = HOST_FRAME_CRC_STRUCT.unpack_from(raw, len(raw) - 2)
calc_crc = dxl_crc16(raw[:-2], 0x0000)
if rx_crc != calc_crc:
raise ValueError(f"CRC-16 mismatch: rx=0x{rx_crc:04X}, calc=0x{calc_crc:04X}")
payload = raw[HOST_FRAME_HEADER_STRUCT.size : len(raw) - 2]
return msg_type, seq, payload
def rad_to_0p1mrad(rad: float) -> int:
scaled = int(round(float(rad) * 10000.0))
return max(-32767, min(32767, scaled))
def pack_cmd_joints(
seq: int,
goal_rad_15: list[float],
torque_enable: bool = True,
estop: bool = False,
clear_faults: bool = False,
led0_rgb: tuple[int, int, int] = (0, 36, 34),
led1_rgb: tuple[int, int, int] = (0, 12, 32),
) -> bytes:
if len(goal_rad_15) != TOTAL_DOF:
raise ValueError(f"Expected {TOTAL_DOF} joint targets, got {len(goal_rad_15)}")
flags = 0
if torque_enable:
flags |= HOST_CMD_FLAG_TORQUE_ENABLE
if estop:
flags |= HOST_CMD_FLAG_ESTOP
if clear_faults:
flags |= HOST_CMD_FLAG_CLEAR_FAULTS
fixed_goals = [rad_to_0p1mrad(v) for v in goal_rad_15]
payload = CMD_JOINTS_PAYLOAD_STRUCT.pack(flags, *fixed_goals, *led0_rgb, *led1_rgb)
return host_frame_pack(HOST_MSG_CMD_JOINTS, seq, payload)
def unpack_telemetry(payload: bytes) -> Dict[str, Any]:
if len(payload) != TELEMETRY_PAYLOAD_STRUCT.size:
raise ValueError(f"Expected 194-byte telemetry payload, got {len(payload)}")
unpacked = TELEMETRY_PAYLOAD_STRUCT.unpack(payload)
uptime_us = unpacked[0]
status_flags = unpacked[1]
vbat_mv = unpacked[2]
bus_5v_mv = unpacked[3]
bus_current_ma = unpacked[4]
bus_power_mw = unpacked[5]
torso_accel_mg = list(unpacked[6:9])
torso_gyro_mrad_s = list(unpacked[9:12])
head_accel_mg = list(unpacked[12:15])
head_gyro_mrad_s = list(unpacked[15:18])
tof_min_mm = unpacked[18]
tof_grid_4mm = list(unpacked[19:83])
pos_raw = unpacked[83:98]
vel_raw = unpacked[98:113]
load_raw = unpacked[113:128]
return {
"uptime_us": uptime_us,
"status_flags": status_flags,
"torque_enabled": bool(status_flags & SPINE_STATUS_TORQUE_ENABLED),
"watchdog_tripped": bool(status_flags & SPINE_STATUS_WATCHDOG_TRIPPED),
"estop_latched": bool(status_flags & SPINE_STATUS_ESTOP_LATCHED),
"vbat_v": vbat_mv * 0.001,
"bus_5v_v": bus_5v_mv * 0.001,
"bus_current_a": bus_current_ma * 0.001,
"bus_watts": bus_power_mw * 0.001,
"torso_accel_m_s2": [v * 0.00980665 for v in torso_accel_mg],
"torso_gyro_rad_s": [v * 0.001 for v in torso_gyro_mrad_s],
"head_accel_m_s2": [v * 0.00980665 for v in head_accel_mg],
"head_gyro_rad_s": [v * 0.001 for v in head_gyro_mrad_s],
"tof_min_m": tof_min_mm * 0.001,
"tof_8x8_m": [z * 0.004 for z in tof_grid_4mm],
"joint_pos_rad": [p * 0.0001 for p in pos_raw],
"joint_vel_rad_s": [v * 0.001 for v in vel_raw],
"joint_load_ma": list(load_raw),
}
class PosixUartLink:
"""Zero-dependency POSIX termios UART link for Radxa Zero 3W / Linux (1 or 2 Mbps 8N1)."""
def __init__(self, port: str = "", baud: int = 1_000_000, fd: int | None = None) -> None:
import termios
import tty
self.port = port
self.baud = baud
self._owns_fd = fd is None
self._fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) if fd is None else fd
os.set_blocking(self._fd, False)
try:
tty.setraw(self._fd)
attrs = termios.tcgetattr(self._fd)
baud_map = {
115200: termios.B115200,
921600: termios.B921600,
1000000: getattr(termios, "B1000000", termios.B921600),
2000000: getattr(termios, "B2000000", termios.B921600),
}
if baud not in baud_map:
if self._owns_fd:
os.close(self._fd)
raise ValueError(f"Unsupported UART baud rate {baud}")
bconst = baud_map[baud]
attrs[4] = bconst
attrs[5] = bconst
attrs[2] |= termios.CLOCAL | termios.CREAD
attrs[2] &= ~termios.CRTSCTS
termios.tcsetattr(self._fd, termios.TCSANOW, attrs)
except termios.error:
if self._owns_fd:
os.close(self._fd)
raise
self._rx_buf = bytearray()
def fileno(self) -> int:
return self._fd
def write_frame(self, wire_bytes: bytes) -> None:
view = memoryview(wire_bytes)
sent = 0
while sent < len(view):
_, wlist, _ = select.select([], [self._fd], [], 0.02)
if not wlist:
break
sent += os.write(self._fd, view[sent:])
def poll_frames(self) -> list[tuple[int, int, bytes]]:
frames: list[tuple[int, int, bytes]] = []
while True:
rlist, _, _ = select.select([self._fd], [], [], 0.0)
if not rlist:
break
try:
chunk = os.read(self._fd, 1024)
except BlockingIOError:
break
if not chunk:
break
self._rx_buf.extend(chunk)
while True:
zero_pos = self._rx_buf.find(0)
if zero_pos < 0:
if len(self._rx_buf) > 1024:
self._rx_buf.clear()
break
raw_cobs = bytes(self._rx_buf[:zero_pos])
del self._rx_buf[: zero_pos + 1]
if not raw_cobs:
continue
try:
frames.append(host_frame_unpack(raw_cobs))
except ValueError:
continue
return frames
def close(self) -> None:
if self._fd >= 0 and self._owns_fd:
os.close(self._fd)
self._fd = -1
class UnixJsonServer:
"""Thread-per-connection newline-delimited JSON-RPC server over AF_UNIX."""
def __init__(self, sock_path: str | Path, handler: Callable[[Dict[str, Any]], Dict[str, Any]]) -> None:
self.sock_path = Path(sock_path)
self.handler = handler
self._stop_event = threading.Event()
self._sock: socket.socket | None = None
self._accept_thread: threading.Thread | None = None
def start(self) -> None:
self.sock_path.parent.mkdir(parents=True, exist_ok=True)
if self.sock_path.exists():
self.sock_path.unlink()
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(str(self.sock_path))
os.chmod(self.sock_path, 0o600)
srv.listen(16)
srv.settimeout(0.15)
self._sock = srv
self._accept_thread = threading.Thread(target=self._accept_loop, name="unix-rpc-accept", daemon=True)
self._accept_thread.start()
def _accept_loop(self) -> None:
assert self._sock is not None
while not self._stop_event.is_set():
try:
conn, _ = self._sock.accept()
except socket.timeout:
continue
except OSError:
break
t = threading.Thread(target=self._client_loop, args=(conn,), daemon=True)
t.start()
def _client_loop(self, conn: socket.socket) -> None:
conn.settimeout(1.0)
buf = bytearray()
try:
while not self._stop_event.is_set():
try:
data = conn.recv(4096)
except socket.timeout:
continue
except OSError:
break
if not data:
break
buf.extend(data)
while True:
nl = buf.find(b"\n")
if nl < 0:
break
line = bytes(buf[:nl])
del buf[: nl + 1]
if not line.strip():
continue
try:
req = json.loads(line.decode("utf-8"))
resp = self.handler(req)
except Exception as exc: # noqa: BLE001
resp = {"ok": False, "error": str(exc)}
payload = (json.dumps(resp, separators=(",", ":")) + "\n").encode("utf-8")
conn.sendall(payload)
finally:
try:
conn.close()
except OSError:
pass
def stop(self) -> None:
self._stop_event.set()
if self._sock is not None:
try:
self._sock.close()
except OSError:
pass
if self._accept_thread is not None:
self._accept_thread.join(timeout=1.0)
if self.sock_path.exists():
try:
self.sock_path.unlink()
except OSError:
pass
class PersistentUnixClient:
"""Low-jitter persistent AF_UNIX JSON-RPC client for the 50 Hz control loop."""
def __init__(self, sock_path: str | Path, timeout_sec: float = 0.5) -> None:
self.sock_path = str(sock_path)
self.timeout_sec = timeout_sec
self._sock: socket.socket | None = None
self._rx_buf = bytearray()
self._lock = threading.Lock()
def _ensure_connected(self) -> socket.socket:
if self._sock is None:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(self.timeout_sec)
s.connect(self.sock_path)
self._sock = s
self._rx_buf.clear()
return self._sock
def call(self, req: Dict[str, Any]) -> Dict[str, Any]:
raw = (json.dumps(req, separators=(",", ":")) + "\n").encode("utf-8")
with self._lock:
for attempt in range(2):
try:
s = self._ensure_connected()
s.sendall(raw)
while True:
nl = self._rx_buf.find(b"\n")
if nl >= 0:
line = bytes(self._rx_buf[:nl])
del self._rx_buf[: nl + 1]
return json.loads(line.decode("utf-8"))
chunk = s.recv(8192)
if not chunk:
raise ConnectionError("Unix socket closed by peer")
self._rx_buf.extend(chunk)
except OSError:
self.close_unlocked()
if attempt == 1:
raise
raise ConnectionError(f"Failed RPC to {self.sock_path}")
def close_unlocked(self) -> None:
if self._sock is not None:
try:
self._sock.close()
except OSError:
pass
self._sock = None
self._rx_buf.clear()
def close(self) -> None:
with self._lock:
self.close_unlocked()
def unix_rpc_call(sock_path: str | Path, req: Dict[str, Any], timeout_sec: float = 2.0) -> Dict[str, Any]:
"""One-shot Unix-domain-socket RPC helper for CLI invocations."""
client = PersistentUnixClient(sock_path, timeout_sec=timeout_sec)
try:
return client.call(req)
finally:
client.close()