From edba61dbff192b7642423bad47b0534454567da2 Mon Sep 17 00:00:00 2001 From: yassinsolim Date: Sat, 10 Oct 2026 21:01:06 -0600 Subject: [PATCH 01/11] Drive the real arm through the carrier at 1 Mbaud The drive map uses the CAD gear ratios (26:1 reducers, 3:1 wrist belts) and keeps the tool placeholder at CAN ID 6. slcan_bus writes each tick in one go at 1 Mbaud and follows every frame with an empty line, so a BELL can be matched to the frame the carrier refused. The drive node sends a refused move, stop, setup or zero frame again, shows the carrier's status as can.carrier, stops every drive when the e-stop is pressed, and passes new targets on as soon as teleop sends them. mks_setup finds the drives and sets their CAN IDs and bit rates. --- BuildInstructions.md | 6 +- .../launch/ground_station.launch.py | 7 +- waybionic_teleop/config/arm_drives.yaml | 43 ++-- waybionic_teleop/package.xml | 2 + waybionic_teleop/setup.py | 1 + waybionic_teleop/test/test_can_drives.py | 208 +++++++++++++++-- waybionic_teleop/test/test_drive_map.py | 23 +- waybionic_teleop/test/test_mks_can.py | 13 ++ waybionic_teleop/test/test_mks_setup.py | 34 +++ .../test/test_sim_arm_drives_node.py | 91 +++++++- waybionic_teleop/test/test_slcan_bus.py | 190 +++++++++++++++ waybionic_teleop/test/test_straight_cut.py | 2 +- waybionic_teleop/test/test_tool_motor.py | 6 +- waybionic_teleop/waybionic_teleop/carrier.py | 27 +++ waybionic_teleop/waybionic_teleop/mks_can.py | 31 ++- .../waybionic_teleop/mks_drive_sim.py | 2 + .../waybionic_teleop/mks_setup.py | 144 ++++++++++++ .../waybionic_teleop/sim_arm_drives_node.py | 105 ++++++++- .../waybionic_teleop/sim_drives.py | 22 +- .../waybionic_teleop/slcan_bus.py | 218 ++++++++++++++++++ 20 files changed, 1103 insertions(+), 72 deletions(-) create mode 100644 waybionic_teleop/test/test_mks_setup.py create mode 100644 waybionic_teleop/test/test_slcan_bus.py create mode 100644 waybionic_teleop/waybionic_teleop/carrier.py create mode 100644 waybionic_teleop/waybionic_teleop/mks_setup.py create mode 100644 waybionic_teleop/waybionic_teleop/slcan_bus.py diff --git a/BuildInstructions.md b/BuildInstructions.md index 5105335a..cef63a8d 100644 --- a/BuildInstructions.md +++ b/BuildInstructions.md @@ -297,8 +297,8 @@ can report exit code `-2`, indicating the requested SIGINT interruption. `teleop:=true` drives the arm with an Xbox controller through simulated CAN drives; nothing is sent to hardware unless you choose a drive bus, as described in [Real MKS drives over CAN](#real-mks-drives-over-can). The controller mapping is in -`waybionic_teleop/config/xbox_teleop.yaml`, and the placeholder joint-to-drive map -(MKS SERVO42D/57D CAN IDs, gear ratios and the wrist differential) is in +`waybionic_teleop/config/xbox_teleop.yaml`, and the joint-to-drive map (MKS +SERVO42D/57D CAN IDs, the 26:1 and 3:1 gear ratios and the wrist differential) is in `waybionic_teleop/config/arm_drives.yaml`. **Windows (Docker):** connect the controller, then start the teleop version of the @@ -404,7 +404,7 @@ zero, including any cable or gear stop. In simulation, a zero-velocity joint command (including B and controller timeout) sends an MKS F5 frame with zero speed and zero acceleration to each moving drive. An out-of-range encoder target stops all drives instead of updating only part of -the arm. The placeholder drive speed is capped at 300 RPM; the MKS manual warns +the arm. The drive speed is capped at 600 RPM (`max_rpm`); the MKS manual warns against immediate software stops above 1000 RPM. Each drive also runs no faster than 1.5 times its commanded speed plus 1 RPM, and teleop never advances its targets by more than two updates at once, so after a pause the drives do not catch diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index c1526797..a7992718 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -78,12 +78,13 @@ def generate_launch_description(): drive_interface_arg = DeclareLaunchArgument( 'drive_interface', default_value='sim', - description='Drive bus: sim for simulated drives, or a python-can interface such as ' - 'socketcan or slcan for the real MKS drives') + description='Drive bus: sim for simulated drives, slcan for the WayBionic carrier on ' + 'a USB serial port, or a python-can interface such as socketcan') drive_channel_arg = DeclareLaunchArgument( 'drive_channel', default_value='', - description='CAN channel for a real drive bus, such as can0 or /dev/ttyACM0') + description='The carrier serial port or CAN channel, such as /dev/cu.usbmodem1101, ' + '/dev/ttyACM0 or can0') joy_source_arg = DeclareLaunchArgument( 'joy_source', default_value='device', diff --git a/waybionic_teleop/config/arm_drives.yaml b/waybionic_teleop/config/arm_drives.yaml index 2bf528c2..f5b03126 100644 --- a/waybionic_teleop/config/arm_drives.yaml +++ b/waybionic_teleop/config/arm_drives.yaml @@ -1,23 +1,33 @@ -# Placeholder joint-to-drive map for the MKS SERVO42D/57D CAN bus, simulated or real. The CAN -# IDs, gear ratios and factors are not hardware values; replace them once Electrical and -# Mechanical confirm the drives. factors give each motor's output angle per joint angle, so the -# wrist differential turns both side-gear motors together for pitch and oppositely for roll. +# Joint-to-drive map for the arm's MKS drives on CAN, simulated or real. gear_ratio is motor +# turns per output turn, from the CAD: 26:1 cycloidal reducers (26-pin output ring, 25-lobe +# disc) on the base, shoulder and elbow, and 20T-to-60T belts (3:1) on the two wrist motors. +# factors give each motor's output angle per joint angle: the 25T bevel differential turns both +# wrist motors together for pitch and oppositely for roll. If a drive turns the wrong way on +# the bench, negate its factors. The tool drive is a placeholder with no hardware behind it; +# the tool board's motors answer on CAN IDs 7 to 10 (firmware/tool_board/README.md). sim_arm_drives: ros__parameters: rate_hz: 120.0 - # MKS default is 500 kbit/s; 1 Mbit/s keeps six drives at 120 Hz near 40% bus load. + # Set every drive to 1 Mbit/s first (mks_setup, or CanRate on its screen; MKS ships 500k): + # six drives at 120 Hz load the bus about 30% at 1 Mbit/s and 60% at 500 kbit/s. bitrate: 1000000 + # The carrier's USB serial speed (carrier_bridge.ino); only used with interface slcan. + tty_baudrate: 1000000 # Teleop ramps the speed. A steep drive ramp keeps the drives in step with each other: a # gentle one gives every drive the same rpm/s, so the one that must change most falls behind. acc: 255 - max_rpm: 300 + # The fastest teleop speed (60 deg/s) needs 260 rpm on a 26:1 joint; this leaves room for a + # drive that fell behind to catch up. + max_rpm: 600 heartbeat_ms: 500 # Without a new joint command for this long, every drive stops where it is and holds # there, whether or not the last command carried a speed. command_timeout_s: 0.5 - # Provisional until tuned on the arm: a drive more than this many encoder counts (a - # quarter motor turn) from its target for this many ticks in a row has stopped following, - # so every drive stops and the arm must be zeroed again. + # Provisional until tuned on the arm: a drive more than this many encoder counts from its + # target for this many ticks in a row has stopped following, so every drive stops and the + # arm must be zeroed again. 4096 counts is a quarter motor turn: 3.5 degrees through a 26:1 + # reducer, 30 through the 3:1 wrist belts, and about seven ticks of motion at teleop's top + # speed, whose setpoints run one tick ahead. following_error_counts: 4096 following_error_ticks: 12 # Teleop republishes its enable every tick; stop the drives if it goes quiet this long (the @@ -27,29 +37,34 @@ sim_arm_drives: # Simulation only: on a real bus every drive joint needs a URDF limit. unmodeled_joints: [tool_grip] drives: [base_yaw, shoulder, elbow, wrist_left, wrist_right, tool] + # SERVO42D (NEMA17) base_yaw: can_id: 1 - gear_ratio: 1.0 + gear_ratio: 26.0 joints: [joint_1] factors: [1.0] + # SERVO57D (NEMA23) shoulder: can_id: 2 - gear_ratio: 1.0 + gear_ratio: 26.0 joints: [joint_2] factors: [1.0] + # SERVO42D elbow: can_id: 3 - gear_ratio: 1.0 + gear_ratio: 26.0 joints: [joint_3] factors: [1.0] + # SERVO42D, left side gear: pitch minus roll wrist_left: can_id: 4 - gear_ratio: 1.0 + gear_ratio: 3.0 joints: [joint_4, joint_5] factors: [1.0, -1.0] + # SERVO42D, right side gear: pitch plus roll wrist_right: can_id: 5 - gear_ratio: 1.0 + gear_ratio: 3.0 joints: [joint_4, joint_5] factors: [1.0, 1.0] tool: diff --git a/waybionic_teleop/package.xml b/waybionic_teleop/package.xml index 237fc2f4..7ad14a25 100644 --- a/waybionic_teleop/package.xml +++ b/waybionic_teleop/package.xml @@ -16,6 +16,8 @@ visualization_msgs python3-can + + python3-serial ament_flake8 ament_pep257 diff --git a/waybionic_teleop/setup.py b/waybionic_teleop/setup.py index 76495e03..966a4bb5 100644 --- a/waybionic_teleop/setup.py +++ b/waybionic_teleop/setup.py @@ -29,6 +29,7 @@ 'xbox_teleop = waybionic_teleop.xbox_teleop_node:main', 'sim_arm_drives = waybionic_teleop.sim_arm_drives_node:main', 'mks_drive_sim = waybionic_teleop.mks_drive_sim:main', + 'mks_setup = waybionic_teleop.mks_setup:main', 'autoplay = waybionic_teleop.autoplay_node:main', 'joy_udp_receiver = waybionic_teleop.joy_udp_receiver:main', ], diff --git a/waybionic_teleop/test/test_can_drives.py b/waybionic_teleop/test/test_can_drives.py index 76a5ef1e..993700c3 100644 --- a/waybionic_teleop/test/test_can_drives.py +++ b/waybionic_teleop/test/test_can_drives.py @@ -2,7 +2,8 @@ The host drives MKS servos over a python-can interface exactly as it drives the simulation. The end-to-end test uses python-can's in-process virtual bus. The CAN CI job sets -WAYBIONIC_CAN_TEST=socketcan:vcan0 to run it over a kernel CAN interface instead. +WAYBIONIC_CAN_TEST=socketcan:vcan0 to run it over a kernel CAN interface instead. The carrier +tests stand a fake of carrier_bridge's serial port behind the slcan interface. """ import io @@ -13,6 +14,7 @@ import time import uuid +from diagnostic_msgs.msg import DiagnosticStatus import pytest import rclpy from rclpy.executors import SingleThreadedExecutor @@ -21,7 +23,7 @@ from std_msgs.msg import Bool, String from std_srvs.srv import Trigger -from waybionic_teleop import mks_can +from waybionic_teleop import carrier, mks_can, slcan_bus from waybionic_teleop.can_bus import CanBus from waybionic_teleop.mks_drive_sim import serve from waybionic_teleop.sim_arm_drives_node import QUIET_BEFORE_ZERO_S, SimArmDrives @@ -32,6 +34,10 @@ / 'waybionic_arm.urdf').read_text(encoding='utf-8') # The arm's drives without the placeholder tool, whose joint has no URDF limit yet. ARM_DRIVES = ['base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right'] +# Teleop keeps its setpoints a tick ahead of the drives. A target sent once and left must stay +# within following_error_counts of the base's encoder (3390 of 4096 counts through its 26:1 +# reducer), or the drives stop it as a drive that stopped following. +NEAR_TARGET = 0.05 @pytest.fixture @@ -115,10 +121,17 @@ def command(node, speed=1.0, **targets): velocity=velocities)) +def toward(node, speed=1.0, **targets): + """Command the named joints a tick ahead of their encoders, as teleop does.""" + current, step = positions(node), speed * node.period + command(node, speed, **{joint: current[joint] + max(-step, min(step, goal - current[joint])) + for joint, goal in targets.items()}) + + def move(node, executor, **targets): """Stream commands like teleop until the named joints reach their targets.""" def reached(): - command(node, **targets) + toward(node, **targets) return all(abs(positions(node)[joint] - value) < 1e-3 for joint, value in targets.items()) return spin_until(executor, reached) @@ -253,10 +266,11 @@ def test_the_host_drives_mks_servos_over_can(make_node): assert node.authorized, node.stop_reason assert set(node.limits) == set(node.map.joints) assert move(node, executor, joint_1=0.3, joint_4=0.2) - # Wrist pitch turns both differential motors the same way. + # Wrist pitch turns both differential motors the same way, through 3:1 belts. assert servos[4].axis == pytest.approx(servos[5].axis) - assert servos[4].axis == pytest.approx(0.2 / (2 * math.pi) * mks_can.COUNTS_PER_REV, - abs=1.0) + assert servos[4].axis == pytest.approx( + 0.2 * node.map.drives[3].gear_ratio / (2 * math.pi) * mks_can.COUNTS_PER_REV, + abs=1.0) assert node.bus.errors == 0 and node.bus_errors == 0 finally: stop.set() @@ -264,6 +278,165 @@ def test_the_host_drives_mks_servos_over_can(make_node): drives_bus.shutdown() +class FakeCarrier: + """carrier_bridge's USB serial port, with MKS drives on its CAN side and an e-stop.""" + + def __init__(self, servos): + self.servos = servos + self.output = bytearray() + self.writes = [] + self.flags = None + self.unplugged = self.open = False + # Return True to refuse a frame, as the carrier does while its CAN controller is busy. + self.refuse = lambda can_id, data: False + self.last = self.reported = time.monotonic() + + def check(self): + if self.unplugged: + raise OSError(6, 'Device not configured') + + @property + def in_waiting(self): + self.check() + return len(self.output) + + def read(self, size): + self.check() + data = bytes(self.output[:size]) + del self.output[:size] + return data + + def write(self, data): + self.check() + self.writes.append(bytes(data)) + now = time.monotonic() + frames = [(can_id, reply) for can_id, servo in self.servos.items() + for reply in servo.step(now - self.last)] + self.last = now + for line in bytes(data).split(b'\r')[:-1]: + if line[:1] != b't': + # C, Sn, O and an empty line get \r; a frame the carrier puts on the bus, nothing. + self.open = {b'O': True, b'C': False}.get(line, self.open) + self.output += b'\r' + continue + can_id, command = int(line[1:4], 16), bytes.fromhex(line[5:].decode()) + if not self.open or self.refuse(can_id, command): + self.output += b'\a' + continue + frames += [(can_id, reply) for reply in self.servos[can_id].receive(command)] + if self.flags is not None and now - self.reported >= 0.1: + frames.append((carrier.STATUS_ID, bytes([0, self.flags, 0, 0, 0, 0, 0, 0]))) + self.reported = now + for can_id, reply in frames if self.open else []: + self.output += b't%03X%d%s\r' % (can_id, len(reply), reply.hex().upper().encode()) + return len(data) + + def close(self): + pass + + +@pytest.fixture +def carrier_port(monkeypatch): + """Put a fake carrier with the arm's five drives where the drive node opens its port.""" + port = FakeCarrier({can_id: SimulatedServo(can_id) for can_id in range(1, 6)}) + + def open_port(*args, **kwargs): + port.check() + return port + monkeypatch.setattr(slcan_bus.serial, 'serial_for_url', open_port) + return port + + +def carrier_row(node, monkeypatch): + reports = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', reports.append) + node.report() + return next(row for row in reports[-1].status if row.name == 'can.carrier') + + +def test_the_host_drives_the_arm_through_the_carrier(make_node, carrier_port, monkeypatch): + port, servos = carrier_port, carrier_port.servos + node, executor = make_node(interface='slcan', channel='/dev/cu.usbmodem1101', + drives=ARM_DRIVES) + # The carrier opens at the drives' bit rate, and the monitor waits for its first report. + assert port.writes[0] == b'C\rS8\rO\r' + assert carrier_row(node, monkeypatch).level == DiagnosticStatus.WARN + port.flags = carrier.ESTOP_WIRED + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + spin_for(executor, 0.2) + row = carrier_row(node, monkeypatch) + assert row.level == DiagnosticStatus.OK and row.message.startswith('E-stop released') + assert zero(node).success + assert spin_until(executor, lambda: node.commanded is not None) + press_start(node) + assert node.authorized, node.stop_reason + assert move(node, executor, joint_1=0.3) + + # Pressed mid-move, the e-stop stops every drive where it is, and Start waits for its + # release. + def pressed_mid_move(): + toward(node, joint_1=1.0) + if positions(node)['joint_1'] > 0.5: + port.flags = carrier.ESTOP_WIRED | carrier.ESTOP_PRESSED + return not node.authorized + assert spin_until(executor, pressed_mid_move) + assert node.stop_reason == 'E-stop pressed' + assert 0.5 < positions(node)['joint_1'] < 1.0 + assert all(servo.target is None and servo.rpm == 0.0 for servo in servos.values()) + assert carrier_row(node, monkeypatch).level == DiagnosticStatus.ERROR + press_start(node) + assert not node.authorized + port.flags = carrier.ESTOP_WIRED + assert spin_until(executor, lambda: not node.estop_pressed) + press_start(node) + assert node.authorized, node.stop_reason + + # Unplugged, the drives fall silent, which stops the arm until it is zeroed again; the + # carrier is reopened once it is back. + port.unplugged = True + assert spin_until(executor, lambda: all(node.lost)) + assert not node.authorized and not any(node.zeroed) + assert 'USB link lost' in carrier_row(node, monkeypatch).message + port.unplugged = False + assert spin_until(executor, lambda: not any(node.lost)) + assert node.bus.reopens == 1 and port.writes.count(b'C\rS8\rO\r') == 2 + assert node.bus.refused == 0 + + +def test_frames_the_carrier_refuses_go_out_again(make_node, carrier_port, monkeypatch): + port = carrier_port + port.flags = carrier.ESTOP_WIRED + seen = set() + + def busy(can_id, data): + # Refuse every move, stop and zero the first time, as a carrier with a busy CAN + # controller would; resent, it goes out. + if data[0] not in (mks_can.ABSOLUTE_AXIS, mks_can.SET_ZERO) or (can_id, data) in seen: + return False + seen.add((can_id, data)) + return True + port.refuse = busy + node, executor = make_node(interface='slcan', channel='/dev/cu.usbmodem1101', + drives=ARM_DRIVES) + reports = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', reports.append) + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + # Each zero refused is sent again while the zero service waits for the replies. + assert zero(node).success + assert spin_until(executor, lambda: node.commanded is not None and not node.stopping) + press_start(node) + assert node.authorized, node.stop_reason + # A target is sent again only after its refusal, so without the resend the drives would + # never move. + assert move(node, executor, joint_1=0.3, joint_4=0.2) + assert node.authorized, node.stop_reason + node.report() + rows = [row for report in reports for row in report.status if row.name == 'can.carrier'] + assert any(row.level == DiagnosticStatus.WARN and 'frames refused' in row.message + for row in rows) + assert node.bus.refused > 0 and node.bus.errors == 0 and node.bus_errors == 0 + + def test_a_real_bus_needs_a_urdf_limit_for_every_drive_joint(make_node, mock_drives): channel, servos = mock_drives sim, _ = make_node() @@ -310,7 +483,7 @@ def test_a_drive_that_stops_answering_stops_the_arm_until_it_is_zeroed_again(mak def commanding_until_lost(): # Teleop keeps commanding a move while the elbow is silent. - command(node, joint_1=1.0) + toward(node, joint_1=1.0) return node.lost[2] assert spin_until(executor, commanding_until_lost) assert node.commanded is None and not node.zeroed[2] and not node.authorized @@ -332,17 +505,17 @@ def commanding_until_lost(): def test_commands_that_stop_mid_move_stop_the_drives(make_node): - node, executor = make_node() + node, executor = make_node(max_rpm=6) assert spin_until(executor, lambda: node.commanded is not None) press_start(node) - # One command toward a far target, then silence while teleop stays enabled, as if its - # command publisher had died mid-move. - command(node, speed=0.5, joint_1=3.0) + # One slow command, then silence while teleop stays enabled, as if its command publisher + # had died mid-move. + command(node, joint_1=NEAR_TARGET) assert spin_until(executor, enabled_until(node, lambda: node.stale)) assert not node.authorized held = positions(node)['joint_1'] spin_for(executor, 0.5) - assert 0.05 < held < 2.0 + assert 0.005 < held < NEAR_TARGET assert positions(node)['joint_1'] == pytest.approx(held, abs=1e-3) @@ -392,7 +565,7 @@ def test_a_command_without_speeds_stops_the_drives(make_node): node, executor = make_node(max_rpm=6) assert spin_until(executor, lambda: node.commanded is not None) press_start(node) - command(node, joint_1=1.0) + command(node, joint_1=NEAR_TARGET) spin_for(executor, 0.1) assert node.bus.drives[1].target is not None # Positions alone, as a publisher that fills in no velocity sends, never move the arm on @@ -439,11 +612,11 @@ def counted(reason): stops.append(reason) stop_all(reason) node.stop_all = counted - command(node, joint_1=0.5) + command(node, joint_1=NEAR_TARGET) assert spin_until(executor, enabled_until(node, lambda: node.stale)) spin_for(executor, 1.0) assert len(stops) == 1 - command(node, joint_1=0.5) + command(node, joint_1=NEAR_TARGET) assert not node.stale # Moving again takes a fresh Start. assert not node.authorized @@ -453,7 +626,7 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): node, executor = make_node(max_rpm=6) assert spin_until(executor, lambda: node.commanded is not None) press_start(node) - command(node, joint_1=1.0) + command(node, joint_1=NEAR_TARGET) spin_for(executor, 0.1) assert node.bus.drives[1].target is not None node.on_command(JointState()) @@ -468,7 +641,8 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): assert not node.authorized assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) press_start(node) - assert move(node, executor, joint_1=0.3) + # 6 rpm turns the base 0.024 rad/s through its reducer. + assert move(node, executor, joint_1=0.01) def test_silence_before_the_first_command_leaves_the_drives_holding(make_node): diff --git a/waybionic_teleop/test/test_drive_map.py b/waybionic_teleop/test/test_drive_map.py index 5743994d..79eb53c4 100644 --- a/waybionic_teleop/test/test_drive_map.py +++ b/waybionic_teleop/test/test_drive_map.py @@ -1,4 +1,4 @@ -"""Joint positions to drive encoder counts with the placeholder drive map.""" +"""Joint positions to drive encoder counts with the arm's drive map.""" import math @@ -15,9 +15,11 @@ def arm_map(parameters): parameters('arm_drives.yaml', 'sim_arm_drives'), COUNTS) -def test_placeholder_map_covers_every_arm_joint(arm_map): +def test_the_map_covers_every_arm_joint_with_the_cad_gear_ratios(arm_map): assert arm_map.joints == ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'tool_grip'] assert [drive.can_id for drive in arm_map.drives] == [1, 2, 3, 4, 5, 6] + # 26:1 cycloidal reducers on the base, shoulder and elbow; 3:1 belts on the wrist motors. + assert [drive.gear_ratio for drive in arm_map.drives] == [26.0, 26.0, 26.0, 3.0, 3.0, 1.0] def test_positions_round_trip_through_counts(arm_map): @@ -29,9 +31,10 @@ def test_positions_round_trip_through_counts(arm_map): def test_wrist_differential_mixes_pitch_and_roll(arm_map): zero = dict.fromkeys(arm_map.joints, 0.0) - quarter = COUNTS // 4 - assert arm_map.to_counts({**zero, 'joint_4': math.pi / 2})[3:5] == [quarter, quarter] - assert arm_map.to_counts({**zero, 'joint_5': math.pi / 2})[3:5] == [-quarter, quarter] + # A quarter turn of the wrist is three quarters of a turn of each motor through the belts. + turn = 3 * COUNTS // 4 + assert arm_map.to_counts({**zero, 'joint_4': math.pi / 2})[3:5] == [turn, turn] + assert arm_map.to_counts({**zero, 'joint_5': math.pi / 2})[3:5] == [-turn, turn] def test_gear_ratio_scales_counts_and_speed(): @@ -43,13 +46,15 @@ def test_gear_ratio_scales_counts_and_speed(): def test_a_setpoint_that_jumped_ahead_is_chased_near_the_commanded_speed(arm_map): period = 1.0 / 120.0 rates = {'joint_1': math.radians(60.0), 'joint_4': 0.5, 'joint_5': 0.2} - # A 100 ms host stall leaves the base setpoint 6 degrees ahead of its drive. + # A 100 ms host stall leaves the base setpoint 6 degrees ahead of its drive, which the + # 26:1 reducer makes more than the drive's top speed covers in one period. ahead = {joint: rates.get(joint, 0.0) * 0.1 for joint in arm_map.joints} counts = arm_map.to_counts(dict.fromkeys(arm_map.joints, 0.0)) - free = arm_map.synchronized(ahead, counts, period, 300) - capped = arm_map.synchronized(ahead, counts, period, 300, rates) + top = mks_can.MAX_SPEED_RPM + free = arm_map.synchronized(ahead, counts, period, top) + capped = arm_map.synchronized(ahead, counts, period, top, rates) commanded = arm_map.to_rpm(rates) - assert commanded[0] == pytest.approx(10.0) and free[0][1] == 120 + assert commanded[0] == pytest.approx(260.0) and free[0][1] == top # Each wrist drive is capped by its own mix of pitch and roll. for (axis, rpm), (free_axis, free_rpm), limit in zip(capped, free, commanded): assert axis == free_axis and 1 <= rpm <= 1.5 * limit + 1.0 diff --git a/waybionic_teleop/test/test_mks_can.py b/waybionic_teleop/test/test_mks_can.py index 3c64d4d2..4437c8bc 100644 --- a/waybionic_teleop/test/test_mks_can.py +++ b/waybionic_teleop/test/test_mks_can.py @@ -19,11 +19,24 @@ (mks_can.set_heartbeat(1, 500), '98000001F48E'), (mks_can.set_zero(1), '9293'), (mks_can.stop(1, 4), 'F5000004000000FA'), + (mks_can.set_bitrate(1, 1000000), '8A038E'), + (mks_can.set_bitrate(1, 500000), '8A028D'), + (mks_can.set_can_id(1, 3), '8B00038F'), + (mks_can.emergency_stop(1), 'F7F8'), + (mks_can.emergency_stop(0), 'F7F7'), ]) def test_frames_match_the_manual(data, expected): assert data.hex().upper() == expected +@pytest.mark.parametrize('build', [ + lambda: mks_can.set_bitrate(1, 800000), lambda: mks_can.set_can_id(1, 0), + lambda: mks_can.set_can_id(1, 0x800)]) +def test_configuration_frames_reject_values_the_drive_does_not_take(build): + with pytest.raises(ValueError): + build() + + def test_encoder_reply_decodes_negative_values(): code, arguments = mks_can.parse(1, mks_can.frame(1, mks_can.READ_ENCODER, bytes.fromhex('FFFFFFFFFFF0'))) diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py new file mode 100644 index 00000000..480425fd --- /dev/null +++ b/waybionic_teleop/test/test_mks_setup.py @@ -0,0 +1,34 @@ +"""Bench set-up of the MKS drives: finding them, new CAN IDs and bit rates.""" + +import pytest + +from waybionic_teleop import mks_setup +from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo + + +@pytest.fixture +def bus(): + # Two drives as they ship, one already set up as the elbow. + return SimulatedBus([SimulatedServo(1), SimulatedServo(3)], 500000) + + +def test_scan_finds_the_drives_that_answer(bus): + bus.drives[3].axis = 0x4000 + assert mks_setup.scan(bus, [1, 2, 3]) == {1: 0, 3: 0x4000} + + +def test_a_drive_takes_a_free_can_id(bus): + assert 'now answers on 4' in mks_setup.set_id(bus, 1, 4) + assert mks_setup.scan(bus, [1, 4]) == {4: 0} + + +def test_a_can_id_in_use_or_without_a_drive_is_refused(bus): + with pytest.raises(SystemExit, match='taken'): + mks_setup.set_id(bus, 1, 3) + with pytest.raises(SystemExit, match='no drive'): + mks_setup.set_id(bus, 2, 5) + + +def test_a_drive_switches_its_bit_rate(bus): + assert '1000000 bit/s' in mks_setup.set_bitrate(bus, 3, 1000000) + assert bus.drives[3].bitrate == 1000000 diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 23b9bf8a..7c631d3a 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -115,8 +115,86 @@ def test_a_setpoint_far_ahead_is_chased_near_its_commanded_speed(node): ready(node) node.on_command(command(node, velocities={'joint_1': 0.2}, joint_1=0.5)) advance(node) - # 0.2 rad/s is 1.9 rpm at the placeholder 1:1 gearing; the gap alone would ask 300 rpm. - assert int.from_bytes(sent_frame(node, 0)[1][:2], 'big') == 3 + # 0.2 rad/s is 49.7 rpm through the base's 26:1 reducer; the gap alone would ask 600 rpm. + assert int.from_bytes(sent_frame(node, 0)[1][:2], 'big') == 75 + + +def test_a_command_goes_out_at_once_unless_the_next_tick_stops_the_drives(node): + ready(node) + node.on_command(command(node, joint_1=0.5)) + base = node.bus.drives[1] + target = base.target + assert target is not None + # After a host pause past the heartbeat, the next tick stops the drives instead. + node.last_tick -= node.heartbeat_s + node.on_command(command(node, joint_1=0.6)) + assert base.target == target + node.tick() + assert_stopped(node) + + +def capture_sends(node, monkeypatch): + sent, send = [], node.bus.send + + def recorded(can_id, data): + sent.append(bytes(data)) + return send(can_id, data) + monkeypatch.setattr(node.bus, 'send', recorded) + return sent + + +def last_frame(node, index): + return bytes.fromhex(node.last_command[index].split('#')[1]) + + +def test_a_move_or_stop_the_carrier_refused_goes_out_again_unless_replaced(node, monkeypatch): + ready(node) + # The base takes every frame but stands still, so its target never changes by itself. + monkeypatch.setattr(node.bus.drives[1], 'step', lambda dt: []) + node.on_command(command(node, velocities={'joint_1': 0.2}, joint_1=0.5)) + advance(node) + target, sent = last_frame(node, 0), capture_sends(node, monkeypatch) + advance(node) + assert target not in sent + # The carrier answers BELL a tick after send() returned True. + node.on_refused(1, target, False) + advance(node) + assert sent.count(target) == 1 + # A refusal of a target that a later one replaced changes nothing. + node.on_command(command(node, velocities={'joint_1': 0.2}, joint_1=0.6)) + newer, sent[:] = last_frame(node, 0), [] + node.on_refused(1, target, False) + advance(node) + assert newer != target and newer not in sent and target not in sent + # A refused stop goes out again on the next tick, and Start waits for it meanwhile. + node.on_enabled(Bool(data=False)) + stop = mks_can.stop(1, 0) + assert last_frame(node, 0) == stop and not node.stopping + node.on_refused(1, stop, False) + assert node.stopping == {0} + node.on_enabled(Bool(data=True)) + assert not node.authorized + advance(node) + assert not node.stopping and sent.count(stop) == 2 + + +def test_a_refused_setup_or_zero_frame_goes_out_again_only_while_needed(node, monkeypatch): + advance(node) + sent = capture_sends(node, monkeypatch) + heartbeat, zero = mks_can.set_heartbeat(2, node.heartbeat_ms), mks_can.set_zero(3) + node.on_refused(2, heartbeat, False) + advance(node) + assert heartbeat not in sent + # A setting the shoulder has not confirmed goes out on the next tick, not a timeout later. + node.unconfirmed[1] = {mks_can.SET_HEARTBEAT} + node.on_refused(2, heartbeat, False) + advance(node) + assert heartbeat in sent and not node.unconfirmed[1] + # A zero goes out again only while the zero service waits, never later. + node.on_refused(3, zero, False) + assert zero not in sent + node.on_refused(3, zero, True) + assert zero in sent @pytest.mark.parametrize('fault', [ @@ -189,12 +267,13 @@ def test_host_pause_trips_watchdog_before_any_stale_frame_can_rearm_it(node): def test_int24_overflow_rejects_the_entire_coordinated_move(node): ready(node) + ratio = node.map.drives[0].gear_ratio node.map.drives[0].gear_ratio = 20000.0 node.on_command(command(node, joint_1=0.5, joint_2=0.5)) advance(node) assert node.rejected == 1 assert_stopped(node) - node.map.drives[0].gear_ratio = 1.0 + node.map.drives[0].gear_ratio = ratio valid = command(node, joint_1=0.5) node.on_enabled(Bool(data=True)) node.on_command(valid) @@ -301,10 +380,12 @@ def test_a_drive_that_stops_following_its_targets_stops_every_drive(node, monkey # The base accepts every move, but its encoder no longer turns. monkeypatch.setattr(base, 'step', lambda dt: []) behind = [] + # The base motor turns 1.2 rad/s, whatever its reducer. + rate = 1.2 / node.map.drives[0].gear_ratio for tick in range(1, 100): node.on_enabled(Bool(data=True)) - node.on_command(command(node, velocities={'joint_1': 1.2}, - joint_1=1.2 * tick * node.period)) + node.on_command(command(node, velocities={'joint_1': rate}, + joint_1=rate * tick * node.period)) advance(node) behind.append(node.behind[0]) if not node.authorized: diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py new file mode 100644 index 00000000..4521e5ac --- /dev/null +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -0,0 +1,190 @@ +"""The carrier's serial link: batched writes, refusals, and recovering from a lost USB.""" + +import os +import shutil +import subprocess +import time + +import pytest + +from waybionic_teleop import carrier, mks_can, slcan_bus +from waybionic_teleop.slcan_bus import SlcanBus + + +class FakeSerial: + """A USB serial port that can be unplugged.""" + + def __init__(self): + self.writes, self.inbox, self.unplugged, self.closed = [], bytearray(), False, False + + def _check(self): + if self.unplugged: + raise OSError(6, 'Device not configured') + + @property + def in_waiting(self): + self._check() + return len(self.inbox) + + def read(self, size): + self._check() + chunk = bytes(self.inbox[:size]) + del self.inbox[:size] + return chunk + + def write(self, data): + self._check() + self.writes.append(bytes(data)) + return len(data) + + def close(self): + self.closed = True + + +@pytest.fixture +def clock(monkeypatch): + now = [1000.0] + monkeypatch.setattr(slcan_bus.time, 'monotonic', lambda: now[0]) + return now + + +@pytest.fixture +def ports(): + return [] + + +@pytest.fixture +def bus(clock, ports): + def open_port(): + ports.append(FakeSerial()) + return ports[-1] + return SlcanBus('/dev/cu.usbmodem1101', 1000000, open_port=open_port) + + +def test_it_opens_the_bridge_at_the_bit_rate_then_writes_a_tick_in_one_go(bus, ports): + assert ports[0].writes == [b'C\rS8\rO\r'] + assert bus.send(1, mks_can.read_encoder(1)) and bus.send(2, mks_can.read_encoder(2)) + assert len(ports[0].writes) == 1 + assert bus.receive() is None + # The carrier answers the empty line after each frame, whether or not it took the frame. + assert ports[0].writes[1] == b't00123132\r\rt00223133\r\r' + + +def test_replies_are_parsed_across_reads(bus, ports): + ports[0].inbox += b'\r\r\rt0013F5' + assert bus.receive() is None + ports[0].inbox += b'01F7\rt7F080005000000000000\r' + assert bus.receive() == (1, bytes.fromhex('F501F7')) + assert bus.receive() == (carrier.STATUS_ID, bytes.fromhex('0005000000000000')) + assert bus.receive() is None + assert bus.errors == 0 + + +def test_a_refusal_is_matched_to_the_frame_it_answers(bus, ports): + frames = [(can_id, mks_can.read_encoder(can_id)) for can_id in (1, 2, 3)] + for frame in frames: + bus.send(*frame) + assert bus.receive() is None + # C, S8 and O, then the first frame is taken and the second refused, with a drive's reply + # in between. + ports[0].inbox += b'\r\r\r\r\at00183100000000000032\r\r\r' + assert bus.receive() == (1, bytes.fromhex('3100000000000032')) + assert bus.take_refused() == [frames[1]] and bus.take_refused() == [] + assert bus.refused == 1 and bus.errors == 0 + + +def test_a_refused_open_is_an_error_that_says_why(bus, ports): + ports[0].inbox += b'\r\r\a' + bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is None + assert bus.errors == 1 and '1000000 bit/s' in bus.problem + # Closed, the carrier refuses every frame. + ports[0].inbox += b'\a\r' + bus.receive() + assert bus.take_refused() == [(1, mks_can.read_encoder(1))] and bus.errors == 1 + + +def test_a_closed_carrier_that_still_answers_is_opened_again(bus, ports, clock): + ports[0].inbox += b'\r\r\r' + for _ in range(3): + clock[0] += slcan_bus.SILENCE_S / 2 + bus.send(1, mks_can.read_encoder(1)) + bus.receive() + # A carrier that reset answers every line, but passes on no frames until it is opened. + ports[0].inbox += b'\a\r' + bus.step(0.0) + assert ports[0].writes[-1] == b'C\rS8\rO\r' + + +def test_an_unplugged_carrier_is_reopened_and_set_up_again(bus, ports, clock): + ports[0].unplugged = True + bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is None + assert not bus.connected and 'Device not configured' in bus.problem + assert not bus.send(1, mks_can.read_encoder(1)) + bus.step(0.0) + assert len(ports) == 1 + clock[0] += slcan_bus.REOPEN_EVERY_S + bus.step(0.0) + assert bus.connected and bus.reopens == 1 and ports[1].writes == [b'C\rS8\rO\r'] + + +def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): + ports[0].inbox += b't7F080005000000000000\r' + bus.receive() + clock[0] += slcan_bus.SILENCE_S / 2 + bus.step(0.0) + assert len(ports[0].writes) == 1 + clock[0] += slcan_bus.SILENCE_S + bus.step(0.0) + assert ports[0].writes[-1] == b'C\rS8\rO\r' + + +def test_the_carrier_status_frame_decodes(): + status = carrier.parse_status(bytes.fromhex('0707' + '5DC0' + '0002' + '0304')) + assert status == {'sequence': 7, 'estop': 'pressed', 'supply_v': 24.0, 'can_errors': 2, + 'failed_writes': 3, 'refused_lines': 4} + unwired = carrier.parse_status(bytes(8)) + assert unwired['estop'] is None and unwired['supply_v'] is None + with pytest.raises(ValueError): + carrier.parse_status(bytes(7)) + + +def slcan_sim(): + try: + from ament_index_python.packages import get_package_prefix + path = os.path.join(get_package_prefix('waybionic_can'), 'lib', 'waybionic_can', + 'slcan_sim') + except (ImportError, LookupError, ValueError): + path = shutil.which('slcan_sim') + return path if path and os.access(path, os.X_OK) else None + + +@pytest.mark.skipif(slcan_sim() is None, reason='waybionic_can slcan_sim is not built') +def test_the_simulated_carrier_answers_through_the_real_bridge_code(): + sim = subprocess.Popen([slcan_sim(), '--ids', '1', '--move-ms', '100'], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + try: + port = sim.stdout.readline().strip() + bus = SlcanBus(port, 500000) + frames = [] + + def wait_for(done, seconds=2.0): + deadline = time.monotonic() + seconds + while not done() and time.monotonic() < deadline: + bus.step(0.0) + frame = bus.receive() + if frame is None: + time.sleep(0.002) + else: + frames.append(frame) + return done() + + assert wait_for(lambda: any(can_id == carrier.STATUS_ID for can_id, _ in frames)) + bus.send(1, mks_can.read_encoder(1)) + assert wait_for(lambda: (1, bytes.fromhex('3100000000000032')) in frames) + assert bus.errors == 0 + bus.shutdown() + finally: + sim.terminate() + sim.wait() diff --git a/waybionic_teleop/test/test_straight_cut.py b/waybionic_teleop/test/test_straight_cut.py index f445e501..9d4ba077 100644 --- a/waybionic_teleop/test/test_straight_cut.py +++ b/waybionic_teleop/test/test_straight_cut.py @@ -90,7 +90,7 @@ def test_the_next_joint_space_setpoint_stops_at_a_joint_limit(drives, parameters def test_a_saturated_drive_slows_every_drive_by_the_same_factor(drives): mapping = arm_map(drives, 30.0) counts = mapping.to_counts(DOWN) - velocities = {'joint_1': 2.0, 'joint_2': 0.5} + velocities = {'joint_1': 4.0, 'joint_2': 0.5} period, max_rpm = 1.0 / drives['rate_hz'], drives['max_rpm'] future = extrapolate(DOWN, velocities, period) free = mapping.synchronized(future, counts, period, 100 * max_rpm) diff --git a/waybionic_teleop/test/test_tool_motor.py b/waybionic_teleop/test/test_tool_motor.py index bc78232e..24c6c6ba 100644 --- a/waybionic_teleop/test/test_tool_motor.py +++ b/waybionic_teleop/test/test_tool_motor.py @@ -11,8 +11,6 @@ FIRMWARE = Path(__file__).resolve().parents[2] / 'firmware' / 'tool_board' ID = 7 TURN = mks_can.COUNTS_PER_REV -# The MKS emergency stop (F7h); the host does not send it, so mks_can has no builder for it. -EMERGENCY_STOP = 0xF7 # Drives one ToolMotor (3200 steps per turn, one turn of travel either way) from stdin: # frame HEX hand it a frame wait MS let time pass, then update once @@ -248,8 +246,8 @@ def test_a_ramp_that_would_run_on_past_the_travel_limit_stops_at_it(program): def test_the_emergency_stop_holds_at_once_and_says_so(program): out = motor(program, *READY, mks_can.absolute_axis(ID, TURN, 60, 200), 'run 10', - mks_can.frame(ID, EMERGENCY_STOP), 'state', 'run 100') - assert out[4] == status(EMERGENCY_STOP, 1) + mks_can.emergency_stop(ID), 'state', 'run 100') + assert out[4] == status(mks_can.EMERGENCY_STOP, 1) held = state(out[5]) assert held['position'] == held['target'] == 10 and not held['braking'] assert out[6] == '-' diff --git a/waybionic_teleop/waybionic_teleop/carrier.py b/waybionic_teleop/waybionic_teleop/carrier.py new file mode 100644 index 00000000..cb545be2 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/carrier.py @@ -0,0 +1,27 @@ +""" +Status that the WayBionic carrier sends its host ten times a second. + +It arrives through the SLCAN link as a frame from STATUS_ID but never goes on the CAN bus, +whose drives use low IDs. See carrier_bridge.ino for the layout. +""" + +STATUS_ID = 0x7F0 +ESTOP_WIRED, ESTOP_PRESSED, SUPPLY_WIRED = 0x01, 0x02, 0x04 + + +def parse_status(data): + """Return the carrier's status; e-stop and supply are None until Electrical wires them.""" + data = bytes(data) + if len(data) != 8: + raise ValueError('a carrier status frame carries 8 bytes') + flags = data[1] + return { + 'sequence': data[0], + 'estop': (('pressed' if flags & ESTOP_PRESSED else 'released') + if flags & ESTOP_WIRED else None), + 'supply_v': (int.from_bytes(data[2:4], 'big') / 1000.0 + if flags & SUPPLY_WIRED else None), + 'can_errors': int.from_bytes(data[4:6], 'big'), + 'failed_writes': data[6], + 'refused_lines': data[7], + } diff --git a/waybionic_teleop/waybionic_teleop/mks_can.py b/waybionic_teleop/waybionic_teleop/mks_can.py index 6a26d2e3..35e66c09 100644 --- a/waybionic_teleop/waybionic_teleop/mks_can.py +++ b/waybionic_teleop/waybionic_teleop/mks_can.py @@ -1,9 +1,9 @@ """ -Placeholder CAN frames for MKS SERVO42D/57D drives (CAN user manual V1.0.9 subset). +CAN frames for the arm's MKS SERVO42D/57D drives (CAN user manual V1.0.9 subset). -Electrical has not confirmed the joint drives, so the protocol stays in this module and can -be swapped without touching the teleop or ROS code. Each frame is a standard 11-bit frame -whose ID is the motor ID; the data is a function code, big-endian arguments and a checksum. +The shoulder runs a SERVO57D and the other joints SERVO42D drives. The protocol stays in this +module, so the teleop and ROS code never see it. Each frame is a standard 11-bit frame whose ID +is the motor ID; the data is a function code, big-endian arguments and a checksum. """ COUNTS_PER_REV = 0x4000 @@ -12,14 +12,18 @@ READ_ENCODER = 0x31 SET_MODE = 0x82 +SET_BITRATE = 0x8A +SET_CAN_ID = 0x8B SET_RESPONSE = 0x8C SET_ZERO = 0x92 SET_HEARTBEAT = 0x98 ENABLE = 0xF3 ABSOLUTE_AXIS = 0xF5 +EMERGENCY_STOP = 0xF7 MODE_SR_VFOC = 0x05 RUN_STATUS = {0: 'run failed', 1: 'running', 2: 'run complete', 3: 'stopped at end limit'} +BITRATES = {125000: 0, 250000: 1, 500000: 2, 1000000: 3} def checksum(can_id, body): @@ -103,3 +107,22 @@ def set_heartbeat(can_id, milliseconds): def enable(can_id, on=True): """Lock (on) or release the motor shaft (F3h).""" return frame(can_id, ENABLE, [int(on)]) + + +def emergency_stop(can_id): + """Stop at once, without a ramp (F7h); not advised above 1000 rpm. ID 0 reaches all.""" + return frame(can_id, EMERGENCY_STOP) + + +def set_bitrate(can_id, bitrate): + """Change the drive's CAN bit rate (8Ah). It replies at the old rate, then switches.""" + if bitrate not in BITRATES: + raise ValueError(f'MKS drives run at {sorted(BITRATES)} bit/s, not {bitrate}') + return frame(can_id, SET_BITRATE, [BITRATES[bitrate]]) + + +def set_can_id(can_id, new_id): + """Give the drive a new CAN ID (8Bh); 0 is the broadcast address, so 1-2047.""" + if not 1 <= new_id <= 0x7FF: + raise ValueError(f'CAN ID {new_id} is outside 1-2047') + return frame(can_id, SET_CAN_ID, new_id.to_bytes(2, 'big')) diff --git a/waybionic_teleop/waybionic_teleop/mks_drive_sim.py b/waybionic_teleop/waybionic_teleop/mks_drive_sim.py index fc9b2287..185aeb59 100644 --- a/waybionic_teleop/waybionic_teleop/mks_drive_sim.py +++ b/waybionic_teleop/waybionic_teleop/mks_drive_sim.py @@ -26,6 +26,8 @@ def serve(bus, servos, stop, period=0.001): replies += [(can_id, reply) for reply in servos[can_id].receive(data)] except ValueError: bus.errors += 1 + if servos[can_id].can_id != can_id: + servos[servos[can_id].can_id] = servos.pop(can_id) frame = bus.receive() now = time.monotonic() for can_id, servo in servos.items(): diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py new file mode 100644 index 00000000..07ee5fd2 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -0,0 +1,144 @@ +""" +Set up the arm's MKS drives on the bench: find them, give each its CAN ID, set the bit rate. + +The drives ship as CAN ID 1 at 500 kbit/s. Connect one drive at a time to give it the CAN ID +in arm_drives.yaml, then move every drive to the bus bit rate and check they all answer: + + ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 scan + ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 set-id 1 3 + ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 set-bitrate 3 1000000 + ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 --bitrate 1000000 scan + +The drives' screens (CanID and CanRate) do the same. Stop the ground station's drive node +first: two programs on one carrier would answer each other's frames. +""" + +import argparse +import time + +from waybionic_teleop import carrier, mks_can + + +def open_bus(interface, channel, bitrate, tty_baudrate): + """Open the carrier (slcan) or another python-can interface.""" + if interface == 'slcan': + from waybionic_teleop.slcan_bus import SlcanBus + return SlcanBus(channel, bitrate, tty_baudrate) + from waybionic_teleop.can_bus import CanBus + return CanBus(interface, channel, bitrate) + + +def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): + """Send a frame; return the arguments of the reply with this code, or None.""" + answer_ids = answer_ids or {can_id} + bus.send(can_id, data) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + bus.step(0.0) + frame = bus.receive() + if frame is None: + time.sleep(0.002) + continue + reply_id, reply = frame + try: + reply_code, arguments = mks_can.parse(reply_id, reply) + except ValueError: + continue + if reply_id in answer_ids and reply_code == code: + return arguments + return None + + +def scan(bus, ids): + """Return {CAN ID: encoder count} for the drives that answer.""" + found = {} + for can_id in ids: + arguments = request(bus, can_id, mks_can.read_encoder(can_id), mks_can.READ_ENCODER) + if arguments is not None: + found[can_id] = mks_can.encoder_value(arguments) + return found + + +def set_id(bus, old, new): + """Give the drive at old the CAN ID new; return a message, or raise SystemExit.""" + if old == new: + raise SystemExit(f'the drive already has CAN ID {new}') + if scan(bus, [new]): + raise SystemExit(f'CAN ID {new} is taken; connect only the drive to change') + if not scan(bus, [old]): + raise SystemExit(f'no drive answers on CAN ID {old}') + status = request(bus, old, mks_can.set_can_id(old, new), mks_can.SET_CAN_ID, {old, new}) + if status != b'\x01' or not scan(bus, [new]): + raise SystemExit(f'the drive did not take CAN ID {new}') + return f'The drive on CAN ID {old} now answers on {new}' + + +def set_bitrate(bus, can_id, bitrate): + """Switch one drive's CAN bit rate; return a message, or raise SystemExit.""" + status = request(bus, can_id, mks_can.set_bitrate(can_id, bitrate), mks_can.SET_BITRATE) + if status != b'\x01': + raise SystemExit(f'CAN ID {can_id} did not confirm the new bit rate') + return (f'CAN ID {can_id} now runs at {bitrate} bit/s. Once every drive is switched, ' + f'unplug and replug the carrier (it keeps its first bit rate until reset), then ' + f'scan with --bitrate {bitrate}') + + +def wait_for_carrier(bus, seconds=3.0): + """Give a carrier that resets when its port opens time to boot; True once it reports.""" + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + bus.step(0.0) + frame = bus.receive() + if frame is not None and frame[0] == carrier.STATUS_ID: + return True + if frame is None: + time.sleep(0.01) + return False + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) + parser.add_argument('--interface', default='slcan', + help='slcan for the WayBionic carrier, or a python-can interface') + parser.add_argument('--channel', required=True, + help='for example /dev/cu.usbmodem1101, COM5 or can0') + parser.add_argument('--bitrate', type=int, default=500000, choices=sorted(mks_can.BITRATES), + help="the drives' present CAN bit rate (they ship at 500000)") + parser.add_argument('--tty-baudrate', type=int, default=1000000, + help="the carrier's USB serial speed") + commands = parser.add_subparsers(dest='command', required=True) + scan_command = commands.add_parser('scan', help='list the drives that answer') + scan_command.add_argument('--ids', type=int, nargs='+', default=list(range(1, 17))) + id_command = commands.add_parser('set-id', help='give one drive a new CAN ID') + id_command.add_argument('old', type=int) + id_command.add_argument('new', type=int) + rate_command = commands.add_parser('set-bitrate', help="change one drive's CAN bit rate") + rate_command.add_argument('can_id', type=int) + rate_command.add_argument('rate', type=int, choices=sorted(mks_can.BITRATES)) + commands.add_parser('stop', help='stop every drive at once (F7h to broadcast ID 0)') + args = parser.parse_args(argv) + + bus = open_bus(args.interface, args.channel, args.bitrate, args.tty_baudrate) + try: + if args.interface == 'slcan' and not wait_for_carrier(bus): + print('No status from the carrier; is carrier_bridge flashed? Trying anyway.') + if args.command == 'scan': + found = scan(bus, args.ids) + for can_id, count in found.items(): + print(f'CAN ID {can_id}: encoder {count / mks_can.COUNTS_PER_REV:+.3f} turns') + if not found: + raise SystemExit(f'No drive answered at {args.bitrate} bit/s') + elif args.command == 'set-id': + print(set_id(bus, args.old, args.new)) + elif args.command == 'set-bitrate': + print(set_bitrate(bus, args.can_id, args.rate)) + else: + bus.send(0, mks_can.emergency_stop(0)) + bus.receive() + print('Sent the emergency stop to every drive') + finally: + bus.shutdown() + + +if __name__ == '__main__': + main() diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index dc611aaa..ebd2da04 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -1,9 +1,10 @@ """ Run the arm's joint drives: /joint_commands in, MKS CAN frames, /joint_states out. -The drives are simulated on an in-process bus unless ``interface`` names a python-can interface -(socketcan, slcan, udp_multicast, ...) and ``channel`` the adapter, in which case the same -frames go to real MKS SERVO drives. The command, feedback and diagnostics path is identical. +The drives are simulated on an in-process bus unless ``interface`` names a bus: ``slcan`` for +the WayBionic carrier on a USB serial port, or another python-can interface (socketcan, +udp_multicast, ...) with ``channel`` naming the adapter. The same frames then go to the real MKS +SERVO drives, and the command, feedback and diagnostics path is identical. The encoders count from where the drives were powered on, so nothing moves until every drive has been zeroed with the arm in the zero pose: at start-up in simulation, and through the @@ -31,12 +32,14 @@ from std_msgs.msg import Bool, String from std_srvs.srv import Trigger -from waybionic_teleop import mks_can +from waybionic_teleop import carrier, mks_can from waybionic_teleop.drive_map import drive_map_from_parameters from waybionic_teleop.kinematics import joint_limits from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo REPLY_TIMEOUT_S = 0.5 +# The carrier reports ten times a second. +CARRIER_TIMEOUT_S = 0.5 # Zeroing waits for the joint commands to stop, so teleop must be disabled first. QUIET_BEFORE_ZERO_S = 1.0 # Every drive must confirm these before it moves, so none runs without its heartbeat stop. @@ -100,11 +103,17 @@ def __init__(self, **kwargs): elif not channel: raise ValueError(f'the {self.interface} interface needs a channel, ' 'such as can0, /dev/ttyACM0 or 239.74.163.2') + elif self.interface == 'slcan': + # pyserial is only needed for the carrier. + from waybionic_teleop.slcan_bus import SlcanBus + self.bus = SlcanBus(channel, self.bitrate, int(params.get('tty_baudrate', 1000000))) + self.bus_label = f'carrier on {channel}' else: - # python-can is only needed for a real bus. + # python-can is only needed for other adapters. from waybionic_teleop.can_bus import CanBus self.bus = CanBus(self.interface, channel, self.bitrate) self.bus_label = f'{self.interface} {channel}' + self.carrier, self.carrier_time = None, None self.counts = [None] * len(drives) # Host time since each drive's last encoder reading, which bounds how far it can turn. self.since_count = [0.0] * len(drives) @@ -153,13 +162,12 @@ def __init__(self, **kwargs): self.diagnostics_publisher = self.create_publisher(DiagnosticArray, topic, 10) self.last_tick = time.monotonic() self.report_time, self.report_frames, self.report_bits = self.last_tick, 0, 0 - self.report_errors = 0 + self.report_errors = self.report_refused = 0 self.create_timer(self.period, self.tick) self.create_timer(0.5, self.report) drive_list = ', '.join(f'{drive.name}=CAN {drive.can_id}' for drive in drives) if self.interface == 'sim': - self.get_logger().info( - f'Simulated drives: {drive_list} (placeholder MKS SERVO map, no hardware)') + self.get_logger().info(f'Simulated drives: {drive_list} (no hardware)') else: self.get_logger().info(f'MKS drives on {self.bus_label}: {drive_list}') if not zero_on_start: @@ -202,7 +210,7 @@ def on_zero(self, request, response): deadline = time.monotonic() + REPLY_TIMEOUT_S while not all(self.zeroed) and time.monotonic() < deadline: time.sleep(0.005) - self.drain(time.monotonic()) + self.drain(time.monotonic(), zeroing=True) missing = [drive.name for drive, done in zip(self.map.drives, self.zeroed) if not done] response.success = not missing response.message = ('Zeroed every drive' if response.success @@ -232,7 +240,7 @@ def on_enabled(self, message): self.awaiting_release = False elif (not self.awaiting_release and self.description_valid and all(self.zeroed) and not any(self.unconfirmed) and not self.stopping and None not in self.counts - and self.feedback_fresh(now)): + and self.feedback_fresh(now) and not self.estop_pressed): if not self.authorized: self.commanded = self.map.to_positions(self.counts) self.authorized = True @@ -271,6 +279,17 @@ def on_command(self, message): return self.commanded = positions self.velocities = dict(zip(names, message.velocity)) + # Send now rather than at the next tick, unless that tick will stop the drives. + now = time.monotonic() + if (now - self.last_tick < self.heartbeat_s and self.feedback_fresh(now) + and now - self.enabled_at <= self.enable_timeout): + self.send_targets() + self.drain(now) + + @property + def estop_pressed(self): + # The last report counts even if the carrier has since gone quiet. + return self.carrier is not None and self.carrier['estop'] == 'pressed' def reject_command(self, reason): self.rejected += 1 @@ -407,11 +426,47 @@ def send_targets(self): self.sent[index] = key self.last_command[index] = mks_can.hex_frame(drive.can_id, data) - def drain(self, now): + def drain(self, now, zeroing=False): while (reply := self.bus.receive()) is not None: self.on_reply(*reply, now) + # The carrier answers a frame it refuses after send() has already returned True. + if self.interface == 'slcan': + for can_id, data in self.bus.take_refused(): + self.on_refused(can_id, data, zeroing) + + def on_refused(self, can_id, data, zeroing): + """Send a refused frame again on the next tick, unless a later frame replaced it.""" + index = self.index.get(can_id) + if index is None: + return + if data[0] == mks_can.ABSOLUTE_AXIS: + if self.last_command[index] != mks_can.hex_frame(can_id, data): + return + # Only stops go out while disarmed, and send_stops repeats a stop until it is sent. + if self.authorized: + self.sent[index] = None + else: + self.stopping.add(index) + elif data[0] in self.unconfirmed[index]: + self.setup_time[index] = -math.inf + elif data[0] == mks_can.SET_ZERO and zeroing: + # Only while the zero service waits: a late zero would move the arm's zero pose. + self.bus.send(can_id, data) def on_reply(self, can_id, data, now): + if can_id == carrier.STATUS_ID and self.interface == 'slcan': + pressed = self.estop_pressed + try: + self.carrier, self.carrier_time = carrier.parse_status(data), now + except ValueError as error: + self.bus_errors += 1 + self.get_logger().warning(str(error), throttle_duration_sec=2.0) + return + if self.estop_pressed and not pressed: + # The e-stop cuts the drives' power; Start is refused until it is released. + self.stop_all('E-stop pressed') + self.get_logger().error('E-stop pressed; every drive is stopped') + return index = self.index.get(can_id) try: code, arguments = mks_can.parse(can_id, data) @@ -480,6 +535,8 @@ def report(self): f'{load:.0f}% worst-case load at {self.bitrate // 1000} kbit/s ({self.bus_label})', load_percent=f'{load:.1f}', errors=errors, rejected_commands=self.rejected, interface=self.interface)] + if self.interface == 'slcan': + statuses.append(self.carrier_status(now)) gate_level = (DiagnosticStatus.OK if self.authorized else DiagnosticStatus.ERROR if not self.description_valid else DiagnosticStatus.WARN) @@ -522,6 +579,32 @@ def report(self): message.header.stamp = self.get_clock().now().to_msg() self.diagnostics_publisher.publish(message) + def carrier_status(self, now): + """Report the USB link to the carrier and what the carrier says about the bus.""" + refused, self.report_refused = self.bus.refused - self.report_refused, self.bus.refused + link = {'reopens': self.bus.reopens, 'refused_frames': self.bus.refused} + if not self.bus.connected: + return status('can.carrier', DiagnosticStatus.ERROR, 'unplugged', '', + f'USB link lost ({self.bus.problem}); retrying every second', **link) + if self.carrier_time is None or now - self.carrier_time > CARRIER_TIMEOUT_S: + return status('can.carrier', DiagnosticStatus.WARN, 'silent', '', + 'No status from the carrier: ' + + (self.bus.problem or 'is carrier_bridge flashed?'), **link) + report = self.carrier + estop = report['estop'] or 'not wired' + supply = 'not wired' if report['supply_v'] is None else f'{report["supply_v"]:.1f} V' + message = f'E-stop {estop}, supply {supply}, {report["can_errors"]} CAN errors' + level = DiagnosticStatus.OK + if refused: + # Each refused target or stop goes out again, a tick late. + level, message = DiagnosticStatus.WARN, f'{message}, {refused} frames refused' + if report['estop'] == 'pressed': + level = DiagnosticStatus.ERROR + return status('can.carrier', level, estop, 'e-stop', message, + supply=supply, can_errors=report['can_errors'], + failed_writes=report['failed_writes'], + refused_lines=report['refused_lines'], **link) + def close(self): """Stop the drives and release the bus; the drives' heartbeat would also stop them.""" self.stop_all('Shutting down') diff --git a/waybionic_teleop/waybionic_teleop/sim_drives.py b/waybionic_teleop/waybionic_teleop/sim_drives.py index 63e5a17a..2062ab86 100644 --- a/waybionic_teleop/waybionic_teleop/sim_drives.py +++ b/waybionic_teleop/waybionic_teleop/sim_drives.py @@ -16,8 +16,9 @@ def ramp_rpm_per_s(acc): class SimulatedServo: """Answer bus commands and move like an MKS SERVO42D/57D in SR_vFOC mode.""" - def __init__(self, can_id): + def __init__(self, can_id, bitrate=500000): self.can_id = can_id + self.bitrate = bitrate self.mode = None self.enabled = False self.respond = True @@ -52,6 +53,22 @@ def receive(self, data): self.target, self.rpm = None, 0.0 elif code == mks_can.ABSOLUTE_AXIS and len(arguments) == 6: status = self.start_move(arguments) + elif code == mks_can.EMERGENCY_STOP and not arguments: + self.target, self.rpm, status = None, 0.0, 1 + elif code == mks_can.SET_BITRATE and len(arguments) == 1: + rates = {value: rate for rate, value in mks_can.BITRATES.items()} + status = int(arguments[0] in rates) + # The reply still goes out at the old rate. + reply = [mks_can.frame(self.can_id, code, [status])] + self.bitrate = rates.get(arguments[0], self.bitrate) + return reply if self.respond else [] + elif code == mks_can.SET_CAN_ID and len(arguments) == 2: + new_id = int.from_bytes(arguments, 'big') + status = int(1 <= new_id <= 0x7FF) + reply = [mks_can.frame(self.can_id, code, [status])] + if status: + self.can_id = new_id + return reply if self.respond else [] else: return [] return [mks_can.frame(self.can_id, code, [status])] if self.respond else [] @@ -140,6 +157,9 @@ def send(self, can_id, data): self.errors += 1 return False self._queue(can_id, replies) + if drive.can_id != can_id: + # It took a new CAN ID. + self.drives = {drive.can_id: drive for drive in self.drives.values()} return True def receive(self): diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py new file mode 100644 index 00000000..dc355bf5 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -0,0 +1,218 @@ +""" +Talk to the WayBionic carrier (UNO R4 WiFi and a CAN transceiver) over its USB serial link. + +The carrier speaks a subset of the Lawicel SLCAN protocol (waybionic_can/arduino). python-can's +slcan interface drains the port after every frame and reads one byte at a time, which costs +milliseconds per frame over USB. This writes a control tick's frames in one go and parses +whatever has arrived in one read. If the USB link drops, it keeps reopening the port, and a +carrier that resets (or sits closed after the port opens) is opened again once it goes quiet. + +The carrier says nothing about a frame it puts on the bus, and answers BELL to one it refuses, +such as a frame that arrives while its CAN controller is still busy. Each frame is therefore +followed by an empty line, which the carrier answers with CR, so every answer can be matched to +the line it belongs to. take_refused() hands back the refused frames to be sent again. +""" + +from collections import deque +import time + +import serial + +from waybionic_teleop import mks_can + +BITRATE_CODES = {125000: b'4', 250000: b'5', 500000: b'6', 1000000: b'8'} +DEFAULT_BAUDRATE = 1000000 +REOPEN_EVERY_S = 1.0 +# The carrier sends its status ten times a second while open, so this much quiet means it is +# closed: it reset, or it was still booting when the port opened. +SILENCE_S = 1.0 +# Lines still waiting for an answer; past this the carrier is not answering empty lines. +MAX_PENDING = 256 +BELL = 0x07 +CR = 0x0D + + +def parse_line(line): + """Return (can_id, data) for a standard data frame line such as b't0012313', else None.""" + if len(line) < 5 or line[:1] != b't': + return None + try: + can_id, length = int(line[1:4], 16), int(line[4:5]) + data = bytes.fromhex(line[5:].decode('ascii')) + except (ValueError, UnicodeDecodeError): + return None + return (can_id, data) if len(data) == length <= 8 else None + + +class SlcanBus: + """Send and receive standard 11-bit frames through the carrier, without blocking.""" + + def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): + if bitrate not in BITRATE_CODES: + raise ValueError(f'the carrier runs CAN at {sorted(BITRATE_CODES)} bit/s') + self.port, self.bitrate = port, bitrate + self.open_port = open_port or ( + lambda: serial.serial_for_url(port, baudrate=baudrate, timeout=0)) + self.frames = self.bits = self.errors = self.refused = self.reopens = 0 + self.problem = '' + self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() + # The lines in outgoing, then the lines written but not yet answered, in order: a + # frame's (can_id, data), or the command itself. + self.queued, self.pending = [], deque(maxlen=MAX_PENDING) + self.refusals, self.bell = [], False + self.heard = self.next_try = 0.0 + # A missing adapter at start-up is a configuration error, so let it raise. + self.serial = self.open_port() + self._start() + + @property + def connected(self): + return self.serial is not None + + def send(self, can_id, data): + """Queue a frame for the next write; return False while the carrier is unplugged.""" + data = bytes(data) + if not 0 <= can_id <= 0x7FF or len(data) > 8: + raise ValueError(f'cannot send {can_id:X}#{data.hex()} as a standard frame') + if self.serial is None: + return False + self.outgoing += b't%03X%d%s\r\r' % (can_id, len(data), data.hex().upper().encode()) + self.queued.append((can_id, data)) + self._count(data) + return True + + def take_refused(self): + """Return the frames the carrier refused since the last call, oldest first.""" + refused, self.refusals = self.refusals, [] + return refused + + def receive(self, timeout=0.0): + """Write what is queued, then return the next (can_id, data) frame, or None.""" + self._flush() + if not self.replies: + self._read() + return self.replies.popleft() if self.replies else None + + def step(self, dt): + """Reopen a lost port, or reopen the bridge if the carrier has gone quiet.""" + now = time.monotonic() + if self.serial is not None: + if now - self.heard > SILENCE_S: + self._start() + return + if now < self.next_try: + return + self.next_try = now + REOPEN_EVERY_S + try: + self.serial = self.open_port() + except (serial.SerialException, OSError, ValueError) as error: + self.problem = f'{self.port}: {error}' + return + self.reopens += 1 + self.problem = '' + self._start() + + def shutdown(self): + if self.serial is not None: + self.outgoing += b'C\r' + self.queued.append(b'C') + self._flush() + if self.serial is not None: + self.serial.close() + self.serial = None + + def _start(self): + # Close in case it was left open, set the bit rate, open. Each answers \r, or \a. + commands = [b'C', b'S' + BITRATE_CODES[self.bitrate], b'O'] + self.outgoing[:0] = b''.join(command + b'\r' for command in commands) + self.queued[:0] = commands + # A carrier that reset will never answer the lines written before. + self.pending.clear() + self.bell = False + self.heard = time.monotonic() + self._flush() + + def _flush(self): + if self.serial is None or not self.outgoing: + return + try: + self.serial.write(self.outgoing) + except (serial.SerialException, OSError) as error: + self._lost(error) + return + self.outgoing.clear() + self.pending.extend(self.queued) + self.queued.clear() + + def _read(self): + if self.serial is None: + return + try: + chunk = self.serial.read(self.serial.in_waiting or 1) + except (serial.SerialException, OSError) as error: + self._lost(error) + return + if not chunk: + return + self.incoming += chunk + start = 0 + for end, byte in enumerate(self.incoming): + if byte not in (CR, BELL): + continue + line = bytes(self.incoming[start:end]) + start = end + 1 + if byte == BELL: + self._refused() + elif not line: + self._answered() + elif (frame := parse_line(line)) is not None: + # A closed carrier still answers lines, but passes on no frames. + self.heard = time.monotonic() + self.replies.append(frame) + self._count(frame[1]) + del self.incoming[:start] + if len(self.incoming) > 64: + # No line is that long, so this is noise, such as a baud rate mismatch. + self.errors += 1 + self.incoming.clear() + + def _refused(self): + # A frame's BELL comes before the CR of its empty line; a command answers one or the other. + if self.pending and isinstance(self.pending[0], tuple): + self.bell = True + return + if self.pending and self.pending.popleft() == b'O': + # The carrier keeps the bit rate it first opened at until it resets. + self.problem = f'the carrier would not open at {self.bitrate} bit/s; replug it' + self.errors += 1 + + def _answered(self): + if not self.pending: + return + line = self.pending.popleft() + if line == b'O': + self.problem = '' + if self.bell and isinstance(line, tuple): + self.refused += 1 + self.refusals.append(line) + self.bell = False + + def _lost(self, error): + self.problem = f'{self.port}: {error}' + self.errors += 1 + try: + self.serial.close() + except (serial.SerialException, OSError): + pass + self.serial = None + self.outgoing.clear() + self.queued.clear() + self.pending.clear() + self.bell = False + self.incoming.clear() + self.replies.clear() + self.next_try = time.monotonic() + REOPEN_EVERY_S + + def _count(self, data): + self.frames += 1 + self.bits += mks_can.frame_bits(data) From e8cff92f7e336750628254d28e6332b18437cd3e Mon Sep 17 00:00:00 2001 From: yassinsolim Date: Sat, 10 Oct 2026 21:06:04 -0600 Subject: [PATCH 02/11] Monitor the controller link and cut input latency The UDP receiver reports packet loss, jitter, the longest gap and the round trip of a ping that the bridge answers, and warns when the link is unstable. Only the bridge's own answers time the link, and the bridge answers only the station's pings. The receiver polls every millisecond, and xinput_bridge sends at 250 Hz. --- waybionic_bringup/test/test_teleop_launch.py | 17 ++- waybionic_teleop/test/test_gamepad.py | 11 ++ .../test/test_joy_udp_receiver.py | 59 +++++++++- waybionic_teleop/test/test_xinput_bridge.py | 12 ++ waybionic_teleop/waybionic_teleop/gamepad.py | 26 +++++ .../waybionic_teleop/joy_udp_receiver.py | 108 ++++++++++++++++-- .../waybionic_teleop/xinput_bridge.py | 17 ++- 7 files changed, 231 insertions(+), 19 deletions(-) diff --git a/waybionic_bringup/test/test_teleop_launch.py b/waybionic_bringup/test/test_teleop_launch.py index 6ed965cc..b623676c 100644 --- a/waybionic_bringup/test/test_teleop_launch.py +++ b/waybionic_bringup/test/test_teleop_launch.py @@ -137,10 +137,17 @@ def hold(seconds, *pressed, **axes): sequence += 1 sender.sendto(gamepad.pack(sequence, packet_axes, buttons), ('127.0.0.1', PORT)) rclpy.spin_once(node, timeout_sec=0.02) - try: - rumbles.append(gamepad.unpack_rumble(sender.recv(64))) - except BlockingIOError: - pass + while True: + try: + data, station = sender.recvfrom(64) + except BlockingIOError: + break + # Answer the station's pings as the bridges do. + answer = gamepad.pong(data) + if answer is not None: + sender.sendto(answer, station) + else: + rumbles.append(gamepad.unpack_rumble(data)) def group(): # Only a report sent after the last press counts. @@ -174,6 +181,8 @@ def group(): self.assertTrue(rumbles, 'the controller never rumbled') self.assertGreater(rumbles[0], 0.0) self.assertEqual(rumbles[-1], 0.0) + link = {value.key: value.value for value in diagnostics['controller.link'].values} + self.assertNotEqual(link['round_trip_ms'], '', 'the link was never timed') finally: hold(0.2, 'b') sender.close() diff --git a/waybionic_teleop/test/test_gamepad.py b/waybionic_teleop/test/test_gamepad.py index 2e320a60..e37f4e83 100644 --- a/waybionic_teleop/test/test_gamepad.py +++ b/waybionic_teleop/test/test_gamepad.py @@ -58,3 +58,14 @@ def test_rumble_requests_round_trip_within_zero_to_one(intensity, expected): def test_anything_else_is_not_a_rumble_request(packet): with pytest.raises(ValueError): gamepad.unpack_rumble(packet) + + +def test_a_bridge_answers_a_ping_with_the_same_time(): + ping = gamepad.pack_ping(2**32 + 3, 1234.5) + assert gamepad.unpack_pong(gamepad.pong(ping)) == (3, 1234.5) + # A ping is neither a controller packet nor a rumble request, and pongs are not echoed. + for unpack in (gamepad.unpack, gamepad.unpack_rumble, gamepad.unpack_pong): + with pytest.raises(ValueError): + unpack(ping) + assert gamepad.pong(gamepad.pong(ping)) is None + assert gamepad.pong(gamepad.pack(1, NEUTRAL, [])) is None diff --git a/waybionic_teleop/test/test_joy_udp_receiver.py b/waybionic_teleop/test/test_joy_udp_receiver.py index ed42a83d..26eb2330 100644 --- a/waybionic_teleop/test/test_joy_udp_receiver.py +++ b/waybionic_teleop/test/test_joy_udp_receiver.py @@ -3,13 +3,14 @@ import select import socket +from diagnostic_msgs.msg import DiagnosticStatus import pytest import rclpy from rclpy.parameter import Parameter from sensor_msgs.msg import JoyFeedback from waybionic_teleop import gamepad -from waybionic_teleop.joy_udp_receiver import JoyUdpReceiver +from waybionic_teleop.joy_udp_receiver import JoyUdpReceiver, LinkQuality STICK = [0.5, -0.25, 0.0, 1.0, 0.0, -0.75] START = [int(name == 'start') for name in gamepad.BUTTONS] @@ -109,3 +110,59 @@ def test_rumble_goes_back_to_the_bridge_until_its_link_times_out(receiver): assert not select.select([bridge], [], [], 0.2)[0], 'rumble sent over a timed-out link' finally: bridge.close() + + +def test_link_quality_counts_loss_jitter_and_the_longest_gap(): + link = LinkQuality() + for sequence, now in ((1, 0.000), (2, 0.004), (3, 0.008), (6, 0.020), (7, 0.024)): + link.arrived(sequence, now) + loss, jitter, gap = link.take() + # Packets 4 and 5 never came: 2 of 7. + assert loss == pytest.approx(2 / 7) + assert gap == pytest.approx(0.012) + # Intervals 4, 4, 12, 4 ms vary by 0, 8 and 8 ms. + assert jitter == pytest.approx(0.016 / 3) + assert link.take() == (0.0, 0.0, 0.0) + # A bridge that restarted counts from 1 again; that is not loss. + link.restart() + link.arrived(1, 5.0) + link.arrived(2, 5.004) + assert link.take()[0] == 0.0 + + +def test_the_bridge_times_the_link_and_lost_packets_make_it_warn(receiver, monkeypatch): + reports = [] + monkeypatch.setattr(receiver.diagnostics_publisher, 'publish', reports.append) + bridge, stranger = (socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for _ in range(2)) + + def deliver(sock, data): + sock.sendto(data, receiver.socket.getsockname()) + assert select.select([receiver.socket], [], [], 2.0)[0], 'the packet never arrived' + receiver.poll() + + def link(): + receiver.report() + status = reports[-1].status[0] + return status, {value.key: value.value for value in status.values} + + try: + for sequence in (1, 2, 3): + deliver(bridge, gamepad.pack(sequence, *NEUTRAL)) + # Each report pings the bridge. + _, values = link() + assert values['round_trip_ms'] == '' + assert select.select([bridge], [], [], 2.0)[0], 'the ping never came' + ping = bridge.recv(64) + # Only the bridge's answer times the link. + deliver(stranger, gamepad.pong(ping)) + assert receiver.round_trip is None + deliver(bridge, gamepad.pong(ping)) + assert receiver.round_trip is not None + # Packets 4 to 9 never arrive. + deliver(bridge, gamepad.pack(10, *NEUTRAL)) + status, values = link() + assert status.level == DiagnosticStatus.WARN and status.message.startswith('Unstable') + assert values['loss_percent'] == '85.7' and values['round_trip_ms'] != '' + finally: + bridge.close() + stranger.close() diff --git a/waybionic_teleop/test/test_xinput_bridge.py b/waybionic_teleop/test/test_xinput_bridge.py index cd03c21c..8b1e64d4 100644 --- a/waybionic_teleop/test/test_xinput_bridge.py +++ b/waybionic_teleop/test/test_xinput_bridge.py @@ -81,6 +81,18 @@ def test_a_flood_of_rumble_requests_is_read_a_few_per_update(sockets): assert xinput_bridge.read_rumble(bridge, station.getsockname()) is None +def test_only_the_ground_station_gets_its_ping_back(sockets): + bridge, station, stranger = sockets + ping = gamepad.pack_ping(5, 12.5) + for sock in (stranger, station): + sock.sendto(ping, bridge.getsockname()) + assert select.select([bridge], [], [], 2.0)[0], 'the ping never arrived' + assert xinput_bridge.read_rumble(bridge, station.getsockname()) is None + assert select.select([station], [], [], 2.0)[0], 'the station got no pong' + assert gamepad.unpack_pong(station.recv(64)) == (5, 12.5) + assert not select.select([stranger], [], [], 0.2)[0], 'a stranger got a pong' + + class WindowsSocket: """Raise the errors Windows reports for an oversize datagram and an ICMP reply.""" diff --git a/waybionic_teleop/waybionic_teleop/gamepad.py b/waybionic_teleop/waybionic_teleop/gamepad.py index b266fd87..6954ee6c 100644 --- a/waybionic_teleop/waybionic_teleop/gamepad.py +++ b/waybionic_teleop/waybionic_teleop/gamepad.py @@ -19,6 +19,10 @@ # Sent back to the host bridge to rumble the controller; intensity 0 stops it. RUMBLE_MAGIC = b'WBRM' _RUMBLE = struct.Struct('<4sB3xf') +# The ground station pings the host bridge, which sends the packet straight back as a pong, +# so the station can measure the round trip over the network. +PING_MAGIC, PONG_MAGIC = b'WBPG', b'WBPO' +_PING = struct.Struct('<4sB3xId') def pack(sequence, axes, buttons, connected=True): @@ -56,3 +60,25 @@ def unpack_rumble(data): if magic != RUMBLE_MAGIC or version != VERSION or not 0.0 <= intensity <= 1.0: raise ValueError('not a version 1 WayBionic rumble request') return intensity + + +def pack_ping(nonce, sent): + """Encode a ping carrying a counter and the station's send time in seconds.""" + return _PING.pack(PING_MAGIC, VERSION, nonce & 0xFFFFFFFF, sent) + + +def pong(data): + """Return the bridge's answer to a ping (the same packet as a pong), or None.""" + if len(data) != _PING.size or data[:4] != PING_MAGIC: + return None + return PONG_MAGIC + bytes(data[4:]) + + +def unpack_pong(data): + """Return (nonce, sent) from a pong; raise ValueError for anything else.""" + if len(data) != _PING.size: + raise ValueError(f'expected {_PING.size} bytes, got {len(data)}') + magic, version, nonce, sent = _PING.unpack(data) + if magic != PONG_MAGIC or version != VERSION or not math.isfinite(sent): + raise ValueError('not a version 1 WayBionic pong') + return nonce, sent diff --git a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py index e1129fab..d2b7b13d 100644 --- a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py +++ b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py @@ -1,4 +1,9 @@ -"""Publish sensor_msgs/Joy from the controller packets that xinput_bridge sends from a host.""" +""" +Publish sensor_msgs/Joy from the controller packets that a host bridge sends over UDP. + +The bridge may run on another computer, so the receiver also watches the link: packets lost, +how unevenly they arrive, the longest gap, and the round trip of a ping the bridge answers. +""" import socket import time @@ -10,10 +15,51 @@ from rclpy.node import Node from sensor_msgs.msg import Joy, JoyFeedback -from waybionic_teleop.gamepad import AXES, BUTTONS, pack_rumble, PACKET_SIZE, unpack +from waybionic_teleop.gamepad import (AXES, BUTTONS, pack_ping, pack_rumble, PACKET_SIZE, + PONG_MAGIC, unpack, unpack_pong) # What a connected packet with centred sticks, released triggers and no buttons unpacks to. NEUTRAL = ([0.0] * len(AXES), [0] * len(BUTTONS)) +# Past these the operator feels the arm stutter or lag, so the monitor warns. +UNSTABLE_LOSS = 0.02 +UNSTABLE_GAP_S = 0.1 +UNSTABLE_ROUND_TRIP_S = 0.05 +PING_EVERY_S = 0.5 + + +class LinkQuality: + """Loss, arrival jitter and the longest gap between packets, per report window.""" + + def __init__(self): + self.received = self.lost = self.variations = 0 + self.variation = self.worst_gap = 0.0 + self.restart() + + def restart(self): + """Forget the last packet, as after a bridge restart that reset its count.""" + self.sequence = self.time = self.interval = None + + def arrived(self, sequence, now): + if self.sequence is not None: + self.lost += max(((sequence - self.sequence) & 0xFFFFFFFF) - 1, 0) + interval = now - self.time + self.worst_gap = max(self.worst_gap, interval) + if self.interval is not None: + self.variation += abs(interval - self.interval) + self.variations += 1 + self.interval = interval + self.received += 1 + self.sequence, self.time = sequence, now + + def take(self): + """Return (loss fraction, mean jitter in s, longest gap in s), then start a new window.""" + total = self.received + self.lost + result = (self.lost / total if total else 0.0, + self.variation / self.variations if self.variations else 0.0, + self.worst_gap) + self.received = self.lost = self.variations = 0 + self.variation = self.worst_gap = 0.0 + return result class JoyUdpReceiver(Node): @@ -38,9 +84,13 @@ def __init__(self, **kwargs): self.sender = None self.published = 0 self.rejected = 0 + self.link = LinkQuality() + self.pings = 0 + self.round_trip, self.round_trip_time = None, None self.report_time = time.monotonic() - self.create_timer(0.005, self.poll) - self.create_timer(0.5, self.report) + # Every millisecond, so a packet waits at most that long before it reaches teleop. + self.create_timer(0.001, self.poll) + self.create_timer(PING_EVERY_S, self.report) self.get_logger().info('Waiting for controller packets on udp {}:{}'.format(*self.address)) def poll(self): @@ -55,16 +105,22 @@ def poll(self): self.get_logger().warning(f'UDP receive failed: {error}', throttle_duration_sec=5.0) break + now = time.monotonic() + if data[:4] == PONG_MAGIC: + self.on_pong(data, sender, now) + continue try: sequence, connected, axes, buttons = unpack(data) except ValueError: self.rejected += 1 continue - now = time.monotonic() # A pause longer than the timeout means the bridge restarted and its count reset. resumed = self.last_packet is None or now - self.last_packet > self.timeout if not resumed and not 0 < (sequence - self.sequence) & 0xFFFFFFFF < 0x80000000: continue + if resumed: + self.link.restart() + self.link.arrived(sequence, now) self.sequence, self.last_packet, self.sender = sequence, now, sender if connected: latest = (axes, buttons) @@ -82,6 +138,16 @@ def poll(self): # The bridge has gone; its port may now belong to another program. self.sender = None + def on_pong(self, data, sender, now): + try: + _, sent = unpack_pong(data) + except ValueError: + self.rejected += 1 + return + # Only the bridge's answer to one of this node's pings times the link. + if sender == self.sender and 0.0 <= now - sent < 10.0: + self.round_trip, self.round_trip_time = now - sent, now + def on_feedback(self, message): if message.type != JoyFeedback.TYPE_RUMBLE or message.id != 0 or self.sender is None: return @@ -94,19 +160,41 @@ def report(self): now = time.monotonic() rate = self.published / max(now - self.report_time, 1e-3) self.published, self.report_time = 0, now + loss, jitter, gap = self.link.take() + if self.sender is not None: + self.pings += 1 + try: + self.socket.sendto(pack_ping(self.pings, now), self.sender) + except OSError as error: + self.get_logger().warning(f'Ping not sent: {error}', throttle_duration_sec=5.0) + # Bridges from before the ping was added never answer it. + round_trip = (self.round_trip if self.round_trip_time is not None + and now - self.round_trip_time < 4 * PING_EVERY_S else None) + quality = (f'{100.0 * loss:.1f}% lost, jitter {1000.0 * jitter:.1f} ms, ' + f'longest gap {1000.0 * gap:.0f} ms, round trip ' + + ('unknown' if round_trip is None else f'{1000.0 * round_trip:.1f} ms')) status = DiagnosticStatus(name='controller.link', level=DiagnosticStatus.OK) if self.last_packet is None or now - self.last_packet > self.timeout: status.level = DiagnosticStatus.STALE - status.message = ('No packets on udp {}:{}; run xinput_bridge on the host' + status.message = ('No packets on udp {}:{}; run the controller bridge on the host' .format(*self.address)) elif not self.connected: status.level = DiagnosticStatus.WARN status.message = 'Host bridge is running but no controller is connected' + elif (loss > UNSTABLE_LOSS or gap > UNSTABLE_GAP_S + or (round_trip or 0.0) > UNSTABLE_ROUND_TRIP_S): + status.level = DiagnosticStatus.WARN + status.message = f'Unstable link from {self.sender[0]}: {quality}' else: - status.message = f'Receiving from {self.sender[0]}' - status.values = [KeyValue(key='value', value=f'{rate:.0f}'), - KeyValue(key='unit', value='Hz'), - KeyValue(key='rejected', value=str(self.rejected))] + status.message = f'Receiving from {self.sender[0]}: {quality}' + status.values = [ + KeyValue(key='value', value=f'{rate:.0f}'), KeyValue(key='unit', value='Hz'), + KeyValue(key='rejected', value=str(self.rejected)), + KeyValue(key='loss_percent', value=f'{100.0 * loss:.1f}'), + KeyValue(key='jitter_ms', value=f'{1000.0 * jitter:.1f}'), + KeyValue(key='longest_gap_ms', value=f'{1000.0 * gap:.0f}'), + KeyValue(key='round_trip_ms', + value='' if round_trip is None else f'{1000.0 * round_trip:.1f}')] message = DiagnosticArray(status=[status]) message.header.stamp = self.get_clock().now().to_msg() self.diagnostics_publisher.publish(message) diff --git a/waybionic_teleop/waybionic_teleop/xinput_bridge.py b/waybionic_teleop/waybionic_teleop/xinput_bridge.py index 45401a9d..b93c273b 100644 --- a/waybionic_teleop/waybionic_teleop/xinput_bridge.py +++ b/waybionic_teleop/waybionic_teleop/xinput_bridge.py @@ -13,7 +13,7 @@ import socket import time -from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS, pack, unpack_rumble +from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS, pack, pong, unpack_rumble ERROR_SUCCESS = 0 # game_controller_node rumbles for a second per request unless told to stop; so does this. @@ -56,7 +56,7 @@ def vibration(intensity): def read_rumble(sock, receiver): - """Return the newest rumble intensity that the receiver address sent, or None.""" + """Return the newest rumble intensity the receiver sent, or None; answer its pings.""" intensity = None for _ in range(MAX_READS): try: @@ -68,6 +68,14 @@ def read_rumble(sock, receiver): continue if sender != receiver: continue + answer = pong(data) + if answer is not None: + # Sent straight back, so the station can time the link. + try: + sock.sendto(answer, receiver) + except OSError: + pass + continue try: intensity = unpack_rumble(data) except ValueError: @@ -113,7 +121,7 @@ def main(): parser = argparse.ArgumentParser(description='Send an Xbox controller to the arm.') parser.add_argument('--host', default='127.0.0.1', help='ground station address') parser.add_argument('--port', type=int, default=47300, help='ground station joy_udp_port') - parser.add_argument('--rate', type=float, default=120.0, help='packets per second') + parser.add_argument('--rate', type=float, default=250.0, help='packets per second') parser.add_argument('--slot', type=int, choices=range(4), help='XInput controller slot (default: first connected)') args = parser.parse_args() @@ -149,7 +157,8 @@ def main(): sender.sendto(pack(sequence, axes, buttons, active is not None), receiver) except BlockingIOError: pass - # The ground station answers on the same socket when the arm stops at a limit. + # The ground station answers on the same socket: pings to time the link, and a + # rumble when the arm stops at a limit. intensity = read_rumble(sender, receiver) if intensity is not None and active is not None: set_state(active, ctypes.byref(vibration(intensity))) From c6f48503300b1a383e2793c686a23af647f1f986 Mon Sep 17 00:00:00 2001 From: yassinsolim Date: Sat, 10 Oct 2026 21:10:05 -0600 Subject: [PATCH 03/11] Add macOS commands and instructions for the real arm scripts/macos.sh gains flash, drives and arm. flash stops with a message naming PR #40 while the carrier firmware is not in the checkout. RoboStack adds joy and pyserial. The build instructions cover flashing the carrier, setting up the drives, removing the placeholder tool drive, zeroing, a remote operator and the monitor rows. --- BuildInstructions.md | 148 +++++++++++++++++++++++++++++++++++-------- robostack.yaml | 4 ++ scripts/macos.sh | 58 +++++++++++++++++ 3 files changed, 182 insertions(+), 28 deletions(-) diff --git a/BuildInstructions.md b/BuildInstructions.md index cef63a8d..9282941c 100644 --- a/BuildInstructions.md +++ b/BuildInstructions.md @@ -296,7 +296,7 @@ can report exit code `-2`, indicating the requested SIGINT interruption. `teleop:=true` drives the arm with an Xbox controller through simulated CAN drives; nothing is sent to hardware unless you choose a drive bus, as described in -[Real MKS drives over CAN](#real-mks-drives-over-can). The controller mapping is in +[Real arm](#real-arm-mks-drives-over-can). The controller mapping is in `waybionic_teleop/config/xbox_teleop.yaml`, and the joint-to-drive map (MKS SERVO42D/57D CAN IDs, the 26:1 and 3:1 gear ratios and the wrist differential) is in `waybionic_teleop/config/arm_drives.yaml`. @@ -465,34 +465,105 @@ Press **Ctrl+C** in its window to stop. **Linux:** `ros2 launch waybionic_bringup ground_station.launch.py teleop:=true autoplay:=true`. -## Real MKS Drives over CAN +## Real Arm (MKS Drives over CAN) -`drive_interface` sends the same frames to real MKS SERVO42D/57D drives through a -[python-can](https://python-can.readthedocs.io/) interface. The drive map in -`waybionic_teleop/config/arm_drives.yaml` is still a placeholder: check each CAN ID, -gear ratio and direction before the first powered test, and start with the motors -unloaded. Set every drive to the bitrate in that file (1 Mbit/s; the MKS default is -500 kbit/s). On a real bus every drive joint needs a URDF limit before the host holds or -moves anything (`unmodeled_joints` applies to simulation only), so remove the placeholder -`tool` drive from the map, or give its joint a limit in the URDF. +The controller plugs into the computer, not the Arduino. The computer runs the teleop, +the Cartesian moves (inverse kinematics), the joint limits and collision checks, the +RViz twin and the monitor, then sends MKS frames through the carrier: a UNO R4 WiFi with +a TJA1051T transceiver running `waybionic_can/arduino/carrier_bridge`. The carrier only +passes frames between USB and the CAN bus, and reports its own status. -The computer running ROS needs the USB CAN adapter. Docker Desktop on Windows and -macOS cannot reach USB devices, so use native ROS on Linux or macOS (RoboStack), or -Docker on Linux with `--network host`. +```text +controller -> Mac (ROS 2) -> USB, 1 Mbaud -> carrier -> CAN, 1 Mbit/s -> 5 MKS drives +``` -Linux, SocketCAN adapter (candleLight firmware): +`waybionic_teleop/config/arm_drives.yaml` maps the joints to the drives: CAN IDs 1-5 +(base yaw, shoulder, elbow, wrist left, wrist right), 26:1 cycloidal reducers on the +first three joints and 3:1 belts on the two wrist motors. Its `tool` drive (CAN ID 6) is +a placeholder with no hardware behind it. On a real bus every drive joint needs a URDF +limit before the host holds or moves anything (`unmodeled_joints` applies to simulation +only), and the host waits for every drive in the list, so remove `tool` from `drives` +before driving the real arm. Start with the motors unloaded, and keep the physical E-stop +within reach. -```bash -sudo ip link set can0 up type can bitrate 1000000 -ros2 launch waybionic_bringup ground_station.launch.py teleop:=true drive_interface:=socketcan drive_channel:=can0 +The computer running ROS needs the carrier or USB CAN adapter. Docker Desktop on Windows +and macOS cannot reach USB devices, so use native ROS on macOS (RoboStack, below) or +Linux, or Docker on Linux with `--network host` for a SocketCAN adapter. + +### On a Mac + +Do the [macOS setup](#macos-apple-silicon) first. Then, from the repository root: + +1. Flash the carrier once (and after carrier firmware changes). The firmware comes with + PR #40 (`waybionic_can`); until that is merged, `flash` stops and says so. Plug in + only the carrier, so its port is the only `/dev/cu.usbmodem*`; otherwise set + `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. + + ```bash + brew install arduino-cli + ./scripts/macos.sh flash + ``` + +2. Set up each drive once, alone on the bus: give it its CAN ID (they all ship as 1), + then switch it to 1 Mbit/s. The carrier keeps its first bit rate until it resets, so + replug it, connect every drive, and check they all answer. + + ```bash + ./scripts/macos.sh drives set-id 1 3 # for example the elbow + ./scripts/macos.sh drives set-bitrate 3 1000000 + # after every drive is switched: replug the carrier + ./scripts/macos.sh drives --bitrate 1000000 scan + ``` + +3. With `tool` removed from `drives` in `arm_drives.yaml`, put the arm in the zero pose + (upright, as RViz shows it before anything moves) and start the ground station. A + controller plugged into the Mac (USB or Bluetooth) drives the arm and its twin + together: + + ```bash + ./scripts/macos.sh arm + ``` + +4. In a second Terminal, zero the drives with teleop still disabled, then press Start on + the controller: + + ```bash + ./scripts/macos.sh run ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger + ``` + +5. Check each joint's direction at the slowest speed in the `upper` group. If a drive + turns the wrong way, negate its `factors` in `arm_drives.yaml` and rebuild. + +**Remote operator.** The controller can stay with an operator on another computer. On +the operator's Windows computer, run the controller bridge pointed at the Mac's address: + +```powershell +cd waybionic_teleop +python -m waybionic_teleop.xinput_bridge --host 192.168.1.20 ``` -macOS or Linux, serial-line (slcan) adapter: +On the Mac, listen on the network: ```bash -ros2 launch waybionic_bringup ground_station.launch.py teleop:=true drive_interface:=slcan drive_channel:=/dev/tty.usbmodem1101 +./scripts/macos.sh arm joy_source:=udp joy_udp_bind:=0.0.0.0 ``` +The receiver takes controller packets from any computer that can reach its port, so do +this only on a private network. + +### The engineering monitor + +With `teleop:=true` the monitor shows live rows: + +| Row | Shows | +| --- | --- | +| `controller.link` | Remote controller only: packet rate, loss, jitter, longest gap and network round trip; warns past 2% loss, a 100 ms gap or a 50 ms round trip | +| `teleop.input` | Whether controller input is arriving; teleop disables itself after 0.5 s without it | +| `arm.command_gate` | Whether the drives take teleop's commands, or why they stopped | +| `can.carrier` | The carrier's USB link (reopened every second if unplugged), E-stop and supply (once wired), CAN controller errors, and frames the carrier refused | +| `can.bus` | Frames per second and bus load | +| `drive.*`, `arm.*` | Each drive's reply state and encoder, each joint against its target, and whether the arm is zeroed | + **Zeroing.** The encoders count from where the drives were powered on, so the host publishes no joint states and moves nothing until the arm is zeroed. Put the arm in the zero pose (the pose RViz shows before anything moves), leave teleop disabled, and @@ -503,16 +574,37 @@ ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger ``` Then press Start. Real drives take commands through the same gate as the simulated ones. -If a drive stops answering, for example because the E-stop cut its power, or its encoder -count jumps further than `max_rpm` allows between two readings, as after a brief power -loss, every drive stops and the arm must be zeroed again. The same happens when a drive -reports a failed move (as when its stall protection releases the motor) or an end-limit -stop, or stays more than `following_error_counts` from its target for -`following_error_ticks` ticks; both are provisional values in `arm_drives.yaml`. If the -joint commands stop for 0.5 s, every drive stops where it is, and if the host stops, the +If a drive stops answering, for example because the E-stop cut its power or the carrier +was unplugged, or its encoder count jumps further than `max_rpm` allows between two +readings, as after a brief power loss, every drive stops and the arm must be zeroed +again. The same happens when a drive reports a failed move (as when its stall protection +releases the motor) or an end-limit stop, or stays more than `following_error_counts` from +its target for `following_error_ticks` ticks; both are provisional values in +`arm_drives.yaml`. Once Electrical wires the carrier's E-stop sense, pressing the E-stop +also stops every drive at once, and Start is refused until it is released. If the joint +commands stop for 0.5 s, every drive stops where it is, and if the host stops, the drives' heartbeat stops them. A stop frame the adapter refuses is sent again on every -tick, and Start is refused until it has gone out. After any stop, disable teleop and press -Start again. +tick, and Start is refused until it has gone out. The carrier answers a frame it cannot +pass on yet with BELL; the host sends a refused move, stop or setup frame again on the +next tick, and a refused zero while the zero service waits. After any stop, disable +teleop and press Start again. + +### On Linux + +With the carrier, set up the drives with `mks_setup` (the commands in step 2 above), then +launch: + +```bash +ros2 run waybionic_teleop mks_setup --channel /dev/ttyACM0 scan +ros2 launch waybionic_bringup ground_station.launch.py teleop:=true drive_interface:=slcan drive_channel:=/dev/ttyACM0 +``` + +A SocketCAN adapter (candleLight firmware): + +```bash +sudo ip link set can0 up type can bitrate 1000000 +ros2 launch waybionic_bringup ground_station.launch.py teleop:=true drive_interface:=socketcan drive_channel:=can0 +``` **Without hardware.** `mks_drive_sim` answers on a CAN interface the way the drives do, so the host can be tested end to end over a virtual CAN interface on Linux: diff --git a/robostack.yaml b/robostack.yaml index 1177244c..4845c622 100644 --- a/robostack.yaml +++ b/robostack.yaml @@ -12,6 +12,8 @@ dependencies: - ros-jazzy-rviz-imu-plugin - ros-jazzy-xacro - ros-jazzy-joint-state-publisher-gui + # A controller plugged into the Mac (joy_source:=device). + - ros-jazzy-joy - colcon-common-extensions - compilers - cmake @@ -20,6 +22,8 @@ dependencies: - ninja - pytest <9 - python-can + # The carrier's USB serial link to the real arm. + - pyserial # colcon still relies on the legacy `develop` and `test` commands removed by # newer setuptools. Keep Python ROS packages editable and testable on macOS. - setuptools <72 diff --git a/scripts/macos.sh b/scripts/macos.sh index 2681ec8a..81ecb53b 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -20,7 +20,12 @@ Commands: setup Create/update the RoboStack environment and build the workspace build Build the workspace launch Launch the ground station visualization + flash Compile and upload carrier_bridge to the UNO R4 WiFi (needs arduino-cli) + drives Set up the MKS drives through the carrier, e.g. drives scan (see mks_setup) + arm Drive the real arm: controller on this Mac, carrier on USB run Run any command inside the ROS workspace + +The carrier is found as the only /dev/cu.usbmodem* port; set WAYBIONIC_CARRIER to choose. EOF } @@ -133,6 +138,41 @@ run_workspace() { ' _ "$ROOT" "$@" } +find_carrier() { + local ports + + if [[ -n "${WAYBIONIC_CARRIER:-}" ]]; then + [[ -e "$WAYBIONIC_CARRIER" ]] || fail "WAYBIONIC_CARRIER=$WAYBIONIC_CARRIER does not exist" + CARRIER="$WAYBIONIC_CARRIER" + return + fi + shopt -s nullglob + ports=(/dev/cu.usbmodem*) + shopt -u nullglob + case "${#ports[@]}" in + 0) fail "no /dev/cu.usbmodem* port: plug in the carrier (UNO R4 WiFi)" ;; + 1) CARRIER="${ports[0]}" ;; + *) fail "several ports (${ports[*]}); set WAYBIONIC_CARRIER to the carrier's" ;; + esac +} + +flash_carrier() { + local fqbn="arduino:renesas_uno:unor4wifi" + local sketch="$ROOT/waybionic_can/arduino/carrier_bridge" + local library="$ROOT/waybionic_can/arduino/libraries/WaybionicCan" + + [[ -f "$sketch/carrier_bridge.ino" ]] \ + || fail "carrier_bridge is not in this checkout yet: it comes with PR #40 (waybionic_can)" + command -v arduino-cli >/dev/null 2>&1 \ + || fail "install arduino-cli first: brew install arduino-cli" + find_carrier + arduino-cli core update-index + arduino-cli core install arduino:renesas_uno + arduino-cli compile --fqbn "$fqbn" --library "$library" "$sketch" + arduino-cli upload --fqbn "$fqbn" --port "$CARRIER" "$sketch" + echo "Flashed carrier_bridge to $CARRIER" +} + command_name="${1:-help}" if [[ $# -gt 0 ]]; then shift @@ -158,6 +198,24 @@ case "$command_name" in run_workspace env RMW_IMPLEMENTATION="${RMW_IMPLEMENTATION:-rmw_cyclonedds_cpp}" \ ros2 launch waybionic_bringup ground_station.launch.py "$@" ;; + flash) + check_host + flash_carrier + ;; + drives) + [[ $# -gt 0 ]] || fail "drives needs an mks_setup command, such as scan" + prepare + find_carrier + run_workspace ros2 run waybionic_teleop mks_setup --channel "$CARRIER" "$@" + ;; + arm) + prepare + find_carrier + echo "Carrier: $CARRIER" + run_workspace env RMW_IMPLEMENTATION="${RMW_IMPLEMENTATION:-rmw_cyclonedds_cpp}" \ + ros2 launch waybionic_bringup ground_station.launch.py teleop:=true \ + joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" "$@" + ;; run) [[ $# -gt 0 ]] || fail "run requires a command" prepare From bdc05e9c8f434bfc71b18d9eceb1ead575fd38c0 Mon Sep 17 00:00:00 2001 From: yassinsolim Date: Sat, 10 Oct 2026 21:25:56 -0600 Subject: [PATCH 04/11] Shorten comments in the carrier code and tests --- waybionic_teleop/test/test_can_drives.py | 16 +++++----------- waybionic_teleop/test/test_drive_map.py | 3 +-- waybionic_teleop/test/test_slcan_bus.py | 3 +-- waybionic_teleop/waybionic_teleop/slcan_bus.py | 3 +-- 4 files changed, 8 insertions(+), 17 deletions(-) diff --git a/waybionic_teleop/test/test_can_drives.py b/waybionic_teleop/test/test_can_drives.py index 993700c3..ebec04bf 100644 --- a/waybionic_teleop/test/test_can_drives.py +++ b/waybionic_teleop/test/test_can_drives.py @@ -34,9 +34,7 @@ / 'waybionic_arm.urdf').read_text(encoding='utf-8') # The arm's drives without the placeholder tool, whose joint has no URDF limit yet. ARM_DRIVES = ['base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right'] -# Teleop keeps its setpoints a tick ahead of the drives. A target sent once and left must stay -# within following_error_counts of the base's encoder (3390 of 4096 counts through its 26:1 -# reducer), or the drives stop it as a drive that stopped following. +# A target sent once must stay within following_error_counts: 3390 of 4096 counts at 26:1. NEAR_TARGET = 0.05 @@ -372,8 +370,7 @@ def test_the_host_drives_the_arm_through_the_carrier(make_node, carrier_port, mo assert node.authorized, node.stop_reason assert move(node, executor, joint_1=0.3) - # Pressed mid-move, the e-stop stops every drive where it is, and Start waits for its - # release. + # Pressed mid-move, the e-stop stops every drive, and Start waits for its release. def pressed_mid_move(): toward(node, joint_1=1.0) if positions(node)['joint_1'] > 0.5: @@ -391,8 +388,7 @@ def pressed_mid_move(): press_start(node) assert node.authorized, node.stop_reason - # Unplugged, the drives fall silent, which stops the arm until it is zeroed again; the - # carrier is reopened once it is back. + # Unplugged, the drives fall silent and stop the arm; the carrier reopens once it is back. port.unplugged = True assert spin_until(executor, lambda: all(node.lost)) assert not node.authorized and not any(node.zeroed) @@ -409,8 +405,7 @@ def test_frames_the_carrier_refuses_go_out_again(make_node, carrier_port, monkey seen = set() def busy(can_id, data): - # Refuse every move, stop and zero the first time, as a carrier with a busy CAN - # controller would; resent, it goes out. + # A busy carrier refuses each move, stop and zero once; sent again, it goes out. if data[0] not in (mks_can.ABSOLUTE_AXIS, mks_can.SET_ZERO) or (can_id, data) in seen: return False seen.add((can_id, data)) @@ -426,8 +421,7 @@ def busy(can_id, data): assert spin_until(executor, lambda: node.commanded is not None and not node.stopping) press_start(node) assert node.authorized, node.stop_reason - # A target is sent again only after its refusal, so without the resend the drives would - # never move. + # Every target is refused once, so the drives move only if refused ones go out again. assert move(node, executor, joint_1=0.3, joint_4=0.2) assert node.authorized, node.stop_reason node.report() diff --git a/waybionic_teleop/test/test_drive_map.py b/waybionic_teleop/test/test_drive_map.py index 79eb53c4..ff46283c 100644 --- a/waybionic_teleop/test/test_drive_map.py +++ b/waybionic_teleop/test/test_drive_map.py @@ -46,8 +46,7 @@ def test_gear_ratio_scales_counts_and_speed(): def test_a_setpoint_that_jumped_ahead_is_chased_near_the_commanded_speed(arm_map): period = 1.0 / 120.0 rates = {'joint_1': math.radians(60.0), 'joint_4': 0.5, 'joint_5': 0.2} - # A 100 ms host stall leaves the base setpoint 6 degrees ahead of its drive, which the - # 26:1 reducer makes more than the drive's top speed covers in one period. + # A 100 ms host stall leaves the base setpoint 6 degrees ahead: 3120 rpm for one period. ahead = {joint: rates.get(joint, 0.0) * 0.1 for joint in arm_map.joints} counts = arm_map.to_counts(dict.fromkeys(arm_map.joints, 0.0)) top = mks_can.MAX_SPEED_RPM diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index 4521e5ac..b9397d8b 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -85,8 +85,7 @@ def test_a_refusal_is_matched_to_the_frame_it_answers(bus, ports): for frame in frames: bus.send(*frame) assert bus.receive() is None - # C, S8 and O, then the first frame is taken and the second refused, with a drive's reply - # in between. + # C, S8, O; frame 1 taken; frame 2 refused, a drive's reply in between; frame 3 taken. ports[0].inbox += b'\r\r\r\r\at00183100000000000032\r\r\r' assert bus.receive() == (1, bytes.fromhex('3100000000000032')) assert bus.take_refused() == [frames[1]] and bus.take_refused() == [] diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index dc355bf5..5861df41 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -56,8 +56,7 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): self.frames = self.bits = self.errors = self.refused = self.reopens = 0 self.problem = '' self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() - # The lines in outgoing, then the lines written but not yet answered, in order: a - # frame's (can_id, data), or the command itself. + # Lines queued, then written but unanswered: a frame's (can_id, data) or a command. self.queued, self.pending = [], deque(maxlen=MAX_PENDING) self.refusals, self.bell = [], False self.heard = self.next_try = 0.0 From ce8e4d338a261534cf0945fd721d4073deb1189f Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:28:04 -0600 Subject: [PATCH 05/11] Reopen a carrier that stops answering, and settle stops before closing Past MAX_PENDING unanswered lines the link is reopened instead of dropping the oldest, so a later BELL cannot be matched to the wrong frame. On shutdown the drive node waits up to 0.5 s for the carrier to answer and repeats any stop it refused before the carrier is closed. --- waybionic_teleop/test/conftest.py | 39 ++++++++++++++++++- .../test/test_sim_arm_drives_node.py | 25 ++++++++++++ waybionic_teleop/test/test_slcan_bus.py | 14 +++++++ .../waybionic_teleop/sim_arm_drives_node.py | 11 ++++++ .../waybionic_teleop/slcan_bus.py | 13 ++++++- 5 files changed, 99 insertions(+), 3 deletions(-) diff --git a/waybionic_teleop/test/conftest.py b/waybionic_teleop/test/conftest.py index 88fc6fee..3bb57101 100644 --- a/waybionic_teleop/test/conftest.py +++ b/waybionic_teleop/test/conftest.py @@ -1,4 +1,4 @@ -"""Load a node's parameters from the package config files, flattened the way ROS names them.""" +"""Shared test helpers: node parameters from the package config files, and a fake carrier.""" from pathlib import Path @@ -8,6 +8,43 @@ CONFIG = Path(__file__).resolve().parent.parent / 'config' +class CarrierPort: + """The carrier's USB port: it answers every line, and BELL to each frame it refuses.""" + + def __init__(self, refuse=(), answering=True): + self.refuse, self.answering = list(refuse), answering + self.writes, self.inbox, self.closed = [], bytearray(), False + + @property + def in_waiting(self): + return len(self.inbox) + + def read(self, size): + chunk = bytes(self.inbox[:size]) + del self.inbox[:size] + return chunk + + def write(self, data): + self.writes.append(bytes(data)) + for line in bytes(data).split(b'\r')[:-1] if self.answering else (): + if line[:1] != b't': + # A command, or the empty line after a frame. + self.inbox += b'\r' + elif line in self.refuse: + # Refused once each time it is listed. + self.refuse.remove(line) + self.inbox += b'\a' + return len(data) + + def close(self): + self.closed = True + + +@pytest.fixture +def carrier_port(): + return CarrierPort + + def flatten(values, prefix=''): flat = {} for key, value in values.items(): diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 7c631d3a..001d97ab 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -20,6 +20,7 @@ from waybionic_teleop.kinematics import ArmKinematics, joint_limits from waybionic_teleop.sim_arm_drives_node import QUIET_BEFORE_ZERO_S, REPLY_TIMEOUT_S, SimArmDrives from waybionic_teleop.sim_drives import SimulatedServo +from waybionic_teleop.slcan_bus import SlcanBus from waybionic_teleop.teleop import ArmTeleop, config_from_parameters URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' @@ -197,6 +198,30 @@ def test_a_refused_setup_or_zero_frame_goes_out_again_only_while_needed(node, mo assert zero in sent +def stop_line(can_id): + data = mks_can.stop(can_id, 0) + return b't%03X%d%s' % (can_id, len(data), data.hex().upper().encode()) + + +@pytest.mark.parametrize('answering', [True, False]) +def test_closing_repeats_a_refused_stop_before_the_carrier_closes( + node, monkeypatch, carrier_port, answering): + port = carrier_port(refuse=[stop_line(1)], answering=answering) + node.interface = 'slcan' + node.bus = SlcanBus('/dev/fake', 1000000, open_port=lambda: port) + monkeypatch.setattr(sim_arm_drives_node, 'CLOSE_TIMEOUT_S', 0.2) + started = time.monotonic() + node.close() + written = b''.join(port.writes) + assert written.endswith(b'C\r') and port.closed + if answering: + # The carrier refused the base's stop, so it went out again before the carrier closed. + assert written.count(stop_line(1)) == 2 and written.count(stop_line(2)) == 1 + else: + # A carrier that answers nothing delays closing by the timeout only. + assert written.count(stop_line(1)) == 1 and time.monotonic() - started < 1.0 + + @pytest.mark.parametrize('fault', [ 'missing_position', 'duplicate_joint', 'nonfinite_position', 'nonfinite_speed', 'outside_urdf_limit', diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index b9397d8b..53a5ee82 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -139,6 +139,20 @@ def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): assert ports[0].writes[-1] == b'C\rS8\rO\r' +def test_a_carrier_that_stops_answering_lines_is_opened_again(bus, ports, clock): + # Its status frames keep coming, but no line written gets its answer. + for _ in range(slcan_bus.MAX_PENDING): + bus.send(1, mks_can.read_encoder(1)) + ports[0].inbox += b't7F080005000000000000\r' + bus.receive() + assert not bus.connected and 'stopped answering' in bus.problem and ports[0].closed + # Nothing is left to match a late answer to, so no frame is wrongly called refused. + assert bus.unanswered == 0 and bus.take_refused() == [] + clock[0] += slcan_bus.REOPEN_EVERY_S + bus.step(0.0) + assert bus.connected and ports[1].writes == [b'C\rS8\rO\r'] + + def test_the_carrier_status_frame_decodes(): status = carrier.parse_status(bytes.fromhex('0707' + '5DC0' + '0002' + '0304')) assert status == {'sequence': 7, 'estop': 'pressed', 'supply_v': 24.0, 'can_errors': 2, diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index ebd2da04..5eecbaef 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -42,6 +42,8 @@ CARRIER_TIMEOUT_S = 0.5 # Zeroing waits for the joint commands to stop, so teleop must be disabled first. QUIET_BEFORE_ZERO_S = 1.0 +# How long closing waits for the carrier to take the last stops. +CLOSE_TIMEOUT_S = 0.5 # Every drive must confirm these before it moves, so none runs without its heartbeat stop. SETUP = (mks_can.SET_MODE, mks_can.SET_RESPONSE, mks_can.ENABLE, mks_can.SET_HEARTBEAT) # F5 replies of a drive that no longer follows its targets: run failed, as when stall @@ -608,6 +610,15 @@ def carrier_status(self, now): def close(self): """Stop the drives and release the bus; the drives' heartbeat would also stop them.""" self.stop_all('Shutting down') + if self.interface == 'slcan': + # The carrier may refuse a stop after send() returned True, and no later tick would + # send it again, so wait for its answers and repeat refused stops before closing. + deadline = time.monotonic() + CLOSE_TIMEOUT_S + while (self.bus.connected and (self.stopping or self.bus.unanswered) + and time.monotonic() < deadline): + time.sleep(0.002) + self.drain(time.monotonic()) + self.send_stops() self.bus.shutdown() diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 5861df41..878279e3 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -26,7 +26,8 @@ # The carrier sends its status ten times a second while open, so this much quiet means it is # closed: it reset, or it was still booting when the port opened. SILENCE_S = 1.0 -# Lines still waiting for an answer; past this the carrier is not answering empty lines. +# Lines still waiting for an answer. The carrier answers within a millisecond or two, so this +# many means it stopped answering, and later answers could no longer be matched to their lines. MAX_PENDING = 256 BELL = 0x07 CR = 0x0D @@ -57,7 +58,7 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): self.problem = '' self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() # Lines queued, then written but unanswered: a frame's (can_id, data) or a command. - self.queued, self.pending = [], deque(maxlen=MAX_PENDING) + self.queued, self.pending = [], deque() self.refusals, self.bell = [], False self.heard = self.next_try = 0.0 # A missing adapter at start-up is a configuration error, so let it raise. @@ -68,6 +69,11 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): def connected(self): return self.serial is not None + @property + def unanswered(self): + """Return how many lines, queued or written, the carrier has not answered yet.""" + return len(self.queued) + len(self.pending) + def send(self, can_id, data): """Queue a frame for the next write; return False while the carrier is unplugged.""" data = bytes(data) @@ -142,6 +148,9 @@ def _flush(self): self.outgoing.clear() self.pending.extend(self.queued) self.queued.clear() + if len(self.pending) > MAX_PENDING: + # Start again rather than pin a later answer, such as a refusal, on the wrong line. + self._lost('the carrier stopped answering its lines') def _read(self): if self.serial is None: From 0c0a757839ac09548b37b51bd4bf883bfc3bc8da Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:28:04 -0600 Subject: [PATCH 06/11] Time the controller link only by answers to its own pings Each ping nonce is remembered with the bridge it went to, and only the first pong carrying it counts, so a late or replayed pong cannot refresh the round trip. --- .../test/test_joy_udp_receiver.py | 27 +++++++++++++++++++ .../waybionic_teleop/joy_udp_receiver.py | 21 +++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/waybionic_teleop/test/test_joy_udp_receiver.py b/waybionic_teleop/test/test_joy_udp_receiver.py index 26eb2330..8ad6665a 100644 --- a/waybionic_teleop/test/test_joy_udp_receiver.py +++ b/waybionic_teleop/test/test_joy_udp_receiver.py @@ -166,3 +166,30 @@ def link(): finally: bridge.close() stranger.close() + + +def test_only_the_first_answer_to_a_ping_of_this_node_times_the_link(receiver): + bridge = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + + def deliver(data): + bridge.sendto(data, receiver.socket.getsockname()) + assert select.select([receiver.socket], [], [], 2.0)[0], 'the packet never arrived' + receiver.poll() + + try: + deliver(gamepad.pack(1, *NEUTRAL)) + receiver.report() + assert select.select([bridge], [], [], 2.0)[0], 'the ping never came' + ping = bridge.recv(64) + nonce, sent = gamepad.unpack_pong(gamepad.pong(ping)) + # A pong for a ping this node never sent does not count, even with a fresh time. + deliver(gamepad.pong(gamepad.pack_ping(nonce + 1, sent))) + assert receiver.round_trip is None + deliver(gamepad.pong(ping)) + assert receiver.round_trip is not None + # The same pong again, delayed or replayed, does not refresh the round trip. + receiver.round_trip_time = None + deliver(gamepad.pong(ping)) + assert receiver.round_trip_time is None + finally: + bridge.close() diff --git a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py index d2b7b13d..17f3fa01 100644 --- a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py +++ b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py @@ -25,6 +25,8 @@ UNSTABLE_GAP_S = 0.1 UNSTABLE_ROUND_TRIP_S = 0.05 PING_EVERY_S = 0.5 +# A pong later than this no longer times the link. +PONG_TIMEOUT_S = 10.0 class LinkQuality: @@ -86,6 +88,8 @@ def __init__(self, **kwargs): self.rejected = 0 self.link = LinkQuality() self.pings = 0 + # Pings not answered yet: nonce -> (bridge address, time sent). + self.waiting_pings = {} self.round_trip, self.round_trip_time = None, None self.report_time = time.monotonic() # Every millisecond, so a packet waits at most that long before it reaches teleop. @@ -140,13 +144,16 @@ def poll(self): def on_pong(self, data, sender, now): try: - _, sent = unpack_pong(data) + nonce, _ = unpack_pong(data) except ValueError: self.rejected += 1 return - # Only the bridge's answer to one of this node's pings times the link. - if sender == self.sender and 0.0 <= now - sent < 10.0: - self.round_trip, self.round_trip_time = now - sent, now + # Only the bridge's first answer to one of this node's own pings times the link, so a + # late or repeated pong cannot refresh it. + ping = self.waiting_pings.get(nonce) + if ping is not None and sender == ping[0] == self.sender: + del self.waiting_pings[nonce] + self.round_trip, self.round_trip_time = now - ping[1], now def on_feedback(self, message): if message.type != JoyFeedback.TYPE_RUMBLE or message.id != 0 or self.sender is None: @@ -161,10 +168,14 @@ def report(self): rate = self.published / max(now - self.report_time, 1e-3) self.published, self.report_time = 0, now loss, jitter, gap = self.link.take() + self.waiting_pings = {nonce: ping for nonce, ping in self.waiting_pings.items() + if now - ping[1] < PONG_TIMEOUT_S} if self.sender is not None: self.pings += 1 + nonce = self.pings & 0xFFFFFFFF try: - self.socket.sendto(pack_ping(self.pings, now), self.sender) + self.socket.sendto(pack_ping(nonce, now), self.sender) + self.waiting_pings[nonce] = (self.sender, now) except OSError as error: self.get_logger().warning(f'Ping not sent: {error}', throttle_duration_sec=5.0) # Bridges from before the ping was added never answer it. From fd20c0367382eef16de2c217fa8ae52f0abba658 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:28:04 -0600 Subject: [PATCH 07/11] Confirm the bench stop, and stop every simulated drive on a broadcast mks_setup stop now waits for the carrier to take the F7h frame, sends it again if refused, and fails clearly if it never goes out. Both drive simulators deliver frames to broadcast ID 0 to every drive without a reply, as the MKS manual describes. --- waybionic_teleop/test/test_mks_setup.py | 34 ++++++++++++- waybionic_teleop/test/test_sim_drives.py | 50 ++++++++++++++++++- waybionic_teleop/waybionic_teleop/mks_can.py | 2 + .../waybionic_teleop/mks_drive_sim.py | 9 +++- .../waybionic_teleop/mks_setup.py | 28 ++++++++++- .../waybionic_teleop/sim_drives.py | 18 +++++-- 6 files changed, 133 insertions(+), 8 deletions(-) diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 480425fd..3be8f0f4 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -2,8 +2,12 @@ import pytest -from waybionic_teleop import mks_setup +from waybionic_teleop import mks_can, mks_setup from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo +from waybionic_teleop.slcan_bus import SlcanBus + +STOP = mks_can.emergency_stop(mks_can.BROADCAST_ID) +STOP_LINE = b't000%d%s' % (len(STOP), STOP.hex().upper().encode()) @pytest.fixture @@ -32,3 +36,31 @@ def test_a_can_id_in_use_or_without_a_drive_is_refused(bus): def test_a_drive_switches_its_bit_rate(bus): assert '1000000 bit/s' in mks_setup.set_bitrate(bus, 3, 1000000) assert bus.drives[3].bitrate == 1000000 + + +def test_stop_reaches_every_drive(bus, monkeypatch, capsys): + for can_id, servo in bus.drives.items(): + for data in (mks_can.set_mode(can_id), mks_can.enable(can_id), + mks_can.absolute_axis(can_id, 0x4000, 300, 0)): + servo.receive(data) + servo.step(0.05) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + mks_setup.main(['--interface', 'virtual', '--channel', 'sim', 'stop']) + assert all(servo.target is None and servo.rpm == 0.0 for servo in bus.drives.values()) + assert 'Sent the emergency stop' in capsys.readouterr().out + + +@pytest.mark.parametrize('refusals, sent', [(1, True), (5, False)]) +def test_stop_goes_out_again_until_the_carrier_takes_it(monkeypatch, capsys, carrier_port, + refusals, sent): + port = carrier_port(refuse=[STOP_LINE] * refusals) + monkeypatch.setattr(mks_setup, 'open_bus', + lambda *args: SlcanBus('/dev/fake', 500000, open_port=lambda: port)) + monkeypatch.setattr(mks_setup, 'wait_for_carrier', lambda bus: True) + if sent: + mks_setup.main(['--channel', '/dev/fake', 'stop']) + assert 'Sent the emergency stop' in capsys.readouterr().out + else: + with pytest.raises(SystemExit, match='did not go out'): + mks_setup.main(['--channel', '/dev/fake', 'stop']) + assert b''.join(port.writes).count(STOP_LINE) == min(refusals + 1, 5) diff --git a/waybionic_teleop/test/test_sim_drives.py b/waybionic_teleop/test/test_sim_drives.py index 62ab2bba..29c7cb0f 100644 --- a/waybionic_teleop/test/test_sim_drives.py +++ b/waybionic_teleop/test/test_sim_drives.py @@ -1,8 +1,10 @@ """The simulated drive follows the manual's speed, acceleration and heartbeat rules.""" +import threading + import pytest -from waybionic_teleop import mks_can +from waybionic_teleop import mks_can, mks_drive_sim from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo RUNNING = mks_can.frame(1, mks_can.ABSOLUTE_AXIS, [1]) @@ -101,3 +103,49 @@ def test_bus_routes_replies_and_counts_bad_frames(): bus.send(1, mks_can.read_encoder(2)) bus.send(9, mks_can.read_encoder(9)) assert (bus.frames, bus.errors) == (4, 2) + + +def moving_servos(*can_ids): + servos = {} + for can_id in can_ids: + servo = servos[can_id] = SimulatedServo(can_id) + for data in (mks_can.set_mode(can_id), mks_can.enable(can_id), + mks_can.absolute_axis(can_id, 0x4000, 300, 0)): + servo.receive(data) + run(servo, 0.05) + assert servo.rpm > 0.0 + return servos + + +def test_a_broadcast_stops_every_drive_and_none_replies(): + servos = moving_servos(1, 2) + bus = SimulatedBus(servos.values(), 500000) + # The checksum of a broadcast counts ID 0, so one made for a single drive is malformed. + assert not bus.send(0, mks_can.emergency_stop(1)) and bus.errors == 1 + assert bus.send(0, mks_can.emergency_stop(0)) + assert bus.receive() is None + assert all(servo.target is None and servo.rpm == 0.0 for servo in servos.values()) + + +def test_the_drive_simulator_obeys_a_broadcast_without_replying(): + servos, done = moving_servos(1, 2), threading.Event() + + class Bus: + errors = 0 + + def __init__(self): + self.inbox, self.sent = [(0, mks_can.emergency_stop(0))], [] + + def receive(self, timeout=0.0): + if self.inbox: + return self.inbox.pop(0) + done.set() + return None + + def send(self, can_id, data): + self.sent.append((can_id, data)) + + bus = Bus() + mks_drive_sim.serve(bus, servos, done) + assert all(servo.target is None and servo.rpm == 0.0 for servo in servos.values()) + assert bus.sent == [] and bus.errors == 0 diff --git a/waybionic_teleop/waybionic_teleop/mks_can.py b/waybionic_teleop/waybionic_teleop/mks_can.py index 35e66c09..f28e3c43 100644 --- a/waybionic_teleop/waybionic_teleop/mks_can.py +++ b/waybionic_teleop/waybionic_teleop/mks_can.py @@ -9,6 +9,8 @@ COUNTS_PER_REV = 0x4000 MAX_SPEED_RPM = 3000 MIN_AXIS, MAX_AXIS = -0x800000, 0x7FFFFF +# Every drive acts on a frame to this ID, and none replies (manual part 5, note 1). +BROADCAST_ID = 0 READ_ENCODER = 0x31 SET_MODE = 0x82 diff --git a/waybionic_teleop/waybionic_teleop/mks_drive_sim.py b/waybionic_teleop/waybionic_teleop/mks_drive_sim.py index 185aeb59..564b0849 100644 --- a/waybionic_teleop/waybionic_teleop/mks_drive_sim.py +++ b/waybionic_teleop/waybionic_teleop/mks_drive_sim.py @@ -9,6 +9,7 @@ import threading import time +from waybionic_teleop import mks_can from waybionic_teleop.can_bus import CanBus from waybionic_teleop.sim_drives import SimulatedServo @@ -21,7 +22,13 @@ def serve(bus, servos, stop, period=0.001): frame = bus.receive(period) while frame is not None: can_id, data = frame - if can_id in servos: + if can_id == mks_can.BROADCAST_ID: + try: + for servo in servos.values(): + servo.receive(data, can_id) + except ValueError: + bus.errors += 1 + elif can_id in servos: try: replies += [(can_id, reply) for reply in servos[can_id].receive(data)] except ValueError: diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 07ee5fd2..3cc7ec9d 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -83,6 +83,29 @@ def set_bitrate(bus, can_id, bitrate): f'scan with --bitrate {bitrate}') +def send_confirmed(bus, can_id, data, attempts=5, timeout=0.2): + """ + Send a frame until the interface takes it; return False if it never does. + + The carrier answers BELL to a frame it refuses after send() has returned True, so wait for + its answer, and send a refused frame again. + """ + frame = (can_id, bytes(data)) + for _ in range(attempts): + if bus.send(*frame): + if not hasattr(bus, 'take_refused'): + return True + deadline = time.monotonic() + timeout + while bus.unanswered and time.monotonic() < deadline: + if bus.receive() is None: + time.sleep(0.002) + if not bus.unanswered and frame not in bus.take_refused(): + return True + bus.step(0.0) + time.sleep(0.01) + return False + + def wait_for_carrier(bus, seconds=3.0): """Give a carrier that resets when its port opens time to boot; True once it reports.""" deadline = time.monotonic() + seconds @@ -133,8 +156,9 @@ def main(argv=None): elif args.command == 'set-bitrate': print(set_bitrate(bus, args.can_id, args.rate)) else: - bus.send(0, mks_can.emergency_stop(0)) - bus.receive() + stop = mks_can.emergency_stop(mks_can.BROADCAST_ID) + if not send_confirmed(bus, mks_can.BROADCAST_ID, stop): + raise SystemExit('The emergency stop did not go out; press the E-stop') print('Sent the emergency stop to every drive') finally: bus.shutdown() diff --git a/waybionic_teleop/waybionic_teleop/sim_drives.py b/waybionic_teleop/waybionic_teleop/sim_drives.py index 2062ab86..560c0113 100644 --- a/waybionic_teleop/waybionic_teleop/sim_drives.py +++ b/waybionic_teleop/waybionic_teleop/sim_drives.py @@ -32,9 +32,13 @@ def __init__(self, can_id, bitrate=500000): self.speed = 0 self.acc = 0 - def receive(self, data): - """Handle one command and return the reply frames.""" - code, arguments = mks_can.parse(self.can_id, data) + def receive(self, data, address=None): + """Handle one command sent to address (by default this drive's ID); return the replies.""" + address = self.can_id if address is None else address + replies = self._handle(*mks_can.parse(address, data)) + return [] if address == mks_can.BROADCAST_ID else replies + + def _handle(self, code, arguments): self.quiet_ms = 0.0 if code == mks_can.READ_ENCODER and not arguments: value = round(self.axis).to_bytes(6, 'big', signed=True) @@ -147,6 +151,14 @@ def __init__(self, drives, bitrate): def send(self, can_id, data): """Deliver a frame; return False if no drive could take it.""" self._count(data) + if can_id == mks_can.BROADCAST_ID: + try: + for drive in self.drives.values(): + drive.receive(data, can_id) + except ValueError: + self.errors += 1 + return False + return bool(self.drives) drive = self.drives.get(can_id) if drive is None: self.errors += 1 From 2fd61fd902ed738716ca1b3a15fddbc077309b7e Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:13:05 -0600 Subject: [PATCH 08/11] Write the last stops before waiting, and fail the bench stop on a lost link close() writes the stops at once and closes the carrier in a finally, so a second Ctrl+C cannot skip them. mks_setup stop fails if the link drops while it waits, and says the carrier took the stop, since drives never answer a broadcast. Carrier writes time out after 0.1 s instead of blocking the loop. The real-arm steps now start with confirmed travel and a working E-stop, and check each gear ratio. --- BuildInstructions.md | 8 +++++- waybionic_teleop/test/conftest.py | 6 +++-- waybionic_teleop/test/test_mks_setup.py | 19 +++++++++++--- .../test/test_sim_arm_drives_node.py | 22 ++++++++++++++-- .../waybionic_teleop/mks_setup.py | 10 +++++--- .../waybionic_teleop/sim_arm_drives_node.py | 25 +++++++++++-------- .../waybionic_teleop/slcan_bus.py | 6 ++++- 7 files changed, 73 insertions(+), 23 deletions(-) diff --git a/BuildInstructions.md b/BuildInstructions.md index 9282941c..af6e0182 100644 --- a/BuildInstructions.md +++ b/BuildInstructions.md @@ -486,6 +486,10 @@ only), and the host waits for every drive in the list, so remove `tool` from `dr before driving the real arm. Start with the motors unloaded, and keep the physical E-stop within reach. +Before the drives are first powered, Mechanical confirms each joint's signed travel from +the zero pose against the URDF limits, including any cable or gear stop, and someone +shows that the E-stop cuts power to the drives. + The computer running ROS needs the carrier or USB CAN adapter. Docker Desktop on Windows and macOS cannot reach USB devices, so use native ROS on macOS (RoboStack, below) or Linux, or Docker on Linux with `--network host` for a SocketCAN adapter. @@ -532,7 +536,9 @@ Do the [macOS setup](#macos-apple-silicon) first. Then, from the repository root ``` 5. Check each joint's direction at the slowest speed in the `upper` group. If a drive - turns the wrong way, negate its `factors` in `arm_drives.yaml` and rebuild. + turns the wrong way, negate its `factors` in `arm_drives.yaml` and rebuild. Then move + each joint a known angle, such as 10 degrees in RViz, and measure it on the arm; a + different angle means its gear ratio in `factors` is wrong. **Remote operator.** The controller can stay with an operator on another computer. On the operator's Windows computer, run the controller bridge pointed at the Mac's address: diff --git a/waybionic_teleop/test/conftest.py b/waybionic_teleop/test/conftest.py index 3bb57101..2885590f 100644 --- a/waybionic_teleop/test/conftest.py +++ b/waybionic_teleop/test/conftest.py @@ -13,7 +13,7 @@ class CarrierPort: def __init__(self, refuse=(), answering=True): self.refuse, self.answering = list(refuse), answering - self.writes, self.inbox, self.closed = [], bytearray(), False + self.writes, self.inbox, self.closed, self.broken = [], bytearray(), False, False @property def in_waiting(self): @@ -25,6 +25,8 @@ def read(self, size): return chunk def write(self, data): + if self.broken: + raise OSError(6, 'Device not configured') self.writes.append(bytes(data)) for line in bytes(data).split(b'\r')[:-1] if self.answering else (): if line[:1] != b't': @@ -41,7 +43,7 @@ def close(self): @pytest.fixture -def carrier_port(): +def usb_carrier(): return CarrierPort diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 3be8f0f4..49e2b56e 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -47,20 +47,31 @@ def test_stop_reaches_every_drive(bus, monkeypatch, capsys): monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) mks_setup.main(['--interface', 'virtual', '--channel', 'sim', 'stop']) assert all(servo.target is None and servo.rpm == 0.0 for servo in bus.drives.values()) - assert 'Sent the emergency stop' in capsys.readouterr().out + assert 'The carrier took the emergency stop' in capsys.readouterr().out @pytest.mark.parametrize('refusals, sent', [(1, True), (5, False)]) -def test_stop_goes_out_again_until_the_carrier_takes_it(monkeypatch, capsys, carrier_port, +def test_stop_goes_out_again_until_the_carrier_takes_it(monkeypatch, capsys, usb_carrier, refusals, sent): - port = carrier_port(refuse=[STOP_LINE] * refusals) + port = usb_carrier(refuse=[STOP_LINE] * refusals) monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: SlcanBus('/dev/fake', 500000, open_port=lambda: port)) monkeypatch.setattr(mks_setup, 'wait_for_carrier', lambda bus: True) if sent: mks_setup.main(['--channel', '/dev/fake', 'stop']) - assert 'Sent the emergency stop' in capsys.readouterr().out + assert 'The carrier took the emergency stop' in capsys.readouterr().out else: with pytest.raises(SystemExit, match='did not go out'): mks_setup.main(['--channel', '/dev/fake', 'stop']) assert b''.join(port.writes).count(STOP_LINE) == min(refusals + 1, 5) + + +def test_stop_fails_when_the_carrier_is_unplugged(monkeypatch, usb_carrier): + port = usb_carrier() + monkeypatch.setattr(mks_setup, 'open_bus', + lambda *args: SlcanBus('/dev/fake', 500000, open_port=lambda: port)) + # The carrier booted, then its USB link failed before the stop. + monkeypatch.setattr(mks_setup, 'wait_for_carrier', + lambda bus: setattr(port, 'broken', True) or True) + with pytest.raises(SystemExit, match='did not go out'): + mks_setup.main(['--channel', '/dev/fake', 'stop']) diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 001d97ab..b4099f4f 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -4,6 +4,7 @@ import math from pathlib import Path import time +from types import SimpleNamespace from unittest.mock import MagicMock from diagnostic_msgs.msg import DiagnosticStatus @@ -205,8 +206,8 @@ def stop_line(can_id): @pytest.mark.parametrize('answering', [True, False]) def test_closing_repeats_a_refused_stop_before_the_carrier_closes( - node, monkeypatch, carrier_port, answering): - port = carrier_port(refuse=[stop_line(1)], answering=answering) + node, monkeypatch, usb_carrier, answering): + port = usb_carrier(refuse=[stop_line(1)], answering=answering) node.interface = 'slcan' node.bus = SlcanBus('/dev/fake', 1000000, open_port=lambda: port) monkeypatch.setattr(sim_arm_drives_node, 'CLOSE_TIMEOUT_S', 0.2) @@ -222,6 +223,23 @@ def test_closing_repeats_a_refused_stop_before_the_carrier_closes( assert written.count(stop_line(1)) == 1 and time.monotonic() - started < 1.0 +def test_a_second_ctrl_c_while_closing_still_sends_the_stops_and_closes( + node, monkeypatch, usb_carrier): + port = usb_carrier(answering=False) + node.interface = 'slcan' + node.bus = SlcanBus('/dev/fake', 1000000, open_port=lambda: port) + + def interrupted(seconds): + raise KeyboardInterrupt + monkeypatch.setattr(sim_arm_drives_node, 'time', + SimpleNamespace(monotonic=time.monotonic, sleep=interrupted)) + with pytest.raises(KeyboardInterrupt): + node.close() + written = b''.join(port.writes) + assert written.endswith(b'C\r') and port.closed + assert all(written.count(stop_line(drive.can_id)) == 1 for drive in node.map.drives) + + @pytest.mark.parametrize('fault', [ 'missing_position', 'duplicate_joint', 'nonfinite_position', 'nonfinite_speed', 'outside_urdf_limit', diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 3cc7ec9d..88895041 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -99,7 +99,9 @@ def send_confirmed(bus, can_id, data, attempts=5, timeout=0.2): while bus.unanswered and time.monotonic() < deadline: if bus.receive() is None: time.sleep(0.002) - if not bus.unanswered and frame not in bus.take_refused(): + # A lost link drops its unanswered lines, which is no answer at all. + if (bus.connected and not bus.unanswered + and frame not in bus.take_refused()): return True bus.step(0.0) time.sleep(0.01) @@ -138,7 +140,8 @@ def main(argv=None): rate_command = commands.add_parser('set-bitrate', help="change one drive's CAN bit rate") rate_command.add_argument('can_id', type=int) rate_command.add_argument('rate', type=int, choices=sorted(mks_can.BITRATES)) - commands.add_parser('stop', help='stop every drive at once (F7h to broadcast ID 0)') + commands.add_parser('stop', help='stop every drive at once (F7h to broadcast ID 0); give ' + "the drives' --bitrate") args = parser.parse_args(argv) bus = open_bus(args.interface, args.channel, args.bitrate, args.tty_baudrate) @@ -159,7 +162,8 @@ def main(argv=None): stop = mks_can.emergency_stop(mks_can.BROADCAST_ID) if not send_confirmed(bus, mks_can.BROADCAST_ID, stop): raise SystemExit('The emergency stop did not go out; press the E-stop') - print('Sent the emergency stop to every drive') + # Drives never answer a broadcast, so this is as far as it can be confirmed. + print(f'The carrier took the emergency stop for every drive at {args.bitrate} bit/s') finally: bus.shutdown() diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 5eecbaef..956a6a4c 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -609,17 +609,22 @@ def carrier_status(self, now): def close(self): """Stop the drives and release the bus; the drives' heartbeat would also stop them.""" - self.stop_all('Shutting down') - if self.interface == 'slcan': - # The carrier may refuse a stop after send() returned True, and no later tick would - # send it again, so wait for its answers and repeat refused stops before closing. - deadline = time.monotonic() + CLOSE_TIMEOUT_S - while (self.bus.connected and (self.stopping or self.bus.unanswered) - and time.monotonic() < deadline): - time.sleep(0.002) + try: + self.stop_all('Shutting down') + if self.interface == 'slcan': + # The carrier may refuse a stop after send() returned True, and no later tick + # would send it again, so write the stops now, then wait for the carrier's + # answers and repeat refused stops before closing it. + deadline = time.monotonic() + CLOSE_TIMEOUT_S self.drain(time.monotonic()) - self.send_stops() - self.bus.shutdown() + while (self.bus.connected and (self.stopping or self.bus.unanswered) + and time.monotonic() < deadline): + time.sleep(0.002) + self.drain(time.monotonic()) + self.send_stops() + finally: + # Even if a second Ctrl+C lands here, the queued stops and C still go out. + self.bus.shutdown() def main(): diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 878279e3..6475f34b 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -23,6 +23,9 @@ BITRATE_CODES = {125000: b'4', 250000: b'5', 500000: b'6', 1000000: b'8'} DEFAULT_BAUDRATE = 1000000 REOPEN_EVERY_S = 1.0 +# A carrier that stops reading its port fails the write, so the link is reopened rather than +# the control loop blocking. +WRITE_TIMEOUT_S = 0.1 # The carrier sends its status ten times a second while open, so this much quiet means it is # closed: it reset, or it was still booting when the port opened. SILENCE_S = 1.0 @@ -53,7 +56,8 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): raise ValueError(f'the carrier runs CAN at {sorted(BITRATE_CODES)} bit/s') self.port, self.bitrate = port, bitrate self.open_port = open_port or ( - lambda: serial.serial_for_url(port, baudrate=baudrate, timeout=0)) + lambda: serial.serial_for_url(port, baudrate=baudrate, timeout=0, + write_timeout=WRITE_TIMEOUT_S)) self.frames = self.bits = self.errors = self.refused = self.reopens = 0 self.problem = '' self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() From 760f112f668da4f118c9d555d25c361a56296bb9 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:39:34 -0600 Subject: [PATCH 09/11] Resend refused bench requests and name a lost carrier mks_setup requests now send a frame again when the carrier refuses it, and stop with the carrier's problem when the link drops, instead of reporting that no drive answered. The gear-ratio check points at gear_ratio. --- BuildInstructions.md | 2 +- waybionic_teleop/test/test_mks_setup.py | 28 +++++++++++++++++++ .../waybionic_teleop/mks_setup.py | 8 +++++- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/BuildInstructions.md b/BuildInstructions.md index af6e0182..3a1b6b7f 100644 --- a/BuildInstructions.md +++ b/BuildInstructions.md @@ -538,7 +538,7 @@ Do the [macOS setup](#macos-apple-silicon) first. Then, from the repository root 5. Check each joint's direction at the slowest speed in the `upper` group. If a drive turns the wrong way, negate its `factors` in `arm_drives.yaml` and rebuild. Then move each joint a known angle, such as 10 degrees in RViz, and measure it on the arm; a - different angle means its gear ratio in `factors` is wrong. + different angle means its `gear_ratio` in `arm_drives.yaml` is wrong. **Remote operator.** The controller can stay with an operator on another computer. On the operator's Windows computer, run the controller bridge pointed at the Mac's address: diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 49e2b56e..39fe4562 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -75,3 +75,31 @@ def test_stop_fails_when_the_carrier_is_unplugged(monkeypatch, usb_carrier): lambda bus: setattr(port, 'broken', True) or True) with pytest.raises(SystemExit, match='did not go out'): mks_setup.main(['--channel', '/dev/fake', 'stop']) + + +def test_a_scan_over_a_lost_carrier_says_so_instead_of_no_drive(usb_carrier): + port = usb_carrier() + bus = SlcanBus('/dev/fake', 500000, open_port=lambda: port) + port.broken = True + with pytest.raises(SystemExit, match='Lost the carrier'): + mks_setup.scan(bus, [1]) + + +def test_a_refused_request_goes_out_again(bus): + send, first, refusals = bus.send, [True], [] + + def busy_once(can_id, data): + # The carrier refuses the first frame, as while its CAN controller is busy. + if first: + first.clear() + refusals.append((can_id, bytes(data))) + return True + return send(can_id, data) + + def take_refused(): + taken = refusals[:] + refusals.clear() + return taken + bus.send, bus.take_refused = busy_once, take_refused + bus.drives[3].axis = 0x4000 + assert mks_setup.scan(bus, [3]) == {3: 0x4000} diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 88895041..3fdb429f 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -31,11 +31,17 @@ def open_bus(interface, channel, bitrate, tty_baudrate): def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): """Send a frame; return the arguments of the reply with this code, or None.""" answer_ids = answer_ids or {can_id} - bus.send(can_id, data) + sent = (can_id, bytes(data)) + bus.send(*sent) deadline = time.monotonic() + timeout while time.monotonic() < deadline: bus.step(0.0) frame = bus.receive() + if not getattr(bus, 'connected', True): + raise SystemExit(f'Lost the carrier: {bus.problem}') + # The carrier refuses a frame while its CAN controller is busy. + if hasattr(bus, 'take_refused') and sent in bus.take_refused(): + bus.send(*sent) if frame is None: time.sleep(0.002) continue From da3c309d8497aa5d30d335908deeec04ad60de9e Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:09:42 -0600 Subject: [PATCH 10/11] Keep no more frames unanswered than the carrier can queue The carrier holds at most 32 answers, and a frame it refuses for room needs two, so a stalled bus with many frames unanswered could overflow them and pin later refusals on the wrong frames. A frame beyond the carrier's 16-frame queue is now refused here and handed back like a carrier refusal, and a carrier that leaves the window full for 0.5 s is reopened. --- waybionic_teleop/test/test_slcan_bus.py | 26 +++++++++++-- .../waybionic_teleop/slcan_bus.py | 39 ++++++++++++++----- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index 53a5ee82..d9023baa 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -139,15 +139,35 @@ def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): assert ports[0].writes[-1] == b'C\rS8\rO\r' +def test_no_more_frames_are_unanswered_than_the_carrier_can_queue(bus, ports): + ports[0].inbox += b'\r\r\r' + bus.receive() + frames = [(can_id, mks_can.read_encoder(can_id)) + for can_id in range(1, slcan_bus.CARRIER_QUEUE + 3)] + assert all(bus.send(*frame) for frame in frames) + assert bus.receive() is None + # The rest are refused here, as the carrier would refuse them once its queue is full. + assert b''.join(ports[0].writes[1:]).count(b'\r\r') == slcan_bus.CARRIER_QUEUE + assert bus.take_refused() == frames[slcan_bus.CARRIER_QUEUE:] + assert bus.refused == 0 and bus.unanswered == slcan_bus.CARRIER_QUEUE + ports[0].inbox += b'\r' * slcan_bus.CARRIER_QUEUE + bus.receive() + assert bus.unanswered == 0 + assert bus.send(*frames[-1]) and bus.take_refused() == [] + + def test_a_carrier_that_stops_answering_lines_is_opened_again(bus, ports, clock): # Its status frames keep coming, but no line written gets its answer. - for _ in range(slcan_bus.MAX_PENDING): + for _ in range(slcan_bus.CARRIER_QUEUE): bus.send(1, mks_can.read_encoder(1)) ports[0].inbox += b't7F080005000000000000\r' bus.receive() + assert bus.connected + clock[0] += slcan_bus.ANSWER_TIMEOUT_S + 0.01 + assert not bus.send(1, mks_can.read_encoder(1)) assert not bus.connected and 'stopped answering' in bus.problem and ports[0].closed - # Nothing is left to match a late answer to, so no frame is wrongly called refused. - assert bus.unanswered == 0 and bus.take_refused() == [] + # Nothing is left to match a late answer to, so only frames never written count as refused. + assert bus.unanswered == 0 and bus.take_refused() == [(1, mks_can.read_encoder(1))] * 3 clock[0] += slcan_bus.REOPEN_EVERY_S bus.step(0.0) assert bus.connected and ports[1].writes == [b'C\rS8\rO\r'] diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 6475f34b..08133f17 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -10,7 +10,8 @@ The carrier says nothing about a frame it puts on the bus, and answers BELL to one it refuses, such as a frame that arrives while its CAN controller is still busy. Each frame is therefore followed by an empty line, which the carrier answers with CR, so every answer can be matched to -the line it belongs to. take_refused() hands back the refused frames to be sent again. +the line it belongs to. take_refused() hands back the refused frames to be sent again. No more +lines go unanswered at once than the carrier can queue; a frame beyond that is refused here. """ from collections import deque @@ -29,9 +30,15 @@ # The carrier sends its status ten times a second while open, so this much quiet means it is # closed: it reset, or it was still booting when the port opened. SILENCE_S = 1.0 -# Lines still waiting for an answer. The carrier answers within a millisecond or two, so this -# many means it stopped answering, and later answers could no longer be matched to their lines. -MAX_PENDING = 256 +# The carrier queues 16 frames and holds the answers to the lines after a queued frame until it +# leaves the queue, 32 answers at most. A frame it refuses for room needs two (its BELL and the +# CR after it), so with more lines unanswered than it can queue, a stalled bus could overflow +# them and later answers would be pinned on the wrong lines. Keeping to the queue's size means it +# never refuses a frame for room. +CARRIER_QUEUE = 16 +# The carrier answers within milliseconds, and drops a frame it cannot send after 10 ms, so no +# answer for this long with no room left means it stopped answering its lines. +ANSWER_TIMEOUT_S = 0.5 BELL = 0x07 CR = 0x0D @@ -64,6 +71,8 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): # Lines queued, then written but unanswered: a frame's (can_id, data) or a command. self.queued, self.pending = [], deque() self.refusals, self.bell = [], False + # When a frame was first refused here for room, until the carrier answers a line. + self.full_since = None self.heard = self.next_try = 0.0 # A missing adapter at start-up is a configuration error, so let it raise. self.serial = self.open_port() @@ -85,13 +94,24 @@ def send(self, can_id, data): raise ValueError(f'cannot send {can_id:X}#{data.hex()} as a standard frame') if self.serial is None: return False + if self.unanswered >= CARRIER_QUEUE: + now = time.monotonic() + if self.full_since is None: + self.full_since = now + elif now - self.full_since > ANSWER_TIMEOUT_S: + # Start again rather than pin a later answer, such as a refusal, on the wrong line. + self._lost('the carrier stopped answering its lines') + return False + # Not counted as refused: a burst such as the drives' setup simply waits a tick. + self.refusals.append((can_id, data)) + return True self.outgoing += b't%03X%d%s\r\r' % (can_id, len(data), data.hex().upper().encode()) self.queued.append((can_id, data)) self._count(data) return True def take_refused(self): - """Return the frames the carrier refused since the last call, oldest first.""" + """Return the frames refused since the last call, here or by the carrier, oldest first.""" refused, self.refusals = self.refusals, [] return refused @@ -137,7 +157,7 @@ def _start(self): self.queued[:0] = commands # A carrier that reset will never answer the lines written before. self.pending.clear() - self.bell = False + self.bell, self.full_since = False, None self.heard = time.monotonic() self._flush() @@ -152,9 +172,6 @@ def _flush(self): self.outgoing.clear() self.pending.extend(self.queued) self.queued.clear() - if len(self.pending) > MAX_PENDING: - # Start again rather than pin a later answer, such as a refusal, on the wrong line. - self._lost('the carrier stopped answering its lines') def _read(self): if self.serial is None: @@ -190,6 +207,7 @@ def _read(self): def _refused(self): # A frame's BELL comes before the CR of its empty line; a command answers one or the other. + self.full_since = None if self.pending and isinstance(self.pending[0], tuple): self.bell = True return @@ -199,6 +217,7 @@ def _refused(self): self.errors += 1 def _answered(self): + self.full_since = None if not self.pending: return line = self.pending.popleft() @@ -220,7 +239,7 @@ def _lost(self, error): self.outgoing.clear() self.queued.clear() self.pending.clear() - self.bell = False + self.bell, self.full_since = False, None self.incoming.clear() self.replies.clear() self.next_try = time.monotonic() + REOPEN_EVERY_S From bfde465064884069e4edb7150c6de060edf4d303 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:23:03 -0600 Subject: [PATCH 11/11] Fail the four-node vcan step if any case skips This googletest has no --gtest_fail_if_skipped. It took the flag as unknown, printed its help and exited 0 without running a test, so the step passed with nothing run. The step now fails unless the binary reports passed tests and no skips. --- .github/workflows/can_drives.yml | 14 +++++++++----- waybionic_can/CMakeLists.txt | 4 ++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.github/workflows/can_drives.yml b/.github/workflows/can_drives.yml index 81cb6355..354683c6 100644 --- a/.github/workflows/can_drives.yml +++ b/.github/workflows/can_drives.yml @@ -36,9 +36,13 @@ jobs: waybionic-can-drives python3 -m pytest -v -p no:cacheprovider src/waybionic_ground_station/waybionic_teleop/test/test_can_drives.py - # --gtest_fail_if_skipped turns a missing vcan0 into a red job instead of 11 silent skips. + # The binary skips its cases when vcan0 is missing, so a skip, or no passed tests at all, + # fails the job. This googletest has no --gtest_fail_if_skipped: an unknown flag prints + # the help and exits 0 without running anything. - name: Run the four-node vcan integration test - run: > - docker run --rm --network host waybionic-can-drives - /waybionic_ws/build/waybionic_can/test_vcan_four_node - --gtest_fail_if_skipped + run: | + set -o pipefail + docker run --rm --network host waybionic-can-drives \ + /waybionic_ws/build/waybionic_can/test_vcan_four_node | tee four_node.txt + grep -Eq '^\[ PASSED \] [1-9][0-9]* tests?\.' four_node.txt + ! grep -q 'SKIPPED' four_node.txt diff --git a/waybionic_can/CMakeLists.txt b/waybionic_can/CMakeLists.txt index 78f5e4db..1c224ac0 100644 --- a/waybionic_can/CMakeLists.txt +++ b/waybionic_can/CMakeLists.txt @@ -76,8 +76,8 @@ if(BUILD_TESTING) endif() endforeach() - # Skips itself when the vcan interface is missing. The privileged can_drives.yml job - # runs this binary with --gtest_fail_if_skipped so a missing vcan0 cannot pass CI. + # Skips itself when the vcan interface is missing. The can_drives.yml job runs this binary + # with vcan0 and fails if any case skips, so a missing vcan0 cannot pass CI. if(CMAKE_SYSTEM_NAME STREQUAL "Linux") ament_add_gtest(test_vcan_four_node tests/integration/test_vcan_four_node.cpp TIMEOUT 240) if(TARGET test_vcan_four_node)