From a75317cfea1aad53a0ba89dc02ba49d2ccc061cf Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:27:32 -0600 Subject: [PATCH 01/31] Stop CI failing on shutdown races and float timing CI on main and #54 failed on two flaky tests, not on the install changes. - The launch tests send SIGINT, and rclpy Jazzy's signal thread wakes the executor before it shuts the context down. spin can then raise "Unable to convert call argument '0' to Python object" or an invalid context error while rclpy.ok() is still True, so the old guard re-raised and the node exited with code 1. ros_shutdown.is_shutdown_error now waits up to a second for rclpy to finish shutting down before deciding. sim_arm_drives, xbox_teleop, joy_udp_receiver, autoplay, camera_follower and joint_demo share it; autoplay had no guard at all and failed CI the same way. - The stale-drive test sums the tick period onto a monotonic clock near 4e5 s, which overshoots the 0.5 s report period by a rounding error. Its bounds allow 1e-6 s. - actions/checkout moves to v7, which runs on Node 24. --- .github/workflows/can_drives.yml | 2 +- .github/workflows/firmware.yml | 4 +- .github/workflows/ros2_build_test.yml | 8 +-- waybionic_bringup/scripts/camera_follower.py | 17 ++----- waybionic_bringup/scripts/joint_demo.py | 16 ++---- .../test/test_sim_arm_drives_node.py | 50 ++++++++++++++++--- .../waybionic_teleop/autoplay_node.py | 4 ++ .../waybionic_teleop/joy_udp_receiver.py | 10 +--- .../waybionic_teleop/ros_shutdown.py | 36 +++++++++++++ .../waybionic_teleop/sim_arm_drives_node.py | 10 +--- .../waybionic_teleop/xbox_teleop_node.py | 10 +--- 11 files changed, 102 insertions(+), 65 deletions(-) create mode 100644 waybionic_teleop/waybionic_teleop/ros_shutdown.py diff --git a/.github/workflows/can_drives.yml b/.github/workflows/can_drives.yml index 354683c6..e59396ff 100644 --- a/.github/workflows/can_drives.yml +++ b/.github/workflows/can_drives.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Create vcan0 run: | diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index 6e0d2316..b2e001a9 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Compile for the UNO R4 WiFi uses: arduino/compile-sketches@v1 @@ -41,7 +41,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install Arduino CLI uses: arduino/setup-arduino-cli@v2 diff --git a/.github/workflows/ros2_build_test.yml b/.github/workflows/ros2_build_test.yml index 84ebda71..b4c34f3c 100644 --- a/.github/workflows/ros2_build_test.yml +++ b/.github/workflows/ros2_build_test.yml @@ -21,7 +21,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build test @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build test @@ -49,7 +49,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 # No registry cache: a published layer must come from this build, not from :jazzy. - name: Build and Test with Docker Compose @@ -85,7 +85,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build --no-cache test diff --git a/waybionic_bringup/scripts/camera_follower.py b/waybionic_bringup/scripts/camera_follower.py index a8113e3f..4c35c22b 100755 --- a/waybionic_bringup/scripts/camera_follower.py +++ b/waybionic_bringup/scripts/camera_follower.py @@ -5,11 +5,11 @@ from geometry_msgs.msg import TransformStamped import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.time import Time import tf2_ros +from waybionic_teleop.ros_shutdown import is_shutdown_error class CameraFollower(Node): @@ -66,19 +66,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise - except RuntimeError as error: - # A TF subscription can surface this Jazzy binding error if its ROS context is - # already invalidated during SIGINT. Other runtime errors must still fail. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): - raise - except TypeError as error: - # tf2 can no longer read the lookup time once SIGINT has invalidated the context. - if rclpy.ok() or not str(error).startswith('time must have sec and nanosec'): + except (RuntimeError, TypeError) as error: + if not is_shutdown_error(error): raise finally: node.destroy_node() diff --git a/waybionic_bringup/scripts/joint_demo.py b/waybionic_bringup/scripts/joint_demo.py index 9234c90e..fb9cc552 100755 --- a/waybionic_bringup/scripts/joint_demo.py +++ b/waybionic_bringup/scripts/joint_demo.py @@ -6,7 +6,6 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -14,6 +13,7 @@ from sensor_msgs.msg import JointState from std_msgs.msg import String import tf2_ros +from waybionic_teleop.ros_shutdown import is_shutdown_error ANGLE_TOLERANCE = math.radians(0.1) OFFSET_TOLERANCE = 1e-4 @@ -256,18 +256,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise - except RuntimeError as error: - # Jazzy's binding error when a subscription's context is invalidated during SIGINT. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): - raise - except TypeError as error: - # tf2 can no longer read the lookup time once SIGINT has invalidated the context. - if rclpy.ok() or not str(error).startswith('time must have sec and nanosec'): + except (RuntimeError, TypeError) as error: + if not is_shutdown_error(error): raise finally: node.destroy_node() diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index b1139bfb..58533ef2 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -21,7 +21,14 @@ DriveHealthState, DriveHealthThresholds, ) -from waybionic_teleop import joy_udp_receiver, mks_can, sim_arm_drives_node, xbox_teleop_node +from waybionic_teleop import ( + autoplay_node, + joy_udp_receiver, + mks_can, + ros_shutdown, + sim_arm_drives_node, + xbox_teleop_node, +) from waybionic_teleop.gamepad import AXES, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits from waybionic_teleop.sim_arm_drives_node import ( @@ -60,6 +67,7 @@ (joy_udp_receiver, 'JoyUdpReceiver'), (camera_module, 'CameraFollower'), (joint_demo_module, 'JointDemo'), + (autoplay_node, 'Autoplay'), ] @@ -797,7 +805,7 @@ def test_following_error_is_reported_and_clears_on_a_current_pose_command(node, node.on_command(command( node, - velocities={joint: 0.0 for joint in node.map.joints}, + velocities=dict.fromkeys(node.map.joints, 0.0), joint_1=math.radians(6.0))) clock[0] += 0.1 node.report() @@ -859,7 +867,7 @@ def test_stalled_simulated_drive_is_reported_within_detection_window_and_recover clock[0], servo.enabled, servo.target, servo.rpm) assert stalled, states assert stalled[0][1] == DiagnosticStatus.ERROR - assert stalled[0][0] - fault_started <= 2.0 + REPORT_PERIOD_S + assert stalled[0][0] - fault_started <= 2.0 + REPORT_PERIOD_S + 1e-6 assert float(stalled[0][3]['target_encoder_error_deg']) == pytest.approx(3.0, abs=0.01) assert float(stalled[0][3]['reply_age_sec']) <= REPORT_PERIOD_S assert servo.axis == pytest.approx(0.0) @@ -906,7 +914,8 @@ def test_not_responding_simulated_drive_is_stale_within_one_report_period_and_re node.report() row = next(item for item in published[-1].status if item.name == 'drive.base_yaw') values = {value.key: value.value for value in row.values} - assert clock[0] - fault_started <= REPORT_PERIOD_S + # The clock is a float sum of tick periods, which can overshoot by a rounding error. + assert clock[0] - fault_started <= REPORT_PERIOD_S + 1e-6 assert row.level == DiagnosticStatus.STALE assert values['state'] == DriveHealthState.NOT_RESPONDING.value assert 'target_encoder_error_deg' in values and 'reply_age_sec' in values @@ -1123,8 +1132,14 @@ def test_a_cartesian_tilt_into_a_joint_limit_keeps_the_drives_enabled(node, para assert node.commanded['joint_3'] == pytest.approx(node.limits['joint_3'][1], abs=1e-9) +@pytest.fixture +def short_shutdown_grace(monkeypatch): + monkeypatch.setattr(ros_shutdown, 'SHUTDOWN_GRACE_S', 0.05) + + @pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) -def test_shutdown_only_ignores_an_invalid_shutdown_context(module, class_name, monkeypatch): +def test_shutdown_only_ignores_an_invalid_shutdown_context( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() spin = MagicMock(side_effect=RCLError('the given context is not valid')) monkeypatch.setattr(module, class_name, factory) @@ -1146,7 +1161,8 @@ def test_shutdown_only_ignores_an_invalid_shutdown_context(module, class_name, m @pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) -def test_binding_error_only_ignored_after_context_shutdown(module, class_name, monkeypatch): +def test_binding_error_only_ignored_after_context_shutdown( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() error = RuntimeError("Unable to convert call argument '0' to Python object") spin = MagicMock(side_effect=error) @@ -1170,7 +1186,8 @@ def test_binding_error_only_ignored_after_context_shutdown(module, class_name, m @pytest.mark.parametrize('module, class_name', [ (camera_module, 'CameraFollower'), (joint_demo_module, 'JointDemo')]) -def test_tf_time_error_only_ignored_after_context_shutdown(module, class_name, monkeypatch): +def test_tf_time_error_only_ignored_after_context_shutdown( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() error = TypeError('time must have sec and nanosec, or nanoseconds.') spin = MagicMock(side_effect=error) @@ -1190,3 +1207,22 @@ def test_tf_time_error_only_ignored_after_context_shutdown(module, class_name, m module.main() assert spin.call_count == 3 assert factory.return_value.destroy_node.call_count == 3 + + +@pytest.mark.parametrize('error', [ + RCLError('the given context is not valid'), + RuntimeError("Unable to convert call argument '0' to Python object")]) +@pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) +def test_shutdown_error_waits_for_the_signal_thread_to_shut_rclpy_down( + module, class_name, error, monkeypatch): + # rclpy's SIGINT thread wakes spin before it shuts the context down. + factory = MagicMock() + running = iter([True, True, True]) + monkeypatch.setattr(module, class_name, factory) + monkeypatch.setattr(module.rclpy, 'init', MagicMock()) + monkeypatch.setattr(module.rclpy, 'try_shutdown', MagicMock()) + monkeypatch.setattr(module.rclpy, 'spin', MagicMock(side_effect=error)) + monkeypatch.setattr(module.rclpy, 'ok', lambda: next(running, False)) + module.main() + assert next(running, None) is None + assert factory.return_value.destroy_node.call_count == 1 diff --git a/waybionic_teleop/waybionic_teleop/autoplay_node.py b/waybionic_teleop/waybionic_teleop/autoplay_node.py index 752818fe..9a7ac2b6 100644 --- a/waybionic_teleop/waybionic_teleop/autoplay_node.py +++ b/waybionic_teleop/waybionic_teleop/autoplay_node.py @@ -27,6 +27,7 @@ from waybionic_teleop.demo_script import ( DemoPlayer, operator_active, PIVOT, STALE_S, TeleopState) from waybionic_teleop.kinematics import ArmKinematics +from waybionic_teleop.ros_shutdown import is_shutdown_error HOME_TOLERANCE_RAD = 0.01 @@ -207,6 +208,9 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass + except RuntimeError as error: + if not is_shutdown_error(error): + raise finally: node.destroy_node() rclpy.try_shutdown() diff --git a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py index 2f49e9fe..f5f2559b 100644 --- a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py +++ b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py @@ -10,13 +10,13 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from sensor_msgs.msg import Joy, JoyFeedback from waybionic_teleop.gamepad import (AXES, BUTTONS, pack_ping, pack_rumble, PACKET_SIZE, PONG_MAGIC, unpack, unpack_pong) +from waybionic_teleop.ros_shutdown import is_shutdown_error # What a connected packet with centred sticks, released triggers and no buttons unpacks to. NEUTRAL = ([0.0] * len(AXES), [0] * len(BUTTONS)) @@ -240,14 +240,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: node.socket.close() diff --git a/waybionic_teleop/waybionic_teleop/ros_shutdown.py b/waybionic_teleop/waybionic_teleop/ros_shutdown.py new file mode 100644 index 00000000..32a72da6 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/ros_shutdown.py @@ -0,0 +1,36 @@ +"""Tell an error from a node shutting down on SIGINT apart from a real failure.""" + +import time + +import rclpy + +# How long to wait for rclpy to finish shutting the context down. +SHUTDOWN_GRACE_S = 1.0 + +# Errors spin can raise once SIGINT has started invalidating the ROS context. +SHUTDOWN_ERRORS = ( + # SIGINT can shut down the context before spin recreates its wait set. + 'the given context is not valid', + # Jazzy's binding error when a subscription's context is invalidated. + "Unable to convert call argument '0' to Python object", + # tf2 can no longer read a lookup time once the context is invalid. + 'time must have sec and nanosec', +) + + +def is_shutdown_error(error): + """ + Return whether spin raised this error only because ROS is shutting down. + + On SIGINT, rclpy's signal thread wakes every executor before it shuts the contexts + down, so spin can fail while rclpy.ok() is still true. Wait briefly for the shutdown + to land: the same error while ROS keeps running is a real failure. + """ + if not any(text in str(error) for text in SHUTDOWN_ERRORS): + return False + deadline = time.monotonic() + SHUTDOWN_GRACE_S + while rclpy.ok(): + if time.monotonic() >= deadline: + return False + time.sleep(0.01) + return True diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index f2f4a6cb..86c03381 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -25,7 +25,6 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue from rcl_interfaces.msg import SetParametersResult import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -41,6 +40,7 @@ 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.ros_shutdown import is_shutdown_error from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo REPLY_TIMEOUT_S = 0.5 @@ -736,14 +736,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: if node is not None: diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index 1d71cf3c..4caa3727 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -11,7 +11,6 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -22,6 +21,7 @@ from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits +from waybionic_teleop.ros_shutdown import is_shutdown_error from waybionic_teleop.teleop import ArmTeleop, config_from_parameters JAW_SIZE = (0.006, 0.014, 0.03) @@ -341,14 +341,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: node.destroy_node() From 405300e552bfbf7b9cdf8e6f61b123990db261af Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:27:32 -0600 Subject: [PATCH 02/31] Bring up the real arm through the MCP2515 carrier The bench arm runs from the ground station over an Arduino UNO R4 with an MCP2515 module, with directions, gearing and zeroing checked against the physical arm rather than assumed. - Carrier: the MCP2515 transport lives in the WaybionicCan library with a unit test, carrier_bridge_mcp2515 is the sketch for this board, and the R4's native USB hands the port back for uploads. Its 8 MHz crystal caps CAN at 500 kbit/s, so the drives and config run at 500k. scripts/carrier_usb.py finds the board, and macos.sh can flash it and launch the station against the real arm. - Arm profile: an optional YAML (macos.sh reads ~/.waybionic/arm_profile.yaml) lists the drives an arm has fitted and locks the joints no drive moves (on the bench arm, joint_2 and the tool), so RViz matches the arm and teleop never commands them. The elbow and right wrist drives count the opposite way to the URDF on the bench arm, and the stick scales match what the operator expects when facing the arm. Tests follow the new directions. - Drives: a stopped drive holds until its encoder settles before it gets a new F5 target, so firmware V1.0.9 can't run on to a stale one. Each zero is saved with a fingerprint (raw encoder minus zeroed count, plus the zero status), so a restart keeps it unless the drive lost power. Zeroing is refused while joint commands are still arriving, and the drive node can log every CAN frame for bench debugging. - mks_setup read-error reads a drive's signed position error (39h) without moving it. - RViz opens maximized through a small ground_station_rviz wrapper. - Docs cover the carrier wiring, bring-up checklist and operator steps. Validated on the bench arm and with the CI Docker build (1427 tests). Supersedes #54. --- docs/operator_guide.md | 95 ++- scripts/carrier_usb.py | 92 +++ scripts/macos.sh | 75 +- waybionic_bringup/README.md | 7 + .../launch/ground_station.launch.py | 75 +- waybionic_bringup/rviz/waybionic_unified.rviz | 10 +- waybionic_bringup/test/test_launch_options.py | 51 +- waybionic_bringup/test/test_teleop_launch.py | 12 +- waybionic_can/CMakeLists.txt | 3 +- waybionic_can/arduino/README.md | 149 +++- .../arduino/carrier_bridge/carrier_bridge.ino | 26 +- .../carrier_bridge_mcp2515.ino | 90 +++ .../libraries/WaybionicCan/src/WaybionicCan.h | 6 +- .../src/common/Mcp2515CanTransport.cpp | 540 ++++++++++++++ .../src/common/Mcp2515CanTransport.h | 168 +++++ .../src/mcp2515/ArduinoMcp2515Spi.cpp | 92 +++ .../src/mcp2515/ArduinoMcp2515Spi.h | 45 ++ .../WaybionicCan/src/r4/UsbHandBack.cpp | 43 ++ .../WaybionicCan/src/r4/UsbHandBack.h | 17 + .../docs/HARDWARE_BRINGUP_CHECKLIST.md | 2 +- .../tests/unit/test_mcp2515_transport.cpp | 703 ++++++++++++++++++ waybionic_rviz_plugins/CMakeLists.txt | 10 + waybionic_rviz_plugins/README.md | 5 + .../src/ground_station_rviz.cpp | 61 ++ waybionic_teleop/config/arm_drives.yaml | 19 +- waybionic_teleop/config/xbox_teleop.yaml | 9 +- waybionic_teleop/package.xml | 2 + waybionic_teleop/test/conftest.py | 18 +- waybionic_teleop/test/test_arm_profile.py | 71 ++ waybionic_teleop/test/test_can_drives.py | 89 ++- waybionic_teleop/test/test_collision.py | 14 +- waybionic_teleop/test/test_drive_map.py | 5 +- waybionic_teleop/test/test_frame_log.py | 24 + waybionic_teleop/test/test_mks_can.py | 23 + waybionic_teleop/test/test_mks_setup.py | 66 ++ .../test/test_sim_arm_drives_node.py | 532 ++++++++++++- waybionic_teleop/test/test_sim_drives.py | 32 + waybionic_teleop/test/test_slcan_bus.py | 98 ++- waybionic_teleop/test/test_teleop.py | 28 +- waybionic_teleop/test/test_teleop_node.py | 17 +- .../test/test_xbox_teleop_node.py | 25 +- .../waybionic_teleop/arm_profile.py | 97 +++ .../waybionic_teleop/drive_map.py | 8 +- .../waybionic_teleop/frame_log.py | 54 ++ waybionic_teleop/waybionic_teleop/mks_can.py | 45 +- .../waybionic_teleop/mks_setup.py | 30 +- .../waybionic_teleop/sim_arm_drives_node.py | 405 +++++++++- .../waybionic_teleop/sim_drives.py | 54 +- .../waybionic_teleop/slcan_bus.py | 55 +- waybionic_teleop/waybionic_teleop/teleop.py | 22 +- .../waybionic_teleop/xbox_teleop_node.py | 9 +- 51 files changed, 4038 insertions(+), 190 deletions(-) create mode 100644 scripts/carrier_usb.py create mode 100644 waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp create mode 100644 waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h create mode 100644 waybionic_can/tests/unit/test_mcp2515_transport.cpp create mode 100644 waybionic_rviz_plugins/src/ground_station_rviz.cpp create mode 100644 waybionic_teleop/test/test_arm_profile.py create mode 100644 waybionic_teleop/test/test_frame_log.py create mode 100644 waybionic_teleop/waybionic_teleop/arm_profile.py create mode 100644 waybionic_teleop/waybionic_teleop/frame_log.py diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 9f21a7ab..4ff07df0 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -90,10 +90,10 @@ before starting the SDL bridge. | Start (Xbox Menu button, three lines) | Enable or disable; the arm starts disabled | | B | Stop and hold the current pose | | Y | Switch group: base (joints 1-3), upper (joints 2-5), Cartesian (tool tip) or incision | -| Base group: left stick | Base yaw (left/right) and shoulder (up/down) | -| Base group: right stick up/down | Elbow | -| Upper group: left stick | Shoulder (left/right) and elbow (up/down) | -| Upper group: right stick | Wrist roll (left/right) and wrist pitch (up/down) | +| Base group: left stick | Base yaw (left/right; right turns joint 1 positive, counter-clockwise from above) and shoulder (up/down) | +| Base group: right stick up/down | Elbow (up lifts the elbow, joint 3 negative) | +| Upper group: left stick | Shoulder (left/right) and elbow (up/down; up lifts the elbow, joint 3 negative, as in the base group) | +| Upper group: right stick | Wrist roll (left/right; right turns joint 5 positive, counter-clockwise from above at the zero pose) and wrist pitch (up/down; up turns joint 4 negative) | | Cartesian group: left stick | Tool tip left/right and forward/back, in straight lines | | Cartesian group: right stick | Tool roll (left/right) and tool tip up/down | | Cartesian group: LB (hold) | Move along one axis only: the stick direction pushed furthest | @@ -333,7 +333,10 @@ then run these from the repository root. 1. **Flash the carrier** once, and again after carrier firmware changes. Plug in only the carrier, so its port is the only `/dev/cu.usbmodem*`, or set - `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. + `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. This uploads `carrier_bridge_mcp2515`, + for the arm's MCP2515 module; `./scripts/macos.sh flash carrier_bridge` is only for + a carrier using the R4's own CAN with a TJA1051T. The wrong sketch leaves every + drive silent. ```bash brew install arduino-cli @@ -367,6 +370,11 @@ then run these from the repository root. ./scripts/macos.sh run ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger ``` + `arm` saves the zero in `~/.waybionic/drive_zero.yaml`. While the drives stay + powered, the next `arm` keeps it, so the arm needs no zero pose and no service + call: wait for `Every drive kept its zero`, then press Start. After the drives lose + power, zero again. See [Zeroing and stops](#zeroing-and-stops). + 5. **Check each joint** 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 @@ -433,7 +441,7 @@ Then press Start. Real drives take commands through the same gate as the simulat ones. Every drive stops, and the arm must be zeroed again, when: - a drive stops answering, for example because the E-stop cut its power or the - carrier was unplugged; + carrier was unplugged (unless the zero is saved and the drive kept it, as below); - a drive's encoder count jumps further than `max_rpm` allows between two readings, as after a brief power loss; - a drive reports a failed move (as when its stall protection releases the motor) @@ -441,6 +449,36 @@ ones. Every drive stops, and the arm must be zeroed again, when: - a drive stays more than `following_error_counts` from its target for `following_error_ticks` ticks. Both are provisional values in `arm_drives.yaml`. +**A saved zero.** With `drive_zero_state:=` (`./scripts/macos.sh arm` uses +`~/.waybionic/drive_zero.yaml`), each zero is saved to the file once every drive has +reported it. A restart of the station, or a drive that answers again after it went +quiet, keeps the zero of each drive that shows it didn't lose power since. MKS firmware +V1.0.9 reports that in two reads, checked on the bench on all four drives: + +- The zero status (3Bh) says whether the drive was zeroed since power-on. Power-on + clears it, and the host's setup frames don't. +- The raw encoder (35h) counts from power-on, and a zero leaves it alone. So it minus + the zeroed count (31h) stays the same from one zero until the drive loses power. A + zero made elsewhere, such as by `mks_setup`, changes it. + +A drive whose status shows no zero, or whose offset is more than 16 counts from the +saved one, isn't zeroed, and the log says why. A new zero, a failed move and a +following error delete the file. + +A drive that turns more than `following_error_counts` after its stop, for +`following_error_ticks` ticks, also stops every drive, with teleop enabled or not. That +drive gets another stop. The arm keeps its zero, since that drive's encoder still counts +true. + +When the stick reverses a joint, its drive stops and settles (typically 17 ms, at most +about 40 ms on the bench) before it turns back. MKS firmware V1.0.9 keeps a target sent +while the drive is reversing, and now and then one sent mid-stroke, and runs back to it, up +to 12°, at the next stop. So right behind every stop of a running move, including a +Start or B press, the drive also gets a 60 rpm move to where it's to stay. That's the end +of its last move, at most two ticks of travel ahead. The move is sent again every tick +for 0.25 s. On the bench this kept every stop within 0.1° of base travel. See +[F5h on firmware V1.0.9](../waybionic_can/arduino/README.md#f5h-on-firmware-v109). + Once the carrier's E-stop sense is wired, pressing the E-stop also stops every drive at once, and Start is refused until it's released. If the joint commands stop for 0.5 s, every drive stops where it is, and if the host stops, the drives' heartbeat @@ -452,6 +490,49 @@ service waits. A refused stop frame is sent again on every tick, and Start is refused until it has gone out. After any stop, disable teleop and press Start again. +### Powered hand-guiding + +Powered hand-guiding is not enabled yet. A stopped drive holds position; disabling +teleop does not release it or turn a push into a movement command. + +The intended workflow is an explicitly selected Hand Guide mode: a deliberate push +starts bounded assistance, then release and stillness for a provisional two seconds +capture the new holding position. This changes the holding target, not the calibrated +zero. Stop must leave the mode disarmed rather than let another push restart it. + +The existing-hardware approach is being evaluated with passive encoder recordings +before adding assistance. Encoder displacement and position error are not force +measurements: gravity, friction, settling and externally applied pressure can all +affect them. Initial base-pressure recordings showed a small, direction-dependent +response that did not consistently separate from untouched encoder jitter. + +The drive's `0.00err` display is motor-shaft angular error, not by itself a fault code. +CAN command `39h` reads signed 32-bit position error: 51200 units per motor turn +(not the encoder's 16384 counts per turn). To read it without changing motor settings, +first stop the ground station so only one process owns the carrier, then run: + +```bash +./scripts/macos.sh drives read-error 3 +``` + +This reads the elbow (CAN ID 3). It reports motor degrees, not joint degrees or force; +the display and CAN readback should be compared before using the signal for hand-guiding. +Motor-generated tracking error must not be mistaken for continued hand pressure. + +An elbow press-hold-release recording received all 1424 requested `39h` replies. +Using the manual's scale, it captured brief excursions of +1.73 and -4.25 motor +degrees, with near-zero error between them and after release. The operator also +observed `Err` returning toward zero while still pressing. Thus zero error does not +prove pressure was released, and an opposite-sign transient must not automatically +trigger assistance in the opposite direction. These observations do not validate an +active hand-guiding controller. + +For the configured MKS `SR_vFOC` mode, the V1.0.9 manual describes `Ma` as the maximum +operating current, and its configuration readback is not measured load current. +`Hold Ma` does not apply in vFOC mode (manual sections 3.2-3.4 and 5.1.10). +Reducing current or changing drive PID gains is not a validated hand-guiding shortcut, +particularly for joints supporting the arm's weight. + ### Engineering monitor With `teleop:=true`, the diagnostics panel shows live rows: @@ -464,7 +545,7 @@ With `teleop:=true`, the diagnostics panel shows live rows: | `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.*` | Each drive's reply state and encoder, and its health: `OK`, `FOLLOWING_ERROR`, `STALLED`, `NOT_RESPONDING` or `DISABLED`, with its following error and reply age | -| `arm.*` | Each joint against its target, and whether the arm is zeroed | +| `arm.*` | Each joint against its target, and whether the arm is zeroed or its saved zero is being checked | To try each drive fault in simulation, see [recording drive health sessions](../waybionic_rviz_plugins/README.md#task-7-record-simulated-arm-drive-health-sessions) diff --git a/scripts/carrier_usb.py b/scripts/carrier_usb.py new file mode 100644 index 00000000..c0e63f1a --- /dev/null +++ b/scripts/carrier_usb.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +""" +Find the carrier (Arduino UNO R4) on USB and get it ready for an upload. + +On the UNO R4 WiFi the carrier firmware moves the USB-C port from the ESP32-S3 bridge to the +RA4M1's own USB (waybionic_can/arduino/README.md, "USB link"), but uploads still go through +the bridge. This hands the port back when needed and prints the port to upload to: + + python scripts/carrier_usb.py upload-port [--port PORT] +""" + +import argparse +import sys +import time + +from serial import Serial +from serial.tools import list_ports + +ARDUINO_VID = 0x2341 +WIFI_BRIDGE_PID = 0x1002 +WIFI_NATIVE_PID = 0x006D +MINIMA_PID = 0x0069 +BOARD_PIDS = { + WIFI_BRIDGE_PID: 'UNO R4 WiFi (USB bridge)', + WIFI_NATIVE_PID: 'UNO R4 WiFi (carrier firmware)', + MINIMA_PID: 'UNO R4 Minima', +} +# The carrier hands the port back when it sees this baud rate with DTR still high +# (UsbHandBack.h); about half a second on the bench. +HAND_BACK_BAUD = 1200 +HAND_BACK_TIMEOUT_S = 10.0 + + +def boards(): + return [port for port in list_ports.comports() + if port.vid == ARDUINO_VID and port.pid in BOARD_PIDS] + + +def describe(ports): + return ', '.join(f'{port.device} [{BOARD_PIDS[port.pid]}]' for port in ports) or 'none' + + +def only_board(device=None): + found = boards() + if device: + found = [port for port in found if port.device == device] + if len(found) != 1: + wanted = f' at {device}' if device else '' + sys.exit(f'error: expected one UNO R4{wanted}; found {describe(boards())}') + return found[0] + + +def hand_back(device): + """Ask the carrier firmware at device to give the USB port back to the bridge.""" + link = Serial() + link.port = device + link.baudrate = HAND_BACK_BAUD + link.dtr = True + link.open() + try: + deadline = time.monotonic() + HAND_BACK_TIMEOUT_S + while time.monotonic() < deadline: + bridges = [port for port in boards() if port.pid == WIFI_BRIDGE_PID] + if bridges: + return bridges[0].device + time.sleep(0.05) + finally: + try: + link.close() + except OSError: + pass + sys.exit(f'error: the carrier at {device} did not hand USB back to its bridge within ' + f'{HAND_BACK_TIMEOUT_S:.0f} s; unplug it, plug it back in and try again') + + +def upload_port(device=None): + board = only_board(device) + if board.pid == WIFI_NATIVE_PID: + return hand_back(board.device) + return board.device + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('command', choices=['upload-port']) + parser.add_argument('--port', help='the board to use when several are plugged in') + args = parser.parse_args() + print(upload_port(args.port)) + + +if __name__ == '__main__': + main() diff --git a/scripts/macos.sh b/scripts/macos.sh index 81ecb53b..9ef21c7e 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -20,12 +20,18 @@ 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) + flash Compile and upload the carrier firmware to the UNO R4 WiFi (needs arduino-cli): + carrier_bridge_mcp2515 (default, the arm's MCP2515 module) or carrier_bridge + (the R4's own CAN with a TJA1051T transceiver) 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. +arm uses the arm profile at ~/.waybionic/arm_profile.yaml when it exists (its fitted drives +and locked joints); set WAYBIONIC_ARM_PROFILE to use another file. arm saves each zero in +~/.waybionic/drive_zero.yaml and keeps it on the next start while the drives stay powered; +set WAYBIONIC_DRIVE_ZERO to use another file. EOF } @@ -72,12 +78,45 @@ select_manager() { prepare() { check_host select_manager + SYSROOT_FROM_USER=true if [[ -z "${CONDA_BUILD_SYSROOT:-}" ]]; then CONDA_BUILD_SYSROOT="$(xcrun --show-sdk-path)" + SYSROOT_FROM_USER=false export CONDA_BUILD_SYSROOT fi } +sdk_links() { + # shellcheck disable=SC2016 + run_environment bash -c 'out="$(mktemp)" + printf "int main(void) { return 0; }\n" \ + | CONDA_BUILD_SYSROOT="$1" "${CC:-clang}" -x c - -isysroot "$1" -o "$out" \ + >/dev/null 2>&1 + status=$? + rm -f "$out" + exit "$status"' _ "$1" &2 + CONDA_BUILD_SYSROOT="$sdk" + export CONDA_BUILD_SYSROOT + return + fi + done < <(find /Library/Developer/CommandLineTools/SDKs -maxdepth 1 -name 'MacOSX*.sdk' \ + 2>/dev/null | sort -rV) + echo "warning: no macOS SDK links with the environment's compiler; set" \ + "CONDA_BUILD_SYSROOT to one that does" >&2 +} + setup_environment() { if [[ "$ENV_EXISTS" == true ]]; then echo "Updating $ENV_NAME with $MANAGER..." @@ -109,6 +148,7 @@ run_environment() { build_workspace() { ensure_environment + select_sysroot echo "Building workspace..." ( cd "$ROOT" @@ -157,20 +197,25 @@ find_carrier() { } flash_carrier() { + local name="${1:-carrier_bridge_mcp2515}" local fqbn="arduino:renesas_uno:unor4wifi" - local sketch="$ROOT/waybionic_can/arduino/carrier_bridge" + local sketch="$ROOT/waybionic_can/arduino/$name" local library="$ROOT/waybionic_can/arduino/libraries/WaybionicCan" + local port - [[ -f "$sketch/carrier_bridge.ino" ]] \ - || fail "carrier_bridge is not in this checkout yet: it comes with PR #40 (waybionic_can)" + [[ "$name" == carrier_bridge* && -f "$sketch/$name.ino" ]] \ + || fail "unknown carrier sketch $name: use carrier_bridge or carrier_bridge_mcp2515" command -v arduino-cli >/dev/null 2>&1 \ || fail "install arduino-cli first: brew install arduino-cli" - find_carrier + ensure_environment 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" + # Running carrier firmware has the board's own USB port; uploads go through the WiFi bridge. + port="$(run_environment python "$ROOT/scripts/carrier_usb.py" upload-port \ + ${WAYBIONIC_CARRIER:+--port "$WAYBIONIC_CARRIER"})" + arduino-cli upload --fqbn "$fqbn" --port "$port" "$sketch" + echo "Flashed $name" } command_name="${1:-help}" @@ -199,8 +244,8 @@ case "$command_name" in ros2 launch waybionic_bringup ground_station.launch.py "$@" ;; flash) - check_host - flash_carrier + prepare + flash_carrier "$@" ;; drives) [[ $# -gt 0 ]] || fail "drives needs an mks_setup command, such as scan" @@ -212,9 +257,19 @@ case "$command_name" in prepare find_carrier echo "Carrier: $CARRIER" + profile="${WAYBIONIC_ARM_PROFILE:-$HOME/.waybionic/arm_profile.yaml}" + if [[ -f "$profile" ]]; then + echo "Arm profile: $profile" + elif [[ -n "${WAYBIONIC_ARM_PROFILE:-}" ]]; then + fail "arm profile not found: $profile" + else + profile="" + fi + zero_state="${WAYBIONIC_DRIVE_ZERO:-$HOME/.waybionic/drive_zero.yaml}" 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" "$@" + joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" \ + arm_profile:="$profile" drive_zero_state:="$zero_state" "$@" ;; run) [[ $# -gt 0 ]] || fail "run requires a command" diff --git a/waybionic_bringup/README.md b/waybionic_bringup/README.md index 6fe2bf8c..35f19095 100644 --- a/waybionic_bringup/README.md +++ b/waybionic_bringup/README.md @@ -8,10 +8,16 @@ ros2 launch waybionic_bringup ground_station.launch.py The default starts the new five-joint arm, joint-state GUI, camera follower, and RViz using `waybionic_unified.rviz` with its internal mock diagnostics panel. +RViz starts maximized to the current screen, keeping diagnostics, menus and +controls visible. Use `rviz_maximized:=false` to use the layout's saved window +size instead (1280 x 800 for the bundled layout). +RViz's separate F11 fullscreen mode hides panels and controls; it is not used +for ground station startup. | Argument | Default | Purpose | | --- | --- | --- | | `launch_rviz` | `true` | Start RViz. | +| `rviz_maximized` | `true` | Fill the current screen without hiding panels; false uses the layout's window geometry. Unused when RViz is disabled. | | `use_joint_state_publisher_gui` | `true` | Start the separate joint-state GUI. | | `use_diagnostics` | `true` | Enable the RViz diagnostics panel and permit the demo publisher. | | `use_mock_diagnostics` | `true` | Select internal mock data rather than live topics in the panel; demo mode, teleop and the camera always use live topics. | @@ -21,6 +27,7 @@ RViz using `waybionic_unified.rviz` with its internal mock diagnostics panel. | `teleop` | `false` | Drive the arm with a controller through simulated or real CAN drives. | | `drive_interface` | `sim` | Drive bus: `sim`, or a python-can interface such as `socketcan` or `slcan` for the real MKS drives. | | `drive_channel` | empty | CAN channel for a real drive bus, such as `can0` or `/dev/ttyACM0`. | +| `arm_profile` | empty | YAML file listing this arm's fitted drives and the angles of joints locked without one (`waybionic_teleop/arm_profile.py`); empty means every drive is fitted. | | `joy_source` | `device` | Controller input: local device, UDP host bridge, or none. | | `autoplay` | `false` | Play a scripted demo whenever the controller is left idle. | | `joy_udp_bind` | `127.0.0.1` | UDP receiver bind address; use `0.0.0.0` inside Docker. | diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index dfb8c58f..10134382 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -25,6 +25,7 @@ BOOLEAN_CHOICES = ['true', 'false', 'True', 'False', '1', '0'] BOOLEAN_OPTIONS = { 'launch_rviz': 'true', + 'rviz_maximized': 'true', 'use_joint_state_publisher_gui': 'true', 'use_diagnostics': 'true', 'use_mock_diagnostics': 'true', @@ -124,6 +125,28 @@ def check_files_exist(context, *args, **kwargs): return actions +def _launch_rviz(context): + maximized = IfCondition(LaunchConfiguration('rviz_maximized')).evaluate(context) + # Demo mode, teleop and the camera report on live topics. + live_diagnostics = OrSubstitution( + OrSubstitution(LaunchConfiguration('demo_mode'), LaunchConfiguration('teleop')), + LaunchConfiguration('camera')) + return [Node( + package='waybionic_rviz_plugins' if maximized else 'rviz2', + executable='ground_station_rviz' if maximized else 'rviz2', + name='rviz2', output='screen', + arguments=['-d', LaunchConfiguration('effective_rvizconfig')], + condition=IfCondition(LaunchConfiguration('launch_rviz')), + parameters=[ + {'use_sim_time': LaunchConfiguration('use_sim_time')}, + {'use_mock_diagnostics': AndSubstitution( + LaunchConfiguration('use_mock_diagnostics'), + NotSubstitution(live_diagnostics))}, + {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} + ] + )] + + def generate_launch_description(): waybionic_desc_dir = get_package_share_directory('waybionic_description') waybionic_bringup_dir = get_package_share_directory('waybionic_bringup') @@ -180,6 +203,23 @@ def generate_launch_description(): description='The carrier serial port or CAN channel, such as /dev/cu.usbmodem1101, ' '/dev/ttyACM0 or can0') + drive_frame_log_arg = DeclareLaunchArgument( + 'drive_frame_log', default_value='', + description='File to append every drive frame sent, received or refused to, with its ' + 'host time (waybionic_teleop/frame_log.py); empty records nothing') + + drive_zero_state_arg = DeclareLaunchArgument( + 'drive_zero_state', default_value='', + description='File to save the drive zero in, so a restart keeps it while the drives ' + 'stay powered (SimArmDrives.check_zero); empty saves nothing') + + arm_profile_arg = DeclareLaunchArgument( + 'arm_profile', default_value='', + description="YAML file with this arm's fitted drives and locked joints " + '(waybionic_teleop/arm_profile.py); empty for every drive fitted') + arm_profile = {'arm_profile': ParameterValue(LaunchConfiguration('arm_profile'), + value_type=str)} + joy_source_arg = DeclareLaunchArgument( 'joy_source', default_value='device', description='Controller input: device (local joystick), udp (host bridge) or none') @@ -221,6 +261,10 @@ def generate_launch_description(): 'launch_rviz', default_value='true', choices=BOOLEAN_CHOICES, description='Launch RViz (set false for headless validation)') + rviz_maximized_arg = DeclareLaunchArgument( + 'rviz_maximized', default_value='true', choices=BOOLEAN_CHOICES, + description='Fill the screen with RViz while keeping its panels and controls visible') + rviz_config_arg = DeclareLaunchArgument( 'rvizconfig', default_value=default_rviz_config_path, description='Absolute path to rviz config file') @@ -285,7 +329,7 @@ def generate_launch_description(): package='waybionic_teleop', executable='xbox_teleop', name='xbox_teleop', output='screen', condition=IfCondition(teleop), parameters=[os.path.join(teleop_config_dir, 'xbox_teleop.yaml'), diagnostics_topic, - sim_time] + arm_profile, sim_time] ) drives_node = Node( @@ -295,8 +339,12 @@ def generate_launch_description(): {'interface': ParameterValue(LaunchConfiguration('drive_interface'), value_type=str), 'channel': ParameterValue(LaunchConfiguration('drive_channel'), - value_type=str)}, - sim_time] + value_type=str), + 'frame_log': ParameterValue(LaunchConfiguration('drive_frame_log'), + value_type=str), + 'zero_state': ParameterValue(LaunchConfiguration('drive_zero_state'), + value_type=str)}, + arm_profile, sim_time] ) # RViz orbits view_focus, so the follower also runs for the fixed view. @@ -346,27 +394,18 @@ def generate_launch_description(): }.items() ) - # Demo mode, teleop and the camera report on /diagnostics, so the panel listens to them. - rviz_node = Node( - package='rviz2', executable='rviz2', name='rviz2', output='screen', - arguments=['-d', LaunchConfiguration('effective_rvizconfig')], - condition=IfCondition(LaunchConfiguration('launch_rviz')), - parameters=[ - {'use_sim_time': LaunchConfiguration('use_sim_time')}, - {'use_mock_diagnostics': AndSubstitution( - LaunchConfiguration('use_mock_diagnostics'), - NotSubstitution(OrSubstitution(simulated_joints, camera)))}, - {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} - ] - ) + rviz_node = OpaqueFunction(function=_launch_rviz) return LaunchDescription([ model_arg, use_mock_diag_arg, diag_topic_arg, start_temp_pub_arg, use_jsp_gui_arg, use_diagnostics_arg, demo_mode_arg, demo_speed_arg, teleop_arg, - drive_interface_arg, drive_channel_arg, joy_source_arg, autoplay_arg, + drive_interface_arg, drive_channel_arg, drive_frame_log_arg, drive_zero_state_arg, + arm_profile_arg, + joy_source_arg, autoplay_arg, joy_udp_bind_arg, joy_udp_port_arg, follow_camera_arg, use_sim_time_arg, camera_arg, camera_bind_arg, camera_log_arg, - launch_rviz_arg, rviz_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node, + launch_rviz_arg, rviz_maximized_arg, rviz_config_arg, file_check, + rsp_node, jsp_gui_node, joint_demo_node, joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, camera_follower_node, temp_diag_pub_node, camera_launch, rviz_node ]) diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz index 47796106..5b59a973 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -210,10 +210,10 @@ Window Geometry: collapsed: false Displays: collapsed: false - Height: 2055 + Height: 800 Hide Left Dock: false Hide Right Dock: false - QMainWindow State: 000000ff00000000fd0000000400000000000001a400000774fc020000000bfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003b000000c7000000c700fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000108000002330000023400fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000341000002340000023400fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c010000057b000002340000023400ffffff000000010000010f00000774fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003b00000774000000a000fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000002ea00000037fc0100000002fb0000000800540069006d00650100000000000002ea0000025300fffffffb0000000800540069006d006501000000000000045000000000000000000000002b0000077500000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002d9fc0200000001fc00000014000002d90000003a01000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000001600fffffffb0000000a005600690065007700730100000000ffffffff0000001600fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000001600fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000001600ffffff00000001000001b8000002d9fc0200000001fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000014000002d90000001600ffffff00000003000005000000002dfc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002d900000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: @@ -222,6 +222,6 @@ Window Geometry: collapsed: false Views: collapsed: false - Width: 746 - X: 57 - Y: 4 + Width: 1280 + X: 0 + Y: 0 diff --git a/waybionic_bringup/test/test_launch_options.py b/waybionic_bringup/test/test_launch_options.py index df2263f4..8802457a 100644 --- a/waybionic_bringup/test/test_launch_options.py +++ b/waybionic_bringup/test/test_launch_options.py @@ -2,9 +2,11 @@ import importlib.util from pathlib import Path +from unittest.mock import patch from launch import LaunchContext from launch.actions import DeclareLaunchArgument, RegisterEventHandler +from launch.conditions import IfCondition from launch.events import Shutdown from launch_ros.actions import Node import pytest @@ -63,7 +65,7 @@ def test_carried_over_options_and_arm_default(): for name in ( 'demo_mode', 'demo_speed', 'teleop', 'joy_source', 'joy_udp_bind', 'joy_udp_port', 'follow_camera', 'use_diagnostics', 'drive_interface', - 'drive_channel', 'autoplay', 'camera', 'camera_bind', 'camera_log', + 'drive_channel', 'arm_profile', 'autoplay', 'camera', 'camera_bind', 'camera_log', ): assert name in args assert args['model'].default_value[0].text.endswith('waybionic_arm.urdf') @@ -76,10 +78,55 @@ def test_headless_ignores_unused_rviz_file(context): }) MODULE.check_files_exist(context) assert context.launch_configurations['effective_rvizconfig'] == '/missing/layout.rviz' - assert not node('rviz2').condition.evaluate(context) + assert not MODULE._launch_rviz(context)[0].condition.evaluate(context) assert not node('joint_state_publisher_gui').condition.evaluate(context) +@pytest.mark.parametrize('value', MODULE.BOOLEAN_CHOICES) +def test_rviz_maximized_argument(context, value): + context.launch_configurations['rviz_maximized'] = value + MODULE.check_files_exist(context) + with patch.object(MODULE, 'Node') as constructor: + MODULE._launch_rviz(context) + options = constructor.call_args.kwargs + maximized = value in ('true', 'True', '1') + assert options['package'] == ('waybionic_rviz_plugins' if maximized else 'rviz2') + assert options['executable'] == ('ground_station_rviz' if maximized else 'rviz2') + arguments = options['arguments'] + assert arguments[0] == '-d' + assert arguments[1].perform(context) == ( + context.launch_configurations['effective_rvizconfig']) + assert len(arguments) == 2 + + +def test_rviz_defaults_to_maximized(): + assert declarations()['rviz_maximized'].default_value[0].text == 'true' + + +@pytest.mark.parametrize('mock', ['true', 'false']) +@pytest.mark.parametrize('mode', [None, 'demo_mode', 'teleop', 'camera']) +def test_rviz_keeps_live_diagnostics_selection(context, mock, mode): + context.launch_configurations['use_mock_diagnostics'] = mock + if mode: + context.launch_configurations[mode] = 'true' + with patch.object(MODULE, 'Node') as constructor: + MODULE._launch_rviz(context) + parameters = constructor.call_args.kwargs['parameters'] + use_mock = parameters[1]['use_mock_diagnostics'] + assert IfCondition(use_mock).evaluate(context) == (mock == 'true' and mode is None) + + +def test_default_window_geometry(): + config = yaml.safe_load((ROOT / 'rviz/waybionic_unified.rviz').read_text()) + geometry = config['Window Geometry'] + assert (geometry['Width'], geometry['Height']) == (1280, 800) + state = bytes.fromhex(geometry['QMainWindow State']) + for panel in config['Panels']: + assert state.count(panel['Name'].encode('utf-16-be')) == 1 + assert sum(panel['Class'] == 'waybionic_rviz_plugins/DiagnosticsPanel' + for panel in config['Panels']) == 1 + + @pytest.mark.parametrize('argument', ['model', 'rvizconfig']) def test_missing_required_file(context, argument): context.launch_configurations[argument] = '/missing/file' diff --git a/waybionic_bringup/test/test_teleop_launch.py b/waybionic_bringup/test/test_teleop_launch.py index b623676c..36c5458b 100644 --- a/waybionic_bringup/test/test_teleop_launch.py +++ b/waybionic_bringup/test/test_teleop_launch.py @@ -82,21 +82,23 @@ def hold(seconds, *pressed, **axes): 'teleop never received the controller packets') self.assertEqual(diagnostics['arm.command_gate'].level, DiagnosticStatus.WARN, 'the drives never loaded the robot description') - hold(1.0, left_x=1.0) + # Joy axes are positive left and up: left stick right turns joint_1 positive. + hold(1.0, left_x=-1.0) self.assertAlmostEqual(joints['joint_1'], 0.0, places=3, msg='moved while disabled') hold(0.2, 'start') - hold(1.0, left_x=1.0) + hold(1.0, left_x=-1.0) self.assertGreater(joints['joint_1'], 0.2) hold(0.3, 'y') yaw = joints['joint_1'] - hold(1.0, left_x=1.0, right_y=1.0) + # In the upper group, right stick down tips the wrist down (joint_4 positive). + hold(1.0, left_x=1.0, right_y=-1.0) self.assertAlmostEqual(joints['joint_1'], yaw, places=2) self.assertGreater(joints['joint_4'], 0.2) hold(0.8, right_trigger=-1.0) self.assertGreater(joints['tool_grip'], 0.3) hold(0.2, 'b') pitch = joints['joint_4'] - hold(0.75, right_y=1.0) + hold(0.75, right_y=-1.0) self.assertAlmostEqual(joints['joint_4'], pitch, places=2, msg='moved after B') self.assertEqual(diagnostics['teleop.state'].values[0].value, 'disabled') for drive in ('base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right', 'tool'): @@ -105,7 +107,7 @@ def hold(seconds, *pressed, **axes): stop = mks_can.hex_frame(can_id, mks_can.absolute_axis(can_id, 0, 0, 0)) self.assertEqual(values['last_command'], stop, f'{drive} did not stop') hold(0.2, 'start') - hold(0.9, right_y=1.0) + hold(0.9, right_y=-1.0) self.assertGreater(joints['joint_4'], pitch + 0.05, 'Start did not re-arm') self.assertEqual(diagnostics['teleop.state'].values[0].value, 'enabled') self.assertEqual(diagnostics['can.bus'].level, b'\x00') diff --git a/waybionic_can/CMakeLists.txt b/waybionic_can/CMakeLists.txt index 1c224ac0..f29e37de 100644 --- a/waybionic_can/CMakeLists.txt +++ b/waybionic_can/CMakeLists.txt @@ -15,6 +15,7 @@ set(COMMON_SOURCES ${ARDUINO_LIB_SRC}/common/BusLoad.cpp ${ARDUINO_LIB_SRC}/common/Candump.cpp ${ARDUINO_LIB_SRC}/common/GatewayLogic.cpp + ${ARDUINO_LIB_SRC}/common/Mcp2515CanTransport.cpp ${ARDUINO_LIB_SRC}/common/MksFrame.cpp ${ARDUINO_LIB_SRC}/common/NodeLogic.cpp ${ARDUINO_LIB_SRC}/common/SlcanBridge.cpp @@ -68,7 +69,7 @@ if(BUILD_TESTING) set(UNIT_TESTS test_mks_frame test_node_logic test_gateway_logic test_bringup_console test_slcan_bridge - test_bus_load) + test_bus_load test_mcp2515_transport) foreach(test_name ${UNIT_TESTS}) ament_add_gtest(${test_name} tests/unit/${test_name}.cpp) if(TARGET ${test_name}) diff --git a/waybionic_can/arduino/README.md b/waybionic_can/arduino/README.md index e2a6f28b..62a9bb45 100644 --- a/waybionic_can/arduino/README.md +++ b/waybionic_can/arduino/README.md @@ -1,11 +1,16 @@ -# CAN bench firmware (UNO R4 + TJA1051T + MKS SERVO42D/57D) +# CAN bench firmware (UNO R4 + MKS SERVO42D/57D) This folder holds the Arduino firmware for bringing up the arm's MKS drives on a real classic CAN bus. The shared MKS subset is ported from `waybionic_teleop/mks_can.py` (merged through PR #28) and checked against it byte for byte. The host build in `../CMakeLists.txt` compiles and unit-tests the same library files. -For the supervised session with all five arm drives, use the +There are **two different carrier topologies**: the R4's built-in CAN controller with a +TJA1051T transceiver, and the arm's external [MCP2515 SPI module](#mcp2515-carrier). +Select the matching sketch before flashing; identical host protocols do not make the +hardware interchangeable. + +For a supervised built-in-CAN session with all five arm drives, use the [five-drive hardware checklist](../docs/HARDWARE_BRINGUP_CHECKLIST.md). | Sketch | Board role | Moves anything? | @@ -14,7 +19,8 @@ For the supervised session with all five arm drives, use the | `four_node_bench/gateway/` | Arduino 1 of the four-node bench: the laptop types commands, the board puts them on the bus and tracks which receiver answered | Only when typed | | `four_node_bench/receiver/` | Arduinos 2-4: answer MKS frames like a drive, with a software-only actuator | No (software only) | | `carrier_bridge/` | Laptop USB serial ↔ CAN bridge speaking a subset of SLCAN, so python-can can use it | Forwards whatever the host sends | -| `libraries/WaybionicCan/` | Shared code: MKS framing, receiver/gateway logic, console, SLCAN, UNO R4 CAN transport | - | +| `carrier_bridge_mcp2515/` | Same host protocol, using the external MCP2515 SPI module rather than the R4's built-in CAN controller | Forwards whatever the host sends | +| `libraries/WaybionicCan/` | Shared code: MKS framing, receiver/gateway logic, console, SLCAN, built-in and MCP2515 CAN transports | - | ## Safety rules (read before powering a drive) @@ -30,12 +36,13 @@ For the supervised session with all five arm drives, use the -0x800000..0x7FFFFF, 0-3000 rpm, acc 0-255). They are constants in the sketch (`benchPolicy()` / `MotionPolicy`). Change them only with the leads, then re-upload. - The human-readable bench sketches stay at the drive's factory **500 kbit/s**. The real-arm - host and `carrier_bridge` select **1 Mbit/s CAN** after each drive is configured. + built-in-CAN configuration targets **1 Mbit/s CAN** after each drive is configured. + The MCP2515 arm configuration stays at **500 kbit/s**. - `estop ` sends the manual's F7h immediate emergency-stop command. It is a software command and does not replace the physical E-stop. Drive-ID (8Bh) and bitrate (8Ah) are not implemented in the merged `mks_can.py` or this shared library. -## Hardware topology +## Built-in CAN hardware topology ```text laptop (USB serial: 1000000 baud for carrier_bridge, 115200 for the consoles) @@ -50,12 +57,90 @@ UNO R4 WiFi -- CAN TX = D10 --> TJA1051T TXD 24 V supply, current limited ``` -- **The UNO R4 has a CAN controller built in.** The TJA1051T is only a **transceiver**: it turns the controller's TX/RX logic signals into the differential CAN_H/CAN_L pair. No MCP2515 is used. +- **The UNO R4 has a CAN controller built in.** The TJA1051T is only a **transceiver**: it turns the controller's TX/RX logic signals into the differential CAN_H/CAN_L pair. No MCP2515 is used in this variant. - **Pins:** on the **UNO R4 WiFi**, CAN TX = **D10** and CAN RX = **D13**, as in the official core (`variants/UNOWIFIR4/pins_arduino.h`: `PIN_CAN0_TX 10`, `PIN_CAN0_RX 13`). The **UNO R4 Minima** uses different pins, D4 (TX) and D5 (RX), per `variants/MINIMA/pins_arduino.h`. The sketches use the core's `CAN` object, so they pick the right pins for whichever board you compile for, and they print those pins at boot. - **Termination:** one 120 Ω resistor across CAN_H/CAN_L at **each of the two physical ends** of the bus, and nowhere else. With power off, CAN_H to CAN_L should measure about 60 Ω. - **Bus wiring:** CAN_H to CAN_H and CAN_L to CAN_L on every node. - **Not yet specified by Electrical (TBD, ask Yassin):** how the TJA1051T module is powered, how its mode pin is strapped (it must be in normal mode, not silent), the ground reference between the Arduino, the transceiver and the drive, and the connector pinout on the drive side. This README doesn't guess at them. +## MCP2515 carrier + +The arm's carrier uses `carrier_bridge_mcp2515`: UNO R4 WiFi hardware SPI on D11 +(MOSI), D12 (MISO), D13 (SCK), with CS on D10 and INT on D2. The configured module +oscillator is 8 MHz and CAN runs at 500 kbit/s. D13 is **SPI clock in this topology**, +not a transceiver RXD pin. A pin-level diagnosis for the built-in-CAN topology does +not apply to this carrier. + +`scripts/macos.sh flash` selects this sketch by default. The built-in-CAN sketch +requires `scripts/macos.sh flash carrier_bridge`. Neither operation should be +used as a diagnostic probe without confirming the connected hardware and a safe bench state. + +The MCP2515 receive configuration uses **RXM=00 and explicitly zeroed acceptance +masks/filters**, retaining all standard IDs/data bytes while requiring valid CAN messages. +Do not use RXM=11 as a shortcut for accepting all IDs: according to the +[MCP2515 datasheet, sections 4.1.3 and 4.2.2, page 23](https://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Stand-Alone-CAN-Controller-with-SPI-20001801J.pdf#page=23), +that debug mode also delivers partially assembled messages when CAN errors occur. +The MKS eight-bit checksum can accidentally accept corrupted data; it does not +replace the controller's CAN validation. +All filters use EXIDE=0, so reception is limited to standard frames. Software also +defensively rejects extended and remote frames if they reach the receive buffers. + +RXnIF locks each receive buffer until the firmware clears it **after** copying the +frame. Slow, separate register reads can contribute to overflow of the other +buffer, but do not by themselves cause a pending frame to be overwritten mid-read. +The existing bench-tested SPI read conditioning is retained. Controller errors +remain counted; no encoder-jump or motion-stop checks are relaxed. + +The previous RXM=11 setting is a confirmed software defect. It is not proof that +every historical corrupt host-log entry originated there: those logs contain +neither the CAN wire traffic nor the SPI transactions. A host fault message alone +does not establish a wiring or transceiver fault. + +### Stationary validation of valid-only reception + +The corrected sketch was uploaded to the UNO R4 WiFi and checked on 2026-10-31, +with the arm supported and the operator present. The five-minute check sent only +31h encoder requests to drives 1, 3, 4 and 5 at 500 kbit/s; it sent no enable, zero, +stop or position commands. + +- **143,985 requests and matching replies**, approximately 119.99 Hz per drive. +- Per-drive p95 host-queue-to-next-matching-reply time: **3.96-4.37 ms**. +- No bad MKS checksums; the largest successive count change was **one count**. +- No new host errors, refusals, reopen events, or carrier-counter increases during + the measurement. A separate audit of the raw serial records confirmed the + encoder-only command whitelist and reply totals. + +Carrier counters are cumulative across serial sessions. The refused-line count +increased between sessions from 0 to 1 to 2, before any encoder requests in those +new sessions, and stayed at 2 throughout the five-minute measurement. The initial +absolute-counter check stopped before polling, and the later measurement explicitly +recorded its baseline rather than resetting the counter. The subsequent +[serial-close check](#serial-close-acknowledgement) isolated a host lifecycle issue, +not evidence of a CAN wiring fault. + +E-stop and supply-voltage telemetry reported **unknown**, not healthy or faulty. +The operator's physical power cutoff, not those unavailable telemetry inputs, was +the safeguard for this stationary check. + +This validates stationary request/reply traffic only. It does **not** establish +calibration accuracy, motion safety, or the source of every historical corrupt +frame. Comparable motion-traffic testing and, if corruption recurs, independent +CAN/SPI capture remain necessary before declaring that failure resolved. + +### Serial-close acknowledgement + +A control-only bench comparison reproduced a refused-line increment when USB was +closed immediately after writing SLCAN `C`. The tested in-band close/open, +flush-before-close and acknowledged-close cycles did not increment it. The host +now waits up to 250 ms for the carrier's close acknowledgement before releasing +USB, rather than treating `write()` as proof that the final line was received. +Timeouts, refusals and disconnects are reported; the port is still released. + +With the corrected host, **30 USB close/reopen cycles and 120 encoder requests** +completed with matching replies and no counter increase. Close acknowledgements +took at most **2.90 ms** in that run. This change does not alter the drive node's +stop/hold sequence and does not send additional motor commands. + ## Bitrate | Where | Bitrate | Status | @@ -63,10 +148,13 @@ UNO R4 WiFi -- CAN TX = D10 --> TJA1051T TXD | MKS drives as shipped | 500 kbit/s | Factory default | | Bench sketches (`kCanBitrate`) | 500 kbit/s | Match drives as shipped | | Real-arm host through `carrier_bridge` | 1 Mbit/s | Target for the five arm drives | +| Real-arm host through `carrier_bridge_mcp2515` | 500 kbit/s | Current 8 MHz MCP2515 arm configuration | | Carrier USB serial | 1,000,000 baud | Separate serial-link setting, not CAN bitrate | -Configure each drive alone before using the real-arm host. The carrier keeps the CAN rate at -which it first opened until reset, so replug it before checking the shared 1 Mbit/s bus: +The following migration is **only for the built-in-CAN 1 Mbit/s topology**, not the +8 MHz MCP2515 carrier (which cannot use 1 Mbit/s with this driver). Configure each +drive alone. The carrier keeps the CAN rate at which it first opened until reset, +so replug it before checking the shared 1 Mbit/s bus: ```bash ./scripts/macos.sh drives set-bitrate 3 1000000 @@ -285,6 +373,7 @@ must remain effective with the carrier absent or failed. | Command | Status | Source | | --- | --- | --- | | 31h READ_ENCODER + 6-byte signed reply | Implemented and verified against merged vectors and an ~81k-case cross-check with `mks_can.py` | `mks_can.py`, `test_mks_can.py` | +| 39h READ_POSITION_ERROR + signed int32 | Python decoder and read-only `mks_setup read-error` query; 1424 matching replies in an elbow pressure recording | `mks_can.py`, `mks_setup.py`, their unit tests | | 82h SET_MODE (05h SR_vFOC) | Implemented and verified | same | | 8Ch SET_RESPONSE | Implemented and verified | same | | 98h SET_HEARTBEAT | Implemented and verified | same | @@ -297,6 +386,50 @@ must remain effective with the carrier absent or failed. "Verified" means checked against the repo's reference implementation and its manual vectors. The real-hardware check is the frame log from the bench session. +The observed `39h` reply has DLC 6: command byte, four signed error bytes, and checksum. +Its scale is 51200 units per motor turn, unlike the `31h` encoder's 16384 counts per +turn. It is motor-shaft position error, not a fault code or a measured force. See +[powered hand-guiding](../../docs/operator_guide.md#powered-hand-guiding) for the limits +of using it to infer a push. + +### F5h on firmware V1.0.9 + +The bench drives (SERVO42D_CAN, firmware V1.0.9, hardware 2) take the F5h frames above as the +manual says, with one exception found with `waybionic_teleop`'s 120 Hz target stream. A target +sent while a running move is reversing or slowing to turn back can be kept, and so can an +occasional target sent mid-stroke in the same direction. Once the moves stop (F5h speed 0, +F7h, or the last target reached), the drive runs to that kept target at the old speed, up to +12° of base travel and 0.07-0.9 s after the frame. Frame logs show the run starting 3-5 ms +after the stop. Each runaway ended 1-8 counts from a target sent earlier. The exact trigger +isn't known. + +The drive node avoids this in two ways. + +- **No target behind a running move.** When the commanded target passes the last encoder + reading against the drive's direction, the node sends an F5h stop (speed 0, acc 0). It + sends no new target until the drive has settled: 12 ms after the stop, with no encoder + step in the old direction; or a run-complete reply after the stop, with a step under 5 + counts. The bench pause before the drive turns back is 17 ms median, 42 ms worst case. + Over the same random stick profiles on the base, streaming straight through each reversal + ran away 7 times in 80 cycles; the stop and settle ran away 0 times in 80 (p≈0.007). +- **A hold right behind every stop.** Every stop of a running move is followed at once by an + F5h to where the drive is to stay, at 60 rpm. That is the stopped move's last target, at + most two ticks of travel past the last encoder reading. The hold goes out again every tick + for 0.25 s. A drive that may have lost its zero (lost, faulted, being zeroed) or whose + E-stop is pressed gets no hold. Bench, base, 80 ramped-down stops per variant: + + | After the stop | Runs to a kept target | Worst excursion | + | --- | --- | --- | + | One re-target once a run showed | 7 | 2515 counts (2.1°) | + | Hold every tick from 8 ms | 8 | 1282 counts (1.1°) | + | Hold 1 ms after the stop, then every tick | 5, each caught | 437 counts (0.37°) | + | **Hold right behind the stop, then every tick** (the node) | **0** | **107 counts (0.09°)** | + +`sim_drives.py` models the kept target so the tests catch any regression. + +The speed-0, acc-0 stop itself overshoots by about 100 counts on the base, then creeps back to +the last F5h target. + ## Verification status | What | Status | diff --git a/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino b/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino index fe397e51..a81f5b26 100644 --- a/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino +++ b/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino @@ -1,8 +1,9 @@ /* WayBionic carrier bridge prototype: laptop USB serial <-> UNO R4 <-> TJA1051T <-> CAN bus. - Speaks a documented SUBSET of the Lawicel SLCAN protocol (see SlcanBridge.h). The real-arm - host opens it at 1,000,000 baud over USB serial and selects the CAN bus bitrate separately. + Speaks a documented SUBSET of the Lawicel SLCAN protocol (see SlcanBridge.h) over the RA4M1's + own USB port, so the serial baud rate the host opens it at does not matter, except 1200: that + hands the port back for an upload (UsbHandBack.h). The host selects the CAN bus bitrate with Sn. Standard 11-bit data frames only. The CAN controller stays off until the host sends 'O', so the board puts nothing on the bus by itself. Host frames wait in a bounded queue while the @@ -19,8 +20,15 @@ #include -// This is the USB serial baud rate, not the CAN bus bitrate. Both ends must use this value. -static const unsigned long kSerialBaud = 1000000; +#if defined(ARDUINO_UNOWIFIR4) +// The UNO R4 WiFi's USB-C port normally belongs to its ESP32-S3, whose USB bridge firmware stops +// passing bytes on for good, in one direction or the other, under steady two-way traffic. +// Defining this hands the port to the RA4M1's own USB at boot (pin P408), as on the UNO R4 Minima, +// so SerialUSB below reaches the host directly. See README.md, "USB link". +void __USBStart(); +void __maybe_start_usb() {__USBStart();} +#endif + static const uint32_t kStatusPeriodMs = 100; static waybionic::R4CanTransport can; @@ -34,7 +42,7 @@ public: class SerialSlcanOutput : public waybionic::SlcanOutput { public: - void write(const char * text) override {Serial.print(text);} + void write(const char * text) override {SerialUSB.print(text);} }; static R4Starter starter; @@ -44,13 +52,15 @@ static uint32_t lastStatusMs = 0; void setup() { - Serial.begin(kSerialBaud); + // USB ignores the baud rate. + SerialUSB.begin(0); } void loop() { - while (Serial.available() > 0) { - bridge.handleChar(static_cast(Serial.read()), millis()); + waybionic::handBackUsbWhenAsked(); + while (SerialUSB.available() > 0) { + bridge.handleChar(static_cast(SerialUSB.read()), millis()); } bridge.drainTransmit(millis()); bridge.pollCan(); diff --git a/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino b/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino new file mode 100644 index 00000000..330dda2e --- /dev/null +++ b/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino @@ -0,0 +1,90 @@ +/* + WayBionic carrier bridge for an MCP2515 CAN module: laptop USB serial <-> UNO R4 <-> SPI <-> + MCP2515 + TJA1050 module <-> CAN bus. + + Same SLCAN subset, USB link and carrier status frame as carrier_bridge.ino (see + SlcanBridge.h), so the ground station cannot tell the two apart. Only the CAN controller + differs: this one is the external MCP2515 the arm's bench uses instead of the R4's own. + + Wiring (UNO R4 WiFi): + MCP2515 CS -> D10 MCP2515 SO (MISO) -> D12 + MCP2515 INT -> D2 MCP2515 SI (MOSI) -> D11 + MCP2515 SCK -> D13 VCC 5 V, GND + kCrystalHz must match the oscillator printed on the module's can (8.000 MHz on the bench). + + Each 'O' from the host makes Mcp2515CanTransport check the chip and run its loopback + self-test before joining the bus; a link that fails is answered with BELL. Its controller + errors and failed link checks are both reported as CAN errors in the status frame. + + As in carrier_bridge.ino, nothing else is printed on the serial port, and the CAN controller + stays in configuration mode (off the bus) until the host sends 'O'. +*/ + +#include + +#if defined(ARDUINO_UNOWIFIR4) +// Take the USB-C port off the WiFi board's ESP32-S3 bridge, as carrier_bridge.ino explains. +void __USBStart(); +void __maybe_start_usb() {__USBStart();} +#endif + +static const uint32_t kStatusPeriodMs = 100; +static const uint8_t kChipSelectPin = 10; +static const uint8_t kInterruptPin = 2; +static const uint32_t kCrystalHz = 8000000; + +static waybionic::ArduinoMcp2515Spi spi(kChipSelectPin, kInterruptPin); +static waybionic::Mcp2515CanTransport can(spi, kCrystalHz); + +class Mcp2515Starter : public waybionic::CanStarter +{ +public: + bool start(uint32_t bitrate) override {return can.begin(bitrate);} +}; + +class SerialSlcanOutput : public waybionic::SlcanOutput +{ +public: + void write(const char * text) override {SerialUSB.print(text);} +}; + +static Mcp2515Starter starter; +static SerialSlcanOutput serialOutput; +static waybionic::SlcanBridge bridge(can, starter, serialOutput); +static uint32_t lastStatusMs = 0; + +void setup() +{ + // USB ignores the baud rate. + SerialUSB.begin(0); + spi.begin(); + // A board reset leaves the MCP2515 as it was, possibly still on the bus: take it off. + can.end(); +} + +void loop() +{ + waybionic::handBackUsbWhenAsked(); + while (SerialUSB.available() > 0) { + bridge.handleChar(static_cast(SerialUSB.read()), millis()); + } + can.service(); + bridge.drainTransmit(millis()); + // Each receive() empties the MCP2515's two buffers before taking the next frame. + bridge.pollCan(); + + const uint32_t now = millis(); + if (now - lastStatusMs >= kStatusPeriodMs) { + lastStatusMs = now; + const waybionic::BenchTelemetry bench = waybionic::readBenchTelemetry(); + waybionic::CarrierStatus status; + status.estop_wired = bench.estop != waybionic::EstopState::kUnknown; + status.estop_pressed = bench.estop == waybionic::EstopState::kPressed; + status.supply_wired = bench.supply_known; + status.supply_millivolts = static_cast( + bench.supply_millivolts > 0xFFFF ? 0xFFFF : bench.supply_millivolts); + status.can_errors = can.errorEvents() + can.linkFaults(); + status.failed_writes = can.failedWrites(); + bridge.reportStatus(status); + } +} diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h b/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h index e633b837..b0cba287 100644 --- a/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h @@ -2,7 +2,8 @@ // Arduino entry point for the WayBionic CAN code. Everything under common/ is plain C++ with // no Arduino, Linux or ROS headers, no heap and no exceptions; the waybionic_can CMake build -// compiles and tests the same files on the host. r4/ is the only board-specific part. +// compiles and tests the same files on the host. r4/ (the UNO R4's built-in CAN controller) and +// mcp2515/ (an MCP2515 module on SPI) are the only board-specific parts. #include "common/BenchTelemetry.h" #include "common/BringupConsole.h" @@ -12,9 +13,12 @@ #include "common/GatewayLogic.h" #include "common/IActuator.h" #include "common/ICanTransport.h" +#include "common/Mcp2515CanTransport.h" #include "common/MksFrame.h" #include "common/NodeLogic.h" #include "common/SlcanBridge.h" #include "common/SoftwareActuator.h" +#include "mcp2515/ArduinoMcp2515Spi.h" #include "r4/R4CanTransport.h" +#include "r4/UsbHandBack.h" diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp new file mode 100644 index 00000000..60da878b --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp @@ -0,0 +1,540 @@ +#include "common/Mcp2515CanTransport.h" + +namespace waybionic +{ +namespace +{ + +// SPI instructions +constexpr uint8_t kReset = 0xC0; +constexpr uint8_t kRead = 0x03; +constexpr uint8_t kWrite = 0x02; +constexpr uint8_t kBitModify = 0x05; +constexpr uint8_t kRequestToSend0 = 0x81; + +// Registers +constexpr uint8_t kCanStat = 0x0E; +constexpr uint8_t kCanCtrl = 0x0F; +constexpr uint8_t kTec = 0x1C; +constexpr uint8_t kRec = 0x1D; +constexpr uint8_t kCnf3 = 0x28; +constexpr uint8_t kCnf2 = 0x29; +constexpr uint8_t kCnf1 = 0x2A; +constexpr uint8_t kCanIntE = 0x2B; +constexpr uint8_t kCanIntF = 0x2C; +constexpr uint8_t kEflg = 0x2D; +constexpr uint8_t kTxb0Ctrl = 0x30; +constexpr uint8_t kTxb0Sidh = 0x31; +constexpr uint8_t kTxb2Data = 0x56; +constexpr uint8_t kRxb0Ctrl = 0x60; +constexpr uint8_t kRxb0Sidh = 0x61; +constexpr uint8_t kRxb1Ctrl = 0x70; +constexpr uint8_t kRxb1Sidh = 0x71; +// Six acceptance filters and two masks, four registers each. +constexpr uint8_t kAcceptanceBases[] = {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}; + +// TXB2's data bytes are never transmitted. They hold zeros so that reading two of them leaves +// the chip's SO output low before the read that matters. +constexpr uint8_t kZeroScratch = kTxb2Data + 2; + +constexpr uint8_t kModeMask = 0xE0; +constexpr uint8_t kModeNormal = 0x00; +constexpr uint8_t kModeLoopback = 0x40; +constexpr uint8_t kModeConfig = 0x80; + +constexpr uint8_t kRx0If = 0x01; +constexpr uint8_t kRx1If = 0x02; +constexpr uint8_t kTxReq = 0x08; +constexpr uint8_t kSidlSrr = 0x10; +constexpr uint8_t kSidlIde = 0x08; +constexpr uint8_t kRx0Ovr = 0x40; +constexpr uint8_t kRx1Ovr = 0x80; +constexpr uint8_t kErrorStateMask = 0x3F; // EWARN, RXWAR, TXWAR, RXEP, TXEP, TXBO + +constexpr uint8_t kRxModeMask = 0x60; +constexpr uint8_t kRollover = 0x04; + +constexpr uint32_t kOscillatorStartMs = 5; +constexpr uint32_t kModeChangeMs = 10; +constexpr uint32_t kSelfTestWaitMs = 5; + +uint32_t nextRandom(uint32_t & state) +{ + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +// The patterns the bench link got wrong most: all ones, alternating bits, a single set MSB, the +// drives' 31h replies around zero, and random bytes. +void selfTestFrame(const uint16_t n, uint32_t & random, Frame & frame) +{ + frame = Frame{}; + frame.id = static_cast((n * 0x2B5u + 1u) & kMaxStandardCanId); + frame.dlc = (n % 8 == 7) ? static_cast(n % (kMaxCanDataBytes + 1)) : kMaxCanDataBytes; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + uint8_t value = 0; + switch (n % 6) { + case 0: value = 0xFF; break; + case 1: value = 0x00; break; + case 2: value = (i % 2) ? 0x55 : 0xAA; break; + case 3: value = static_cast(0x80u >> i); break; + case 4: value = (i == 0) ? 0x31 : ((n / 6) % 2 ? 0xFF : 0x00); break; + default: value = static_cast(nextRandom(random)); break; + } + frame.data[i] = i < frame.dlc ? value : 0; + } + if (n % 6 == 4 && frame.dlc == kMaxCanDataBytes) { + uint32_t sum = frame.id; + for (uint8_t i = 0; i + 1 < kMaxCanDataBytes; ++i) { + sum += frame.data[i]; + } + frame.data[kMaxCanDataBytes - 1] = static_cast(sum); + } +} + +bool sameFrame(const Frame & a, const Frame & b) +{ + if (a.id != b.id || a.dlc != b.dlc) { + return false; + } + for (uint8_t i = 0; i < a.dlc; ++i) { + if (a.data[i] != b.data[i]) { + return false; + } + } + return true; +} + +} // namespace + +Mcp2515CanTransport::Mcp2515CanTransport(Mcp2515Spi & spi, const uint32_t crystal_hz) +: spi_(spi), crystal_hz_(crystal_hz) +{ +} + +bool Mcp2515CanTransport::timing( + const uint32_t crystal_hz, const uint32_t bitrate, uint8_t & cnf1, uint8_t & cnf2, + uint8_t & cnf3) +{ + // One time quantum is 2 * (BRP + 1) oscillator periods and a bit is 8 quanta: sync 1, + // propagation 2, phase 1 3, phase 2 2. + constexpr uint32_t kQuantaPerBit = 8; + if (bitrate == 0 || crystal_hz % (2 * kQuantaPerBit * bitrate) != 0) { + return false; + } + const uint32_t prescaler = crystal_hz / (2 * kQuantaPerBit * bitrate); + if (prescaler < 1 || prescaler > 64) { + return false; + } + cnf1 = static_cast(prescaler - 1); // SJW 1 quantum + cnf2 = 0x91; // BTLMODE, phase 1 = 3, propagation = 2 + cnf3 = 0x01; // phase 2 = 2 + return true; +} + +uint8_t Mcp2515CanTransport::readRegister(const uint8_t address) +{ + spi_.select(); + spi_.transfer(kRead); + spi_.transfer(kZeroScratch); + spi_.transfer(0x00); + spi_.transfer(0x00); + spi_.deselect(); + + spi_.select(); + spi_.transfer(kRead); + spi_.transfer(address); + const uint8_t value = spi_.transfer(0x00); + spi_.deselect(); + return value; +} + +void Mcp2515CanTransport::writeRegisters( + const uint8_t address, const uint8_t * data, const uint8_t length) +{ + spi_.select(); + spi_.transfer(kWrite); + spi_.transfer(address); + for (uint8_t i = 0; i < length; ++i) { + spi_.transfer(data[i]); + } + spi_.deselect(); +} + +void Mcp2515CanTransport::bitModify(const uint8_t address, const uint8_t mask, const uint8_t value) +{ + spi_.select(); + spi_.transfer(kBitModify); + spi_.transfer(address); + spi_.transfer(mask); + spi_.transfer(value); + spi_.deselect(); +} + +void Mcp2515CanTransport::instruction(const uint8_t code) +{ + spi_.select(); + spi_.transfer(code); + spi_.deselect(); +} + +bool Mcp2515CanTransport::setMode(const uint8_t mode) +{ + bitModify(kCanCtrl, kModeMask, mode); + const uint32_t start = spi_.millis(); + do { + if ((readRegister(kCanStat) & kModeMask) == mode) { + return true; + } + } while (spi_.millis() - start < kModeChangeMs); + return false; +} + +bool Mcp2515CanTransport::configure(const uint8_t mode) +{ + instruction(kReset); + spi_.delayMs(kOscillatorStartMs); + // The zero scratch first: every read below depends on it. + static const uint8_t kZeros[kMaxCanDataBytes] = {}; + writeRegisters(kTxb2Data, kZeros, kMaxCanDataBytes); + if ((readRegister(kCanStat) & kModeMask) != kModeConfig) { + return false; // no chip, or it does not answer + } + const uint8_t cnf[3] = {cnf_[2], cnf_[1], cnf_[0]}; // CNF3, CNF2, CNF1 are consecutive + writeRegisters(kCnf3, cnf, 3); + // RXM=11 also accepts partial, errored messages (DS20001801J, section 4.2.2). + // RXM=00, standard-frame filters and zero masks accept every standard ID/data byte, + // but only valid CAN messages. + for (const uint8_t base : kAcceptanceBases) { + writeRegisters(base, kZeros, 4); + } + writeRegister(kRxb0Ctrl, kRollover); + writeRegister(kRxb1Ctrl, 0x00); + writeRegister(kCanIntE, kRx0If | kRx1If); + writeRegister(kCanIntF, 0x00); + writeRegister(kEflg, 0x00); + return linkHealthy(kModeConfig) && setMode(mode); +} + +bool Mcp2515CanTransport::linkHealthy(const uint8_t mode) +{ + if (!(readRegister(kCnf1) == cnf_[0] && readRegister(kCnf2) == cnf_[1] && + readRegister(kCnf3) == cnf_[2] && readRegister(kZeroScratch) == 0 && + readRegister(kZeroScratch + 1) == 0 && (readRegister(kCanStat) & kModeMask) == mode && + (readRegister(kRxb0Ctrl) & (kRxModeMask | kRollover)) == kRollover && + (readRegister(kRxb1Ctrl) & kRxModeMask) == 0)) + { + return false; + } + // Masks and filters read as zero outside configuration mode, irrespective of their values. + if (mode == kModeConfig) { + for (const uint8_t base : kAcceptanceBases) { + for (uint8_t i = 0; i < 4; ++i) { + if (readRegister(static_cast(base + i)) != 0) { + return false; + } + } + } + } + return true; +} + +bool Mcp2515CanTransport::start() +{ + tx_pending_ = false; + tx_aborting_ = false; + link_suspect_ = false; + // Frames read since the last good link check may have been read wrong. + clearReceived(); + if (!configure(kModeLoopback)) { + ++link_faults_; + instruction(kReset); + return false; + } + self_test_ = runSelfTest(kSelfTestFrames); + writeRegister(kCanIntF, 0x00); + writeRegister(kEflg, 0x00); + rxb1_older_ = false; + if (!self_test_.passed() || !setMode(kModeNormal)) { + ++link_faults_; + instruction(kReset); + return false; + } + const uint32_t now = spi_.millis(); + last_error_sample_ms_ = now; + last_link_check_ms_ = now; + tec_ = 0; + rec_ = 0; + eflg_ = 0; + return true; +} + +bool Mcp2515CanTransport::begin(const uint32_t bitrate) +{ + uint8_t cnf1 = 0; + uint8_t cnf2 = 0; + uint8_t cnf3 = 0; + if (!timing(crystal_hz_, bitrate, cnf1, cnf2, cnf3)) { + return false; + } + if (open_ && bitrate == bitrate_) { + return true; + } + open_ = false; + bitrate_ = bitrate; + cnf_[0] = cnf1; + cnf_[1] = cnf2; + cnf_[2] = cnf3; + open_ = start(); + // Only a transport that was running gets restarted by service(); the host retries a failed + // open itself. + running_ = open_; + bus_load_.reset(bitrate_, spi_.millis()); + return open_; +} + +void Mcp2515CanTransport::end() +{ + instruction(kReset); + spi_.delayMs(kOscillatorStartMs); + open_ = false; + running_ = false; + tx_pending_ = false; + tx_aborting_ = false; + clearReceived(); +} + +void Mcp2515CanTransport::loadTransmit(const Frame & frame) +{ + uint8_t buffer[5 + kMaxCanDataBytes] = {}; + buffer[0] = static_cast(frame.id >> 3); + buffer[1] = static_cast((frame.id & 0x07) << 5); + buffer[4] = frame.dlc; + for (uint8_t i = 0; i < frame.dlc; ++i) { + buffer[5 + i] = frame.data[i]; + } + writeRegisters(kTxb0Sidh, buffer, static_cast(5 + frame.dlc)); + instruction(kRequestToSend0); +} + +bool Mcp2515CanTransport::transmitIdle(const uint32_t now_ms) +{ + if (!tx_pending_) { + return true; + } + if ((readRegister(kTxb0Ctrl) & kTxReq) == 0) { + tx_pending_ = false; + tx_aborting_ = false; + return true; + } + if (!tx_aborting_ && now_ms - tx_started_ms_ >= kTransmitTimeoutMs) { + // A frame nobody acknowledged would otherwise be retried until someone does, and a stale + // motion command must not reach a drive that comes back later. + bitModify(kTxb0Ctrl, kTxReq, 0x00); + tx_aborting_ = true; + ++failed_writes_; + if ((readRegister(kTxb0Ctrl) & kTxReq) == 0) { + tx_pending_ = false; + tx_aborting_ = false; + return true; + } + } + return false; +} + +bool Mcp2515CanTransport::send(const Frame & frame) +{ + if (!open_ || !isValidFrame(frame)) { + return false; + } + const uint32_t now = spi_.millis(); + if (!transmitIdle(now)) { + return false; + } + loadTransmit(frame); + tx_pending_ = true; + tx_started_ms_ = now; + bus_load_.note(frame, now); + return true; +} + +Mcp2515CanTransport::ReadResult Mcp2515CanTransport::readReceived(Frame & frame) +{ + const uint8_t flags = readRegister(kCanIntF) & (kRx0If | kRx1If); + if (flags == 0) { + return ReadResult::kNone; + } + // With rollover a frame goes to RXB0, or to RXB1 while RXB0 is full, so RXB0 holds the older + // frame when both are full. Once RXB0 is emptied ahead of a waiting RXB1, the next frame to + // reach RXB0 is newer than RXB1's. + const bool first = (flags & kRx0If) != 0 && !(rxb1_older_ && (flags & kRx1If) != 0); + rxb1_older_ = first && (flags & kRx1If) != 0; + const uint8_t base = first ? kRxb0Sidh : kRxb1Sidh; + const uint8_t sidh = readRegister(base); + const uint8_t sidl = readRegister(static_cast(base + 1)); + ReadResult result = ReadResult::kDropped; + if ((sidl & (kSidlIde | kSidlSrr)) == 0) { + Frame got; + got.id = static_cast((static_cast(sidh) << 3) | (sidl >> 5)); + const uint8_t dlc = readRegister(static_cast(base + 4)) & 0x0F; + got.dlc = dlc > kMaxCanDataBytes ? kMaxCanDataBytes : dlc; + for (uint8_t i = 0; i < got.dlc; ++i) { + got.data[i] = readRegister(static_cast(base + 5 + i)); + } + frame = got; + result = ReadResult::kFrame; + } else { + ++dropped_frames_; + } + // RXnIF locks this buffer until cleared (DS20001801J, section 4.1.3), including between + // the separate SPI register reads above. + bitModify(kCanIntF, first ? kRx0If : kRx1If, 0x00); + return result; +} + +void Mcp2515CanTransport::collectReceived() +{ + for (uint8_t reads = 0; reads < kMaxReadsPerCall && rx_count_ < kReceiveQueueCapacity && + spi_.interruptAsserted(); ++reads) + { + Frame frame; + const ReadResult result = readReceived(frame); + if (result == ReadResult::kNone) { + return; + } + if (result == ReadResult::kFrame) { + rx_queue_[(rx_head_ + rx_count_) % kReceiveQueueCapacity] = frame; + ++rx_count_; + bus_load_.note(frame, spi_.millis()); + } + } +} + +void Mcp2515CanTransport::clearReceived() +{ + rx_head_ = 0; + rx_count_ = 0; + rxb1_older_ = false; +} + +bool Mcp2515CanTransport::receive(Frame & frame, const uint32_t timeout_ms) +{ + if (!open_) { + return false; + } + const uint32_t start = spi_.millis(); + for (;;) { + collectReceived(); + if (rx_count_ > 0) { + frame = rx_queue_[rx_head_]; + rx_head_ = static_cast((rx_head_ + 1) % kReceiveQueueCapacity); + --rx_count_; + return true; + } + if (spi_.millis() - start >= timeout_ms) { + return false; + } + } +} + +void Mcp2515CanTransport::sampleErrors() +{ + const uint8_t eflg = readRegister(kEflg); + const uint8_t tec = readRegister(kTec); + const uint8_t rec = readRegister(kRec); + // With rollover the chip flags RX0OVR, not RX1OVR, when a frame finds both buffers full + // (measured on the bench chip); either way a frame was lost. + if ((eflg & (kRx0Ovr | kRx1Ovr)) != 0) { + ++receive_overflows_; + bitModify(kEflg, kRx0Ovr | kRx1Ovr, 0x00); + } + const uint8_t entered = static_cast(eflg & kErrorStateMask & ~eflg_); + if (entered != 0 || tec > tec_ || rec > rec_) { + ++error_events_; + } + eflg_ = eflg; + tec_ = tec; + rec_ = rec; +} + +void Mcp2515CanTransport::checkLink() +{ + if (linkHealthy(kModeNormal)) { + link_suspect_ = false; + return; + } + ++link_faults_; + if (!link_suspect_) { + link_suspect_ = true; // confirm on the next check before restarting + return; + } + // Two failed checks in a row: the chip lost its configuration (a reset or brownout) or the + // link is broken. Start again; service() keeps retrying while that fails. + ++restarts_; + open_ = start(); +} + +void Mcp2515CanTransport::service() +{ + if (!running_) { + return; + } + const uint32_t now = spi_.millis(); + if (!open_) { + if (now - last_link_check_ms_ >= kLinkCheckPeriodMs) { + last_link_check_ms_ = now; + ++restarts_; + open_ = start(); + } + return; + } + if (tx_pending_) { + transmitIdle(now); + } + collectReceived(); + if (now - last_error_sample_ms_ >= kErrorSamplePeriodMs) { + last_error_sample_ms_ = now; + sampleErrors(); + } + if (now - last_link_check_ms_ >= kLinkCheckPeriodMs) { + last_link_check_ms_ = now; + checkLink(); + } +} + +Mcp2515CanTransport::SelfTest Mcp2515CanTransport::runSelfTest(const uint16_t frames) +{ + SelfTest result; + uint32_t random = 0x2545F491u; + for (uint16_t n = 0; n < frames; n += 2) { + // Two at a time, so the second rolls over into RXB1 and both buffers are read. + const uint8_t count = (frames - n >= 2) ? 2 : 1; + Frame sent[2]; + for (uint8_t k = 0; k < count; ++k) { + selfTestFrame(static_cast(n + k), random, sent[k]); + loadTransmit(sent[k]); + const uint32_t start = spi_.millis(); + while ((readRegister(kTxb0Ctrl) & kTxReq) != 0 && + spi_.millis() - start < kSelfTestWaitMs) + { + } + } + for (uint8_t k = 0; k < count; ++k) { + ++result.frames; + const uint32_t start = spi_.millis(); + while (!spi_.interruptAsserted() && spi_.millis() - start < kSelfTestWaitMs) { + } + Frame got; + if (!spi_.interruptAsserted() || readReceived(got) != ReadResult::kFrame) { + ++result.missing; + } else if (!sameFrame(got, sent[k])) { + ++result.bad; + } + } + } + return result; +} + +} // namespace waybionic diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h new file mode 100644 index 00000000..5c90c85b --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h @@ -0,0 +1,168 @@ +#pragma once + +#include + +#include "common/BusLoad.h" +#include "common/Frame.h" +#include "common/ICanTransport.h" + +namespace waybionic +{ + +// SPI access to one MCP2515: chip select, byte transfer, its INT pin and a clock. The Arduino +// implementation is mcp2515/ArduinoMcp2515Spi.h; the unit tests use a simulated chip. +class Mcp2515Spi +{ +public: + virtual ~Mcp2515Spi() = default; + virtual void select() = 0; + virtual uint8_t transfer(uint8_t out) = 0; + virtual void deselect() = 0; + // True while INT is low. Only the receive-buffer interrupts are enabled, so this means a + // received frame is waiting. + virtual bool interruptAsserted() = 0; + virtual uint32_t millis() = 0; + virtual void delayMs(uint32_t ms) = 0; +}; + +// CAN through an MCP2515 controller on SPI, the common "MCP2515 + TJA1050" module. +// +// Register reads use the one method measured clean on the WayBionic bench link. On that link +// the chip sometimes shifts a read out one bit early (its SO output is one clock ahead), which +// depends on the previous SPI transaction, and multi-byte "burst" reads slip inside the burst. +// Writes, bit-modify and instructions were not observed to be affected in those tests. +// Every read here is a single byte, preceded by a two-byte read of TXB2's data registers, +// which are kept at zero and never +// transmitted. With that, 8000 loopback frames had no bad byte and 800 drive replies out of 800 +// were valid; burst reads of the same frames were wrong 84 % of the time. +// +// Transmission uses TXB0 only, so frames leave in the order they are sent. A frame that has +// not left after kTransmitTimeoutMs (nobody ACKs it: drives unpowered, open bus) is aborted and +// counted rather than sent late. Reception uses both buffers with rollover; INT shows when a +// frame is waiting, so an idle poll costs no SPI traffic. The chip holds only two frames and a +// conditioned read of one takes about a quarter of a millisecond, so service() moves them into a +// queue here as they arrive and receive() hands them out in arrival order. +// RXM=00 with standard-frame filters and zero masks admits all standard IDs but rejects +// errored CAN messages, unlike debug RXM=11 which can expose partially assembled messages. +// RXnIF remains set until the full frame is copied, so new traffic cannot overwrite a +// buffer while it is being read. +// +// begin() resets the chip, checks that it answers and holds its configuration, then sends +// kSelfTestFrames through the chip's internal loopback (nothing reaches the bus) and only joins +// the bus if every frame read back exactly. A link too noisy for the read method is refused +// instead of handing out wrong data. +class Mcp2515CanTransport : public ICanTransport +{ +public: + static constexpr uint32_t kTransmitTimeoutMs = 20; + static constexpr uint32_t kErrorSamplePeriodMs = 10; + static constexpr uint32_t kLinkCheckPeriodMs = 100; + static constexpr uint16_t kSelfTestFrames = 96; + static constexpr uint8_t kReceiveQueueCapacity = 16; + // At most this many frames are read from the chip per call, which bounds a call's time. + static constexpr uint8_t kMaxReadsPerCall = 4; + + struct SelfTest + { + uint16_t frames = 0; + uint16_t bad = 0; // read back with a different ID, length or data byte + uint16_t missing = 0; // never arrived + bool passed() const {return frames > 0 && bad == 0 && missing == 0;} + }; + + // crystal_hz is the oscillator on the module, usually 8 or 16 MHz. + Mcp2515CanTransport(Mcp2515Spi & spi, uint32_t crystal_hz); + + // Reset, configure, self-test and join the bus. Calling it again at the running bitrate is a + // no-op; another bitrate reconfigures the chip. False leaves the chip off the bus. If the + // chip later loses its configuration, service() restarts it. + bool begin(uint32_t bitrate); + // Reset the chip into configuration mode: off the bus, nothing acknowledged. + void end(); + bool isOpen() const {return open_;} + uint32_t bitrate() const {return bitrate_;} + + bool send(const Frame & frame) override; + // Extended and remote frames that reach software are dropped and counted: every protocol + // here uses 11-bit data frames. + bool receive(Frame & frame, uint32_t timeout_ms) override; + + // Call every loop pass, and between slow jobs such as writing to a serial port: moves received + // frames off the chip, finishes or aborts the pending transmission, samples the controller's + // error state and checks the SPI link. Does SPI work only when something is due. + void service(); + + const SelfTest & lastSelfTest() const {return self_test_;} + // Controller error-state changes: error counters rising, warning/passive/bus-off entered. + uint32_t errorEvents() const {return error_events_;} + // Frames aborted because they did not leave in time. + uint32_t failedWrites() const {return failed_writes_;} + // Failed checks of the SPI link or the chip's configuration, and failed (re)starts. + uint32_t linkFaults() const {return link_faults_;} + // Times the chip lost a frame because both of its receive buffers were full. + uint32_t receiveOverflows() const {return receive_overflows_;} + uint32_t droppedFrames() const {return dropped_frames_;} + uint32_t restarts() const {return restarts_;} + uint8_t transmitErrorCount() const {return tec_;} + uint8_t receiveErrorCount() const {return rec_;} + uint8_t errorFlags() const {return eflg_;} + // Frames sent and received since begin(). + BusLoad & busLoad() {return bus_load_;} + + // CNF1..CNF3 for 8 time quanta per bit with the sample point at 75 %. False if the crystal + // cannot make the bitrate exactly with those quanta (8 MHz cannot make 1 Mbit/s). + static bool timing( + uint32_t crystal_hz, uint32_t bitrate, uint8_t & cnf1, uint8_t & cnf2, uint8_t & cnf3); + +private: + enum class ReadResult : uint8_t {kNone, kFrame, kDropped}; + + uint8_t readRegister(uint8_t address); + void writeRegisters(uint8_t address, const uint8_t * data, uint8_t length); + void writeRegister(uint8_t address, uint8_t value) {writeRegisters(address, &value, 1);} + void bitModify(uint8_t address, uint8_t mask, uint8_t value); + void instruction(uint8_t code); + bool setMode(uint8_t mode); + bool configure(uint8_t mode); + bool start(); + void loadTransmit(const Frame & frame); + ReadResult readReceived(Frame & frame); + void collectReceived(); + void clearReceived(); + bool transmitIdle(uint32_t now_ms); + void sampleErrors(); + bool linkHealthy(uint8_t mode); + void checkLink(); + SelfTest runSelfTest(uint16_t frames); + + Mcp2515Spi & spi_; + uint32_t crystal_hz_; + bool running_ = false; // opened by begin(); service() restarts it if the chip drops out + bool open_ = false; + uint32_t bitrate_ = 0; + uint8_t cnf_[3] = {}; + bool tx_pending_ = false; + bool tx_aborting_ = false; + uint32_t tx_started_ms_ = 0; + uint32_t last_error_sample_ms_ = 0; + uint32_t last_link_check_ms_ = 0; + bool link_suspect_ = false; + // Set when RXB1 holds a frame older than whatever RXB0 receives next. + bool rxb1_older_ = false; + Frame rx_queue_[kReceiveQueueCapacity]; + uint8_t rx_head_ = 0; + uint8_t rx_count_ = 0; + SelfTest self_test_; + uint32_t error_events_ = 0; + uint32_t failed_writes_ = 0; + uint32_t link_faults_ = 0; + uint32_t receive_overflows_ = 0; + uint32_t dropped_frames_ = 0; + uint32_t restarts_ = 0; + uint8_t tec_ = 0; + uint8_t rec_ = 0; + uint8_t eflg_ = 0; + BusLoad bus_load_; +}; + +} // namespace waybionic diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp new file mode 100644 index 00000000..f13d1e1d --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp @@ -0,0 +1,92 @@ +#include "mcp2515/ArduinoMcp2515Spi.h" + +#if defined(ARDUINO) + +#include +#include + +namespace waybionic +{ + +ArduinoMcp2515Spi::ArduinoMcp2515Spi( + const uint8_t cs_pin, const uint8_t int_pin, const uint32_t clock_hz) +: cs_pin_(cs_pin), int_pin_(int_pin), clock_hz_(clock_hz) +{ +} + +void ArduinoMcp2515Spi::begin() +{ + pinMode(cs_pin_, OUTPUT); + digitalWrite(cs_pin_, HIGH); + pinMode(int_pin_, INPUT); +#if defined(ARDUINO_ARCH_RENESAS) + // Every register read is two transactions, so chip select through the port's set/reset + // register instead of digitalWrite saves a tenth of each read. + const bsp_io_port_pin_t pin = g_pin_cfg[cs_pin_].pin; + const uintptr_t port_stride = + reinterpret_cast(R_PORT1) - reinterpret_cast(R_PORT0); + R_PORT0_Type * const port = reinterpret_cast( + reinterpret_cast(R_PORT0) + port_stride * (static_cast(pin) >> 8)); + cs_set_reset_ = &port->PCNTR3; + cs_mask_ = 1u << (static_cast(pin) & 0xFFu); +#endif + // Not SPI.end() first: on the UNO R4 core it faults if SPI has not been started. + SPI.begin(); +} + +void ArduinoMcp2515Spi::csLow() +{ + if (cs_set_reset_ != nullptr) { + *cs_set_reset_ = cs_mask_ << 16; // the upper half resets the pin + } else { + digitalWrite(cs_pin_, LOW); + } +} + +void ArduinoMcp2515Spi::csHigh() +{ + if (cs_set_reset_ != nullptr) { + *cs_set_reset_ = cs_mask_; + } else { + digitalWrite(cs_pin_, HIGH); + } +} + +void ArduinoMcp2515Spi::select() +{ + SPI.beginTransaction(SPISettings(clock_hz_, MSBFIRST, SPI_MODE0)); + csLow(); +} + +uint8_t ArduinoMcp2515Spi::transfer(const uint8_t out) +{ + return SPI.transfer(out); +} + +void ArduinoMcp2515Spi::deselect() +{ + csHigh(); + SPI.endTransaction(); + // The MCP2515 needs chip select high for 50 ns between transactions; the next select is + // further off than that, and these cover it even if it were not (21 ns each at 48 MHz). + __asm__ volatile("nop\n nop\n nop"); +} + +bool ArduinoMcp2515Spi::interruptAsserted() +{ + return digitalRead(int_pin_) == LOW; +} + +uint32_t ArduinoMcp2515Spi::millis() +{ + return ::millis(); +} + +void ArduinoMcp2515Spi::delayMs(const uint32_t ms) +{ + delay(ms); +} + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h new file mode 100644 index 00000000..c85829cd --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h @@ -0,0 +1,45 @@ +#pragma once + +// The MCP2515 module on the board's hardware SPI pins (UNO R4: D11 MOSI, D12 MISO, D13 SCK), +// with chip select and INT on any digital pins. Mcp2515CanTransport does the rest. + +#if defined(ARDUINO) + +#include + +#include "common/Mcp2515CanTransport.h" + +namespace waybionic +{ + +class ArduinoMcp2515Spi : public Mcp2515Spi +{ +public: + // 8 MHz is the clock the bench link was validated at; the MCP2515 allows up to 10 MHz. + ArduinoMcp2515Spi(uint8_t cs_pin, uint8_t int_pin, uint32_t clock_hz = 8000000); + + // Call once from setup(), before the transport's begin(). + void begin(); + + void select() override; + uint8_t transfer(uint8_t out) override; + void deselect() override; + bool interruptAsserted() override; + uint32_t millis() override; + void delayMs(uint32_t ms) override; + +private: + void csLow(); + void csHigh(); + + uint8_t cs_pin_; + uint8_t int_pin_; + uint32_t clock_hz_; + // The port's set/reset register for chip select, where the core has one (UNO R4). + volatile uint32_t * cs_set_reset_ = nullptr; + uint32_t cs_mask_ = 0; +}; + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp new file mode 100644 index 00000000..56de9d89 --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp @@ -0,0 +1,43 @@ +#include "r4/UsbHandBack.h" + +#if defined(ARDUINO_UNOWIFIR4) + +#include + +void goBootloader(); + +namespace waybionic +{ + +static const uint32_t kHandBackBaud = 1200; +static const uint32_t kDisconnectMs = 250; + +void handBackUsbWhenAsked() +{ + if (SerialUSB.baud() != kHandBackBaud) { + return; + } + // The host's DTR drop would otherwise run the core's immediate reset from the USB interrupt. + __disable_irq(); + R_USB_FS0->SYSCFG_b.DPRPU = 0; + R_BSP_SoftwareDelay(kDisconnectMs, BSP_DELAY_UNITS_MILLISECONDS); + // Already handed back: stop the bootloader pulsing P408 to do it again while the host is + // enumerating the bridge. + R_SYSTEM->PRCR = 0xA502; + R_SYSTEM->VBTBKR[1] = 0; + R_SYSTEM->PRCR = 0xA500; + goBootloader(); +} + +} // namespace waybionic + +#else + +namespace waybionic +{ + +void handBackUsbWhenAsked() {} + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h new file mode 100644 index 00000000..0ccf3cbc --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h @@ -0,0 +1,17 @@ +#pragma once + +namespace waybionic +{ + +// For sketches that take the UNO R4 WiFi's USB-C port off the ESP32-S3 bridge (see +// carrier_bridge.ino). Call at the top of loop(): when the host sets 1200 baud and keeps DTR +// high, it disconnects for long enough that the host notices, then restarts in the bootloader +// with the port back on the bridge, ready for an upload. Does nothing on other boards. +// +// The core's own 1200-baud reset (DTR low) also restarts in the bootloader, but it drops the +// connection and resets at once. The bridge, whose pull-up never went off, takes the line +// back too quickly for macOS to see a disconnect, so it keeps the dead device and never finds +// the bridge. +void handBackUsbWhenAsked(); + +} // namespace waybionic diff --git a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md index 13332476..478f90d2 100644 --- a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md +++ b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md @@ -28,7 +28,7 @@ With only the UNO R4 WiFi connected over USB: ```bash brew install arduino-cli -./scripts/macos.sh flash +./scripts/macos.sh flash carrier_bridge ``` Expected: the helper finds one `/dev/cu.usbmodem*`, compiles `carrier_bridge`, uploads it, and diff --git a/waybionic_can/tests/unit/test_mcp2515_transport.cpp b/waybionic_can/tests/unit/test_mcp2515_transport.cpp new file mode 100644 index 00000000..b9de7b57 --- /dev/null +++ b/waybionic_can/tests/unit/test_mcp2515_transport.cpp @@ -0,0 +1,703 @@ +// Mcp2515CanTransport against a simulated MCP2515 whose SPI link has the bench fault: a read +// comes back shifted one bit (the next register's MSB shifted in) unless it is a single byte +// right after a two-byte read of zeros. The real link is kinder; this model is the strict form +// of the rule the transport must follow, so every test below fails if any read breaks it. + +#include + +#include +#include +#include +#include + +#include "common/Mcp2515CanTransport.h" +#include "common/MksFrame.h" + +namespace waybionic +{ +namespace +{ + +constexpr uint8_t kCanStat = 0x0E; +constexpr uint8_t kCanCtrl = 0x0F; +constexpr uint8_t kTec = 0x1C; +constexpr uint8_t kRec = 0x1D; +constexpr uint8_t kCnf1 = 0x2A; +constexpr uint8_t kCanIntE = 0x2B; +constexpr uint8_t kCanIntF = 0x2C; +constexpr uint8_t kEflg = 0x2D; +constexpr uint8_t kTxb0Ctrl = 0x30; +constexpr uint8_t kTxb2Data = 0x56; +constexpr uint8_t kRxb0Ctrl = 0x60; +constexpr uint8_t kRxb0Sidh = 0x61; +constexpr uint8_t kRxb1Ctrl = 0x70; +constexpr uint8_t kRxb1Sidh = 0x71; + +class FakeMcp2515 : public Mcp2515Spi +{ +public: + enum class Link {kClean, kSlipping, kBroken}; + + FakeMcp2515() + { + std::memset(regs, 0xA5, sizeof(regs)); + reset(); + } + + void select() override + { + index_ = 0; + instruction_ = 0; + read_count_ = 0; + read_all_zero_ = true; + } + + uint8_t transfer(const uint8_t out) override + { + ++transfers; + if (!present) { + return 0xFF; + } + const size_t index = index_++; + if (index == 0) { + instruction_ = out; + if (out == 0xC0) { + reset(); + } else if (out == 0x81) { + requestToSend(); + } + return 0x00; + } + switch (instruction_) { + case 0x03: // READ + if (index == 1) { + address_ = out; + return 0x00; + } + return readByte(); + case 0x02: // WRITE + if (index == 1) { + address_ = out; + } else { + writeRegister(address_++, out, 0xFF); + } + return 0x00; + case 0x05: // BIT MODIFY + if (index == 1) { + address_ = out; + } else if (index == 2) { + mask_ = out; + } else if (index == 3) { + writeRegister(address_, out, mask_); + } + return 0x00; + default: + return 0x00; + } + } + + void deselect() override + { + conditioned_ = instruction_ == 0x03 && read_count_ == 2 && read_all_zero_; + } + + bool interruptAsserted() override {return (regs[kCanIntF] & regs[kCanIntE]) != 0;} + uint32_t millis() override {return now_ms++;} + void delayMs(const uint32_t ms) override {now_ms += ms;} + + uint8_t mode() const {return regs[kCanStat] & 0xE0;} + + // A frame arriving from the bus, into RXB0 or (rollover) RXB1. + bool deliver( + const Frame & frame, const uint8_t sidl_flags = 0, const bool valid_can = true) + { + if (!valid_can) { + ++regs[kRec]; + regs[kCanIntF] |= 0x80; // MERRF + } + uint8_t base = 0; + uint8_t flag = 0; + if ((regs[kCanIntF] & 0x01) == 0) { + base = kRxb0Sidh; + flag = 0x01; + } else if ((regs[kRxb0Ctrl] & 0x04) != 0 && (regs[kCanIntF] & 0x02) == 0) { + base = kRxb1Sidh; + flag = 0x02; + } else { + // Measured on the bench chip: with rollover, a frame finding both buffers full sets + // RX0OVR (and ERRIF), not RX1OVR. + regs[kEflg] |= 0x40; + regs[kCanIntF] |= 0x20; + return false; + } + // DS20001801J section 4.2.2: debug RXM=11 also accepts partial, errored messages. + if (!valid_can && (regs[base - 1] & 0x60) != 0x60) { + return false; + } + regs[base] = static_cast(frame.id >> 3); + regs[base + 1] = static_cast(((frame.id & 0x07) << 5) | sidl_flags); + regs[base + 2] = 0; + regs[base + 3] = 0; + regs[base + 4] = frame.dlc; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + regs[base + 5 + i] = frame.data[i]; + } + regs[kCanIntF] |= flag; + return true; + } + + // The pending TXB0 frame got its ACK. + void acknowledge() + { + if (regs[kTxb0Ctrl] & 0x08) { + transmitted.push_back(pending_); + regs[kTxb0Ctrl] &= static_cast(~0x08); + } + } + + uint8_t regs[128]; + // Frames on the wire: each lands the moment a receive buffer is freed. + std::vector arriving; + Link link = Link::kSlipping; + bool present = true; + bool auto_ack = true; + uint32_t now_ms = 1000; + uint32_t transfers = 0; + uint32_t aborted = 0; + std::vector transmitted; + std::function on_read; + +private: + void reset() + { + // Data registers keep what they held; only the control registers have reset values. + regs[kCanStat] = 0x80; + regs[kCanCtrl] = 0x87; + for (uint8_t a = 0x28; a <= 0x2D; ++a) { + regs[a] = 0; + } + regs[kTec] = 0; + regs[kTec + 1] = 0; + regs[kTxb0Ctrl] = 0; + regs[kRxb0Ctrl] = 0; + regs[0x70] = 0; + } + + uint8_t readByte() + { + if (on_read) { + on_read(address_ & 0x7F); + } + const uint8_t value = regs[address_ & 0x7F]; + const uint8_t next = regs[(address_ + 1) & 0x7F]; + ++address_; + ++read_count_; + read_all_zero_ = read_all_zero_ && value == 0; + const bool clean = link == Link::kClean || + (link == Link::kSlipping && read_count_ == 1 && conditioned_); + return clean ? value : static_cast((value << 1) | (next >> 7)); + } + + void writeRegister(const uint8_t address, const uint8_t value, const uint8_t mask) + { + const uint8_t a = address & 0x7F; + const uint8_t merged = static_cast((regs[a] & ~mask) | (value & mask)); + if (a == kCanStat) { + return; // read-only + } + if (a == kCanCtrl) { + regs[a] = merged; + regs[kCanStat] = static_cast((regs[kCanStat] & 0x1F) | (merged & 0xE0)); + return; + } + if (a == kCanIntF) { + const bool freed = (regs[a] & 0x03 & ~merged) != 0; + regs[a] = merged; + if (freed && !arriving.empty()) { + deliver(arriving.front()); + arriving.erase(arriving.begin()); + } + return; + } + if (a == kTxb0Ctrl) { + if ((regs[a] & 0x08) && !(merged & 0x08)) { + ++aborted; + regs[a] = static_cast((merged & ~0x08) | 0x40); // ABTF + return; + } + regs[a] = merged; + return; + } + regs[a] = merged; + } + + void requestToSend() + { + Frame frame; + frame.id = static_cast((regs[0x31] << 3) | (regs[0x32] >> 5)); + frame.dlc = regs[0x35] & 0x0F; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + frame.data[i] = i < frame.dlc ? regs[0x36 + i] : 0; + } + regs[kTxb0Ctrl] = 0x08; + if (mode() == 0x40) { + regs[kTxb0Ctrl] = 0; + deliver(frame); + return; + } + pending_ = frame; + if (auto_ack) { + acknowledge(); + } + } + + size_t index_ = 0; + uint8_t instruction_ = 0; + uint8_t address_ = 0; + uint8_t mask_ = 0; + uint8_t read_count_ = 0; + bool read_all_zero_ = true; + bool conditioned_ = false; + Frame pending_; +}; + +Frame makeFrame(const uint16_t id, std::initializer_list bytes) +{ + Frame frame; + frame.id = id; + for (const uint8_t b : bytes) { + frame.data[frame.dlc++] = b; + } + return frame; +} + +void expectSame(const Frame & expected, const Frame & got) +{ + EXPECT_EQ(expected.id, got.id); + ASSERT_EQ(expected.dlc, got.dlc); + for (uint8_t i = 0; i < expected.dlc; ++i) { + EXPECT_EQ(expected.data[i], got.data[i]) << "byte " << int(i); + } +} + +TEST(Mcp2515Timing, EightQuantaPerBit) +{ + uint8_t c1 = 0; + uint8_t c2 = 0; + uint8_t c3 = 0; + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 500000, c1, c2, c3)); + EXPECT_EQ(0x00, c1); // the register set the bench drives answered at, AA_MCP2515's 8 MHz/500k + EXPECT_EQ(0x91, c2); + EXPECT_EQ(0x01, c3); + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 250000, c1, c2, c3)); + EXPECT_EQ(0x01, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 125000, c1, c2, c3)); + EXPECT_EQ(0x03, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(16000000, 1000000, c1, c2, c3)); + EXPECT_EQ(0x00, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(16000000, 500000, c1, c2, c3)); + EXPECT_EQ(0x01, c1); + EXPECT_FALSE(Mcp2515CanTransport::timing(8000000, 1000000, c1, c2, c3)); + EXPECT_FALSE(Mcp2515CanTransport::timing(8000000, 0, c1, c2, c3)); +} + +TEST(Mcp2515Fake, BurstAndUnconditionedReadsSlip) +{ + // Guards the model itself: without the method, the transport tests would prove nothing. + FakeMcp2515 chip; + chip.regs[0x40] = 0x31; + chip.regs[0x41] = 0xFF; + chip.regs[0x42] = 0x00; + chip.select(); + chip.transfer(0x03); + chip.transfer(0x40); + const uint8_t first = chip.transfer(0); + const uint8_t second = chip.transfer(0); + chip.deselect(); + EXPECT_NE(0x31, first); + EXPECT_NE(0xFF, second); +} + +TEST(Mcp2515Transport, BeginConfiguresSelfTestsAndJoinsTheBus) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + EXPECT_TRUE(can.isOpen()); + EXPECT_EQ(500000u, can.bitrate()); + EXPECT_EQ(0x00, chip.mode()); + EXPECT_EQ(0x00, chip.regs[kCnf1]); + EXPECT_EQ(0x91, chip.regs[kCnf1 - 1]); + EXPECT_EQ(0x01, chip.regs[kCnf1 - 2]); + EXPECT_EQ(0x03, chip.regs[kCanIntE]); + EXPECT_EQ(0x04, chip.regs[kRxb0Ctrl]); + EXPECT_EQ(0x00, chip.regs[kRxb1Ctrl]); + // Reset does not initialize these in the fake; configuration must set every filter and + // both complete masks, including the standard-frame data-byte mask bits. + for (const uint8_t base : {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}) { + for (uint8_t i = 0; i < 4; ++i) { + EXPECT_EQ(0, chip.regs[base + i]) << "register " << int(base + i); + } + } + for (uint8_t i = 0; i < 8; ++i) { + EXPECT_EQ(0x00, chip.regs[kTxb2Data + i]); + } + EXPECT_TRUE(can.lastSelfTest().passed()); + EXPECT_EQ(Mcp2515CanTransport::kSelfTestFrames, can.lastSelfTest().frames); + EXPECT_TRUE(chip.transmitted.empty()); // the self-test never reaches the bus + EXPECT_EQ(0u, can.linkFaults()); +} + +TEST(Mcp2515Transport, BeginAgainAtTheSameBitrateIsANoOp) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const uint32_t transfers = chip.transfers; + EXPECT_TRUE(can.begin(500000)); + EXPECT_EQ(transfers, chip.transfers); +} + +TEST(Mcp2515Transport, RefusesAMissingChipAnUnreachableBitrateAndABrokenLink) +{ + FakeMcp2515 absent; + absent.present = false; + Mcp2515CanTransport no_chip(absent, 8000000); + EXPECT_FALSE(no_chip.begin(500000)); + EXPECT_FALSE(no_chip.isOpen()); + EXPECT_EQ(1u, no_chip.linkFaults()); + + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + EXPECT_FALSE(can.begin(1000000)); + EXPECT_FALSE(can.isOpen()); + + FakeMcp2515 broken; + broken.link = FakeMcp2515::Link::kBroken; + Mcp2515CanTransport noisy(broken, 8000000); + EXPECT_FALSE(noisy.begin(500000)); + EXPECT_FALSE(noisy.isOpen()); + EXPECT_EQ(0x80, broken.mode()); // left off the bus +} + +TEST(Mcp2515Transport, ReceivesExactFramesFromBothBuffersInOrder) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + + const Frame reply = makeFrame(3, {0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x38}); + const Frame ones = makeFrame(0x7FF, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}); + ASSERT_TRUE(chip.deliver(reply)); + ASSERT_TRUE(chip.deliver(ones)); // RXB0 full: rolls over into RXB1 + ASSERT_TRUE(can.receive(got, 0)); + expectSame(reply, got); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(ones, got); + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_FALSE(chip.interruptAsserted()); + + const Frame short_frame = makeFrame(0x123, {0x80}); + const Frame empty = makeFrame(0x001, {}); + ASSERT_TRUE(chip.deliver(short_frame)); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(short_frame, got); + ASSERT_TRUE(chip.deliver(empty)); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(empty, got); + EXPECT_EQ(4u, can.busLoad().totalFrames()); +} + +TEST(Mcp2515Transport, KeepsArrivalOrderWhenAFrameLandsAfterFlagClear) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 0x01}); + const Frame b = makeFrame(3, {0x31, 0x03}); + const Frame c = makeFrame(4, {0x31, 0x04}); + const Frame d = makeFrame(5, {0x31, 0x05}); + ASSERT_TRUE(chip.deliver(a)); + ASSERT_TRUE(chip.deliver(b)); // RXB1 + // C lands in RXB0 as soon as A is read out of it, while B still waits in RXB1; D then rolls + // over into RXB1 once B is read. + chip.arriving = {c, d}; + for (const Frame & expected : {a, b, c, d}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_TRUE(chip.arriving.empty()); +} + +TEST(Mcp2515Transport, PendingBuffersStayLockedDuringRegisterReads) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 1, 2, 3, 4, 5, 6, 7}); + const Frame b = makeFrame(3, {0xF5, 0x02, 0xFA}); + ASSERT_TRUE(chip.deliver(a)); + ASSERT_TRUE(chip.deliver(b)); + bool injected = false; + chip.on_read = [&](const uint8_t address) { + if (!injected && address == kRxb0Sidh + 5) { + injected = true; + EXPECT_EQ(0x03, chip.regs[kCanIntF] & 0x03); + EXPECT_FALSE(chip.deliver(makeFrame(5, {0xF5, 0x02, 0xFC}))); + } + }; + for (const Frame & expected : {a, b}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + EXPECT_TRUE(injected); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_GT(can.receiveOverflows(), 0u); +} + +TEST(Mcp2515Fake, DebugReceiveModeExposesErroredCanMessages) +{ + FakeMcp2515 chip; + chip.regs[kRxb0Ctrl] = 0x64; + chip.regs[kRxb1Ctrl] = 0x60; + // Recorded at 1793447327.347629 in the bench host log. Its MKS checksum passes; + // the log does not establish whether the original CAN message had a protocol error. + const Frame partial = makeFrame(5, {0x31, 0x02, 0xFC, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + mks::Message message; + ASSERT_EQ(mks::ParseResult::kOk, mks::parseFrame(partial, message)); + ASSERT_TRUE(chip.deliver(partial, 0, false)); + ASSERT_TRUE(chip.deliver(partial, 0, false)); + EXPECT_EQ(0x03, chip.regs[kCanIntF] & 0x03); +} + +TEST(Mcp2515Transport, RejectsErroredCanMessagesEvenWithValidMksChecksums) +{ + for (const bool rollover : {false, true}) { + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame good = makeFrame(5, {0x31, 0xFF, 0xFF, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + const Frame partial = makeFrame(5, {0x31, 0x02, 0xFC, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + if (rollover) { + ASSERT_TRUE(chip.deliver(good)); + } + ASSERT_FALSE(chip.deliver(partial, 0, false)); + ASSERT_TRUE(chip.deliver(good)); + for (int i = 0; i < (rollover ? 2 : 1); ++i) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(good, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_GT(can.errorEvents(), 0u); + EXPECT_EQ(1, can.receiveErrorCount()); + } +} + +TEST(Mcp2515Transport, DetectsAndRepairsUnexpectedDebugReceiveMode) +{ + for (const uint8_t ctrl : {kRxb0Ctrl, kRxb1Ctrl}) { + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[ctrl] |= 0x60; + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_GE(can.linkFaults(), 2u); + EXPECT_EQ(1u, can.restarts()); + EXPECT_EQ(0, chip.regs[kRxb0Ctrl] & 0x60); + EXPECT_EQ(0, chip.regs[kRxb1Ctrl] & 0x60); + } +} + +TEST(Mcp2515Transport, ReceiveStatusBitsDoNotTriggerLinkFaults) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[kRxb0Ctrl] |= 0x0B; // RXRTR, BUKT1, FILHIT0 + chip.regs[kRxb1Ctrl] |= 0x0F; // RXRTR, FILHIT + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_EQ(0u, can.linkFaults()); + EXPECT_EQ(0u, can.restarts()); +} + +TEST(Mcp2515Transport, VerifiesEveryFilterAndMaskByteBeforeJoiningTheBus) +{ + for (const uint8_t base : {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}) { + for (uint8_t i = 0; i < 4; ++i) { + FakeMcp2515 chip; + chip.on_read = [&](const uint8_t address) { + if (address == base + i) { + chip.regs[address] |= 0x01; + } + }; + Mcp2515CanTransport can(chip, 8000000); + EXPECT_FALSE(can.begin(500000)) << "register " << int(base + i); + EXPECT_EQ(0x80, chip.mode()); + EXPECT_TRUE(chip.transmitted.empty()); + EXPECT_GT(can.linkFaults(), 0u); + } + } +} + +TEST(Mcp2515Transport, ServiceQueuesFramesBeyondTheChipsTwoBuffers) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + std::vector sent; + for (uint8_t n = 0; n < Mcp2515CanTransport::kReceiveQueueCapacity + 2; n += 2) { + for (uint8_t k = 0; k < 2; ++k) { + sent.push_back(makeFrame(static_cast(0x100 + n + k), {n, k})); + ASSERT_TRUE(chip.deliver(sent.back())); + } + can.service(); + } + // The queue is full and the chip holds the last two; one more frame is lost and counted. + EXPECT_TRUE(chip.interruptAsserted()); + EXPECT_FALSE(chip.deliver(makeFrame(0x7FF, {}))); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_EQ(1u, can.receiveOverflows()); + for (const Frame & expected : sent) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); +} + +TEST(Mcp2515Transport, DropsExtendedAndRemoteFrames) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + ASSERT_TRUE(chip.deliver(makeFrame(5, {1, 2}), 0x08)); // IDE + ASSERT_TRUE(chip.deliver(makeFrame(6, {}), 0x10)); // SRR: standard remote frame + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_EQ(2u, can.droppedFrames()); + EXPECT_FALSE(chip.interruptAsserted()); +} + +TEST(Mcp2515Transport, SendsInOrderThroughOneBuffer) +{ + FakeMcp2515 chip; + chip.auto_ack = false; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame first = makeFrame(1, {0x31, 0x32}); + const Frame second = makeFrame(4, {0xF5, 0x01, 0x2C, 0x02, 0x00, 0x40, 0x00, 0x60}); + ASSERT_TRUE(can.send(first)); + EXPECT_FALSE(can.send(second)); // TXB0 still busy + chip.acknowledge(); + ASSERT_TRUE(can.send(second)); + chip.acknowledge(); + ASSERT_EQ(2u, chip.transmitted.size()); + expectSame(first, chip.transmitted[0]); + expectSame(second, chip.transmitted[1]); + EXPECT_EQ(0u, can.failedWrites()); + + Frame invalid; + invalid.id = 0x800; + EXPECT_FALSE(can.send(invalid)); +} + +TEST(Mcp2515Transport, AbortsAFrameNobodyAcknowledges) +{ + FakeMcp2515 chip; + chip.auto_ack = false; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + ASSERT_TRUE(can.send(makeFrame(1, {0xF5, 0x00}))); + const uint32_t sent_at = chip.now_ms; + while (chip.now_ms - sent_at < Mcp2515CanTransport::kTransmitTimeoutMs + 5) { + can.service(); + } + EXPECT_EQ(1u, chip.aborted); + EXPECT_EQ(1u, can.failedWrites()); + chip.acknowledge(); // the drive powers up: the stale frame must not go out now + EXPECT_TRUE(chip.transmitted.empty()); + chip.auto_ack = true; + ASSERT_TRUE(can.send(makeFrame(1, {0x31, 0x32}))); + ASSERT_EQ(1u, chip.transmitted.size()); +} + +TEST(Mcp2515Transport, CountsErrorStatesAndReceiveOverflows) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[kTec] = 128; + chip.regs[kEflg] = 0x15 | 0x40; // error passive and warning, RXB0 overflowed + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_EQ(1u, can.errorEvents()); + EXPECT_EQ(1u, can.receiveOverflows()); + EXPECT_EQ(128, can.transmitErrorCount()); + EXPECT_EQ(0x15, can.errorFlags()); + EXPECT_EQ(0x15, chip.regs[kEflg]); // overflow flag cleared, state flags are the chip's +} + +TEST(Mcp2515Transport, RestartsAChipThatLostItsConfiguration) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + // A brownout resets the chip: configuration mode, timing registers cleared. + chip.select(); + chip.transfer(0xC0); + chip.deselect(); + ASSERT_EQ(0x80, chip.mode()); + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_GE(can.linkFaults(), 2u); + EXPECT_EQ(1u, can.restarts()); + EXPECT_TRUE(can.isOpen()); + EXPECT_EQ(0x00, chip.mode()); + EXPECT_EQ(0x00, chip.regs[0x2A]); + EXPECT_EQ(0x91, chip.regs[0x29]); +} + +TEST(Mcp2515Transport, EndLeavesTheBus) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + can.end(); + EXPECT_FALSE(can.isOpen()); + EXPECT_EQ(0x80, chip.mode()); + EXPECT_FALSE(can.send(makeFrame(1, {0x31, 0x32}))); + for (int i = 0; i < 300; ++i) { + can.service(); + } + EXPECT_EQ(0x80, chip.mode()); +} + +} // namespace +} // namespace waybionic diff --git a/waybionic_rviz_plugins/CMakeLists.txt b/waybionic_rviz_plugins/CMakeLists.txt index 9e133adf..50a6f8f1 100644 --- a/waybionic_rviz_plugins/CMakeLists.txt +++ b/waybionic_rviz_plugins/CMakeLists.txt @@ -43,10 +43,16 @@ target_include_directories(${PROJECT_NAME} PUBLIC target_link_libraries(${PROJECT_NAME} Qt5::Widgets) ament_target_dependencies(${PROJECT_NAME} ${THIS_PACKAGE_INCLUDE_DEPENDS}) +add_executable(ground_station_rviz src/ground_station_rviz.cpp) +target_compile_features(ground_station_rviz PRIVATE cxx_std_17) +target_link_libraries(ground_station_rviz Qt5::Widgets) +ament_target_dependencies(ground_station_rviz rclcpp rviz_common) + if(APPLE) # RoboStack exports optional Python type-support dylibs through RViz targets. # Do not retain those unused dylibs in this C++-only plugin. target_link_options(${PROJECT_NAME} PRIVATE "LINKER:-dead_strip_dylibs") + target_link_options(ground_station_rviz PRIVATE "LINKER:-dead_strip_dylibs") endif() pluginlib_export_plugin_description_file(rviz_common plugin_description.xml) @@ -59,6 +65,10 @@ install( RUNTIME DESTINATION bin ) +install(TARGETS ground_station_rviz + DESTINATION lib/${PROJECT_NAME} +) + install( DIRECTORY include/ DESTINATION include/${PROJECT_NAME} diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index 3044505e..ba759dab 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -2,6 +2,11 @@ RViz2-native diagnostics and monitoring UI for WayBionic. This package is diagnostics-only: it provides the engineer monitoring panel, mock/live diagnostics switching, and a temporary `/diagnostics` publisher for local validation. +It also provides `ground_station_rviz`, the ground station's RViz entry point. +It uses RViz's normal application initialization and then maximizes the window +with Qt, rather than entering RViz's panel-hiding fullscreen mode. It accepts +the normal RViz and ROS arguments and does not send motor commands. + Monitoring-only scope: - No motor commands from this package. diff --git a/waybionic_rviz_plugins/src/ground_station_rviz.cpp b/waybionic_rviz_plugins/src/ground_station_rviz.cpp new file mode 100644 index 00000000..1d90eebf --- /dev/null +++ b/waybionic_rviz_plugins/src/ground_station_rviz.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +#include +#include + +#include "rclcpp/rclcpp.hpp" +#include "rviz_common/logging.hpp" +#include "rviz_common/ros_integration/ros_client_abstraction.hpp" +#include "rviz_common/visualization_frame.hpp" +#include "rviz_common/visualizer_app.hpp" + +int main(int argc, char ** argv) +{ + auto arguments = rclcpp::remove_ros_arguments(argc, argv); + // RViz's Ogre renderer needs X11 on Wayland unless the operator overrides Qt. + if (qEnvironmentVariable("XDG_SESSION_TYPE") == "wayland" && + !qEnvironmentVariableIsSet("QT_QPA_PLATFORM") && + std::find(arguments.begin(), arguments.end(), "-platform") == arguments.end()) + { + qputenv("QT_QPA_PLATFORM", "xcb"); + } + std::vector qt_arguments; + for (auto & argument : arguments) { + qt_arguments.push_back(argument.data()); + } + int qt_argc = static_cast(qt_arguments.size()); + qt_arguments.push_back(nullptr); + QApplication application(qt_argc, qt_arguments.data()); + const auto logger = rclcpp::get_logger("rviz2"); + rviz_common::set_logging_handlers( + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_DEBUG(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_INFO(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_WARN(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_ERROR(logger, "%s", message.c_str()); + }); + rviz_common::VisualizerApp visualizer( + std::make_unique()); + visualizer.setApp(&application); + if (!visualizer.init(argc, argv)) { + return EXIT_FAILURE; + } + for (auto * widget : QApplication::topLevelWidgets()) { + if (auto * frame = qobject_cast(widget)) { + frame->showMaximized(); + return application.exec(); + } + } + qCritical("RViz initialized without a visualization window"); + return EXIT_FAILURE; +} diff --git a/waybionic_teleop/config/arm_drives.yaml b/waybionic_teleop/config/arm_drives.yaml index 9a4a448e..4ac48950 100644 --- a/waybionic_teleop/config/arm_drives.yaml +++ b/waybionic_teleop/config/arm_drives.yaml @@ -8,10 +8,12 @@ sim_arm_drives: ros__parameters: rate_hz: 120.0 - # 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. + # Every drive and the carrier must run CAN at this rate. MKS drives ship at 500k (mks_setup or + # CanRate on a drive's screen changes it), and the carrier's MCP2515 module, with its 8 MHz + # crystal, runs 500 kbit/s at most. Six drives at 120 Hz load the bus about 60% at 500 kbit/s. + bitrate: 500000 + # The carrier's link is native USB, which ignores the baud rate, except that 1200 hands the + # port back for an upload (UsbHandBack.h). 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. @@ -54,24 +56,25 @@ sim_arm_drives: gear_ratio: 26.0 joints: [joint_2] factors: [1.0] - # SERVO42D + # SERVO42D. Its motor counts down as the elbow turns the URDF's positive way (bench arm). elbow: can_id: 3 gear_ratio: 26.0 joints: [joint_3] - factors: [1.0] + factors: [-1.0] # SERVO42D, left side gear: pitch minus roll wrist_left: can_id: 4 gear_ratio: 3.0 joints: [joint_4, joint_5] factors: [1.0, -1.0] - # SERVO42D, right side gear: pitch plus roll + # SERVO42D, right side gear: pitch plus roll. Its motor counts the opposite way to the left + # one (bench arm), so pitch turns the two encoders opposite ways and roll the same way. wrist_right: can_id: 5 gear_ratio: 3.0 joints: [joint_4, joint_5] - factors: [1.0, 1.0] + factors: [-1.0, -1.0] tool: can_id: 6 gear_ratio: 1.0 diff --git a/waybionic_teleop/config/xbox_teleop.yaml b/waybionic_teleop/config/xbox_teleop.yaml index 8af6fd18..10c18b31 100644 --- a/waybionic_teleop/config/xbox_teleop.yaml +++ b/waybionic_teleop/config/xbox_teleop.yaml @@ -22,14 +22,19 @@ xbox_teleop: tilt_up_button: dpad_right tilt_down_button: dpad_left groups: [base, upper, cartesian, incision] + # Left stick right turns joint_1 positive (counter-clockwise seen from above), which is to + # the right of an operator facing the arm. Right stick up lifts the elbow (joint_3 negative). base: joints: [joint_1, joint_2, joint_3] axes: [left_x, left_y, right_y] - scales: [1.0, 1.0, 1.0] + scales: [-1.0, 1.0, -1.0] + # Left stick up lifts the elbow (joint_3 negative), as in the base group. Right stick up tips + # the wrist up (joint_4 negative), and right turns the wrist roll positive (counter-clockwise + # from above at the zero pose), as the operator preferred on the bench arm. upper: joints: [joint_2, joint_3, joint_4, joint_5] axes: [left_x, left_y, right_y, right_x] - scales: [1.0, 1.0, 1.0, 1.0] + scales: [1.0, -1.0, -1.0, -1.0] # Straight tool-tip moves in base_link: forward (x), left (y), up (z), then tool roll. The # lock button keeps only the strongest of x, y and z; the tilt buttons pivot the tool about # its tip. diff --git a/waybionic_teleop/package.xml b/waybionic_teleop/package.xml index fb6395f0..1bc5c0bc 100644 --- a/waybionic_teleop/package.xml +++ b/waybionic_teleop/package.xml @@ -20,6 +20,8 @@ python3-can python3-serial + + python3-yaml ament_flake8 ament_pep257 diff --git a/waybionic_teleop/test/conftest.py b/waybionic_teleop/test/conftest.py index 2885590f..01c0267b 100644 --- a/waybionic_teleop/test/conftest.py +++ b/waybionic_teleop/test/conftest.py @@ -29,7 +29,9 @@ def write(self, data): 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': + if line == b'V': + self.inbox += b'V0100\r' + elif line[:1] != b't': # A command, or the empty line after a frame. self.inbox += b'\r' elif line in self.refuse: @@ -47,6 +49,20 @@ def usb_carrier(): return CarrierPort +# The bench arm: the shoulder motor is not wired and the shoulder is fixed upright; no tool. +BENCH_PROFILE = """\ +fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] +locked_joints: {joint_2: 0.0, tool_grip: 0.0} +""" + + +@pytest.fixture +def bench_profile(tmp_path): + path = tmp_path / 'arm_profile.yaml' + path.write_text(BENCH_PROFILE, encoding='utf-8') + return str(path) + + def flatten(values, prefix=''): flat = {} for key, value in values.items(): diff --git a/waybionic_teleop/test/test_arm_profile.py b/waybionic_teleop/test/test_arm_profile.py new file mode 100644 index 00000000..b92709e7 --- /dev/null +++ b/waybionic_teleop/test/test_arm_profile.py @@ -0,0 +1,71 @@ +"""An arm profile says which drives one arm has and holds still the joints it lacks.""" + +import pytest + +from waybionic_teleop.arm_profile import ( + ArmProfile, + fit_drive_parameters, + load_profile, + profile_from_dict, +) + + +def test_no_profile_fits_every_drive(parameters): + params = parameters('arm_drives.yaml', 'sim_arm_drives') + assert load_profile('') == ArmProfile() + assert fit_drive_parameters(params, ArmProfile()) == params + + +def test_the_bench_profile_runs_four_drives_and_holds_the_shoulder(parameters, bench_profile): + params = parameters('arm_drives.yaml', 'sim_arm_drives') + profile = load_profile(bench_profile) + assert profile.locked_joints == {'joint_2': 0.0, 'tool_grip': 0.0} + fitted = fit_drive_parameters(params, profile) + assert fitted['drives'] == ['base_yaw', 'elbow', 'wrist_left', 'wrist_right'] + assert params['drives'][1] == 'shoulder' + + +@pytest.mark.parametrize('data, message', [ + ([], 'must be a mapping'), + ({'fitted': ['base_yaw']}, 'unknown keys'), + ({'fitted_drives': []}, 'distinct drive names'), + ({'fitted_drives': ['elbow', 'elbow']}, 'distinct drive names'), + ({'fitted_drives': 'elbow'}, 'distinct drive names'), + ({'locked_joints': ['joint_2']}, 'map joint names'), + ({'locked_joints': {'joint_2': float('nan')}}, 'finite angle'), + ({'locked_joints': {'joint_2': True}}, 'finite angle'), + ({'locked_joints': {'joint_2': 'up'}}, 'finite angle'), +]) +def test_a_malformed_profile_is_refused(data, message): + with pytest.raises(ValueError, match=message): + profile_from_dict(data) + + +def test_an_unreadable_profile_is_refused(tmp_path): + with pytest.raises(ValueError, match='cannot read'): + load_profile(str(tmp_path / 'missing.yaml')) + broken = tmp_path / 'broken.yaml' + broken.write_text('fitted_drives: [base_yaw\n', encoding='utf-8') + with pytest.raises(ValueError, match='cannot read'): + load_profile(str(broken)) + + +def test_an_empty_profile_file_fits_every_drive(tmp_path): + empty = tmp_path / 'empty.yaml' + empty.write_text('', encoding='utf-8') + assert load_profile(str(empty)) == ArmProfile() + + +@pytest.mark.parametrize('profile, message', [ + # Nothing would report where the shoulder is. + (ArmProfile(('base_yaw', 'elbow', 'wrist_left', 'wrist_right', 'tool')), r"\['joint_2'\]"), + (ArmProfile(('base_yaw', 'elbow', 'gripper')), 'lacks'), + # A fitted drive would move a joint the model holds still. + (ArmProfile(None, {'joint_1': 0.0}), 'moved by fitted drives'), + # One wrist motor moves both wrist joints, so neither can be locked while it is fitted. + (ArmProfile(('base_yaw', 'shoulder', 'elbow', 'wrist_left', 'tool'), {'joint_4': 0.0}), + 'moved by fitted drives'), +]) +def test_a_profile_that_does_not_match_the_map_is_refused(parameters, profile, message): + with pytest.raises(ValueError, match=message): + fit_drive_parameters(parameters('arm_drives.yaml', 'sim_arm_drives'), profile) diff --git a/waybionic_teleop/test/test_can_drives.py b/waybionic_teleop/test/test_can_drives.py index ebec04bf..e126d818 100644 --- a/waybionic_teleop/test/test_can_drives.py +++ b/waybionic_teleop/test/test_can_drives.py @@ -26,7 +26,7 @@ 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 +from waybionic_teleop.sim_arm_drives_node import HOLD_RPM, QUIET_BEFORE_ZERO_S, SimArmDrives from waybionic_teleop.sim_drives import SimulatedServo BITRATE = 1000000 @@ -101,6 +101,19 @@ def positions(node): return node.map.to_positions(node.counts) +def assert_holding(node): + """Each drive on the bus is stopped, or runs on only to its hold near where it stopped.""" + # Two ticks at full speed past the count, and a count of rounding. + reach = 2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + 31 + for index, drive in enumerate(node.map.drives): + servo = node.bus.drives.get(drive.can_id) + if servo is None: + continue + assert servo.target in (None, node.held[index]) + assert (servo.rpm == 0.0 if servo.target is None + else abs(servo.target - servo.axis) <= reach and servo.speed <= HOLD_RPM) + + def press_start(node): """Load the URDF limits, then release and press Start the way teleop reports it.""" node.on_description(String(data=URDF)) @@ -111,7 +124,7 @@ def press_start(node): def command(node, speed=1.0, **targets): """Refresh the enable and send one complete command toward the named joint targets.""" current = positions(node) - goal = {**(node.commanded or current), **targets} + goal = {**(node.commanded or current), **node.locked, **targets} velocities = [math.copysign(speed, goal[joint] - current[joint]) if joint in targets else 0.0 for joint in goal] node.on_enabled(Bool(data=True)) @@ -264,8 +277,9 @@ 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, through 3:1 belts. - assert servos[4].axis == pytest.approx(servos[5].axis) + # Wrist pitch turns the two differential motors through 3:1 belts, the right one + # mounted to count the opposite way. + assert servos[4].axis == pytest.approx(-servos[5].axis) 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) @@ -312,6 +326,9 @@ def write(self, data): for reply in servo.step(now - self.last)] self.last = now for line in bytes(data).split(b'\r')[:-1]: + if line == b'V': + self.output += b'V0100\r' + continue 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) @@ -357,7 +374,7 @@ def test_the_host_drives_the_arm_through_the_carrier(make_node, carrier_port, mo 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 port.writes[0] == b'V\rC\rS6\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)) @@ -395,7 +412,7 @@ def pressed_mid_move(): 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.reopens == 1 and port.writes.count(b'V\rC\rS6\rO\r') == 2 assert node.bus.refused == 0 @@ -431,6 +448,35 @@ def busy(can_id, data): assert node.bus.refused > 0 and node.bus.errors == 0 and node.bus_errors == 0 +def test_an_arm_without_its_shoulder_drive_zeroes_and_moves_through_the_carrier( + make_node, carrier_port, monkeypatch, bench_profile): + port = carrier_port + # Only the drives the bench arm has wired answer; a frame for any other fails the test. + del port.servos[2] + port.flags = carrier.ESTOP_WIRED + node, executor = make_node(interface='slcan', channel='/dev/cu.usbmodem1101', + arm_profile=bench_profile) + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + 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, joint_4=0.2) + assert dict(zip(states[-1].name, states[-1].position))['joint_2'] == 0.0 + reports = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', reports.append) + node.report() + assert all(row.level == DiagnosticStatus.OK for row in reports[-1].status), [ + (row.name, row.message) for row in reports[-1].status + if row.level != DiagnosticStatus.OK] + sent = {int(line[1:4], 16) for data in port.writes for line in data.split(b'\r') + if line[:1] == b't'} + assert sent == {1, 3, 4, 5} + assert node.bus.errors == 0 and node.bus.refused == 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() @@ -482,7 +528,7 @@ def commanding_until_lost(): assert spin_until(executor, commanding_until_lost) assert node.commanded is None and not node.zeroed[2] and not node.authorized # Every other drive was told to stop where it is. - assert all(servo.target is None for servo in node.bus.drives.values()) + assert_holding(node) node.bus.drives[3] = elbow assert spin_until(executor, lambda: not node.lost[2] and not node.unconfirmed[2]) @@ -498,6 +544,29 @@ def commanding_until_lost(): assert node.authorized +def test_a_relaunch_keeps_the_zero_while_the_drives_stay_powered( + make_node, mock_drives, tmp_path): + channel, servos = mock_drives + saved = tmp_path / 'drive_zero.yaml' + servos[1].axis = mks_can.COUNTS_PER_REV / 2 + node, executor = make_node(interface='virtual', channel=channel, drives=ARM_DRIVES, + zero_state=str(saved)) + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + assert zero(node).success + assert spin_until(executor, saved.exists) + # Pushed by hand while the station is down; raw and zeroed counts move alike. + servos[1].axis = 1234.0 + relaunched, executor = make_node(interface='virtual', channel=channel, drives=ARM_DRIVES, + zero_state=str(saved)) + assert not any(relaunched.zeroed) + assert spin_until(executor, lambda: all(relaunched.zeroed)) + assert spin_until(executor, lambda: relaunched.commanded is not None) + assert relaunched.counts[0] == 1234 + press_start(relaunched) + assert relaunched.authorized, relaunched.stop_reason + assert relaunched.bus.errors == 0 and relaunched.bus_errors == 0 + + def test_commands_that_stop_mid_move_stop_the_drives(make_node): node, executor = make_node(max_rpm=6) assert spin_until(executor, lambda: node.commanded is not None) @@ -567,7 +636,7 @@ def test_a_command_without_speeds_stops_the_drives(make_node): targets = dict(node.commanded) node.on_command(JointState(name=list(targets), position=list(targets.values()))) assert not node.authorized and node.rejected == 1 - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) stopped = positions(node)['joint_1'] spin_for(executor, 0.5) assert positions(node)['joint_1'] == pytest.approx(stopped, abs=1e-3) @@ -625,7 +694,7 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): assert node.bus.drives[1].target is not None node.on_command(JointState()) assert not node.authorized and node.rejected == 1 - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) response = zero(node) assert not response.success and 'still arriving' in response.message # Neither an invalid nor a valid command moves the arm again without a fresh Start. @@ -633,7 +702,7 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): command(node, joint_1=0.3) spin_for(executor, 0.1) assert not node.authorized - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) press_start(node) # 6 rpm turns the base 0.024 rad/s through its reducer. assert move(node, executor, joint_1=0.01) diff --git a/waybionic_teleop/test/test_collision.py b/waybionic_teleop/test/test_collision.py index b083c26b..4fafc204 100644 --- a/waybionic_teleop/test/test_collision.py +++ b/waybionic_teleop/test/test_collision.py @@ -88,11 +88,11 @@ def test_teleop_backs_out_of_a_collision_but_never_goes_deeper(parameters, check teleop.update(*sample(button), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] == pytest.approx(start['joint_3']) assert 'forearm_link: table' in teleop.blocked for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] < start['joint_3'] - 0.1 @@ -106,8 +106,8 @@ def test_teleop_stops_before_the_forearm_reaches_the_table(parameters, check): assert teleop.active_group.name == 'upper' stopped = False for _ in range(round(4.0 / DT)): - # Left stick up bends the elbow down towards the table. - teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) + # Left stick down bends the elbow down towards the table. + teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) if any(hit.endswith(': table') for hit in teleop.blocked): stopped = True # The published one-period lookahead stops with the refused step. @@ -117,7 +117,7 @@ def test_teleop_stops_before_the_forearm_reaches_the_table(parameters, check): assert stopped and teleop.targets['joint_3'] < LIMITS['joint_3'][1] - 0.05 elbow = teleop.targets['joint_3'] for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] < elbow - 0.05 @@ -157,7 +157,7 @@ def test_teleop_refuses_a_step_that_presses_one_contact_deeper(parameters, check teleop.update(*sample(button), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] == start['joint_3'] assert teleop.blocked == ['forearm_link: table'] @@ -189,7 +189,7 @@ def test_teleop_refuses_to_slide_the_forearm_further_into_the_side_of_the_base( teleop.update(*sample('start'), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_x=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_x=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_1'] == start['joint_1'] assert teleop.blocked == ['forearm_link: base_link'] # Raising the shoulder backs it out. diff --git a/waybionic_teleop/test/test_drive_map.py b/waybionic_teleop/test/test_drive_map.py index ff46283c..200df09f 100644 --- a/waybionic_teleop/test/test_drive_map.py +++ b/waybionic_teleop/test/test_drive_map.py @@ -32,9 +32,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) # A quarter turn of the wrist is three quarters of a turn of each motor through the belts. + # The right motor counts the opposite way to the left one (bench arm). 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] + 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(): diff --git a/waybionic_teleop/test/test_frame_log.py b/waybionic_teleop/test/test_frame_log.py new file mode 100644 index 00000000..e182dca0 --- /dev/null +++ b/waybionic_teleop/test/test_frame_log.py @@ -0,0 +1,24 @@ +from waybionic_teleop import mks_can +from waybionic_teleop.frame_log import parse_line, RecordingBus +from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo + + +def test_every_frame_sent_received_or_refused_is_written_in_order(tmp_path): + path = tmp_path / 'frames.log' + sim = SimulatedBus([SimulatedServo(1)], 500000) + bus = RecordingBus(sim, str(path)) + assert bus.send(1, mks_can.read_encoder(1)) + reply = bus.receive() + assert reply is not None and bus.receive() is None + # Everything else, such as the simulated drives, still comes from the wrapped bus. + assert bus.drives is sim.drives and bus.frames == sim.frames + sim.take_refused = lambda: [(1, mks_can.stop(1, 0))] + assert bus.take_refused() == [(1, mks_can.stop(1, 0))] + bus.shutdown() + lines = [parse_line(line) for line in path.read_text().splitlines()] + assert [line[1:] for line in lines] == [ + ('tx', 1, mks_can.read_encoder(1)), + ('rx', *reply), + ('refused', 1, mks_can.stop(1, 0)), + ] + assert lines[0][0] <= lines[1][0] <= lines[2][0] diff --git a/waybionic_teleop/test/test_mks_can.py b/waybionic_teleop/test/test_mks_can.py index 14f1b8dc..1cbb8b06 100644 --- a/waybionic_teleop/test/test_mks_can.py +++ b/waybionic_teleop/test/test_mks_can.py @@ -13,6 +13,7 @@ (mks_can.absolute_axis(1, 0, 0, 4), 'F5000004000000FA'), (mks_can.absolute_axis(1, 0, 0, 0), 'F5000000000000F6'), (mks_can.read_encoder(1), '3132'), + (mks_can.read_position_error(3), '393C'), (mks_can.set_mode(1), '820588'), (mks_can.enable(1), 'F301F5'), (mks_can.emergency_stop(1), 'F7F8'), @@ -52,6 +53,28 @@ def test_encoder_reply_preserves_the_signed_int48_limits(raw, expected): assert mks_can.encoder_value(bytes.fromhex(raw)) == expected +@pytest.mark.parametrize('raw, expected', [ + ('00000000', 0), + ('0000C800', 51200), + ('FFFF3800', -51200), + ('80000000', -(1 << 31)), + ('7FFFFFFF', (1 << 31) - 1), +]) +def test_position_error_preserves_the_signed_int32_value(raw, expected): + code, arguments = mks_can.parse( + 3, mks_can.frame(3, mks_can.READ_POSITION_ERROR, bytes.fromhex(raw))) + assert code == mks_can.READ_POSITION_ERROR + assert mks_can.position_error_value(arguments) == expected + if abs(expected) == 51200: + assert expected * 360 / mks_can.ERROR_COUNTS_PER_REV == (360 if expected > 0 else -360) + + +@pytest.mark.parametrize('length', [0, 1, 2, 3, 5, 6]) +def test_position_error_rejects_a_truncated_or_wrong_length_reply(length): + with pytest.raises(ValueError, match='four bytes'): + mks_can.position_error_value(bytes(length)) + + @pytest.mark.parametrize('can_id, data', [ (1, bytes.fromhex('3133')), (1, b'\x31'), diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 39fe4562..0fe1a561 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -1,5 +1,7 @@ """Bench set-up of the MKS drives: finding them, new CAN IDs and bit rates.""" +from collections import deque + import pytest from waybionic_teleop import mks_can, mks_setup @@ -103,3 +105,67 @@ def take_refused(): bus.send, bus.take_refused = busy_once, take_refused bus.drives[3].axis = 0x4000 assert mks_setup.scan(bus, [3]) == {3: 0x4000} + + +class ErrorReadBus: + """Supply recorded error replies without a simulation of motor torque.""" + + def __init__(self, replies): + self.replies = deque(replies) + self.sent = [] + self.closed = False + + def send(self, can_id, data): + self.sent.append((can_id, data)) + return True + + def step(self, dt): + pass + + def receive(self): + return self.replies.popleft() if self.replies else None + + def shutdown(self): + self.closed = True + + +def test_read_error_is_signed_and_sends_only_a_read(monkeypatch, capsys): + # CAN ID 3 + 39h + FFFF3800 has checksum 72h; -51200 is -360 motor degrees. + bus = ErrorReadBus([ + (0x7F0, bytes(8)), + (3, bytes.fromhex('39FFFF380072')), + ]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + mks_setup.main(['--interface', 'virtual', '--channel', 'fake', 'read-error', '3']) + assert bus.sent == [(3, bytes.fromhex('393C'))] + assert bus.closed + assert '-360.000000 motor deg (-51200 error counts)' in capsys.readouterr().out + + +@pytest.mark.parametrize('reply, reason', [ + (bytes.fromhex('39003C'), 'four bytes'), + (bytes.fromhex('39000000003D'), 'bad frame'), +]) +def test_read_error_reports_bad_replies_and_releases_the_bus(monkeypatch, reply, reason): + bus = ErrorReadBus([(3, reply)]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + with pytest.raises(SystemExit, match=reason): + mks_setup.main(['--interface', 'virtual', '--channel', 'fake', 'read-error', '3']) + assert bus.closed + assert bus.sent == [(3, bytes.fromhex('393C'))] + + +def test_read_error_reports_an_unanswered_request(): + bus = ErrorReadBus([]) + with pytest.raises(SystemExit, match='did not report its position error'): + mks_setup.read_error(bus, 3) + assert bus.sent == [(3, bytes.fromhex('393C'))] + + +@pytest.mark.parametrize('can_id', ['0', '-1', '2032', '2048']) +def test_read_error_rejects_invalid_or_reserved_ids_before_opening_usb(monkeypatch, can_id): + def unexpected_open(*args): + pytest.fail('invalid input opened USB') + monkeypatch.setattr(mks_setup, 'open_bus', unexpected_open) + with pytest.raises(SystemExit): + mks_setup.main(['--channel', 'fake', 'read-error', can_id]) diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 58533ef2..607480a7 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -23,6 +23,7 @@ ) from waybionic_teleop import ( autoplay_node, + carrier, joy_udp_receiver, mks_can, ros_shutdown, @@ -32,14 +33,18 @@ from waybionic_teleop.gamepad import AXES, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits from waybionic_teleop.sim_arm_drives_node import ( + HOLD_RPM, + HOLD_S, QUIET_BEFORE_ZERO_S, REPLY_TIMEOUT_S, REPORT_PERIOD_S, SimArmDrives, + START_DEADBAND_COUNTS, ) from waybionic_teleop.sim_drives import SimulatedServo from waybionic_teleop.slcan_bus import SlcanBus from waybionic_teleop.teleop import ArmTeleop, config_from_parameters +import yaml URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' / 'waybionic_arm.urdf').read_text(encoding='utf-8') @@ -117,8 +122,15 @@ def sent_frame(node, index): def assert_stopped(node): assert not node.authorized - assert all(servo.enabled and servo.target is None and servo.rpm == 0.0 - for servo in node.bus.drives.values()) + # Two ticks at full speed past the count, and a count of rounding. + reach = (2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + + START_DEADBAND_COUNTS + 1) + for index, drive in enumerate(node.map.drives): + servo = node.bus.drives[drive.can_id] + # A drive stopped mid-move runs on only to its hold, its last move's nearby end. + assert servo.enabled and servo.target in (None, node.held[index]) + assert (servo.rpm == 0.0 if servo.target is None + else abs(servo.target - servo.axis) <= reach and servo.speed <= HOLD_RPM) assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6)) for index in range(len(node.map.drives))) @@ -379,6 +391,8 @@ def test_stale_encoder_feedback_stops_before_sending_another_position(node): assert not node.authorized node.on_enabled(Bool(data=False)) node.on_enabled(Bool(data=True)) + # The base was stopped mid-move, so it moves again once a reading shows it has settled. + advance(node) node.on_command(command(node, joint_1=1.0)) advance(node) assert node.authorized and node.bus.drives[1].target is not None @@ -427,7 +441,11 @@ def failing(data): node.on_command(command(node, joint_1=0.31, joint_2=0.31)) advance(node) assert not node.authorized and not node.zeroed[1] and 'shoulder' in node.stop_reason - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + # The others hold where their moves end; the shoulder, no longer trusted, gets no hold. + assert_stopped(node) + advance(node) + assert shoulder.target is None and node.hold_tick[1] == -1 + assert node.hold_tick[0] == node.ticks published = [] monkeypatch.setattr(node.diagnostics_publisher, 'publish', published.append) node.report() @@ -463,6 +481,265 @@ def test_a_drive_that_stops_following_its_targets_stops_every_drive(node, monkey assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) +def test_a_reversing_drive_stops_before_it_gets_a_target_behind_it(node, monkeypatch): + ready(node) + clock = [time.monotonic()] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + # A gentler ramp keeps the base turning when the stick reverses, and a slow stroke back + # lets the fast stroke forward put the next target behind the still-turning base. + node.acc = 240 + base = node.bus.drives[1] + stops, angle, turns, latched = capture_sends(node, monkeypatch), 0.0, [0.0], [] + rates = [0.5] * 30 + [-0.3] * 40 + [0.5] * 20 + [0.0] * 30 + for previous, rate in zip([0.5] + rates, rates): + if rate != previous: + turns.append(base.axis) + angle += rate * node.period + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={'joint_1': rate}, joint_1=angle)) + clock[0] += node.period + advance(node) + # Firmware V1.0.9 would run back to this target after the next stop. + latched.append(base.latched) + assert node.authorized and latched == [None] * len(rates) + # Each reversal and the final hold stopped the base, which followed the stick both ways. + assert stops.count(mks_can.stop(1, 0)) >= 3 + assert turns[0] < turns[1] > turns[2] < turns[3] + held = base.axis + for _ in range(60): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + assert base.axis == held and node.authorized + + +def test_a_drive_that_turns_after_its_stop_stops_every_drive_but_keeps_its_zero(node): + ready(node) + node.following_error, node.following_ticks = 400, 5 + hold = command(node, velocities={}) + node.on_command(hold) + advance(node) + assert node.sent[0] == (None, 0) and node.held[0] == 0 + # The base runs on to a target its firmware kept from before the stop. + base = node.bus.drives[1] + base.target, base.speed, base.acc = 20000, 60, 0 + for _ in range(100): + node.on_enabled(Bool(data=True)) + node.on_command(hold) + advance(node) + if not node.authorized: + break + assert node.stop_reason.startswith('base_yaw turned +') and all(node.zeroed) + assert 400 < base.axis < 2000 and base.target is None and base.rpm == 0.0 + + +def stroke(node, clock, ticks, rate=0.5): + """Turn the base with the stick for some ticks of a mocked clock; return its angle.""" + angle = 0.0 + for _ in range(ticks): + angle += rate * node.period + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={'joint_1': rate}, joint_1=angle)) + clock[0] += node.period + advance(node) + return angle + + +@pytest.fixture +def clock(monkeypatch): + clock = [time.monotonic()] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + return clock + + +def test_a_target_kept_by_the_firmware_never_runs_past_the_hold_behind_the_stop(node, clock): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 20) + up = node.direction[0] + assert up + # Firmware V1.0.9 kept a target from earlier in the stroke, and runs back to it at once + # when the stick's release stops the base. + base.latched = (round(base.axis) - 3000 * up, 300, 0) + stopped = base.axis + node.on_command(command(node, velocities={}, joint_1=angle)) + assert base.latched is None and base.target == node.held[0] + assert 0 <= (node.held[0] - stopped) * up <= ( + 2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + START_DEADBAND_COUNTS) + lowest = stopped * up + for _ in range(60): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + lowest = min(lowest, base.axis * up) + # The hold right behind the stop took over before the base turned back at all. + assert node.authorized and lowest == stopped * up and base.axis == node.held[0] + + +def test_a_target_kept_by_the_firmware_is_taken_over_within_a_tick_of_the_hold( + node, clock, monkeypatch): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 20) + up = node.direction[0] + assert up + node.on_command(command(node, velocities={}, joint_1=angle)) + stopped_at, held = clock[0], node.held[0] + + def hold_tick(): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + for _ in range(5): + hold_tick() + # The base reaches its hold, then runs back to a target its firmware kept. The hold goes + # out again on the next tick, before the following error could stop the arm. + base.target, base.speed, base.acc = held - 20000 * up, 300, 0 + farthest = 0 + for _ in range(20): + hold_tick() + farthest = max(farthest, (held - base.axis) * up) + assert node.authorized and 0 < farthest < 1500 and base.axis == held + # Once HOLD_S has passed, nothing but stops goes out to a drive at rest. + while clock[0] - stopped_at < HOLD_S: + hold_tick() + sent = capture_sends(node, monkeypatch) + for _ in range(10): + hold_tick() + assert all(frame[0] != mks_can.ABSOLUTE_AXIS for frame in sent) + + +def test_a_drive_disabled_mid_stroke_is_held_every_tick_for_the_hold_time( + node, clock, monkeypatch): + ready(node) + base = node.bus.drives[1] + stroke(node, clock, 20) + up = node.direction[0] + assert up + sent = capture_sends(node, monkeypatch) + node.on_enabled(Bool(data=False)) + stopped_at, held = clock[0], node.held[0] + hold = mks_can.absolute_axis(1, held, min(HOLD_RPM, node.max_rpm), node.acc) + # The hold goes out right behind the stop, a little ahead of the base, never behind it. + assert sent == [mks_can.stop(1, 0), hold] and (held - base.axis) * up >= 0 + ticks = [] + for _ in range(40): + sent.clear() + clock[0] += node.period + advance(node) + ticks.append((clock[0] - stopped_at, sent.count(hold))) + assert all(holds == 1 for elapsed, holds in ticks if elapsed < HOLD_S - 1e-6) + assert all(holds == 0 for elapsed, holds in ticks if elapsed > HOLD_S + 1e-6) + assert not node.authorized and base.axis == held and base.target is None + + +@pytest.mark.parametrize('state', ['moving', 'disabled', 'holding']) +def test_zeroing_sends_no_hold_in_the_old_coordinates(node, clock, monkeypatch, state): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 10) + if state == 'disabled': + node.on_enabled(Bool(data=False)) + elif state == 'holding': + node.on_command(command(node, velocities={}, joint_1=angle)) + assert node.authorized + if state != 'moving': + # Its hold, a few thousand counts out, would be within reach of the new zero. + assert node.hold_until[0] > clock[0] and 0 < abs(node.held[0]) < node.following_error + sent = capture_sends(node, monkeypatch) + node.zero() + for _ in range(10): + clock[0] += node.period + advance(node) + assert all(node.zeroed) and node.counts[0] == 0 + assert not [frame for frame in sent + if frame[0] == mks_can.ABSOLUTE_AXIS and frame[1:3] != b'\x00\x00'] + assert base.axis == 0 and base.target is None + + +def test_a_drive_that_turns_after_a_disable_stops_every_drive_again(node, clock): + ready(node) + node.following_error, node.following_ticks = 400, 5 + base = node.bus.drives[1] + stroke(node, clock, 20) + up = node.direction[0] + node.on_enabled(Bool(data=False)) + held = node.held[0] + for _ in range(40): + clock[0] += node.period + advance(node) + assert not node.authorized and base.axis == held and node.stop_reason == 'Teleop disabled' + # Its hold over, the base runs on to a target its firmware kept, though disarmed. + base.target, base.speed, base.acc = held + 20000 * up, 60, 0 + for _ in range(100): + clock[0] += node.period + advance(node) + if node.stop_reason != 'Teleop disabled': + break + assert node.stop_reason.startswith('base_yaw turned ') and all(node.zeroed) + assert 400 < (base.axis - held) * up < 2000 and base.target is None and base.rpm == 0.0 + + +def test_a_hold_from_an_old_count_never_pulls_the_drive_back(node, clock): + ready(node) + base = node.bus.drives[1] + stroke(node, clock, 20) + up, speed = node.direction[0], node.sent[0][1] + # The base's last few counts were lost, so the node's count is four ticks behind it. + lag = 4 * node.period + node.counts[0] -= round(up * lag * speed / 60.0 * mks_can.COUNTS_PER_REV) + node.since_count[0] += lag + node.on_enabled(Bool(data=False)) + assert (node.held[0] - base.axis) * up >= -1 + + +def test_no_hold_goes_out_once_an_estop_press_is_released(node, clock, monkeypatch): + ready(node) + stroke(node, clock, 20) + node.interface = 'slcan' + monkeypatch.setattr(node.bus, 'take_refused', lambda: [], raising=False) + sent = capture_sends(node, monkeypatch) + flags = carrier.ESTOP_WIRED + node.on_reply(carrier.STATUS_ID, bytes([1, flags | carrier.ESTOP_PRESSED, 0, 0, 0, 0, 0, 0]), + clock[0]) + assert node.stop_reason == 'E-stop pressed' and mks_can.stop(1, 0) in sent + clock[0] += node.period + advance(node) + node.on_reply(carrier.STATUS_ID, bytes([2, flags, 0, 0, 0, 0, 0, 0]), clock[0]) + assert not node.estop_pressed + for _ in range(10): + clock[0] += node.period + advance(node) + # The drives may have restarted with new counts, so nothing but stops went out. + assert not [frame for frame in sent + if frame[0] == mks_can.ABSOLUTE_AXIS and frame[1:3] != b'\x00\x00'] + + +def test_closing_mid_move_holds_the_drive_until_the_hold_time_is_over(node, usb_carrier): + ready(node) + node.on_command(command(node, velocities={'joint_1': 0.5}, joint_1=0.5)) + for _ in range(3): + advance(node) + assert node.sent[0][0] is not None + port = usb_carrier() + node.interface = 'slcan' + node.bus = SlcanBus('/dev/fake', 1000000, open_port=lambda: port) + started = time.monotonic() + node.close() + written = b''.join(port.writes) + frames = [line for line in written.split(b'\r') if line.startswith(b't')] + hold = mks_can.absolute_axis(1, node.held[0], min(HOLD_RPM, node.max_rpm), node.acc) + hold_line = b't001%d%s' % (len(hold), hold.hex().upper().encode()) + # The hold goes out right behind the base's stop, then about once a tick for HOLD_S. + assert frames[frames.index(stop_line(1)) + 1] == hold_line + assert 0.6 * HOLD_S / node.period <= frames.count(hold_line) <= HOLD_S / node.period + 2 + assert written.endswith(b'C\r') and port.closed + assert HOLD_S <= time.monotonic() - started < sim_arm_drives_node.CLOSE_TIMEOUT_S + 0.1 + + def test_a_drive_that_restarts_between_polls_is_set_up_and_zeroed_again(node): start = dict.fromkeys(node.map.joints, 0.0) start['joint_2'] = 1.2 @@ -485,6 +762,143 @@ def test_a_drive_that_restarts_between_polls_is_set_up_and_zeroed_again(node): assert not node.authorized +@pytest.fixture +def drives_with(monkeypatch, parameters): + """Make drive nodes with changed parameters, all destroyed after the test.""" + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + made = [] + + def make(**changes): + configured = parameters('arm_drives.yaml', 'sim_arm_drives') + configured.update(changes) + made.append(SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()])) + return made[-1] + yield make + for made_node in made: + made_node.destroy_node() + rclpy.try_shutdown(context=context) + + +def zeroed_with_state(drives_with, path): + """Zero drives powered on away from the zero pose, saving the zero to path.""" + node = drives_with(zero_state=str(path), zero_on_start=False) + for index, servo in enumerate(node.bus.drives.values()): + # Power-on starts the raw encoder at the shaft's magnetic angle. + servo.raw_shift, servo.axis = 1000 * index + 7, 5000.0 + advance(node) + assert not path.exists() + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + for _ in range(3): + advance(node) + return node + + +def restart(drives_with, old, path): + """Start the node again on the same simulated drives, as a relaunch does.""" + node = drives_with(zero_state=str(path), zero_on_start=False) + node.bus = old.bus + for index in range(len(node.map.drives)): + node.set_up(index) + return node + + +def test_a_zero_is_saved_once_every_drive_reports_its_fingerprint(drives_with, tmp_path): + path = tmp_path / 'state' / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + assert saved == {drive.name: {'can_id': drive.can_id, 'offset': 1000 * index + 5007} + for index, drive in enumerate(node.map.drives)} + assert not node.checks and not list(tmp_path.glob('state/*.partial')) + + +def test_a_restart_keeps_the_zero_of_drives_that_stayed_powered(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + # The arm is driven or pushed elsewhere before the station restarts. + for servo in old.bus.drives.values(): + servo.axis = 2000.0 + node = restart(drives_with, old, path) + assert not any(node.zeroed) and node.checks + published = [] + node.state_publisher.publish = published.append + for _ in range(3): + advance(node) + assert all(node.zeroed) and not node.checks + assert node.counts == [2000] * len(node.map.drives) + assert published[-1].position[:len(node.map.joints)] == pytest.approx( + list(node.map.to_positions(node.counts).values())) + ready(node) + + +def test_a_restart_after_a_power_cycle_does_not_keep_the_zero(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + for drive in old.map.drives: + # Powered on again where its raw encoder reads its saved offset, so only the zero + # status shows it lost its zero. + old.bus.drives[drive.can_id].power_cycle(saved[drive.name]['offset']) + node = restart(drives_with, old, path) + for _ in range(3): + advance(node) + assert not any(node.zeroed) and not node.checks + node.on_description(String(data=URDF)) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized + + +def test_a_restart_does_not_keep_a_zero_made_elsewhere(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + base = old.bus.drives[old.map.drives[0].can_id] + base.axis = 3000.0 + base.receive(mks_can.set_zero(base.can_id)) + node = restart(drives_with, old, path) + for _ in range(3): + advance(node) + assert node.zeroed == [False] + [True] * (len(node.map.drives) - 1) + + +def test_a_fault_or_a_new_zero_forgets_the_saved_zero(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + node.zero() + assert not path.exists() and not node.saved_zero + for _ in range(3): + advance(node) + assert path.exists() + node.fault(0, 'is 5000 counts from its target') + assert not path.exists() and not node.saved_zero + for _ in range(3): + advance(node) + assert not path.exists() + restarted = restart(drives_with, node, path) + assert not restarted.checks and not any(restarted.zeroed) + + +def test_a_drive_that_answers_again_keeps_its_zero_unless_it_lost_power(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + ready(node) + can_id = node.map.drives[0].can_id + for power_cycled in (False, True): + unplugged = node.bus.drives.pop(can_id) + for _ in range(node.max_unanswered + 3): + advance(node) + assert node.lost[0] and not node.zeroed[0] and not node.authorized + if power_cycled: + unplugged.power_cycle(5007) + node.bus.drives[can_id] = unplugged + for _ in range(3): + advance(node) + assert not node.lost[0] and node.zeroed[0] is not power_cycled + assert node.held[0] is None and not node.checks + + def test_zeroing_waits_until_teleop_stops_streaming_to_an_arm_that_lost_its_zero(node): ready(node) held = command(node, joint_1=0.3, joint_2=0.3) @@ -530,6 +944,8 @@ def test_a_stop_the_interface_refuses_is_sent_again_until_it_goes_out(node, monk advance(node) base = node.bus.drives[1] assert base.target is not None + up = node.direction[0] + assert up send, refusing = node.bus.send, [True] def full(can_id, data): @@ -548,7 +964,9 @@ def full(can_id, data): assert not node.authorized refusing[0] = False advance(node) - assert not node.stopping and base.target is None and base.rpm == 0.0 + # The hold is taken where the drive was once its stop went out, so it never pulls back. + assert not node.stopping and base.target == node.held[0] and base.rpm == 0.0 + assert (node.held[0] - base.axis) * up >= 0 node.on_enabled(Bool(data=True)) assert node.authorized @@ -1054,17 +1472,20 @@ def test_zero_speed_f5_stops_six_drives_and_negative_targets_rearm(node): node.on_command(command(node, velocities=dict.fromkeys(POSE, 0.0), **measured)) advance(node) assert node.authorized - assert all(drive.enabled and drive.target is None and drive.rpm == 0.0 - for drive in node.bus.drives.values()) + servos = [node.bus.drives[drive.can_id] for drive in node.map.drives] + # Each drive stops, then runs on only to its hold, the nearby end of its move. + assert all(servo.enabled and servo.target == held and abs(held - servo.axis) <= 60 + for servo, held in zip(servos, node.held)) assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6)) for index in range(len(node.map.drives))) - held = [drive.axis for drive in node.bus.drives.values()] advance(node, 0.6) - assert [drive.axis for drive in node.bus.drives.values()] == held + assert [servo.axis for servo in servos] == node.held assert_stopped(node) node.on_enabled(Bool(data=False)) node.on_enabled(Bool(data=True)) + # Its hold reached, the next quiet encoder step lets each drive move again. + advance(node) reverse = dict.fromkeys(POSE, -0.4) reverse.update(joint_5=0.1, tool_grip=0.2) rates = dict.fromkeys(POSE, -0.2) @@ -1132,6 +1553,101 @@ def test_a_cartesian_tilt_into_a_joint_limit_keeps_the_drives_enabled(node, para assert node.commanded['joint_3'] == pytest.approx(node.limits['joint_3'][1], abs=1e-9) +@pytest.fixture +def bench(monkeypatch, parameters, bench_profile): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + configured = {**parameters('arm_drives.yaml', 'sim_arm_drives'), + 'arm_profile': bench_profile} + node = SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()]) + yield node + node.destroy_node() + rclpy.try_shutdown(context=context) + + +def test_an_arm_without_a_shoulder_drive_publishes_the_shoulder_where_it_is_fixed( + bench, monkeypatch): + states = [] + monkeypatch.setattr(bench.state_publisher, 'publish', states.append) + assert [drive.can_id for drive in bench.map.drives] == [1, 3, 4, 5] + assert sorted(bench.bus.drives) == [1, 3, 4, 5] + ready(bench) + published = dict(zip(states[-1].name, states[-1].position)) + assert set(published) == {'joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', + 'tool_grip'} + assert published['joint_2'] == 0.0 and published['tool_grip'] == 0.0 + + +def test_a_command_must_hold_a_locked_joint_where_it_is(bench): + ready(bench) + bench.on_command(command(bench, joint_1=0.5, joint_2=0.0, tool_grip=0.0)) + advance(bench) + assert bench.authorized and bench.rejected == 0 + assert set(bench.commanded) == set(bench.map.joints) + assert bench.bus.drives[1].target is not None + bench.on_command(command(bench, joint_1=0.5, joint_2=0.1, tool_grip=0.0)) + assert not bench.authorized and bench.stop_reason == 'joint_2 is locked at 0 rad' + ready(bench) + # Leaving a locked joint out is as incomplete as leaving out a driven one. + bench.on_command(command(bench, joint_1=0.5, tool_grip=0.0)) + assert not bench.authorized and bench.stop_reason.startswith('incomplete') + + +def test_a_profile_that_leaves_a_joint_unaccounted_for_stops_the_node( + monkeypatch, parameters, tmp_path): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + profile = tmp_path / 'arm_profile.yaml' + profile.write_text('fitted_drives: [base_yaw, elbow, wrist_left, wrist_right]\n', + encoding='utf-8') + configured = {**parameters('arm_drives.yaml', 'sim_arm_drives'), + 'arm_profile': str(profile)} + context = rclpy.Context() + rclpy.init(context=context) + try: + with pytest.raises(ValueError, match='joint_2'): + SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()]) + finally: + rclpy.try_shutdown(context=context) + + +def test_teleop_drives_an_arm_with_a_locked_shoulder_without_a_stop( + bench, parameters, monkeypatch): + states = [] + monkeypatch.setattr(bench.state_publisher, 'publish', states.append) + ready(bench) + arm = ArmKinematics.from_urdf(URDF) + teleop = ArmTeleop(config_from_parameters(parameters('xbox_teleop.yaml', 'xbox_teleop')), + joint_limits(URDF, arm.joints), arm, locked=bench.locked) + + def measured(): + return dict(zip(states[-1].name, states[-1].position)) + teleop.enable(measured(), [0.0] * len(AXES)) + assert teleop.enabled, teleop.note + # The base group's sticks ask for the base, the shoulder and the elbow at once; then, with + # the elbow bent, the Cartesian group asks for a straight move only the shoulder could make. + sticks = [[0.0] * len(AXES) for _ in range(2)] + for axis in ('left_x', 'left_y', 'right_y'): + sticks[0][AXES.index(axis)] = 1.0 + sticks[1][AXES.index('left_y')] = 1.0 + for group, axes in zip(('base', 'cartesian'), sticks): + teleop.group = [item.name for item in teleop.groups].index(group) + for _ in range(60): + teleop.update(axes, [0] * len(BUTTONS), measured(), bench.period) + targets = teleop.command_targets + bench.on_enabled(Bool(data=True)) + bench.on_command(JointState( + name=list(targets), position=list(targets.values()), + velocity=[teleop.velocities[joint] for joint in targets])) + advance(bench) + assert bench.authorized, bench.stop_reason + assert 'joint_2' in teleop.blocked, group + assert bench.rejected == 0 + assert abs(measured()['joint_1']) > 0.1 and measured()['joint_2'] == 0.0 + + @pytest.fixture def short_shutdown_grace(monkeypatch): monkeypatch.setattr(ros_shutdown, 'SHUTDOWN_GRACE_S', 0.05) diff --git a/waybionic_teleop/test/test_sim_drives.py b/waybionic_teleop/test/test_sim_drives.py index 2318bb4c..0dc682c8 100644 --- a/waybionic_teleop/test/test_sim_drives.py +++ b/waybionic_teleop/test/test_sim_drives.py @@ -95,6 +95,38 @@ def test_f5_stop_is_immediate_and_a_new_negative_target_rearms_the_drive(): assert servo.target == -0x4000 and servo.rpm < 0.0 and servo.axis < held +@pytest.mark.parametrize('end', [mks_can.stop(1, 0), mks_can.emergency_stop(1), None]) +def test_a_target_that_reverses_a_running_move_is_run_to_once_the_moves_stop(end): + # Firmware V1.0.9 on the bench: the reversing target is kept while later targets steer the + # move, and the drive runs back to it on its own after a stop or its last target. + servo = ready_servo() + servo.receive(mks_can.absolute_axis(1, 0x8000, 300, 0)) + run(servo, 0.05) + assert servo.rpm > 0.0 + servo.receive(mks_can.absolute_axis(1, -0x1000, 300, 0)) + run(servo, 0.02) + servo.receive(mks_can.absolute_axis(1, round(servo.axis) + 2000, 300, 0)) + if end is None: + run(servo, 0.05) + else: + servo.receive(end) + run(servo, 1.0) + assert servo.axis == -0x1000 and servo.latched is None + + +def test_a_drive_that_stops_before_it_reverses_runs_only_to_its_last_target(): + servo = ready_servo() + servo.receive(mks_can.absolute_axis(1, 0x8000, 300, 0)) + run(servo, 0.05) + servo.receive(mks_can.stop(1, 0)) + servo.receive(mks_can.absolute_axis(1, -0x1000, 300, 0)) + run(servo, 1.0) + held = servo.axis + assert servo.receive(mks_can.stop(1, 0)) == [COMPLETE] + run(servo, 1.0) + assert servo.axis == held == -0x1000 + + def test_stalled_test_fault_keeps_replying_without_advancing_and_recovers(): servo = ready_servo() initial_axis = servo.axis diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index d9023baa..92a68121 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -10,6 +10,9 @@ from waybionic_teleop import carrier, mks_can, slcan_bus from waybionic_teleop.slcan_bus import SlcanBus +# The carrier's answer to V, which comes before the answers to C, Sn and O. +VERSION = b'V0100\r' + class FakeSerial: """A USB serial port that can be unplugged.""" @@ -45,6 +48,11 @@ def close(self): def clock(monkeypatch): now = [1000.0] monkeypatch.setattr(slcan_bus.time, 'monotonic', lambda: now[0]) + + def sleep(seconds): + now[0] += seconds + + monkeypatch.setattr(slcan_bus.time, 'sleep', sleep) return now @@ -62,7 +70,7 @@ def 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 ports[0].writes == [b'V\rC\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 @@ -71,7 +79,7 @@ def test_it_opens_the_bridge_at_the_bit_rate_then_writes_a_tick_in_one_go(bus, p def test_replies_are_parsed_across_reads(bus, ports): - ports[0].inbox += b'\r\r\rt0013F5' + ports[0].inbox += VERSION + b'\r\r\rt0013F5' assert bus.receive() is None ports[0].inbox += b'01F7\rt7F080005000000000000\r' assert bus.receive() == (1, bytes.fromhex('F501F7')) @@ -85,15 +93,29 @@ 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, 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' + # V, C, S8, O; frame 1 taken; frame 2 refused, a drive's reply in between; frame 3 taken. + ports[0].inbox += VERSION + 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_answers_left_from_the_last_session_are_not_pinned_on_new_lines(bus, ports): + # The last program closed the port as the carrier answered its last lines: their ends, a + # BELL for a frame cut off by its C, a drive's reply and a status frame come out first. + ports[0].inbox += b'00000032\r\a\r\rt00183100000000000032\rt7F080F00000000010011\r' + bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is None + ports[0].inbox += VERSION + b'\r\r\r\r' + assert bus.receive() is None + assert bus.errors == 0 and bus.problem == '' and bus.unanswered == 0 + assert bus.take_refused() == [] and bus.refused == 0 + ports[0].inbox += b't00183100000000000033\r' + assert bus.receive() == (1, bytes.fromhex('3100000000000033')) + + def test_a_refused_open_is_an_error_that_says_why(bus, ports): - ports[0].inbox += b'\r\r\a' + ports[0].inbox += VERSION + 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 @@ -104,7 +126,7 @@ def test_a_refused_open_is_an_error_that_says_why(bus, ports): def test_a_closed_carrier_that_still_answers_is_opened_again(bus, ports, clock): - ports[0].inbox += b'\r\r\r' + ports[0].inbox += VERSION + b'\r\r\r' for _ in range(3): clock[0] += slcan_bus.SILENCE_S / 2 bus.send(1, mks_can.read_encoder(1)) @@ -112,7 +134,7 @@ def test_a_closed_carrier_that_still_answers_is_opened_again(bus, ports, clock): # 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' + assert ports[0].writes[-1] == b'V\rC\rS8\rO\r' def test_an_unplugged_carrier_is_reopened_and_set_up_again(bus, ports, clock): @@ -125,7 +147,7 @@ def test_an_unplugged_carrier_is_reopened_and_set_up_again(bus, ports, clock): 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'] + assert bus.connected and bus.reopens == 1 and ports[1].writes == [b'V\rC\rS8\rO\r'] def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): @@ -136,11 +158,11 @@ def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): 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' + assert ports[0].writes[-1] == b'V\rC\rS8\rO\r' def test_no_more_frames_are_unanswered_than_the_carrier_can_queue(bus, ports): - ports[0].inbox += b'\r\r\r' + ports[0].inbox += VERSION + 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)] @@ -170,7 +192,7 @@ def test_a_carrier_that_stops_answering_lines_is_opened_again(bus, ports, clock) 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'] + assert bus.connected and ports[1].writes == [b'V\rC\rS8\rO\r'] def test_the_carrier_status_frame_decodes(): @@ -183,6 +205,57 @@ def test_the_carrier_status_frame_decodes(): carrier.parse_status(bytes(7)) +def test_shutdown_waits_for_the_close_acknowledgement_before_releasing_usb(bus, ports): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + ports[0].inbox += b't7F080100000000000000\r\r' + bus.shutdown() + assert ports[0].writes[-1] == b'C\r' + assert ports[0].closed and not bus.connected + assert not ports[0].inbox and bus.unanswered == 0 + assert bus.errors == 0 and bus.problem == '' + writes = list(ports[0].writes) + bus.shutdown() + assert ports[0].writes == writes + + +def test_shutdown_times_out_and_reports_an_unacknowledged_close(bus, ports, clock, capfd): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + start = clock[0] + bus.shutdown() + assert ports[0].closed and not bus.connected + assert slcan_bus.CLOSE_TIMEOUT_S <= clock[0] - start <= slcan_bus.CLOSE_TIMEOUT_S + 0.002 + assert bus.errors == 1 and 'acknowledge close' in bus.problem + assert 'acknowledge close' in capfd.readouterr().err + + +@pytest.mark.parametrize('unplugged', [False, True]) +def test_shutdown_reports_a_refusal_or_disconnect_and_still_releases_usb( + bus, ports, unplugged, capfd): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + ports[0].unplugged = unplugged + ports[0].inbox += b'\a' + bus.shutdown() + assert ports[0].closed and not bus.connected + assert bus.errors == 1 + assert 'close' in capfd.readouterr().err.lower() + + +def test_an_interrupted_close_still_releases_usb(bus, ports, monkeypatch): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + + def interrupted_read(): + raise KeyboardInterrupt + + monkeypatch.setattr(bus, '_read', interrupted_read) + with pytest.raises(KeyboardInterrupt): + bus.shutdown() + assert ports[0].closed and not bus.connected + + def slcan_sim(): try: from ament_index_python.packages import get_package_prefix @@ -199,7 +272,8 @@ def test_the_simulated_carrier_answers_through_the_real_bridge_code(): stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) try: port = sim.stdout.readline().strip() - bus = SlcanBus(port, 500000) + # A pty ignores the baud rate, and macOS refuses a custom rate such as 1000000 on one. + bus = SlcanBus(port, 500000, baudrate=115200) frames = [] def wait_for(done, seconds=2.0): diff --git a/waybionic_teleop/test/test_teleop.py b/waybionic_teleop/test/test_teleop.py index 9c3dc252..3ec923e1 100644 --- a/waybionic_teleop/test/test_teleop.py +++ b/waybionic_teleop/test/test_teleop.py @@ -71,6 +71,23 @@ def test_enable_waits_for_joint_states(teleop): assert not teleop.enabled and teleop.warning and 'joint_2' in teleop.note +def test_a_locked_joint_stays_exactly_at_its_angle(params, arm): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, arm, + locked={'joint_2': 0.25, 'tool_grip': 0.0, 'not_a_joint': 1.0}) + assert teleop.limits['joint_2'] == (0.25, 0.25) and 'not_a_joint' not in teleop.limits + # Even a measured value a rounding error away is sent back exactly. + press(teleop, 'start', {**HOME, 'joint_2': 0.25 + 1e-12}) + assert teleop.enabled and teleop.command_targets['joint_2'] == 0.25 + for axes, joint in (({'left_x': -1.0, 'left_y': 1.0}, 'joint_2'), + ({'right_trigger': -1.0}, 'tool_grip')): + teleop.update(*sample(**axes), HOME, DT) + assert joint in teleop.blocked + assert teleop.command_targets['joint_2'] == 0.25 + assert teleop.command_targets['tool_grip'] == 0.0 + assert teleop.velocities['joint_2'] == teleop.velocities['tool_grip'] == 0.0 + assert teleop.targets['joint_1'] > 0.0 + + @pytest.mark.parametrize('axes', [{'left_x': 0.8}, {'right_y': -0.5}, {'right_trigger': -0.6}]) def test_enable_refuses_held_or_stuck_inputs(teleop, axes): teleop.update(*sample('start', **axes), HOME, DT) @@ -88,9 +105,10 @@ def test_enable_refuses_held_tilt_and_home_buttons(params, arm, button): def test_base_group_moves_yaw_shoulder_and_elbow(teleop): press(teleop, 'start') - run(teleop, 1.0, left_x=1.0, left_y=-1.0, right_y=0.5) + run(teleop, 1.0, left_x=-1.0, left_y=-1.0, right_y=0.5) targets = teleop.targets - assert targets['joint_1'] > 0.3 and targets['joint_2'] < -0.3 and targets['joint_3'] > 0.1 + # Stick right turns the base the positive way; right stick up lifts the elbow (negative). + assert targets['joint_1'] > 0.3 and targets['joint_2'] < -0.3 and targets['joint_3'] < -0.1 assert targets['joint_4'] == targets['joint_5'] == 0.0 @@ -101,7 +119,9 @@ def test_y_switches_to_the_upper_joints_and_leaves_the_base_alone(teleop): targets = teleop.targets assert teleop.active_group.name == 'upper' assert targets['joint_1'] == 0.0 and targets['joint_2'] > 0.3 - assert targets['joint_3'] > 0.3 and targets['joint_4'] > 0.3 and targets['joint_5'] < -0.3 + # Left stick up lifts the elbow (negative), as in the base group. Right stick up tips the + # wrist up, and right turns the roll positive (counter-clockwise). + assert targets['joint_3'] < -0.3 and targets['joint_4'] < -0.3 and targets['joint_5'] > 0.3 def test_small_stick_drift_is_ignored(teleop): @@ -132,7 +152,7 @@ def test_b_stop_needs_a_fresh_start_with_centered_sticks_to_rearm(teleop): teleop.update(*sample(), pose, DT) press(teleop, 'start', pose) assert teleop.enabled and teleop.targets == pose - run(teleop, 0.4, left_x=-1.0) + run(teleop, 0.4, left_x=1.0) assert teleop.targets['joint_1'] < pose['joint_1'] diff --git a/waybionic_teleop/test/test_teleop_node.py b/waybionic_teleop/test/test_teleop_node.py index 87e85f69..8cd86e17 100644 --- a/waybionic_teleop/test/test_teleop_node.py +++ b/waybionic_teleop/test/test_teleop_node.py @@ -9,7 +9,8 @@ from std_msgs.msg import String from std_srvs.srv import Trigger -from waybionic_teleop.sim_arm_drives_node import SimArmDrives +from waybionic_teleop import mks_can +from waybionic_teleop.sim_arm_drives_node import SimArmDrives, START_DEADBAND_COUNTS from waybionic_teleop.xbox_teleop_node import XboxTeleop URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' @@ -122,11 +123,21 @@ def enable(): drives.last_tick -= 0.05 drives.tick() stopped_at = motor.axis - assert motor.rpm == 0.0 and motor.target is None + # The stop is followed by a hold at the moving drive's last target, no farther than + # two ticks of full-speed travel plus the start deadband, and never behind the stop. + held = drives.held[0] + reach = (2 * drives.period * drives.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + + START_DEADBAND_COUNTS + 1) + assert motor.target == held and stopped_at - 1 <= held <= stopped_at + reach for _ in range(10): drives.last_tick -= 0.05 drives.tick() - assert motor.axis == stopped_at and not drives.authorized + assert motor.target in (None, held) and motor.axis == pytest.approx(held, abs=1) + rested = motor.axis + for _ in range(10): + drives.last_tick -= 0.05 + drives.tick() + assert motor.axis == rested and not drives.authorized if valid_replacement: enable() heard = drives.command_time diff --git a/waybionic_teleop/test/test_xbox_teleop_node.py b/waybionic_teleop/test/test_xbox_teleop_node.py index 36f1b384..61eb8e13 100644 --- a/waybionic_teleop/test/test_xbox_teleop_node.py +++ b/waybionic_teleop/test/test_xbox_teleop_node.py @@ -96,11 +96,11 @@ def test_a_host_pause_disables_even_if_controller_packets_look_fresh(node, monke def test_a_late_tick_moves_the_targets_at_most_two_periods(node): ready(node) for _ in range(20): - tick(node, left_x=1.0) + tick(node, left_x=-1.0) speed = node.teleop.velocities['joint_1'] assert speed == pytest.approx(node.teleop.speed) before = node.teleop.targets['joint_1'] - tick(node, left_x=1.0, elapsed=0.1) + tick(node, left_x=-1.0, elapsed=0.1) assert node.teleop.targets['joint_1'] - before == pytest.approx( 2 * node.config.period * speed) @@ -125,7 +125,7 @@ def step(message=None): step(joy()) step(joy('start')) for _ in range(10): - step(joy(left_x=1.0)) + step(joy(left_x=-1.0)) assert node.teleop.enabled and node.teleop.velocities['joint_1'] > 0 last_input = clock.now # The drives trail the moving target. @@ -192,6 +192,23 @@ def test_the_rate_and_input_timeout_must_be_positive(monkeypatch, parameters, ch rclpy.try_shutdown(context=context) +def test_the_arm_profile_pins_its_locked_joints(monkeypatch, parameters, bench_profile): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + params = {**parameters('xbox_teleop.yaml', 'xbox_teleop'), 'arm_profile': bench_profile} + node = XboxTeleop(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in params.items()]) + try: + node.load(String(data=URDF)) + assert node.teleop.limits['joint_2'] == (0.0, 0.0) + assert node.teleop.limits['tool_grip'] == (0.0, 0.0) + assert node.teleop.limits['joint_1'][0] < node.teleop.limits['joint_1'][1] + finally: + node.destroy_node() + rclpy.try_shutdown(context=context) + + def test_a_stick_wavering_at_a_limit_rumbles_at_most_once_a_second(node, monkeypatch): clock = Clock() monkeypatch.setattr(xbox_teleop_node, 'time', clock) @@ -216,7 +233,7 @@ def step(*pressed, **axes): # The base group's right stick pushes the elbow into its limit, past the deadzone every # other tick, so the arm is blocked and released 60 times a second. for index in range(round(2.5 / period)): - step(right_y=0.2 if index % 2 == 0 else 0.0) + step(right_y=-0.2 if index % 2 == 0 else 0.0) starts = [at for at, intensity in rumbles if intensity > 0] assert starts[0] == first assert len(starts) == 3 diff --git a/waybionic_teleop/waybionic_teleop/arm_profile.py b/waybionic_teleop/waybionic_teleop/arm_profile.py new file mode 100644 index 00000000..3c973aff --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/arm_profile.py @@ -0,0 +1,97 @@ +""" +How one physical arm differs from the arm map in config/arm_drives.yaml. + +The map describes every drive the arm is designed with. A profile is a small YAML file that +says which of them this arm actually has on its bus, and holds still each joint that no +fitted drive moves, at the angle it is fixed at, so the model in RViz matches the arm: + + # The shoulder motor is not wired yet; the shoulder is fixed upright. + fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] + locked_joints: {joint_2: 0.0, tool_grip: 0.0} + +Angles are in radians, in the joint's URDF frame. The drive node publishes a locked joint at +its angle and refuses commands that would move it; teleop treats it as a joint whose limits +are that angle. +""" + +from dataclasses import dataclass, field +import math + +import yaml + +KEYS = {'fitted_drives', 'locked_joints'} + + +@dataclass(frozen=True) +class ArmProfile: + # None means every drive in the map is fitted. + fitted_drives: tuple = None + locked_joints: dict = field(default_factory=dict) + + +def load_profile(path): + """Return the ArmProfile in the YAML file at path, or the default one for no path.""" + if not path: + return ArmProfile() + try: + with open(path, encoding='utf-8') as stream: + data = yaml.safe_load(stream) + except (OSError, yaml.YAMLError) as error: + raise ValueError(f'cannot read the arm profile {path}: {error}') from None + return profile_from_dict(data if data is not None else {}, path) + + +def profile_from_dict(data, source='the arm profile'): + if not isinstance(data, dict): + raise ValueError(f'{source} must be a mapping') + unknown = sorted(set(data) - KEYS) + if unknown: + raise ValueError(f'{source} has unknown keys {unknown}; expected {sorted(KEYS)}') + fitted = data.get('fitted_drives') + if fitted is not None: + if (not isinstance(fitted, list) or not fitted + or any(not isinstance(name, str) for name in fitted) + or len(set(fitted)) != len(fitted)): + raise ValueError(f'{source}: fitted_drives must list distinct drive names') + fitted = tuple(fitted) + locked = data.get('locked_joints') or {} + if not isinstance(locked, dict) or any(not isinstance(joint, str) for joint in locked): + raise ValueError(f'{source}: locked_joints must map joint names to angles') + angles = {} + for joint, angle in locked.items(): + if isinstance(angle, bool) or not isinstance(angle, (int, float)) or not math.isfinite( + angle): + raise ValueError(f'{source}: locked joint {joint} needs a finite angle in radians') + angles[joint] = float(angle) + return ArmProfile(fitted, angles) + + +def fit_drive_parameters(params, profile): + """ + Return the drive node's parameters with only the profile's fitted drives. + + Every joint that only an unfitted drive moves must be locked, or nothing would report + where it is. + """ + drives = list(params['drives']) + if profile.fitted_drives is None: + fitted = drives + else: + unknown = sorted(set(profile.fitted_drives) - set(drives)) + if unknown: + raise ValueError(f'the arm profile fits drives {unknown} that the arm map lacks') + fitted = [name for name in drives if name in profile.fitted_drives] + + def joints(names): + try: + return {joint for name in names for joint in params[f'{name}.joints']} + except KeyError as missing: + raise ValueError(f'missing drive parameter {missing}') from None + driven = joints(fitted) + moved = sorted(driven & set(profile.locked_joints)) + if moved: + raise ValueError(f'locked joints {moved} are moved by fitted drives') + loose = sorted(joints(drives) - driven - set(profile.locked_joints)) + if loose: + raise ValueError(f'no fitted drive moves {loose}; lock them in the arm profile') + return {**params, 'drives': fitted} diff --git a/waybionic_teleop/waybionic_teleop/drive_map.py b/waybionic_teleop/waybionic_teleop/drive_map.py index a0913d2d..3c0bca73 100644 --- a/waybionic_teleop/waybionic_teleop/drive_map.py +++ b/waybionic_teleop/waybionic_teleop/drive_map.py @@ -69,10 +69,14 @@ def to_counts(self, positions): return [round(angle / (2 * math.pi) * self.counts_per_rev) for angle in self._shaft(positions)] + def shaft_rpm(self, velocities): + """Return each drive's signed shaft speed in rpm (positive counts up) for rad/s.""" + rates = self._shaft({joint: velocities.get(joint, 0.0) for joint in self.joints}) + return [rate * 60.0 / (2 * math.pi) for rate in rates] + def to_rpm(self, velocities): """Return each drive's shaft speed in rpm for joint velocities in rad/s.""" - rates = self._shaft({joint: velocities.get(joint, 0.0) for joint in self.joints}) - return [abs(rate) * 60.0 / (2 * math.pi) for rate in rates] + return [abs(rate) for rate in self.shaft_rpm(velocities)] def to_positions(self, counts): """Return joint positions in radians from one encoder reading per drive.""" diff --git a/waybionic_teleop/waybionic_teleop/frame_log.py b/waybionic_teleop/waybionic_teleop/frame_log.py new file mode 100644 index 00000000..72255d79 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/frame_log.py @@ -0,0 +1,54 @@ +"""Record every frame the drive node sends, receives or gets refused, for bench analysis.""" + +import time + + +def parse_line(line): + """Return (host time, kind, can_id, data) for a line that RecordingBus wrote.""" + stamp, kind, frame = line.split() + can_id, data = frame.split('#') + return float(stamp), kind, int(can_id, 16), bytes.fromhex(data) + + +class RecordingBus: + """ + Pass frames through to a bus, writing one line per frame to a file. + + Each line is the host's wall-clock time, the kind and the frame, such as + ``1793438841.369542 tx 001#F5008200FFE3A09A``. Kinds: tx (queued to the bus), unsent (the + bus was unplugged), rx (a frame the bus received) and refused (a frame the carrier or the + bus refused after send() returned True). + """ + + def __init__(self, bus, path): + self.bus = bus + self.file = open(path, 'a', encoding='ascii', buffering=1 << 16) + + def __getattr__(self, name): + return getattr(self.bus, name) + + def send(self, can_id, data): + sent = self.bus.send(can_id, data) + self._write('tx' if sent else 'unsent', can_id, data) + return sent + + def receive(self, *args, **kwargs): + frame = self.bus.receive(*args, **kwargs) + if frame is not None: + self._write('rx', *frame) + return frame + + def take_refused(self): + refused = self.bus.take_refused() + for can_id, data in refused: + self._write('refused', can_id, data) + return refused + + def shutdown(self): + try: + self.bus.shutdown() + finally: + self.file.close() + + def _write(self, kind, can_id, data): + self.file.write(f'{time.time():.6f} {kind} {can_id:03X}#{bytes(data).hex().upper()}\n') diff --git a/waybionic_teleop/waybionic_teleop/mks_can.py b/waybionic_teleop/waybionic_teleop/mks_can.py index f28e3c43..1004827e 100644 --- a/waybionic_teleop/waybionic_teleop/mks_can.py +++ b/waybionic_teleop/waybionic_teleop/mks_can.py @@ -7,12 +7,16 @@ """ COUNTS_PER_REV = 0x4000 +ERROR_COUNTS_PER_REV = 51200 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 +READ_RAW_ENCODER = 0x35 +READ_POSITION_ERROR = 0x39 +READ_ZERO_STATUS = 0x3B SET_MODE = 0x82 SET_BITRATE = 0x8A SET_CAN_ID = 0x8B @@ -80,12 +84,51 @@ def read_encoder(can_id): def encoder_value(arguments): - """Decode the signed 48-bit value of a 31h reply.""" + """Decode the signed 48-bit value of a 31h or 35h reply.""" if len(arguments) != 6: raise ValueError('an encoder reply carries 6 bytes') return int.from_bytes(arguments, 'big', signed=True) +def read_raw_encoder(can_id): + """ + Request the raw cumulative encoder value (35h), which a zero (92h) leaves alone. + + It counts from the shaft's magnetic angle at power-on, so it minus the 31h value stays the + same from one zero until the drive loses power (bench, firmware V1.0.9). + """ + return frame(can_id, READ_RAW_ENCODER) + + +def read_position_error(can_id): + """Request motor-shaft position error (39h), not a fault code or force measurement.""" + return frame(can_id, READ_POSITION_ERROR) + + +def position_error_value(arguments): + """Decode signed int32 position error; 51200 units represent one motor turn.""" + if len(arguments) != 4: + raise ValueError('a position error reply carries four bytes') + return int.from_bytes(arguments, 'big', signed=True) + + +def read_zero_status(can_id): + """Request the zero status (3Bh); zero_is_set reads its reply.""" + return frame(can_id, READ_ZERO_STATUS) + + +def zero_is_set(arguments): + """ + Return whether a 3Bh reply says the axis was zeroed since power-on. + + The drives answer two bytes, the second 1 after a zero (92h) and 2 from power-on until one + (bench, firmware V1.0.9). + """ + if len(arguments) != 2: + raise ValueError('a zero status reply carries 2 bytes') + return arguments[1] == 1 + + def set_mode(can_id, mode=MODE_SR_VFOC): """Select the work mode (82h); SR_vFOC is bus control with FOC.""" return frame(can_id, SET_MODE, [mode]) diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 3fdb429f..1326b017 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -5,6 +5,7 @@ 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 read-error 3 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 @@ -46,9 +47,13 @@ def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): time.sleep(0.002) continue reply_id, reply = frame + if reply_id == carrier.STATUS_ID: + continue try: reply_code, arguments = mks_can.parse(reply_id, reply) - except ValueError: + except ValueError as error: + if reply_id in answer_ids: + raise SystemExit(str(error)) from error continue if reply_id in answer_ids and reply_code == code: return arguments @@ -65,6 +70,18 @@ def scan(bus, ids): return found +def read_error(bus, can_id): + """Read signed position error without changing the drive's configuration or motion.""" + arguments = request( + bus, can_id, mks_can.read_position_error(can_id), mks_can.READ_POSITION_ERROR) + if arguments is None: + raise SystemExit(f'CAN ID {can_id} did not report its position error (39h)') + try: + return mks_can.position_error_value(arguments) + except ValueError as error: + raise SystemExit(f'CAN ID {can_id}: {error}') from error + + def set_id(bus, old, new): """Give the drive at old the CAN ID new; return a message, or raise SystemExit.""" if old == new: @@ -140,6 +157,9 @@ def main(argv=None): 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))) + error_command = commands.add_parser( + 'read-error', help='read signed motor position error (39h); does not move the motor') + error_command.add_argument('can_id', type=int) 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) @@ -149,6 +169,9 @@ def main(argv=None): commands.add_parser('stop', help='stop every drive at once (F7h to broadcast ID 0); give ' "the drives' --bitrate") args = parser.parse_args(argv) + if args.command == 'read-error' and ( + not 1 <= args.can_id <= 0x7FF or args.can_id == carrier.STATUS_ID): + parser.error('read-error needs a drive CAN ID from 1 to 2047, excluding carrier ID 2032') bus = open_bus(args.interface, args.channel, args.bitrate, args.tty_baudrate) try: @@ -164,6 +187,11 @@ def main(argv=None): print(set_id(bus, args.old, args.new)) elif args.command == 'set-bitrate': print(set_bitrate(bus, args.can_id, args.rate)) + elif args.command == 'read-error': + error = read_error(bus, args.can_id) + degrees = error * 360.0 / mks_can.ERROR_COUNTS_PER_REV + print(f'CAN ID {args.can_id}: position error {degrees:+.6f} motor deg ' + f'({error:+d} error counts)') else: stop = mks_can.emergency_stop(mks_can.BROADCAST_ID) if not send_confirmed(bus, mks_can.BROADCAST_ID, stop): diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 86c03381..23aa6300 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -9,7 +9,13 @@ 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 ``~/zero`` service on real drives. A drive that stops answering is treated as power-cycled: -every drive stops and the arm must be zeroed again. +every drive stops and the arm must be zeroed again. With ``zero_state`` naming a file, each +zero is saved there, and a drive keeps it, at start-up or once it answers again, if it shows +it has not lost power since: see ``check_zero``. + +``arm_profile`` names a file (waybionic_teleop/arm_profile.py) that lists the drives this arm +has fitted; each joint no fitted drive moves is published at its locked angle, and a command +must leave it there. Joint commands are accepted only after a valid robot_description and a fresh teleop enable that teleop keeps republishing. Whoever publishes ``/joint_commands`` must keep publishing @@ -17,9 +23,20 @@ drive stops where it is, whatever speed it was last given, so a publisher that dies cannot leave the arm running on to its last target. After any stop, teleop must be disabled and enabled again before the arm moves. + +A drive never gets a target behind a move it is running. MKS firmware V1.0.9 can keep such a +target and run to it on its own once the moves stop, even after a stop frame, so a drive is +stopped first, and after any stop of a running move it starts a new one only once its encoder +has stopped advancing. The firmware also keeps an occasional target sent mid-move, and runs +back to it once the move stops, however it stops. So every stop of a running move is followed +at once by a target where the drive is to stay, sent again every tick for ``HOLD_S``, which +takes such a run over within a tick. A drive that turns more than ``following_error_counts`` +after its stop while the arm is enabled stops every drive. """ +import datetime import math +import os import time from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue @@ -38,10 +55,13 @@ DriveHealthThresholds, ) from waybionic_teleop import carrier, mks_can +from waybionic_teleop.arm_profile import fit_drive_parameters, load_profile from waybionic_teleop.drive_map import drive_map_from_parameters +from waybionic_teleop.frame_log import RecordingBus from waybionic_teleop.kinematics import joint_limits from waybionic_teleop.ros_shutdown import is_shutdown_error from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo +import yaml REPLY_TIMEOUT_S = 0.5 REPORT_PERIOD_S = 0.5 @@ -56,6 +76,28 @@ # F5 replies of a drive that no longer follows its targets: run failed, as when stall # protection releases the motor, and stopped at an end limit. RUN_FAULTS = (0, 3) +# Teleop sends a locked joint's angle back unchanged; anything beyond rounding is a move. +LOCKED_TOLERANCE_RAD = 1e-6 +# A drive stopped mid-move starts again once an encoder reading this long after its stop no +# longer advances the old way, or once it reports the stop complete and barely moves. Bench +# reversals on firmware V1.0.9 settled in 17 ms (median) and 42 ms at most at 120 Hz. +SETTLE_S = 0.012 +SETTLED_STEP_COUNTS = 5 +# A drive at rest starts a move only toward a target this far ahead in the commanded +# direction, so a target that its stop overshot never starts a move the wrong way. +START_DEADBAND_COUNTS = 30 +# After the stop of a running move, a drive gets its hold target right behind the stop and +# again every tick for HOLD_S, at HOLD_RPM at most. On the bench (firmware V1.0.9, base, 80 +# stops each), no run back to a kept target started with the hold right behind the stop, and +# none went past 107 counts; with the hold 1 ms later, 5 started and ended within 437 counts, +# and with only a re-target once a run showed, 7 ran up to 2515 counts. +HOLD_RPM = 60 +HOLD_S = 0.25 +# A drive keeps its zero across a restart of this node only while its zero status says it was +# zeroed since power-on and its raw-minus-zeroed encoder offset is the one saved at the zero, +# give or take the counts it turns between two replies at rest (bench: 2 at most). +ZERO_MATCH_COUNTS = 16 +ZERO_CHECK_TIMEOUT_S = 2.0 def status(name, level, value, unit, message, **extra): @@ -72,6 +114,10 @@ def __init__(self, **kwargs): **kwargs) params = {name: self.get_parameter(name).value for name in self.list_parameters([], 0).names} + # Joints whose drive this arm lacks hold still at the profile's angles. + profile = load_profile(params.get('arm_profile', '')) + params = fit_drive_parameters(params, profile) + self.locked = dict(profile.locked_joints) self.map = drive_map_from_parameters(params, mks_can.COUNTS_PER_REV) self.acc = int(params['acc']) self.max_rpm = int(params['max_rpm']) @@ -104,8 +150,9 @@ def __init__(self, **kwargs): if self.interface != 'sim': # Real drives move only joints whose URDF limits are known. unmodeled = set() - elif not unmodeled <= set(self.map.joints): + elif not unmodeled <= set(self.map.joints) | set(self.locked): raise ValueError('unmodeled_joints must name drives in the simulated map') + unmodeled -= set(self.locked) self.modeled_joints = [joint for joint in self.map.joints if joint not in unmodeled] if not self.modeled_joints: raise ValueError('at least one drive joint needs a URDF limit') @@ -128,6 +175,9 @@ def __init__(self, **kwargs): from waybionic_teleop.can_bus import CanBus self.bus = CanBus(self.interface, channel, self.bitrate) self.bus_label = f'{self.interface} {channel}' + if frame_log := params.get('frame_log', ''): + self.bus = RecordingBus(self.bus, os.path.expanduser(frame_log)) + self.get_logger().info(f'Recording every drive frame to {frame_log}') self.test_fault = None if self.interface == 'sim': self.declare_parameter('test_fault', 'none') @@ -145,6 +195,17 @@ def __init__(self, **kwargs): self.setup_time = [None] * len(drives) self.state = ['starting'] * len(drives) self.sent = [None] * len(drives) + # Each drive's running move: +1 or -1 counts up or down, 0 at rest. After the stop of + # a running move, (time of the stop, its direction) until the drive has settled. + self.direction = [0] * len(drives) + self.settling = [None] * len(drives) + # Where each drive was told to stay at its last stop, which it must keep, and until + # when that target goes out again every tick, with the tick it last went out. + self.held = [None] * len(drives) + self.hold_until = [-math.inf] * len(drives) + self.hold_tick = [-1] * len(drives) + self.ticks = 0 + self.completed = [-math.inf] * len(drives) self.drive_health_monitors = [ DriveHealthMonitor(health_thresholds) for _ in drives] self.drive_health_states = [None] * len(drives) @@ -167,6 +228,10 @@ def __init__(self, **kwargs): self.awaiting_release = True self.rejected = 0 self.bus_errors = 0 + # The file the zero is saved in, each drive's saved offset (see check_zero), the + # offsets read since the last zero, and the drives whose zero is being checked. + self.zero_state = os.path.expanduser(params.get('zero_state', '') or '') + self.saved_zero, self.zero_offsets, self.checks = {}, {}, {} if self.interface == 'sim': self.add_on_set_parameters_callback(self.on_test_fault_parameter) for index in range(len(drives)): @@ -174,6 +239,10 @@ def __init__(self, **kwargs): zero_on_start = params.get('zero_on_start', self.interface == 'sim') if zero_on_start: self.zero() + else: + self.saved_zero = self.load_zero() + for index in self.saved_zero: + self.check_zero(index, 'restore') self.stop_reason = 'Waiting for robot_description and a released Start button' topic = params.get('diagnostics_topic', '/diagnostics') latched = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) @@ -193,7 +262,10 @@ def __init__(self, **kwargs): 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: + if self.checks: + self.get_logger().info( + f'Checking whether the drives kept the zero saved in {self.zero_state}') + elif not zero_on_start: self.get_logger().warning(f'Not zeroed. {self.zero_hint()}') def zero_hint(self): @@ -220,10 +292,14 @@ def stop_all(self, reason): def zero(self): """Make the current pose every drive's zero.""" + # A hold in the old coordinates would move the arm after the zero, so none goes out. + self.zeroed = [False] * len(self.map.drives) + self.forget_zero() self.stop_all('Zeroing the drives') + self.held = [None] * len(self.map.drives) + self.hold_until = [-math.inf] * len(self.map.drives) for drive in self.map.drives: self.bus.send(drive.can_id, mks_can.set_zero(drive.can_id)) - self.zeroed = [False] * len(self.map.drives) def on_zero(self, request, response): if time.monotonic() - self.command_time < QUIET_BEFORE_ZERO_S: @@ -241,6 +317,115 @@ def on_zero(self, request, response): self.get_logger().info(response.message) return response + def check_zero(self, index, purpose): + """ + Read a drive's zero fingerprint, to save it after a zero or restore it with ``restore``. + + The raw encoder (35h) counts from power-on and a zero leaves it alone, so it minus the + zeroed count stays the same from one zero until the drive loses power, and the zero + status (3Bh) says whether the drive was zeroed since power-on. A drive keeps its saved + zero only if its status shows a zero, which a power cycle clears, and its offset is the + saved one, which a zero made elsewhere would change. + """ + self.checks[index] = {'purpose': purpose, 'raw': None, 'count': None, 'set': None, + 'deadline': time.monotonic() + ZERO_CHECK_TIMEOUT_S} + + def send_checks(self, now): + for index, check in list(self.checks.items()): + drive = self.map.drives[index] + if self.heard[index] is None or now - self.heard[index] > REPLY_TIMEOUT_S: + # The check times out only while the drive answers, as the carrier may still + # be starting. + check['deadline'] = now + ZERO_CHECK_TIMEOUT_S + continue + if now > check['deadline']: + del self.checks[index] + self.get_logger().warning( + f'{drive.name} did not report its zero status, so its zero is ' + + ('not saved' if check['purpose'] == 'save' + else f'not restored. {self.zero_hint()}')) + continue + if check['raw'] is None: + self.bus.send(drive.can_id, mks_can.read_raw_encoder(drive.can_id)) + if check['set'] is None: + self.bus.send(drive.can_id, mks_can.read_zero_status(drive.can_id)) + + def finish_check(self, index): + check = self.checks[index] + if None in (check['raw'], check['count'], check['set']): + return + del self.checks[index] + name = self.map.drives[index].name + offset = check['raw'] - check['count'] + if check['purpose'] == 'save': + if not check['set']: + self.get_logger().warning(f'{name} does not report its zero, so it is not saved') + return + self.zero_offsets[index] = offset + if len(self.zero_offsets) == len(self.map.drives): + self.save_zero() + return + saved = self.saved_zero[index] + if not check['set']: + reason = 'lost power since its last zero' + elif abs(offset - saved) > ZERO_MATCH_COUNTS: + reason = f'was zeroed elsewhere since (offset {offset}, saved {saved})' + else: + self.zeroed[index] = True + # Its last hold is from before it went quiet, so it gets a new one at its next stop. + self.held[index], self.hold_until[index] = None, -math.inf + self.get_logger().info(f'{name} kept its zero') + if all(self.zeroed): + self.get_logger().info('Every drive kept its zero; teleop can be enabled') + return + self.get_logger().warning(f'{name} {reason}, so it is not zeroed. {self.zero_hint()}') + + def load_zero(self): + """Return each drive's saved offset by index, for the drives the zero file names.""" + if not self.zero_state: + return {} + try: + with open(self.zero_state, encoding='utf-8') as file: + saved = yaml.safe_load(file)['drives'] + return {index: int(saved[drive.name]['offset']) + for index, drive in enumerate(self.map.drives) + if drive.name in saved and int(saved[drive.name]['can_id']) == drive.can_id} + except FileNotFoundError: + return {} + except (OSError, yaml.YAMLError, AttributeError, KeyError, TypeError, + ValueError) as error: + self.get_logger().warning(f'Ignoring the zero saved in {self.zero_state}: {error}') + return {} + + def save_zero(self): + drives = {drive.name: {'can_id': drive.can_id, 'offset': self.zero_offsets[index]} + for index, drive in enumerate(self.map.drives)} + saved = {'saved': datetime.datetime.now().isoformat(timespec='seconds'), + 'drives': drives} + partial = self.zero_state + '.partial' + try: + os.makedirs(os.path.dirname(self.zero_state) or '.', exist_ok=True) + with open(partial, 'w', encoding='utf-8') as file: + yaml.safe_dump(saved, file, sort_keys=False) + os.replace(partial, self.zero_state) + except OSError as error: + self.get_logger().warning(f'Could not save the zero to {self.zero_state}: {error}') + return + self.saved_zero = dict(self.zero_offsets) + self.get_logger().info(f'Saved the zero to {self.zero_state}') + + def forget_zero(self): + """Drop the saved zero, so no later start or reconnect restores it.""" + self.saved_zero, self.zero_offsets, self.checks = {}, {}, {} + if not self.zero_state: + return + try: + os.remove(self.zero_state) + except FileNotFoundError: + pass + except OSError as error: + self.get_logger().warning(f'Could not remove {self.zero_state}: {error}') + def on_description(self, message): self.disarm('Robot description changed', require_release=True) try: @@ -277,7 +462,14 @@ def disarm(self, reason, require_release=False): self.awaiting_release = self.awaiting_release or require_release self.commanded = None self.velocities.clear() - self.sent = [None] * len(self.map.drives) + # A drive whose stop has not gone out yet still runs its last move. + self.sent = [sent if index in self.stopping else None + for index, sent in enumerate(self.sent)] + # The stops just sent must settle before a fresh Start moves those drives again. + now = time.monotonic() + self.settling = [(now, direction) if direction else settling + for direction, settling in zip(self.direction, self.settling)] + self.direction = [0] * len(self.map.drives) self.stop_reason = reason def on_command(self, message): @@ -285,13 +477,20 @@ def on_command(self, message): if not self.authorized or self.commanded is None: return names = message.name - if (len(names) != len(self.map.joints) or set(names) != set(self.map.joints) + expected = set(self.map.joints) | set(self.locked) + if (len(names) != len(expected) or set(names) != expected or len(message.position) != len(names) or len(message.velocity) != len(names) or any(not math.isfinite(value) for value in message.position) or any(not math.isfinite(value) for value in message.velocity)): self.reject_command('incomplete, duplicate or nonfinite joint command') return positions = dict(zip(names, message.position)) + velocities = dict(zip(names, message.velocity)) + for joint, angle in self.locked.items(): + if abs(positions.pop(joint) - angle) > LOCKED_TOLERANCE_RAD: + self.reject_command(f'{joint} is locked at {angle:g} rad') + return + del velocities[joint] measured = self.map.to_positions(self.counts) for joint, (lower, upper) in self.limits.items(): position, actual = positions[joint], measured[joint] @@ -301,7 +500,7 @@ def on_command(self, message): self.reject_command(f'{joint} target outside its URDF range') return self.commanded = positions - self.velocities = dict(zip(names, message.velocity)) + self.velocities = velocities # 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) @@ -323,6 +522,7 @@ def reject_command(self, reason): def tick(self): now = time.monotonic() dt, self.last_tick = now - self.last_tick, now + self.ticks += 1 # The old motion must consume the entire elapsed host time before any new frame # can reset its heartbeat. A pause requires a released and newly pressed Start. self.bus.step(dt) @@ -354,6 +554,8 @@ def tick(self): self.disarm('Teleop enable timed out', require_release=True) if self.authorized and self.commanded is not None: self.send_targets() + self.send_holds(now) + self.send_checks(now) for index, drive in enumerate(self.map.drives): self.bus.send(drive.can_id, mks_can.read_encoder(drive.can_id)) self.unanswered[index] += 1 @@ -365,6 +567,7 @@ def tick(self): if self.commanded is None: # Hold the actual encoder pose while disarmed, including after a host pause. self.commanded = dict(positions) + positions.update(self.locked) message = JointState(name=list(positions), position=list(positions.values())) message.header.stamp = self.get_clock().now().to_msg() self.state_publisher.publish(message) @@ -384,23 +587,43 @@ def lose(self, index, reason): """Treat a drive as power-cycled: every drive stops until the arm is zeroed again.""" name = self.map.drives[index].name self.lost[index], self.zeroed[index] = True, False + self.checks.pop(index, None) self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped') def check_following(self): for index, (sent, count) in enumerate(zip(self.sent, self.counts)): - axis = sent[0] if self.authorized and sent else None - if axis is None or count is None or abs(axis - count) <= self.following_error: + # A stopped drive must stay where it stopped, armed or not, as its firmware can + # run on to a kept target after any stop. + target = None + if self.authorized and sent: + target = self.held[index] if sent[0] is None else sent[0] + elif not self.authorized and index not in self.stopping and self.zeroed[index]: + target = self.held[index] + if target is None or count is None or abs(target - count) <= self.following_error: self.behind[index] = 0 continue self.behind[index] += 1 - if self.behind[index] >= self.following_ticks: - self.fault(index, f'is {abs(axis - count)} counts from its target') + if self.behind[index] < self.following_ticks: + continue + if self.authorized and sent[0] is not None: + self.fault(index, f'is {abs(target - count)} counts from its target') + continue + # Its encoder still counts true, so the arm keeps its zero. Its last stop did not + # hold it, so it gets another, and no hold drives it back that far. + name = self.map.drives[index].name + reason = f'{name} turned {count - target:+d} counts after its stop' + self.held[index], self.hold_until[index] = None, -math.inf + self.stopping.add(index) + self.stop_all(reason) + self.get_logger().error(f'{reason}; every drive is stopped') def fault(self, index, reason): """Stop every drive after one stops following; the arm must be zeroed again.""" name = self.map.drives[index].name self.zeroed[index] = False + # A restart must not bring back a zero the arm no longer follows. + self.forget_zero() self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped. {self.zero_hint()}') @@ -413,41 +636,111 @@ def stop_drives(self): def send_stops(self): # A refused stop goes out again on every tick, as the encoder polls keep the drive's # heartbeat from stopping it. + now = time.monotonic() for index in sorted(self.stopping): drive = self.map.drives[index] data = mks_can.stop(drive.can_id, 0) + # The hold is where the drive is once the stop goes out, not when it was asked for. + target, running = self.hold_target(index, now) if self.bus.send(drive.can_id, data): self.stopping.discard(index) - self.sent[index] = (None, 0) + self.sent[index], self.held[index] = (None, 0), target self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + self.hold_until[index] = -math.inf + if running: + self.start_hold(index, now) def send_targets(self): try: moves = self.map.synchronized(self.commanded, self.counts, self.period, self.max_rpm, self.velocities) - motor_rates = self.map.to_rpm(self.velocities) + motor_rates = self.map.shaft_rpm(self.velocities) commands = [] # Preflight every int24 axis and frame before sending any coupled motor an update. - for drive, (axis, speed), rpm in zip(self.map.drives, moves, motor_rates): + for drive, (axis, speed) in zip(self.map.drives, moves): if not mks_can.MIN_AXIS <= axis <= mks_can.MAX_AXIS: raise ValueError(f'{drive.name}: axis {axis} is outside int24') - if rpm == 0.0: - key = (None, 0) - data = mks_can.absolute_axis(drive.can_id, 0, 0, 0) - else: - key = (axis, speed) - data = mks_can.absolute_axis(drive.can_id, axis, speed, self.acc) - commands.append((key, data)) + commands.append(mks_can.absolute_axis(drive.can_id, axis, speed, self.acc)) except (ValueError, OverflowError) as error: self.reject_command(f'Cannot synchronize drives: {error}') return - for index, (drive, (key, data)) in enumerate(zip(self.map.drives, commands)): - if self.sent[index] == key: - continue - # A frame the interface refused is sent again on the next tick. - if self.bus.send(drive.can_id, data): - self.sent[index] = key - self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + for index, (drive, (axis, speed), rpm, data) in enumerate( + zip(self.map.drives, moves, motor_rates, commands)): + ahead, direction = axis - self.counts[index], self.direction[index] + if (rpm == 0.0 or self.settling[index] is not None + or (direction and ahead * direction < 0)): + # A refused stop goes out again on the next tick, like a refused target. + self.hold(index) + elif direction or (abs(ahead) > START_DEADBAND_COUNTS and ahead * rpm > 0): + if self.sent[index] != (axis, speed) and self.bus.send(drive.can_id, data): + self.sent[index], self.held[index] = (axis, speed), None + self.hold_until[index] = -math.inf + self.direction[index] = direction or (1 if ahead > 0 else -1) + self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + + def hold(self, index): + """Stop one armed drive where it is; a running move must then settle.""" + if self.sent[index] != (None, 0): + drive = self.map.drives[index] + data = mks_can.stop(drive.can_id, 0) + now = time.monotonic() + target, running = self.hold_target(index, now) + if not self.bus.send(drive.can_id, data): + return + self.sent[index], self.held[index] = (None, 0), target + self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + if running: + self.start_hold(index, now) + else: + self.hold_until[index] = -math.inf + if self.direction[index]: + self.settling[index] = (time.monotonic(), self.direction[index]) + self.direction[index] = 0 + + def hold_target(self, index, now): + """Return where a drive about to be stopped is to stay, and if it must be held there.""" + sent, count = self.sent[index], self.counts[index] + if self.held[index] is not None and now < self.hold_until[index]: + # A stop ends the drive's run to its hold, after which it must keep holding. + return self.held[index], True + if not sent or sent[0] is None or count is None: + return count, False + # The running move's end, though never more than a lagging drive covers in two ticks, + # or since its last count if that is older. + axis, speed = sent + reach = round(max(2 * self.period, self.since_count[index] + self.period) * speed + / 60.0 * mks_can.COUNTS_PER_REV) + START_DEADBAND_COUNTS + target = min(max(axis, count - reach), count + reach) + return min(max(target, mks_can.MIN_AXIS), mks_can.MAX_AXIS), True + + def start_hold(self, index, now): + self.hold_until[index] = now + HOLD_S + self.send_hold(index, now) + + def send_holds(self, now): + for index in range(len(self.map.drives)): + if now < self.hold_until[index] and self.hold_tick[index] != self.ticks: + self.send_hold(index, now) + + def send_hold(self, index, now): + """Send a drive its hold target, unless it may have lost the zero that target uses.""" + held, count, heard = self.held[index], self.counts[index], self.heard[index] + if (held is None or count is None or heard is None or now - heard > REPLY_TIMEOUT_S + or abs(held - count) > self.following_error or index in self.stopping + or not self.zeroed[index] or self.lost[index] or self.estop_pressed): + return + can_id = self.map.drives[index].can_id + # Not a last command: a refused hold simply goes out again on the next tick. + if self.bus.send(can_id, mks_can.absolute_axis( + can_id, held, min(HOLD_RPM, self.max_rpm), self.acc)): + self.hold_tick[index] = self.ticks + + def settle(self, index, step): + """Let a stopped drive move again once an encoder step shows it no longer runs on.""" + stopped_at, old = self.settling[index] + if ((self.completed[index] > stopped_at and abs(step) < SETTLED_STEP_COUNTS) + or (time.monotonic() - stopped_at > SETTLE_S and step * old <= 0)): + self.settling[index] = None def drain(self, now, zeroing=False): while (reply := self.bus.receive()) is not None: @@ -465,7 +758,8 @@ def on_refused(self, can_id, data, zeroing): 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. + # While disarmed the last command is a stop, as holds never are one, and + # send_stops repeats a stop until it is sent. if self.authorized: self.sent[index] = None else: @@ -487,7 +781,9 @@ def on_reply(self, can_id, data, now): return if self.estop_pressed and not pressed: # The e-stop cuts the drives' power; Start is refused until it is released. + # A drive may restart with a new count, so no hold goes out after the release. self.stop_all('E-stop pressed') + self.hold_until = [-math.inf] * len(self.map.drives) self.get_logger().error('E-stop pressed; every drive is stopped') return index = self.index.get(can_id) @@ -503,8 +799,13 @@ def on_reply(self, can_id, data, now): # It may have been power-cycled, which loses its settings and its zero. self.lost[index] = False self.set_up(index) - self.get_logger().warning( - f'{self.map.drives[index].name} answers again. {self.zero_hint()}') + name = self.map.drives[index].name + if index in self.saved_zero: + self.check_zero(index, 'restore') + self.get_logger().warning( + f'{name} answers again; checking whether it kept its zero') + else: + self.get_logger().warning(f'{name} answers again. {self.zero_hint()}') failed = None jump = None try: @@ -517,13 +818,27 @@ def on_reply(self, can_id, data, now): if previous is not None and abs(count - previous) > most: jump = count - previous self.counts[index], self.since_count[index] = count, 0.0 + if index in self.checks: + self.checks[index]['count'] = count + if self.settling[index] is not None and previous is not None: + self.settle(index, count - previous) + elif code == mks_can.READ_RAW_ENCODER: + if index in self.checks: + self.checks[index]['raw'] = mks_can.encoder_value(arguments) + elif code == mks_can.READ_ZERO_STATUS: + if index in self.checks: + self.checks[index]['set'] = mks_can.zero_is_set(arguments) elif code == mks_can.ABSOLUTE_AXIS and arguments: self.state[index] = mks_can.RUN_STATUS.get(arguments[0], f'status {arguments[0]}') if arguments[0] in RUN_FAULTS: failed = self.state[index] + elif arguments[0] == 2: + self.completed[index] = time.monotonic() elif code == mks_can.SET_ZERO and arguments[:1] == b'\x01': # Later encoder replies were read after the zero. self.zeroed[index], self.counts[index] = True, None + if self.zero_state: + self.check_zero(index, 'save') elif arguments[:1] == b'\x00': self.state[index] = f'setup {code:02X}h failed' elif code in SETUP: @@ -538,7 +853,9 @@ def on_reply(self, can_id, data, now): if jump is not None: # A drive that browned out and restarted answers well before it counts as silent. self.lose(index, f'encoder jumped {jump:+d} counts') - # Only stop frames go out while disarmed, and a released motor refuses those too. + if index in self.checks: + self.finish_check(index) + # Only stops and holds go out while disarmed, and a released motor refuses those too. if failed and self.authorized: self.fault(index, failed) @@ -567,8 +884,11 @@ def report(self): 'enabled' if self.authorized else 'stopped', '', self.stop_reason or 'Receiving validated teleop setpoints')) if not all(self.zeroed): - statuses.append(status('arm.zero', DiagnosticStatus.WARN, 'no', '', - f'Not zeroed. {self.zero_hint()}')) + restoring = any(check['purpose'] == 'restore' for check in self.checks.values()) + statuses.append(status( + 'arm.zero', DiagnosticStatus.WARN, 'checking' if restoring else 'no', '', + 'Checking whether the drives kept their saved zero' if restoring + else f'Not zeroed. {self.zero_hint()}')) elif None not in self.counts: positions = self.map.to_positions(self.counts) commanded = self.commanded or {} @@ -715,14 +1035,23 @@ def close(self): 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. + # answers and repeat refused stops before closing it. The holds behind the + # stops go out every period meanwhile, as on any tick. deadline = time.monotonic() + CLOSE_TIMEOUT_S self.drain(time.monotonic()) - while (self.bus.connected and (self.stopping or self.bus.unanswered) - and time.monotonic() < deadline): + last_hold = time.monotonic() + while self.bus.connected and time.monotonic() < deadline: + now = time.monotonic() + holding = any(now < until for until in self.hold_until) + if not (self.stopping or self.bus.unanswered or holding): + break time.sleep(0.002) - self.drain(time.monotonic()) + now = time.monotonic() + self.drain(now) self.send_stops() + if now - last_hold >= self.period: + last_hold, self.ticks = now, self.ticks + 1 + self.send_holds(now) finally: # Even if a second Ctrl+C lands here, the queued stops and C still go out. self.bus.shutdown() diff --git a/waybionic_teleop/waybionic_teleop/sim_drives.py b/waybionic_teleop/waybionic_teleop/sim_drives.py index 032a6491..4fc08b11 100644 --- a/waybionic_teleop/waybionic_teleop/sim_drives.py +++ b/waybionic_teleop/waybionic_teleop/sim_drives.py @@ -6,6 +6,11 @@ from waybionic_teleop import mks_can MAX_STEP_S = 0.01 +# Firmware V1.0.9 keeps a target behind a running move. Bench runs sent 250 targets up to one +# 120 Hz host tick of travel behind the drive without one being kept, so only a target farther +# behind than this much travel is kept here. The bench drives also kept an occasional target +# ahead of the move, which tests set as latched directly. +LATCH_MARGIN_S = 0.01 def ramp_rpm_per_s(acc): @@ -31,10 +36,17 @@ def __init__(self, can_id, bitrate=500000): self.quiet_ms = 0.0 self.heartbeat_stops = 0 self.axis = 0.0 + # The raw encoder (35h) is the axis plus this shift, which a zero (92h) grows by the + # axis it clears; power-on resets the axis to 0 at the shaft's magnetic angle. + self.raw_shift = 0 + self.zero_set = False self.rpm = 0.0 self.target = None self.speed = 0 self.acc = 0 + # Firmware V1.0.9 keeps a target that reverses a running move, as on the bench, and + # runs to it once the moves stop: at a stop, an emergency stop or the last target. + self.latched = None def set_test_fault(self, fault=None): """Activate or clear a simulator-only drive fault.""" @@ -47,7 +59,14 @@ def set_test_fault(self, fault=None): if fault == 'disabled': self._enabled_before_test_fault = self.enabled self.enabled = False - self.target, self.rpm = None, 0.0 + self.target, self.rpm, self.latched = None, 0.0, None + + def power_cycle(self, magnetic_angle=0): + """Lose power and come back where the shaft is: settings, move and zero are gone.""" + self.mode, self.enabled, self.heartbeat_ms, self.quiet_ms = None, False, 0, 0.0 + self.respond, self.active = True, True + self.target, self.rpm, self.latched, self.speed, self.acc = None, 0.0, None, 0, 0 + self.axis, self.raw_shift, self.zero_set = 0.0, int(magnetic_angle), False def receive(self, data, address=None): """Handle one command sent to address (by default this drive's ID); return the replies.""" @@ -61,6 +80,14 @@ def _handle(self, code, arguments): value = round(self.axis).to_bytes(6, 'big', signed=True) return ([mks_can.frame(self.can_id, code, value)] if self._responding() else []) + if code == mks_can.READ_RAW_ENCODER and not arguments: + value = (round(self.axis) + self.raw_shift).to_bytes(6, 'big', signed=True) + return ([mks_can.frame(self.can_id, code, value)] + if self._responding() else []) + if code == mks_can.READ_ZERO_STATUS and not arguments: + value = [2, 1 if self.zero_set else 2] + return ([mks_can.frame(self.can_id, code, value)] + if self._responding() else []) if code == mks_can.SET_MODE and len(arguments) == 1: self.mode, status = arguments[0], 1 elif code == mks_can.SET_RESPONSE and len(arguments) == 2: @@ -68,16 +95,19 @@ def _handle(self, code, arguments): elif code == mks_can.SET_HEARTBEAT and len(arguments) == 4: self.heartbeat_ms, status = int.from_bytes(arguments, 'big'), 1 elif code == mks_can.SET_ZERO and not arguments: - self.axis, self.rpm, self.target, status = 0.0, 0.0, None, 1 + self.raw_shift += round(self.axis) + self.axis, self.rpm, self.target, self.latched, status = 0.0, 0.0, None, None, 1 + self.zero_set = True elif code == mks_can.ENABLE and len(arguments) == 1: self.enabled = bool(arguments[0]) and self.test_fault != 'disabled' status = 1 if not self.enabled: - self.target, self.rpm = None, 0.0 + self.target, self.rpm, self.latched = None, 0.0, None 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 + self._run_latched() 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) @@ -109,11 +139,23 @@ def start_move(self, arguments): self.target = None if not self.acc: self.rpm = 0.0 - return 2 + return 1 if self._run_latched() else 2 return 1 - self.target = int.from_bytes(arguments[3:], 'big', signed=True) + target = int.from_bytes(arguments[3:], 'big', signed=True) + margin = abs(self.rpm) / 60.0 * mks_can.COUNTS_PER_REV * LATCH_MARGIN_S + if (self.rpm * (target - self.axis) < 0 and abs(target - self.axis) > margin + and self.latched is None): + self.latched = (target, self.speed, self.acc) + self.target = target return 1 + def _run_latched(self): + """Start the move to a latched target, as V1.0.9 does once its moves stop.""" + if self.latched is None: + return False + (self.target, self.speed, self.acc), self.latched = self.latched, None + return True + def step(self, dt): """Advance the motor by dt seconds and return any frames it sends unprompted.""" frames = [] @@ -154,6 +196,8 @@ def _advance(self, dt): remaining = self.target - self.axis if abs(remaining) < 0.5 or (move * remaining > 0 and abs(move) >= abs(remaining)): self.axis, self.rpm, self.target = float(self.target), 0.0, None + if self._run_latched(): + return [] if self._responding() and self.active: return [mks_can.frame(self.can_id, mks_can.ABSOLUTE_AXIS, [2])] return [] diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 08133f17..05bc88c7 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -12,9 +12,17 @@ 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. No more lines go unanswered at once than the carrier can queue; a frame beyond that is refused here. + +SLCAN has no sessions, so the carrier can still have answers to send from before: the last +program may have closed the port with answers still in the carrier's USB buffer, or a quiet +carrier may answer lines written before it was opened again. Each start therefore asks for the +version first and drops everything until that answer, so no old answer is pinned on a new line. +Shutdown waits briefly for the close acknowledgement before releasing USB: write() alone +does not guarantee the carrier has received the final line. """ from collections import deque +import logging import time import serial @@ -27,6 +35,7 @@ # 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 +CLOSE_TIMEOUT_S = 0.25 # 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 @@ -142,22 +151,41 @@ def step(self, dt): self._start() def shutdown(self): - if self.serial is not None: + if self.serial is None: + return + errors, refused = self.errors, self.refused + try: self.outgoing += b'C\r' self.queued.append(b'C') self._flush() - if self.serial is not None: - self.serial.close() - self.serial = None + deadline = time.monotonic() + CLOSE_TIMEOUT_S + while self.serial is not None and self.pending and time.monotonic() < deadline: + self._read() + if self.pending: + time.sleep(0.001) + if self.serial is not None and self.pending: + self.errors += 1 + self.problem = f'carrier did not acknowledge close within {CLOSE_TIMEOUT_S:g} s' + if self.errors > errors or self.refused > refused: + if not self.problem: + self.problem = 'carrier refused a command or sent malformed data while closing' + logging.getLogger(__name__).warning('Carrier close: %s', self.problem) + finally: + if self.serial is not None: + try: + self.serial.close() + finally: + self.serial = None def _start(self): - # Close in case it was left open, set the bit rate, open. Each answers \r, or \a. + # Close in case it was left open, set the bit rate, open. Each answers \r, or \a. The + # version's answer, such as V0100, comes first and marks where this start's answers begin. commands = [b'C', b'S' + BITRATE_CODES[self.bitrate], b'O'] - self.outgoing[:0] = b''.join(command + b'\r' for command in commands) + self.outgoing[:0] = b'V\r' + b''.join(command + b'\r' for command in commands) self.queued[:0] = commands - # A carrier that reset will never answer the lines written before. + # Answers to the lines written before are dropped until the version's answer. self.pending.clear() - self.bell, self.full_since = False, None + self.syncing, self.bell, self.full_since = True, False, None self.heard = time.monotonic() self._flush() @@ -190,7 +218,10 @@ def _read(self): continue line = bytes(self.incoming[start:end]) start = end + 1 - if byte == BELL: + if self.syncing: + # Bytes from before may run into the answer, so look only at the line's end. + self.syncing = not (byte == CR and line[-5:-4] == b'V') + elif byte == BELL: self._refused() elif not line: self._answered() @@ -212,8 +243,10 @@ def _refused(self): 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' + # An R4's own CAN controller keeps the rate it first opened at until it resets. + self.problem = (f'the carrier would not open CAN at {self.bitrate} bit/s: an 8 MHz ' + 'MCP2515 runs 500000 at most, and one that opened at another rate ' + 'needs a replug') self.errors += 1 def _answered(self): diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index bd003642..7a997bc7 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -134,8 +134,13 @@ def check_config(config): class ArmTeleop: """Hold joint targets and move them with the active group's sticks while enabled.""" - def __init__(self, config, limits, kinematics=None, collision=None): - """Take the config, {joint: (lower, upper)} radians, ArmKinematics and ArmCollision.""" + def __init__(self, config, limits, kinematics=None, collision=None, locked=None): + """ + Take the config, {joint: (lower, upper)} radians, ArmKinematics and ArmCollision. + + locked gives {joint: angle} for joints that cannot move on this arm, which then stay + at that angle as if it were both of their limits. + """ check_config(config) self.config = config self.kinematics = kinematics @@ -153,6 +158,10 @@ def __init__(self, config, limits, kinematics=None, collision=None): f'{group.mode.capitalize()} group {group.name} does not match the URDF chain') self.limits = dict(limits) self.limits[config.tool_joint] = config.tool_limits + self.locked = {joint: angle for joint, angle in (locked or {}).items() + if joint in self.limits} + for joint, angle in self.locked.items(): + self.limits[joint] = (angle, angle) self.enabled = False self.group = 0 self.level = config.speed_level @@ -261,6 +270,7 @@ def enable(self, measured, axes): self.targets = {joint: measured[joint] for joint in self.limits} self.command_targets = dict(self.targets) self.velocities = dict.fromkeys(self.limits, 0.0) + self.pin_locked() self.stop_cartesian() self.wait_for_center = False self.enabled, self.note, self.warning = True, '', False @@ -275,6 +285,13 @@ def disable(self, measured, note, warning=False): self.targets.update({joint: measured[joint] for joint in self.limits if joint in measured and math.isfinite(measured[joint])}) self.command_targets = dict(self.targets) + self.pin_locked() + + def pin_locked(self): + # A solve may leave a locked joint a rounding error off its angle; send it unchanged. + for joint, angle in self.locked.items(): + self.targets[joint] = self.command_targets[joint] = angle + self.velocities[joint] = 0.0 def stop_cartesian(self): self.linear, self.tilt, self.roll, self.insert = (0.0, 0.0, 0.0), 0.0, 0.0, 0.0 @@ -325,6 +342,7 @@ def move(self, axes, homing, dt): self.command_targets[joint] = clamp( target + velocity * config.period, min(lower, target), max(upper, target)) self.avoid_collisions(before) + self.pin_locked() def avoid_collisions(self, before): """Undo this step's arm motion if it would take a link into the table or the base.""" diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index 4caa3727..9a5cc3d4 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -2,8 +2,9 @@ Drive the arm from an Xbox controller: /joy in, /joint_commands out. Mapping and limits come from config/xbox_teleop.yaml and the robot_description joint limits; -the logic lives in :mod:`waybionic_teleop.teleop`. The node also reports its state on -/diagnostics and draws a placeholder end effector and a status label in RViz. +a joint the arm profile (``arm_profile``) locks stays at its angle. The logic lives in +:mod:`waybionic_teleop.teleop`. The node also reports its state on /diagnostics and draws a +placeholder end effector and a status label in RViz. """ import math @@ -18,6 +19,7 @@ from std_msgs.msg import Bool, String from visualization_msgs.msg import Marker, MarkerArray +from waybionic_teleop.arm_profile import load_profile from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits @@ -67,6 +69,7 @@ def __init__(self, **kwargs): self.base_frame = params['base_frame'] self.table_height = float(params.get('table_height', 0.0)) self.clearance = float(params.get('collision_clearance', 0.01)) + self.locked = load_profile(params.get('arm_profile', '')).locked_joints self.teleop = None self.problem = 'Waiting for robot_description' self.joy = None @@ -126,7 +129,7 @@ def load(self, message): kinematics = None self.get_logger().warning(f'Cartesian group unavailable: {error}') try: - self.teleop = ArmTeleop(self.config, limits, kinematics, collision) + self.teleop = ArmTeleop(self.config, limits, kinematics, collision, self.locked) except ValueError as error: self.teleop, self.problem = None, str(error) self.get_logger().error(f'Teleop disabled: {error}') From 7c523b85e75246980d07972169b163888abd73fd Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:30:42 -0600 Subject: [PATCH 03/31] Load vcan without linux-modules-extra on new runner kernels The ubuntu-24.04 runners moved to kernel 7.0.0-1017-azure, which has no linux-modules-extra package: Ubuntu deprecated it, and from 6.15 its modules ship in linux-modules (actions/runner-images#15026). The vcan job now loads vcan directly and installs the extra package only when an older kernel still needs it. --- .github/workflows/can_drives.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/can_drives.yml b/.github/workflows/can_drives.yml index e59396ff..892234a7 100644 --- a/.github/workflows/can_drives.yml +++ b/.github/workflows/can_drives.yml @@ -18,11 +18,14 @@ jobs: - name: Checkout Repository uses: actions/checkout@v7 + # Kernels from 6.15 ship vcan in linux-modules; older ones need linux-modules-extra. - name: Create vcan0 run: | - sudo apt-get update - sudo apt-get install -y "linux-modules-extra-$(uname -r)" - sudo modprobe vcan + if ! sudo modprobe vcan; then + sudo apt-get update + sudo apt-get install -y "linux-modules-extra-$(uname -r)" + sudo modprobe vcan + fi sudo ip link add dev vcan0 type vcan sudo ip link set up vcan0 From c47589248f721013eeaa0994b9b0c98712ffed65 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:57:39 -0600 Subject: [PATCH 04/31] Record why gravity compensation needs torque-controlled drives Seeed's reBot-DevArm floats because every control tick it sends each motor a gravity feed-forward torque. The MKS SERVO42D/57D V1.0.9 CAN manual has no torque or current command and no current readback, so that cannot be done on these drives. A bench test on the base yaw tried the nearest workaround: with the vFOC integral gain at zero, position error could stand in for torque. 96h returned "set success" for Ki=0 and Ki=1, but reading the gain back still gave 100, also after disabling and re-enabling the drive. Held pushes decayed to zero error within 1-3 s with and without the write. The drives were restored to Kp=220, Ki=100 and read back. --- docs/operator_guide.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 4ff07df0..599be972 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -533,6 +533,18 @@ operating current, and its configuration readback is not measured load current. Reducing current or changing drive PID gains is not a validated hand-guiding shortcut, particularly for joints supporting the arm's weight. +Gravity compensation like Seeed's reBot-DevArm (a torque feed-forward from the arm's +model, so the arm floats under the hand) needs torque-controlled actuators. The MKS +drives accept only position and speed commands and report no current or torque, so +it is not possible on this arm without different motors or a force/torque sensor. + +Bench test of a sensorless workaround, base yaw (CAN ID 1, no gravity load), firmware +V1.0.9, factory vFOC gains Kp=220, Ki=100, Kd=270, Kv=320 on every drive: writing Ki=0 +or Ki=1 with `96h` returns "set success", but `00 96 00` still reads Ki=100, also after +disabling and re-enabling the drive. Held pushes decayed back to near-zero `39h` error +within 1-3 seconds with and without the write, so the position error cannot stand in +for a torque sensor. The drives were restored to Ki=100 and read back. + ### Engineering monitor With `teleop:=true`, the diagnostics panel shows live rows: From 10d17439166b96d914da7d1dbc9285058d9a6bb0 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:57:39 -0600 Subject: [PATCH 05/31] Keep arrival order when a frame rolls over during a buffer read RXB0 locks until its flag is cleared, so a frame arriving while A is copied out of it rolls into RXB1, and the next frame takes RXB0 the moment A is released. The flags were read once before the copy, so B in RXB1 went unnoticed and C was returned ahead of it: encoder readings could arrive out of order. Read CANINTF again after releasing RXB0. RXB1 only fills while RXB0 is full, so a frame waiting there then is older than anything RXB0 takes next. The new test injects B during A's register reads and C at the flag clear, and failed before the change. Flashed to the bench carrier: 60 s read-only soak, 7200 of 7200 encoder replies per drive at 120 Hz, no CAN error or refusal counter changes. --- .../src/common/Mcp2515CanTransport.cpp | 5 +++- .../tests/unit/test_mcp2515_transport.cpp | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp index 60da878b..be38f28c 100644 --- a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp @@ -370,7 +370,6 @@ Mcp2515CanTransport::ReadResult Mcp2515CanTransport::readReceived(Frame & frame) // frame when both are full. Once RXB0 is emptied ahead of a waiting RXB1, the next frame to // reach RXB0 is newer than RXB1's. const bool first = (flags & kRx0If) != 0 && !(rxb1_older_ && (flags & kRx1If) != 0); - rxb1_older_ = first && (flags & kRx1If) != 0; const uint8_t base = first ? kRxb0Sidh : kRxb1Sidh; const uint8_t sidh = readRegister(base); const uint8_t sidl = readRegister(static_cast(base + 1)); @@ -391,6 +390,10 @@ Mcp2515CanTransport::ReadResult Mcp2515CanTransport::readReceived(Frame & frame) // RXnIF locks this buffer until cleared (DS20001801J, section 4.1.3), including between // the separate SPI register reads above. bitModify(kCanIntF, first ? kRx0If : kRx1If, 0x00); + // RXB1 only fills while RXB0 is full, which includes the reads above, so a frame waiting in + // RXB1 once RXB0 is released is older than whatever RXB0 takes next. Two frames cannot + // arrive within this one SPI read, so RXB1's is not a newer overflow from after the release. + rxb1_older_ = first && (readRegister(kCanIntF) & kRx1If) != 0; return result; } diff --git a/waybionic_can/tests/unit/test_mcp2515_transport.cpp b/waybionic_can/tests/unit/test_mcp2515_transport.cpp index b9de7b57..816b1dff 100644 --- a/waybionic_can/tests/unit/test_mcp2515_transport.cpp +++ b/waybionic_can/tests/unit/test_mcp2515_transport.cpp @@ -434,6 +434,36 @@ TEST(Mcp2515Transport, KeepsArrivalOrderWhenAFrameLandsAfterFlagClear) EXPECT_TRUE(chip.arriving.empty()); } +TEST(Mcp2515Transport, KeepsArrivalOrderWhenAFrameRollsOverWhileTheOtherBufferIsRead) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + const Frame b = makeFrame(3, {0x31, 0x03}); + const Frame c = makeFrame(4, {0x31, 0x04}); + ASSERT_TRUE(chip.deliver(a)); + bool injected = false; + chip.on_read = [&](const uint8_t address) { + if (!injected && address == kRxb0Sidh + 5) { + injected = true; + // RXB1 was empty when the read of A began; A still locks RXB0, so B rolls into RXB1 + // and C takes RXB0 the moment A is released. + EXPECT_TRUE(chip.deliver(b)); + chip.arriving = {c}; + } + }; + for (const Frame & expected : {a, b, c}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + EXPECT_TRUE(injected); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_TRUE(chip.arriving.empty()); +} + TEST(Mcp2515Transport, PendingBuffersStayLockedDuringRegisterReads) { FakeMcp2515 chip; From 88e264bc75b52f6a68420be2f8d3481d4d5cd17e Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:57:39 -0600 Subject: [PATCH 06/31] Stop a failing frame log from interrupting drive control RecordingBus wrote its log inside send(), receive() and shutdown(), so a full disk raised after the bus had taken a frame. At shutdown that aborted the loop that stops each drive before the rest had their stop, and skipped the holds. A failed write or close now stops the recording and reports it once through the node's logger; the bus carries on. --- waybionic_teleop/test/test_frame_log.py | 59 +++++++++++++++++++ .../waybionic_teleop/frame_log.py | 28 ++++++++- .../waybionic_teleop/sim_arm_drives_node.py | 3 +- 3 files changed, 86 insertions(+), 4 deletions(-) diff --git a/waybionic_teleop/test/test_frame_log.py b/waybionic_teleop/test/test_frame_log.py index e182dca0..f2c2d9d6 100644 --- a/waybionic_teleop/test/test_frame_log.py +++ b/waybionic_teleop/test/test_frame_log.py @@ -1,3 +1,5 @@ +import errno + from waybionic_teleop import mks_can from waybionic_teleop.frame_log import parse_line, RecordingBus from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo @@ -22,3 +24,60 @@ def test_every_frame_sent_received_or_refused_is_written_in_order(tmp_path): ('refused', 1, mks_can.stop(1, 0)), ] assert lines[0][0] <= lines[1][0] <= lines[2][0] + + +class FullDisk: + """A log file whose writes (and, with fail_close, final flush) fail like a full disk.""" + + def __init__(self, fail_write=True, fail_close=True): + self.fail_write, self.fail_close = fail_write, fail_close + self.writes = self.closes = 0 + + def write(self, text): + self.writes += 1 + if self.fail_write: + raise OSError(errno.ENOSPC, 'No space left on device') + + def close(self): + self.closes += 1 + if self.fail_close: + raise OSError(errno.ENOSPC, 'No space left on device') + + +def recording_bus_on(file, tmp_path, messages): + sim = SimulatedBus([SimulatedServo(1)], 500000) + bus = RecordingBus(sim, str(tmp_path / 'frames.log'), report=messages.append) + bus.file.close() + bus.file = file + sim.stopped = False + sim.shutdown = lambda: setattr(sim, 'stopped', True) + return bus, sim + + +def test_a_failing_log_never_interrupts_the_bus(tmp_path): + messages = [] + disk = FullDisk() + bus, sim = recording_bus_on(disk, tmp_path, messages) + for _ in range(3): + # The stops at shutdown go through send(), so a log error must not reach the caller. + assert bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is not None + assert disk.writes == 1 + assert len(messages) == 1 + assert 'No space left on device' in messages[0] and 'frames.log' in messages[0] + bus.shutdown() + assert sim.stopped and disk.closes == 1 + assert len(messages) == 1 + + +def test_a_log_that_cannot_be_closed_is_reported_without_blocking_shutdown(tmp_path): + messages = [] + disk = FullDisk(fail_write=False) + bus, sim = recording_bus_on(disk, tmp_path, messages) + assert bus.send(1, mks_can.read_encoder(1)) + assert messages == [] + bus.shutdown() + assert sim.stopped and disk.closes == 1 + assert len(messages) == 1 and 'No space left on device' in messages[0] + bus.shutdown() + assert disk.closes == 1 diff --git a/waybionic_teleop/waybionic_teleop/frame_log.py b/waybionic_teleop/waybionic_teleop/frame_log.py index 72255d79..d29a1c3b 100644 --- a/waybionic_teleop/waybionic_teleop/frame_log.py +++ b/waybionic_teleop/waybionic_teleop/frame_log.py @@ -18,10 +18,15 @@ class RecordingBus: ``1793438841.369542 tx 001#F5008200FFE3A09A``. Kinds: tx (queued to the bus), unsent (the bus was unplugged), rx (a frame the bus received) and refused (a frame the carrier or the bus refused after send() returned True). + + The recording never gets in the way of the drives: if the file cannot be written or closed, + such as on a full disk, report() is called once with the reason and recording stops. """ - def __init__(self, bus, path): + def __init__(self, bus, path, report=None): self.bus = bus + self.path = path + self.report = report or (lambda message: None) self.file = open(path, 'a', encoding='ascii', buffering=1 << 16) def __getattr__(self, name): @@ -48,7 +53,24 @@ def shutdown(self): try: self.bus.shutdown() finally: - self.file.close() + self._stop_recording() def _write(self, kind, can_id, data): - self.file.write(f'{time.time():.6f} {kind} {can_id:03X}#{bytes(data).hex().upper()}\n') + if self.file is None: + return + try: + self.file.write( + f'{time.time():.6f} {kind} {can_id:03X}#{bytes(data).hex().upper()}\n') + except OSError as error: + self._stop_recording(error) + + def _stop_recording(self, error=None): + file, self.file = self.file, None + if file is None: + return + try: + file.close() + except OSError as close_error: + error = error or close_error + if error is not None: + self.report(f'Stopped recording drive frames to {self.path}: {error}') diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 23aa6300..0efe5d71 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -176,7 +176,8 @@ def __init__(self, **kwargs): self.bus = CanBus(self.interface, channel, self.bitrate) self.bus_label = f'{self.interface} {channel}' if frame_log := params.get('frame_log', ''): - self.bus = RecordingBus(self.bus, os.path.expanduser(frame_log)) + self.bus = RecordingBus(self.bus, os.path.expanduser(frame_log), + self.get_logger().error) self.get_logger().info(f'Recording every drive frame to {frame_log}') self.test_fault = None if self.interface == 'sim': From bbee54eb4adab7c5b98437da21277f339044faa9 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:57:45 -0600 Subject: [PATCH 07/31] Fix the bench-tool edge cases found in review of the carrier bring-up - carrier_usb.py: with --port naming one carrier while another UNO R4 WiFi was already in bridge mode, the upload went to the other board. The bridge handed back is now the one at the carrier's USB location, or, where there is no location, the only bridge that was not already there. Checked on the bench: the bridge re-enumerated at 1-1 as the carrier had. - mks_setup.py: the carrier's status ID (2032) was dropped as a reply on every bus, hiding a drive on SocketCAN, and set-id could move a drive there through the carrier where it could no longer be found. Only the carrier's link reserves it now, and set-id refuses it before sending. - arm_profile.py: a locked joint that is not in the arm map (a typo) now fails at start-up instead of making every teleop command refused. - slcan_bus.py: a refused open also names a missing MCP2515 or a failed link self-test, so a wiring fault is not read as a bit rate problem. - HARDWARE_BRINGUP_CHECKLIST.md: the flash output, port selection and USB baud rate now match the native-USB carrier. --- scripts/carrier_usb.py | 31 ++++-- .../docs/HARDWARE_BRINGUP_CHECKLIST.md | 12 ++- waybionic_teleop/test/test_arm_profile.py | 2 + waybionic_teleop/test/test_carrier_usb.py | 95 +++++++++++++++++++ waybionic_teleop/test/test_mks_setup.py | 27 +++++- .../waybionic_teleop/arm_profile.py | 3 + .../waybionic_teleop/mks_setup.py | 17 +++- .../waybionic_teleop/slcan_bus.py | 10 +- 8 files changed, 177 insertions(+), 20 deletions(-) create mode 100644 waybionic_teleop/test/test_carrier_usb.py diff --git a/scripts/carrier_usb.py b/scripts/carrier_usb.py index c0e63f1a..26805e63 100644 --- a/scripts/carrier_usb.py +++ b/scripts/carrier_usb.py @@ -50,33 +50,48 @@ def only_board(device=None): return found[0] -def hand_back(device): - """Ask the carrier firmware at device to give the USB port back to the bridge.""" +def bridges(): + return [port for port in boards() if port.pid == WIFI_BRIDGE_PID] + + +def handed_back_bridge(carrier, already_bridged): + """Return the device of the bridge that took over the carrier's USB port, once it has.""" + if carrier.location: + found = [port for port in bridges() if port.location == carrier.location] + else: + found = [port for port in bridges() if port.device not in already_bridged] + return found[0].device if len(found) == 1 else None + + +def hand_back(carrier): + """Ask the carrier firmware on this port to give the USB port back to the bridge.""" + # Another UNO R4 WiFi may already be in bridge mode: it is not the one handed back. + already_bridged = {port.device for port in bridges()} link = Serial() - link.port = device + link.port = carrier.device link.baudrate = HAND_BACK_BAUD link.dtr = True link.open() try: deadline = time.monotonic() + HAND_BACK_TIMEOUT_S while time.monotonic() < deadline: - bridges = [port for port in boards() if port.pid == WIFI_BRIDGE_PID] - if bridges: - return bridges[0].device + bridge = handed_back_bridge(carrier, already_bridged) + if bridge: + return bridge time.sleep(0.05) finally: try: link.close() except OSError: pass - sys.exit(f'error: the carrier at {device} did not hand USB back to its bridge within ' + sys.exit(f'error: the carrier at {carrier.device} did not hand USB back to its bridge within ' f'{HAND_BACK_TIMEOUT_S:.0f} s; unplug it, plug it back in and try again') def upload_port(device=None): board = only_board(device) if board.pid == WIFI_NATIVE_PID: - return hand_back(board.device) + return hand_back(board) return board.device diff --git a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md index 478f90d2..8db605fd 100644 --- a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md +++ b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md @@ -31,10 +31,12 @@ brew install arduino-cli ./scripts/macos.sh flash carrier_bridge ``` -Expected: the helper finds one `/dev/cu.usbmodem*`, compiles `carrier_bridge`, uploads it, and -prints `Flashed carrier_bridge to ...`. If several ports exist, set -`WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. The firmware uses **1,000,000 baud on USB serial**. -That is independent of the selected **1,000,000 bit/s CAN bus** rate. +Expected: the helper compiles `carrier_bridge`, finds the upload port with +`scripts/carrier_usb.py upload-port` (which hands USB back to the WiFi bridge when the running +carrier firmware has it), uploads, and prints `Flashed carrier_bridge`. If several UNO R4 +boards are plugged in, set `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. The firmware uses the +RA4M1's native USB, so the serial baud rate has no effect (1200 baud only asks it to hand USB +back for an upload). That is independent of the selected **1,000,000 bit/s CAN bus** rate. Before changing drive settings, connect one factory drive at 500 kbit/s and run: @@ -165,7 +167,7 @@ carrier's status frame is host-only ID `0x7F0`; it is not transmitted on CAN. Date / repository commit: Operators / lead present: Carrier port / firmware result: -USB serial baud: 1000000 +USB serial: native USB (baud rate ignored) CAN bitrate: 1000000 bit/s Termination / powered-off resistance: Supply setting / current limit: diff --git a/waybionic_teleop/test/test_arm_profile.py b/waybionic_teleop/test/test_arm_profile.py index b92709e7..1d8c39a1 100644 --- a/waybionic_teleop/test/test_arm_profile.py +++ b/waybionic_teleop/test/test_arm_profile.py @@ -60,6 +60,8 @@ def test_an_empty_profile_file_fits_every_drive(tmp_path): # Nothing would report where the shoulder is. (ArmProfile(('base_yaw', 'elbow', 'wrist_left', 'wrist_right', 'tool')), r"\['joint_2'\]"), (ArmProfile(('base_yaw', 'elbow', 'gripper')), 'lacks'), + # A mistyped joint would only show later, as every teleop command being refused. + (ArmProfile(None, {'joint_9': 0.0}), r"locks joints \['joint_9'\] that the arm map lacks"), # A fitted drive would move a joint the model holds still. (ArmProfile(None, {'joint_1': 0.0}), 'moved by fitted drives'), # One wrist motor moves both wrist joints, so neither can be locked while it is fitted. diff --git a/waybionic_teleop/test/test_carrier_usb.py b/waybionic_teleop/test/test_carrier_usb.py new file mode 100644 index 00000000..e58cc267 --- /dev/null +++ b/waybionic_teleop/test/test_carrier_usb.py @@ -0,0 +1,95 @@ +"""Handing the carrier's USB port back for an upload must pick the selected board's bridge.""" + +import importlib.util +from pathlib import Path +from types import SimpleNamespace + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / 'scripts' / 'carrier_usb.py' + + +@pytest.fixture +def usb(): + spec = importlib.util.spec_from_file_location('carrier_usb', SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class Port: + def __init__(self, device, pid, location): + self.device, self.vid, self.pid, self.location = device, 0x2341, pid, location + + +class Machine: + """USB ports that change when the carrier gives its port back after a few polls.""" + + def __init__(self, usb, ports, reenumerated, polls_until_bridge=3): + self.usb, self.ports, self.reenumerated = usb, list(ports), reenumerated + self.polls_until_bridge = polls_until_bridge + self.opened = [] + + def comports(self): + if self.opened: + self.polls_until_bridge -= 1 + if self.polls_until_bridge <= 0: + return self.reenumerated + return self.ports + + def serial(self): + link = SimpleNamespace(port=None, baudrate=None, dtr=None, close=lambda: None) + link.open = lambda: self.opened.append((link.port, link.baudrate, link.dtr)) + return link + + +@pytest.fixture +def machine(usb, monkeypatch): + def make(ports, reenumerated, **kwargs): + fake = Machine(usb, ports, reenumerated, **kwargs) + monkeypatch.setattr(usb.list_ports, 'comports', fake.comports) + monkeypatch.setattr(usb, 'Serial', fake.serial) + monkeypatch.setattr(usb.time, 'sleep', lambda seconds: None) + return fake + return make + + +def test_the_selected_carriers_own_bridge_is_returned_not_another_boards(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, '20-1') + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + own_bridge = Port('/dev/cu.usbmodem3301', usb.WIFI_BRIDGE_PID, '20-1') + fake = machine([carrier, other_bridge], [other_bridge, own_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem3301' + assert fake.opened == [('/dev/cu.usbmodem1101', usb.HAND_BACK_BAUD, True)] + + +def test_the_bridge_may_keep_the_carriers_device_name(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, '20-1') + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + own_bridge = Port('/dev/cu.usbmodem1101', usb.WIFI_BRIDGE_PID, '20-1') + machine([carrier, other_bridge], [other_bridge, own_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem1101' + + +def test_without_a_usb_location_only_a_new_bridge_counts(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, None) + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, None) + new_bridge = Port('/dev/cu.usbmodem3301', usb.WIFI_BRIDGE_PID, None) + machine([carrier, other_bridge], [other_bridge, new_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem3301' + + +def test_a_bridge_already_there_is_never_taken_for_the_handed_back_one(usb, machine, monkeypatch): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, None) + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, None) + machine([carrier, other_bridge], [other_bridge], polls_until_bridge=1) + monkeypatch.setattr(usb, 'HAND_BACK_TIMEOUT_S', 0.05) + with pytest.raises(SystemExit, match='did not hand USB back'): + usb.upload_port('/dev/cu.usbmodem1101') + + +def test_a_board_already_in_bridge_mode_is_used_as_it_is(usb, machine): + bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + fake = machine([bridge], [bridge]) + assert usb.upload_port('/dev/cu.usbmodem2201') == '/dev/cu.usbmodem2201' + assert fake.opened == [] diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 0fe1a561..a8b86858 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -4,7 +4,7 @@ import pytest -from waybionic_teleop import mks_can, mks_setup +from waybionic_teleop import carrier, mks_can, mks_setup from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo from waybionic_teleop.slcan_bus import SlcanBus @@ -169,3 +169,28 @@ def unexpected_open(*args): monkeypatch.setattr(mks_setup, 'open_bus', unexpected_open) with pytest.raises(SystemExit): mks_setup.main(['--channel', 'fake', 'read-error', can_id]) + + +def test_a_drive_may_use_the_carriers_status_id_off_the_carrier(): + # Only the carrier's own link reserves that ID; on SocketCAN it is an ordinary CAN ID. + bus = SimulatedBus([SimulatedServo(1)], 500000) + assert 'now answers on 2032' in mks_setup.set_id(bus, 1, carrier.STATUS_ID) + assert mks_setup.scan(bus, [carrier.STATUS_ID]) == {carrier.STATUS_ID: 0} + + +@pytest.mark.parametrize('old, new', [(1, carrier.STATUS_ID), (carrier.STATUS_ID, 1)]) +def test_the_carriers_status_id_is_refused_before_a_drive_is_changed(usb_carrier, old, new): + port = usb_carrier() + bus = SlcanBus('/dev/fake', 500000, open_port=lambda: port) + with pytest.raises(SystemExit, match='reserved for the carrier'): + mks_setup.set_id(bus, old, new) + assert not any(line.startswith(b't') for line in b''.join(port.writes).split(b'\r')) + + +def test_read_error_accepts_the_carriers_status_id_off_the_carrier(monkeypatch, capsys): + reply = mks_can.frame(carrier.STATUS_ID, mks_can.READ_POSITION_ERROR, bytes([0, 0, 0, 100])) + bus = ErrorReadBus([(carrier.STATUS_ID, reply)]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + mks_setup.main(['--interface', 'socketcan', '--channel', 'can0', 'read-error', + str(carrier.STATUS_ID)]) + assert 'position error +0.703125 motor deg (+100 error counts)' in capsys.readouterr().out diff --git a/waybionic_teleop/waybionic_teleop/arm_profile.py b/waybionic_teleop/waybionic_teleop/arm_profile.py index 3c973aff..7f5a9059 100644 --- a/waybionic_teleop/waybionic_teleop/arm_profile.py +++ b/waybionic_teleop/waybionic_teleop/arm_profile.py @@ -88,6 +88,9 @@ def joints(names): except KeyError as missing: raise ValueError(f'missing drive parameter {missing}') from None driven = joints(fitted) + unknown_locked = sorted(set(profile.locked_joints) - joints(drives)) + if unknown_locked: + raise ValueError(f'the arm profile locks joints {unknown_locked} that the arm map lacks') moved = sorted(driven & set(profile.locked_joints)) if moved: raise ValueError(f'locked joints {moved} are moved by fitted drives') diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 1326b017..233b345e 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -29,6 +29,11 @@ def open_bus(interface, channel, bitrate, tty_baudrate): return CanBus(interface, channel, bitrate) +def reserved_ids(bus): + """Return the CAN IDs the interface itself uses, which no drive can answer from.""" + return getattr(bus, 'reserved_ids', frozenset()) + + 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} @@ -47,7 +52,7 @@ def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): time.sleep(0.002) continue reply_id, reply = frame - if reply_id == carrier.STATUS_ID: + if reply_id in reserved_ids(bus): continue try: reply_code, arguments = mks_can.parse(reply_id, reply) @@ -86,6 +91,10 @@ 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}') + reserved = sorted({old, new} & reserved_ids(bus)) + if reserved: + raise SystemExit(f"CAN ID {reserved[0]} is reserved for the carrier's status; " + 'no drive can answer from it through the carrier') if scan(bus, [new]): raise SystemExit(f'CAN ID {new} is taken; connect only the drive to change') if not scan(bus, [old]): @@ -170,8 +179,10 @@ def main(argv=None): "the drives' --bitrate") args = parser.parse_args(argv) if args.command == 'read-error' and ( - not 1 <= args.can_id <= 0x7FF or args.can_id == carrier.STATUS_ID): - parser.error('read-error needs a drive CAN ID from 1 to 2047, excluding carrier ID 2032') + not 1 <= args.can_id <= 0x7FF + or args.interface == 'slcan' and args.can_id == carrier.STATUS_ID): + parser.error('read-error needs a drive CAN ID from 1 to 2047, excluding carrier ID 2032 ' + 'on the carrier') bus = open_bus(args.interface, args.channel, args.bitrate, args.tty_baudrate) try: diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 05bc88c7..04d2abcc 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -27,7 +27,7 @@ import serial -from waybionic_teleop import mks_can +from waybionic_teleop import carrier, mks_can BITRATE_CODES = {125000: b'4', 250000: b'5', 500000: b'6', 1000000: b'8'} DEFAULT_BAUDRATE = 1000000 @@ -67,6 +67,9 @@ def parse_line(line): class SlcanBus: """Send and receive standard 11-bit frames through the carrier, without blocking.""" + # The carrier's status arrives from this ID, so no drive can use it through the carrier. + reserved_ids = frozenset({carrier.STATUS_ID}) + 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') @@ -245,8 +248,9 @@ def _refused(self): if self.pending and self.pending.popleft() == b'O': # An R4's own CAN controller keeps the rate it first opened at until it resets. self.problem = (f'the carrier would not open CAN at {self.bitrate} bit/s: an 8 MHz ' - 'MCP2515 runs 500000 at most, and one that opened at another rate ' - 'needs a replug') + 'MCP2515 runs 500000 at most, one that opened at another rate ' + 'needs a replug, and an MCP2515 that is missing or fails its link ' + 'self-test (check its SPI wiring and power) is refused too') self.errors += 1 def _answered(self): From 2d8568ffb3a15a0b9217e513989a194b82831efa Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:12:55 -0600 Subject: [PATCH 08/31] Let teleop leave locked and disabled joints alone A joint the arm profile locks had (angle, angle) as its limits, so every stick or trigger mapped to it counted as pushing into a limit. The controller rumbled at each push, and the Cartesian and incision groups, which solve the shoulder too, were blocked on the first step. On the bench arm, with the shoulder fixed upright and no tool, that was the vibration whenever a stick needed a joint the arm lacks. A joint that cannot move is now skipped by the sticks, the triggers and the home button, so it is never reported as a limit. The Cartesian and incision groups need every joint, so they are left out while one cannot move, and a joint group with nothing left to move is dropped. set_disabled() adds joints that are switched off at run time. They hold the angle they had when teleop was enabled, changing the set stops teleop where the arm is, and Start is refused if no joint can move. --- waybionic_teleop/test/test_teleop.py | 83 ++++++++++++++++++++- waybionic_teleop/waybionic_teleop/teleop.py | 68 ++++++++++++++--- 2 files changed, 139 insertions(+), 12 deletions(-) diff --git a/waybionic_teleop/test/test_teleop.py b/waybionic_teleop/test/test_teleop.py index 3ec923e1..7b6f623e 100644 --- a/waybionic_teleop/test/test_teleop.py +++ b/waybionic_teleop/test/test_teleop.py @@ -78,16 +78,93 @@ def test_a_locked_joint_stays_exactly_at_its_angle(params, arm): # Even a measured value a rounding error away is sent back exactly. press(teleop, 'start', {**HOME, 'joint_2': 0.25 + 1e-12}) assert teleop.enabled and teleop.command_targets['joint_2'] == 0.25 - for axes, joint in (({'left_x': -1.0, 'left_y': 1.0}, 'joint_2'), - ({'right_trigger': -1.0}, 'tool_grip')): + for axes in ({'left_x': -1.0, 'left_y': 1.0}, {'right_trigger': -1.0}): teleop.update(*sample(**axes), HOME, DT) - assert joint in teleop.blocked + # A joint that cannot move is not a limit the operator hit, so it is never reported: + # the controller would rumble at every push of a stick that cannot do anything. + assert teleop.blocked == [] assert teleop.command_targets['joint_2'] == 0.25 assert teleop.command_targets['tool_grip'] == 0.0 assert teleop.velocities['joint_2'] == teleop.velocities['tool_grip'] == 0.0 assert teleop.targets['joint_1'] > 0.0 +def test_the_cartesian_and_incision_groups_need_every_joint_of_the_arm(params, arm): + free = ArmTeleop(config_from_parameters(params), LIMITS, arm) + assert [group.name for group in free.groups] == ['base', 'upper', 'cartesian', 'incision'] + # They solve all five joints together, so one that cannot move leaves them nowhere to go. + fixed = ArmTeleop(config_from_parameters(params), LIMITS, arm, locked={'joint_2': 0.0}) + assert [group.name for group in fixed.groups] == ['base', 'upper'] + press(fixed, 'start') + press(fixed, 'y') + press(fixed, 'y') + assert fixed.active_group.name == 'base' + + +def test_a_disabled_joint_holds_the_angle_it_had_at_enable(teleop): + assert teleop.set_disabled({'joint_3'}, HOME) + assert not teleop.set_disabled({'joint_3'}, HOME) + pose = {**HOME, 'joint_3': 0.3} + press(teleop, 'start', pose) + run(teleop, 1.0, left_x=-1.0, right_y=-1.0) + assert teleop.targets['joint_1'] > 0.3 + assert teleop.targets['joint_3'] == teleop.command_targets['joint_3'] == 0.3 + assert teleop.velocities['joint_3'] == 0.0 and teleop.blocked == [] + + +def test_a_disabled_joint_is_not_homed_or_driven_by_the_tool_trigger(teleop): + teleop.set_disabled({'joint_3', 'tool_grip'}, HOME) + pose = {**HOME, 'joint_1': 0.4, 'joint_3': 0.3, 'tool_grip': 0.5} + press(teleop, 'start', pose) + run(teleop, 3.0, 'a', right_trigger=1.0) + assert abs(teleop.targets['joint_1']) < 0.01 + assert teleop.targets['joint_3'] == 0.3 and teleop.targets['tool_grip'] == 0.5 + assert teleop.blocked == [] + + +def test_changing_the_disabled_joints_while_enabled_stops_teleop(teleop): + press(teleop, 'start') + assert not teleop.set_disabled(set(), HOME) + assert teleop.enabled + pose = {**HOME, 'joint_1': 0.2} + assert teleop.set_disabled({'joint_1'}, pose) + assert not teleop.enabled and teleop.targets['joint_1'] == 0.2 + assert 'Joint enable changed' in teleop.note and not teleop.warning + # The next Start holds the joint where it is, and the sticks leave it alone. + press(teleop, 'start', pose) + run(teleop, 1.0, left_x=1.0) + assert teleop.enabled and teleop.targets['joint_1'] == 0.2 + + +def test_groups_follow_the_disabled_joints_and_keep_the_active_group(params, arm): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, arm) + press(teleop, 'start', DOWN) + press(teleop, 'y', DOWN) + assert teleop.active_group.name == 'upper' + teleop.set_disabled({'joint_4'}, DOWN) + assert [group.name for group in teleop.groups] == ['base', 'upper'] + assert teleop.active_group.name == 'upper' + teleop.set_disabled(set(), DOWN) + assert [group.name for group in teleop.groups] == ['base', 'upper', 'cartesian', 'incision'] + assert teleop.active_group.name == 'upper' + # A group with nothing left to move is dropped, and the first one left takes over. + teleop.set_disabled({'joint_2', 'joint_3', 'joint_4', 'joint_5'}, DOWN) + assert [group.name for group in teleop.groups] == ['base'] + assert teleop.active_group.name == 'base' + + +def test_teleop_will_not_enable_with_no_joint_able_to_move(teleop): + teleop.set_disabled(set(LIMITS) | {'tool_grip'}, HOME) + press(teleop, 'start') + assert not teleop.enabled and teleop.warning and 'No joint is enabled' in teleop.note + + +def test_only_joints_of_this_arm_can_be_disabled_and_locked_ones_stay_locked(params): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, locked={'joint_2': 0.0}) + assert not teleop.set_disabled({'joint_2', 'not_a_joint'}, HOME) + assert teleop.disabled == set() + + @pytest.mark.parametrize('axes', [{'left_x': 0.8}, {'right_y': -0.5}, {'right_trigger': -0.6}]) def test_enable_refuses_held_or_stuck_inputs(teleop, axes): teleop.update(*sample('start', **axes), HOME, DT) diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index 7a997bc7..267650b1 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -146,11 +146,11 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) self.kinematics = kinematics self.collision = collision # Without kinematics for this arm, the Cartesian and incision groups are left out. - self.groups = [group for group in config.groups - if group.mode not in MOVES or kinematics is not None] - if not self.groups: + self.configured_groups = [group for group in config.groups + if group.mode not in MOVES or kinematics is not None] + if not self.configured_groups: raise ValueError('no joint-space group or compatible Cartesian kinematics') - for group in self.groups: + for group in self.configured_groups: if group.mode in MOVES and ( tuple(group.joints) != kinematics.joints or any(joint not in limits for joint in kinematics.joints)): @@ -162,6 +162,10 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) if joint in self.limits} for joint, angle in self.locked.items(): self.limits[joint] = (angle, angle) + # Joints the operator switched off: each holds the angle it had when teleop was enabled. + self.disabled = set() + self.disabled_angles = {} + self.groups = self.usable_groups() self.enabled = False self.group = 0 self.level = config.speed_level @@ -188,6 +192,42 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) def active_group(self): return self.groups[self.group] + def movable(self, joint): + """Return whether the sticks can move this joint: it is neither locked nor disabled.""" + return joint not in self.locked and joint not in self.disabled + + def usable_groups(self): + """Return the groups with something to move: a Cartesian solve needs every joint.""" + def usable(group): + if group.mode in MOVES: + return all(self.movable(joint) for joint in group.joints) + return any(self.movable(joint) for joint in group.joints) + return [group for group in self.configured_groups if usable(group)] or [ + self.configured_groups[0]] + + def set_disabled(self, joints, measured): + """ + Switch off exactly these joints; return True if that changed anything. + + A disabled joint never moves, so the arm can run without a joint whose drive is faulty + or missing. While enabled, teleop stops where the arm is: the next Start enables the + remaining joints from the measured pose. + """ + joints = {joint for joint in joints if joint in self.limits and joint not in self.locked} + if joints == self.disabled: + return False + if self.enabled: + self.disable(measured, 'Joint enable changed; press Start (Xbox Menu button) to ' + 'enable') + self.disabled = joints + self.disabled_angles = {joint: angle for joint, angle in self.disabled_angles.items() + if joint in joints} + name = self.active_group.name + self.groups = self.usable_groups() + self.group = next((index for index, group in enumerate(self.groups) + if group.name == name), 0) + return True + @property def speed(self): return self.config.max_speed * self.config.speed_levels[self.level] @@ -261,6 +301,10 @@ def enable(self, measured, axes): if missing: self.note, self.warning = 'Waiting for joint states: ' + ', '.join(missing), True return + if not any(self.movable(joint) for joint in self.limits): + self.note = 'No joint is enabled; switch one on in the Joint control panel' + self.warning = True + return if self.motion_input_held(axes): # A stuck or held input must never start moving the arm the moment it is enabled. self.note = 'Center the sticks and release the triggers and buttons, then press Start' @@ -268,6 +312,7 @@ def enable(self, measured, axes): return # Start from the measured pose so enabling never makes the arm jump. self.targets = {joint: measured[joint] for joint in self.limits} + self.disabled_angles = {joint: measured[joint] for joint in self.disabled} self.command_targets = dict(self.targets) self.velocities = dict.fromkeys(self.limits, 0.0) self.pin_locked() @@ -289,7 +334,7 @@ def disable(self, measured, note, warning=False): def pin_locked(self): # A solve may leave a locked joint a rounding error off its angle; send it unchanged. - for joint, angle in self.locked.items(): + for joint, angle in {**self.disabled_angles, **self.locked}.items(): self.targets[joint] = self.command_targets[joint] = angle self.velocities[joint] = 0.0 @@ -307,7 +352,7 @@ def move(self, axes, homing, dt): if homing and not incision: self.stop_cartesian() for joint, (lower, upper) in self.limits.items(): - if joint != config.tool_joint: + if joint != config.tool_joint and self.movable(joint): error = clamp(0.0, lower, upper) - self.targets[joint] desired[joint] = clamp(config.home_gain * error, -self.speed, self.speed) elif self.active_group.mode == 'cartesian': @@ -319,9 +364,14 @@ def move(self, axes, homing, dt): else: group = self.active_group for joint, axis, scale in zip(group.joints, group.axes, group.scales): - desired[joint] += scale * self.stick(axes, axis) * self.speed - desired[config.tool_joint] = config.tool_speed * ( - self.trigger(axes, config.tool_close_axis) - self.trigger(axes, config.tool_open_axis)) + # A joint that cannot move is not a limit to hit, so its stick does nothing. + if self.movable(joint): + desired[joint] += scale * self.stick(axes, axis) * self.speed + desired[config.tool_joint] = 0.0 + if self.movable(config.tool_joint): + desired[config.tool_joint] = config.tool_speed * ( + self.trigger(axes, config.tool_close_axis) + - self.trigger(axes, config.tool_open_axis)) step = config.max_accel * dt for joint, goal in desired.items(): velocity = self.velocities[joint] From adfe6ff20c08239c51b66c4c0897a9ef4e27062b Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:12:55 -0600 Subject: [PATCH 09/31] Let the drive node switch joints off while the arm is stopped A joint can be switched off through arm//set_enabled (std_srvs/SetBool), for a drive that is faulty or not fitted yet, and the states go out on a latched arm/joint_control topic (waybionic_teleop/ joint_control.py): enabled, disabled, or no_drive for a joint the arm profile locks. Like zeroing, a change waits until teleop has stopped streaming. A disabled joint is held where teleop saw it, and a command that moves it is refused. A drive whose joints are all off gets no targets, no following check and no stop, so a faulty drive no longer stops the arm, keeps the zero service from succeeding or keeps the arm from being enabled; its joints are reported where they were last seen, or where the drive says they are while it answers. A hand-moved disabled drive does not slow the others, since it counts as already at its target. One wrist joint off still needs both wrist drives, which hold it. Switching a joint back on needs its drive answering and zeroed before the arm can be enabled again. --- .../test/test_sim_arm_drives_node.py | 326 +++++++++++++++++- .../waybionic_teleop/joint_control.py | 30 ++ .../waybionic_teleop/sim_arm_drives_node.py | 215 ++++++++++-- 3 files changed, 532 insertions(+), 39 deletions(-) create mode 100644 waybionic_teleop/waybionic_teleop/joint_control.py diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 607480a7..4a1d3f03 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -1,5 +1,6 @@ """Exercise the ROS command gate and MKS frames without a hardware CAN interface.""" +from collections import deque import importlib.util import math from pathlib import Path @@ -14,7 +15,7 @@ from rclpy.parameter import Parameter from sensor_msgs.msg import JointState from std_msgs.msg import Bool, String -from std_srvs.srv import Trigger +from std_srvs.srv import SetBool, Trigger from waybionic_control.drive_health import ( DriveHealthMonitor, @@ -1626,26 +1627,315 @@ def measured(): return dict(zip(states[-1].name, states[-1].position)) teleop.enable(measured(), [0.0] * len(AXES)) assert teleop.enabled, teleop.note - # The base group's sticks ask for the base, the shoulder and the elbow at once; then, with - # the elbow bent, the Cartesian group asks for a straight move only the shoulder could make. - sticks = [[0.0] * len(AXES) for _ in range(2)] + # The Cartesian groups solve the shoulder too, so there are none for this arm. + assert [group.name for group in teleop.groups] == ['base', 'upper'] + # The base group's sticks ask for the base, the shoulder and the elbow at once. The + # shoulder cannot move, which is not a limit, so the controller has nothing to rumble about. + axes = [0.0] * len(AXES) for axis in ('left_x', 'left_y', 'right_y'): - sticks[0][AXES.index(axis)] = 1.0 - sticks[1][AXES.index('left_y')] = 1.0 - for group, axes in zip(('base', 'cartesian'), sticks): - teleop.group = [item.name for item in teleop.groups].index(group) - for _ in range(60): - teleop.update(axes, [0] * len(BUTTONS), measured(), bench.period) - targets = teleop.command_targets - bench.on_enabled(Bool(data=True)) - bench.on_command(JointState( - name=list(targets), position=list(targets.values()), - velocity=[teleop.velocities[joint] for joint in targets])) - advance(bench) - assert bench.authorized, bench.stop_reason - assert 'joint_2' in teleop.blocked, group + axes[AXES.index(axis)] = 1.0 + for _ in range(60): + teleop.update(axes, [0] * len(BUTTONS), measured(), bench.period) + targets = teleop.command_targets + bench.on_enabled(Bool(data=True)) + bench.on_command(JointState( + name=list(targets), position=list(targets.values()), + velocity=[teleop.velocities[joint] for joint in targets])) + advance(bench) + assert bench.authorized, bench.stop_reason + assert teleop.blocked == [] assert bench.rejected == 0 assert abs(measured()['joint_1']) > 0.1 and measured()['joint_2'] == 0.0 + assert abs(measured()['joint_3']) > 0.1 + + +def without_drive(drives_with, can_id, **changes): + """Make a node whose drive is not on the bus, as when it is faulty or not yet fitted.""" + node = drives_with(zero_on_start=False, **changes) + node.bus.drives.pop(can_id) + # Whatever it answered while the node was being made is not heard. + node.bus.replies = deque(reply for reply in node.bus.replies if reply[0] != can_id) + return node + + +def arm_up(node): + advance(node) + node.on_description(String(data=URDF)) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def published_joint_control(node, monkeypatch): + messages = [] + monkeypatch.setattr(node.joint_control_publisher, 'publish', messages.append) + return messages + + +def rows(message): + return {row.name: ({item.key: item.value for item in row.values}, row.message) + for row in message.status} + + +def test_a_joint_is_switched_off_only_while_the_arm_is_stopped(node): + ready(node) + ok, message = node.set_joint_enabled('joint_3', False) + assert not ok and 'disable teleop' in message and not node.disabled + node.on_enabled(Bool(data=False)) + node.on_command(command(node)) + ok, message = node.set_joint_enabled('joint_3', False) + assert not ok and 'still arriving' in message + node.command_time -= QUIET_BEFORE_ZERO_S + assert node.set_joint_enabled('joint_3', False) == (True, 'joint_3 is disabled') + assert node.disabled == {'joint_3'} + assert node.set_joint_enabled('joint_3', True) == (True, 'joint_3 is enabled') + assert node.disabled == set() + + +def test_a_joint_with_no_drive_cannot_be_switched(bench): + ok, message = bench.set_joint_enabled('joint_2', True) + assert not ok and 'no drive' in message + assert not bench.set_joint_enabled('not_a_joint', False)[0] + assert bench.disabled == set() + + +def test_a_disabled_joint_gets_no_target_and_the_others_keep_moving(node): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_2=0.1)) + advance(node) + advance(node) + assert node.authorized and node.rejected == 0 + assert node.bus.drives[2].target is not None + assert node.bus.drives[1].target is None + + +@pytest.mark.parametrize('moved, accepted', [(0.005, True), (0.5, False)]) +def test_a_command_must_hold_a_disabled_joint_at_its_anchor(node, moved, accepted): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_1=moved, joint_2=0.1)) + assert node.authorized == accepted + if accepted: + # Count jitter between teleop's reading and ours is absorbed, and sent back exactly. + assert node.commanded['joint_1'] == 0.0 and node.velocities['joint_1'] == 0.0 + else: + assert node.stop_reason == 'joint_1 is disabled' and node.rejected == 1 + + +def test_one_wrist_joint_disabled_keeps_both_wrist_drives_following(node): + assert node.set_joint_enabled('joint_4', False)[0] + assert node.idle == set() + ready(node) + node.on_command(command(node, joint_5=0.2)) + advance(node) + advance(node) + assert node.bus.drives[4].target is not None and node.bus.drives[5].target is not None + node.on_command(command(node, joint_4=0.2)) + assert not node.authorized and node.stop_reason == 'joint_4 is disabled' + node.command_time -= QUIET_BEFORE_ZERO_S + assert node.set_joint_enabled('joint_5', False)[0] and node.idle == {3, 4} + + +def test_a_disabled_drive_that_stops_answering_does_not_stop_the_arm(node, monkeypatch): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + node.bus.drives.pop(1) + node.heard[0] -= 10.0 + for _ in range(node.max_unanswered + 5): + advance(node) + assert node.lost[0] and not node.zeroed[0] + assert node.authorized, node.stop_reason + node.on_command(command(node, joint_2=0.1)) + advance(node) + assert node.authorized and node.bus.drives[2].target is not None + # Every joint is still reported, the disabled one where it was. + published = dict(zip(states[-1].name, states[-1].position)) + assert set(published) == set(node.map.joints) and published['joint_1'] == 0.0 + + +def test_a_disabled_drive_that_never_answered_does_not_keep_the_arm_off(drives_with): + node = without_drive(drives_with, 1) + advance(node) + node.on_description(String(data=URDF)) + # The base drive is not answering, so it cannot be zeroed, and the arm needs it. + assert not node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized + assert node.set_joint_enabled('joint_1', False)[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def test_the_zero_service_succeeds_without_a_disabled_drive_and_saves_the_others( + drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = without_drive(drives_with, 1, zero_state=str(path)) + advance(node) + assert node.set_joint_enabled('joint_1', False)[0] + response = node.on_zero(Trigger.Request(), Trigger.Response()) + assert response.success and 'base_yaw' in response.message + for _ in range(3): + advance(node) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + assert 'base_yaw' not in saved and len(saved) == len(node.map.drives) - 1 + # A drive that is not disabled still has to answer. + node.set_joint_enabled('joint_1', True) + response = node.on_zero(Trigger.Request(), Trigger.Response()) + assert not response.success and 'base_yaw' in response.message + + +def test_a_drive_that_comes_back_after_its_joint_is_enabled_must_be_zeroed(drives_with): + node = without_drive(drives_with, 1) + advance(node) + assert node.set_joint_enabled('joint_1', False)[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + arm_up(node) + node.on_enabled(Bool(data=False)) + node.command_time -= QUIET_BEFORE_ZERO_S + node.bus.drives[1] = SimulatedServo(1) + assert node.set_joint_enabled('joint_1', True)[0] + # The drive was never set up: the node asks again once its reply timeout has passed. + node.setup_time[0] = -math.inf + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized and not node.zeroed[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def test_a_hand_moved_disabled_joint_does_not_slow_the_other_drives(node, monkeypatch): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.bus.drives[1].axis = 20000.0 + seen = [] + synchronized = node.map.synchronized + + def record(positions, counts, *args): + seen.append(list(counts)) + return synchronized(positions, counts, *args) + monkeypatch.setattr(node.map, 'synchronized', record) + node.on_command(command(node, joint_2=0.1)) + advance(node) + assert seen and seen[-1][0] == node.map.to_counts(node.commanded)[0] + + +def test_a_hand_moved_disabled_joint_is_not_a_following_error(node): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_2=0.1)) + advance(node) + node.on_enabled(Bool(data=False)) + for _ in range(3): + advance(node) + node.bus.drives[1].axis = 5.0 * node.following_error + for _ in range(2 * node.following_ticks): + advance(node) + assert node.behind[0] == 0 and not node.stopping + assert node.stop_reason == 'Teleop disabled' + + +def test_the_drive_rows_of_a_disabled_joint_never_report_an_error(node, monkeypatch): + diagnostics = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', diagnostics.append) + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.bus.drives.pop(1) + node.heard[0] -= 10.0 + for _ in range(node.max_unanswered + 5): + advance(node) + node.report() + row = next(item for item in diagnostics[-1].status if item.name == 'drive.base_yaw') + assert row.level == DiagnosticStatus.WARN and 'disabled' in row.message + assert not any(item.level == DiagnosticStatus.ERROR for item in diagnostics[-1].status + if item.name.startswith('drive.')) + + +def test_the_joint_states_are_published_latched_and_on_every_change(node, monkeypatch): + messages = published_joint_control(node, monkeypatch) + assert node.joint_control_publisher.qos_profile.durability == ( + rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL) + assert node.set_joint_enabled('joint_3', False)[0] + assert len(messages) == 1 + found = rows(messages[-1]) + assert list(found) == ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'tool_grip'] + values, text = found['joint_3'] + assert values['state'] == 'disabled' and values['drives'] == 'elbow' + assert text.startswith('disabled: held at') and math.isfinite(float(values['angle'])) + assert {name: found[name][0]['state'] for name in found if name != 'joint_3'} == { + name: 'enabled' for name in found if name != 'joint_3'} + assert found['joint_4'][0]['drives'] == 'wrist_left,wrist_right' + # A refused change publishes nothing new, and the report repeats the state. + ready(node) + assert not node.set_joint_enabled('joint_1', False)[0] + assert len(messages) == 1 + node.report() + assert len(messages) == 2 and rows(messages[-1])['joint_3'][0]['state'] == 'disabled' + + +def test_a_joint_with_no_drive_is_reported_as_such_and_has_no_service(bench, monkeypatch): + messages = published_joint_control(bench, monkeypatch) + bench.report() + found = rows(messages[-1]) + assert found['joint_2'][0]['state'] == 'no_drive' and found['joint_2'][0]['angle'] == '0.0' + assert found['joint_2'][1].startswith('no drive fitted: locked at') + assert found['tool_grip'][0]['state'] == 'no_drive' + assert found['joint_1'][0]['state'] == 'enabled' + assert sorted(bench.joint_services) == ['joint_1', 'joint_3', 'joint_4', 'joint_5'] + + +def test_the_set_enabled_service_changes_a_joint_and_says_why_it_cannot(node): + request = SetBool.Request(data=False) + response = node.on_set_enabled('joint_3', request, SetBool.Response()) + assert response.success and node.disabled == {'joint_3'} + ready(node) + response = node.on_set_enabled('joint_3', SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'disable teleop' in response.message + assert node.disabled == {'joint_3'} + + +def test_teleop_drives_an_arm_with_a_disabled_base_without_a_stop( + node, parameters, monkeypatch): + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + arm = ArmKinematics.from_urdf(URDF) + teleop = ArmTeleop(config_from_parameters(parameters('xbox_teleop.yaml', 'xbox_teleop')), + joint_limits(URDF, arm.joints), arm) + + def measured(): + return dict(zip(states[-1].name, states[-1].position)) + teleop.set_disabled(node.disabled, measured()) + teleop.enable(measured(), [0.0] * len(AXES)) + assert teleop.enabled, teleop.note + axes = [0.0] * len(AXES) + for axis in ('left_x', 'left_y', 'right_y'): + axes[AXES.index(axis)] = 1.0 + for _ in range(60): + teleop.update(axes, [0] * len(BUTTONS), measured(), node.period) + targets = teleop.command_targets + node.on_enabled(Bool(data=True)) + node.on_command(JointState( + name=list(targets), position=list(targets.values()), + velocity=[teleop.velocities[joint] for joint in targets])) + advance(node) + assert node.authorized, node.stop_reason + assert teleop.blocked == [] + assert node.rejected == 0 and node.bus.drives[1].target is None + assert measured()['joint_1'] == 0.0 and abs(measured()['joint_2']) > 0.1 @pytest.fixture diff --git a/waybionic_teleop/waybionic_teleop/joint_control.py b/waybionic_teleop/waybionic_teleop/joint_control.py new file mode 100644 index 00000000..fc4882b2 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/joint_control.py @@ -0,0 +1,30 @@ +""" +The arm's joint enable states, as the drive node publishes them on ``arm/joint_control``. + +The topic carries a latched DiagnosticArray with one row per joint, ``joint_1`` to +``joint_5`` and then ``tool_grip``. A row's name is the joint, its message says what it is +doing, and its values are ``state`` (one of ENABLED, DISABLED or NO_DRIVE), ``drives`` (the +drives that move it, comma separated) and ``angle`` (radians, where the joint was last seen). +The drive node serves ``arm//set_enabled`` (std_srvs/SetBool) for the joints that have +a drive. The RViz joint control panel and the Xbox teleop node both read this topic. +""" + +from diagnostic_msgs.msg import DiagnosticStatus, KeyValue + +TOPIC = 'arm/joint_control' +ENABLED, DISABLED, NO_DRIVE = 'enabled', 'disabled', 'no_drive' + + +def joint_status(joint, state, drives, angle, message): + """Return the row for one joint.""" + return DiagnosticStatus( + name=joint, level=DiagnosticStatus.OK if state == ENABLED else DiagnosticStatus.WARN, + message=message, values=[KeyValue(key='state', value=state), + KeyValue(key='drives', value=','.join(drives)), + KeyValue(key='angle', value=repr(float(angle)))]) + + +def disabled_joints(message): + """Return the joints a joint control message says are switched off.""" + return {row.name for row in message.status + if any(item.key == 'state' and item.value == DISABLED for item in row.values)} diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 0efe5d71..0865c1f4 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -17,6 +17,12 @@ has fitted; each joint no fitted drive moves is published at its locked angle, and a command must leave it there. +A joint can be switched off while the arm is stopped (``arm//set_enabled``, see +waybionic_teleop/joint_control.py), for a drive that is faulty or not fitted yet. It is held +where it was and teleop must leave it there. A drive whose joints are all off gets no targets, +and its silence or its turns do not stop the arm; it is read for the joints' angles while it +answers. One wrist joint off still needs both wrist drives, which then hold it. + Joint commands are accepted only after a valid robot_description and a fresh teleop enable that teleop keeps republishing. Whoever publishes ``/joint_commands`` must keep publishing while the arm is meant to move: once ``command_timeout_s`` passes with no command, every @@ -35,6 +41,7 @@ """ import datetime +import functools import math import os import time @@ -47,14 +54,14 @@ from rclpy.qos import DurabilityPolicy, QoSProfile from sensor_msgs.msg import JointState from std_msgs.msg import Bool, String -from std_srvs.srv import Trigger +from std_srvs.srv import SetBool, Trigger from waybionic_control.drive_health import ( DriveHealthMonitor, DriveHealthState, DriveHealthThresholds, ) -from waybionic_teleop import carrier, mks_can +from waybionic_teleop import carrier, joint_control, mks_can from waybionic_teleop.arm_profile import fit_drive_parameters, load_profile from waybionic_teleop.drive_map import drive_map_from_parameters from waybionic_teleop.frame_log import RecordingBus @@ -78,6 +85,8 @@ RUN_FAULTS = (0, 3) # Teleop sends a locked joint's angle back unchanged; anything beyond rounding is a move. LOCKED_TOLERANCE_RAD = 1e-6 +# A disabled joint is held where teleop saw it, give or take the counts between two readings. +DISABLED_TOLERANCE_RAD = 0.01 # A drive stopped mid-move starts again once an encoder reading this long after its stop no # longer advances the old way, or once it reports the stop complete and barely moves. Bench # reversals on firmware V1.0.9 settled in 17 ms (median) and 42 ms at most at 120 Hz. @@ -158,6 +167,11 @@ def __init__(self, **kwargs): raise ValueError('at least one drive joint needs a URDF limit') drives = self.map.drives self.index = {drive.can_id: index for index, drive in enumerate(drives)} + # Joints switched off at run time, where each was held when the arm was last enabled, + # and where each was last seen, for the drives that no longer tell. + self.disabled, self.anchors, self.last_angle = set(), {}, {} + self.drive_joints = [{joint for joint, factor in drive.factors.items() if factor} + for drive in drives] if self.interface == 'sim': self.bus = SimulatedBus([SimulatedServo(drive.can_id) for drive in drives], self.bitrate) @@ -251,6 +265,12 @@ def __init__(self, **kwargs): self.create_subscription(Bool, 'teleop_enabled', self.on_enabled, latched) self.create_subscription(JointState, 'joint_commands', self.on_command, 10) self.create_service(Trigger, '~/zero', self.on_zero) + self.joint_control_publisher = self.create_publisher( + DiagnosticArray, joint_control.TOPIC, latched) + self.joint_services = { + joint: self.create_service(SetBool, f'arm/{joint}/set_enabled', + functools.partial(self.on_set_enabled, joint)) + for joint in self.map.joints} self.state_publisher = self.create_publisher(JointState, 'joint_states', 10) self.diagnostics_publisher = self.create_publisher(DiagnosticArray, topic, 10) self.last_tick = time.monotonic() @@ -258,6 +278,7 @@ def __init__(self, **kwargs): self.report_errors = self.report_refused = 0 self.create_timer(self.period, self.tick) self.create_timer(REPORT_PERIOD_S, self.report) + self.publish_joint_control() 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} (no hardware)') @@ -308,13 +329,20 @@ def on_zero(self, request, response): return response self.zero() deadline = time.monotonic() + REPLY_TIMEOUT_S - while not all(self.zeroed) and time.monotonic() < deadline: + idle = self.idle + while (not all(self.zeroed[index] for index in self.active(idle)) + and time.monotonic() < deadline): time.sleep(0.005) self.drain(time.monotonic(), zeroing=True) - missing = [drive.name for drive, done in zip(self.map.drives, self.zeroed) if not done] + missing = [drive.name for index, drive in enumerate(self.map.drives) + if not self.zeroed[index] and index not in idle] + skipped = [drive.name for index, drive in enumerate(self.map.drives) + if not self.zeroed[index] and index in idle] response.success = not missing - response.message = ('Zeroed every drive' if response.success - else 'No zero reply from ' + ', '.join(missing)) + response.message = ('No zero reply from ' + ', '.join(missing) if missing + else 'Zeroed every drive but ' + ', '.join(skipped) + + ' (its joints are disabled)' if skipped + else 'Zeroed every drive') self.get_logger().info(response.message) return response @@ -363,7 +391,8 @@ def finish_check(self, index): self.get_logger().warning(f'{name} does not report its zero, so it is not saved') return self.zero_offsets[index] = offset - if len(self.zero_offsets) == len(self.map.drives): + # A drive with its joints off may never answer; it is saved if it did. + if all(other in self.zero_offsets for other in self.active()): self.save_zero() return saved = self.saved_zero[index] @@ -400,7 +429,7 @@ def load_zero(self): def save_zero(self): drives = {drive.name: {'can_id': drive.can_id, 'offset': self.zero_offsets[index]} - for index, drive in enumerate(self.map.drives)} + for index, drive in enumerate(self.map.drives) if index in self.zero_offsets} saved = {'saved': datetime.datetime.now().isoformat(timespec='seconds'), 'drives': drives} partial = self.zero_state + '.partial' @@ -439,19 +468,60 @@ def on_description(self, message): return self.description_valid = True + @property + def idle(self): + """Return the indices of the drives whose joints are all disabled: nothing moves them.""" + return {index for index, joints in enumerate(self.drive_joints) + if joints <= self.disabled} + + def active(self, idle=None): + """Return the indices of the drives that the arm needs.""" + idle = self.idle if idle is None else idle + return [index for index in range(len(self.map.drives)) if index not in idle] + + def trusted(self, index, now): + """Return whether a drive has answered lately and holds the zero.""" + heard = self.heard[index] + return (self.counts[index] is not None and self.zeroed[index] and not self.lost[index] + and heard is not None and now - heard <= REPLY_TIMEOUT_S) + + def full_counts(self, now=None): + """ + Return one encoder count per drive, or None while a drive the arm needs has none. + + A drive whose joints are all off may be missing, faulty or unzeroed: it counts as + wherever its joints were last seen, so the others neither wait for it nor tell it apart. + """ + now = time.monotonic() if now is None else now + idle = self.idle + counts = [] + for index, count in enumerate(self.counts): + if index in idle and not self.trusted(index, now): + angles = {joint: self.last_angle.get(joint, 0.0) for joint in self.map.joints} + count = self.map.to_counts(angles)[index] + elif count is None: + return None + counts.append(count) + return counts + def feedback_fresh(self, now): - return all(heard is not None and now - heard <= REPLY_TIMEOUT_S for heard in self.heard) + return all(self.heard[index] is not None and now - self.heard[index] <= REPLY_TIMEOUT_S + for index in self.active()) def on_enabled(self, message): now = time.monotonic() + counts = self.full_counts(now) if not message.data: self.disarm('Teleop disabled') 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 + elif (not self.awaiting_release and self.description_valid + and all(self.zeroed[index] for index in self.active()) + and not any(self.unconfirmed[index] for index in self.active()) + and not self.stopping and counts is not None and self.feedback_fresh(now) and not self.estop_pressed): if not self.authorized: - self.commanded = self.map.to_positions(self.counts) + self.commanded = self.map.to_positions(counts) + self.anchors = {joint: self.commanded[joint] for joint in self.disabled} self.authorized = True self.enabled_at = now self.stop_reason = '' @@ -492,8 +562,20 @@ def on_command(self, message): self.reject_command(f'{joint} is locked at {angle:g} rad') return del velocities[joint] - measured = self.map.to_positions(self.counts) + for joint in self.disabled: + if abs(positions[joint] - self.anchors[joint]) > DISABLED_TOLERANCE_RAD: + self.reject_command(f'{joint} is disabled') + return + # Teleop's reading may differ by a count or two; the drives get exactly the anchor. + positions[joint], velocities[joint] = self.anchors[joint], 0.0 + counts = self.full_counts() + if counts is None: + self.reject_command('Waiting for drive feedback') + return + measured = self.map.to_positions(counts) for joint, (lower, upper) in self.limits.items(): + if joint in self.disabled: + continue position, actual = positions[joint], measured[joint] # An already-outside encoder may move toward the URDF range, never farther out. if ((position < lower and (actual >= lower or position < actual)) @@ -562,9 +644,12 @@ def tick(self): self.unanswered[index] += 1 self.drain(now) self.check_following() - if not all(self.zeroed) or None in self.counts: + counts = self.full_counts(now) + if not all(self.zeroed[index] for index in self.active()) or counts is None: return - positions = self.map.to_positions(self.counts) + positions = self.map.to_positions(counts) + for joint in self.disabled: + self.last_angle[joint] = positions[joint] if self.commanded is None: # Hold the actual encoder pose while disarmed, including after a host pause. self.commanded = dict(positions) @@ -589,11 +674,21 @@ def lose(self, index, reason): name = self.map.drives[index].name self.lost[index], self.zeroed[index] = True, False self.checks.pop(index, None) + if index in self.idle: + # Nothing is moving because of it, so the arm carries on without it. + self.get_logger().warning(f'{name} {reason}; its joints are disabled, so the arm ' + 'carries on') + return self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped') def check_following(self): + idle = self.idle for index, (sent, count) in enumerate(zip(self.sent, self.counts)): + if index in idle: + # Its joints are off, so a hand that moved it is no fault. + self.behind[index] = 0 + continue # A stopped drive must stay where it stopped, armed or not, as its firmware can # run on to a kept target after any stop. target = None @@ -631,7 +726,9 @@ def fault(self, index, reason): def stop_drives(self): """Stop every drive with the manual's F5 zero-speed, zero-acceleration frame.""" self.velocities.clear() - self.stopping.update(index for index, sent in enumerate(self.sent) if sent != (None, 0)) + idle = self.idle + self.stopping.update(index for index, sent in enumerate(self.sent) + if sent != (None, 0) and index not in idle) self.send_stops() def send_stops(self): @@ -652,8 +749,16 @@ def send_stops(self): self.start_hold(index, now) def send_targets(self): + idle = self.idle + counts = self.full_counts() + if counts is None: + self.reject_command('Waiting for drive feedback') + return + # A drive with its joints off is never moved, so it must not set the others' speed. + wanted = self.map.to_counts(self.commanded) + counts = [wanted[index] if index in idle else count for index, count in enumerate(counts)] try: - moves = self.map.synchronized(self.commanded, self.counts, self.period, self.max_rpm, + moves = self.map.synchronized(self.commanded, counts, self.period, self.max_rpm, self.velocities) motor_rates = self.map.shaft_rpm(self.velocities) commands = [] @@ -667,6 +772,8 @@ def send_targets(self): return for index, (drive, (axis, speed), rpm, data) in enumerate( zip(self.map.drives, moves, motor_rates, commands)): + if index in idle: + continue ahead, direction = axis - self.counts[index], self.direction[index] if (rpm == 0.0 or self.settling[index] is not None or (direction and ahead * direction < 0)): @@ -857,7 +964,7 @@ def on_reply(self, can_id, data, now): if index in self.checks: self.finish_check(index) # Only stops and holds go out while disarmed, and a released motor refuses those too. - if failed and self.authorized: + if failed and self.authorized and index not in self.idle: self.fault(index, failed) def report(self): @@ -884,14 +991,16 @@ def report(self): statuses.append(status('arm.command_gate', gate_level, 'enabled' if self.authorized else 'stopped', '', self.stop_reason or 'Receiving validated teleop setpoints')) - if not all(self.zeroed): + idle = self.idle + counts = self.full_counts(now) + if not all(self.zeroed[index] for index in self.active(idle)): restoring = any(check['purpose'] == 'restore' for check in self.checks.values()) statuses.append(status( 'arm.zero', DiagnosticStatus.WARN, 'checking' if restoring else 'no', '', 'Checking whether the drives kept their saved zero' if restoring else f'Not zeroed. {self.zero_hint()}')) - elif None not in self.counts: - positions = self.map.to_positions(self.counts) + elif counts is not None: + positions = self.map.to_positions(counts) commanded = self.commanded or {} for joint, position in positions.items(): target = math.degrees(commanded.get(joint, position)) @@ -954,6 +1063,10 @@ def report(self): level = DiagnosticStatus.STALE elif health_state is not DriveHealthState.OK: level = DiagnosticStatus.ERROR + if index in idle: + # Its joints are off: whatever it does is not the arm's fault. + level = min(level, DiagnosticStatus.WARN) + text = f'disabled ({text})' statuses.append(status( f'drive.{drive.name}', level, turns, 'rev', f'CAN ID {drive.can_id}: {text}' @@ -963,6 +1076,66 @@ def report(self): message = DiagnosticArray(status=statuses) message.header.stamp = self.get_clock().now().to_msg() self.diagnostics_publisher.publish(message) + self.publish_joint_control() + + def set_joint_enabled(self, joint, enabled): + """ + Switch one joint on or off while the arm is stopped; return (done, what happened). + + Like zeroing, this waits until teleop has stopped streaming. A joint that is switched + on again needs its drive answering and zeroed before the arm can be enabled. + """ + if joint not in self.map.joints: + return False, f'{joint} has no drive on this arm' + if self.authorized or time.monotonic() - self.command_time < QUIET_BEFORE_ZERO_S: + return False, 'Joint commands are still arriving; disable teleop (Start) first' + word = 'enabled' if enabled else 'disabled' + if enabled != (joint in self.disabled): + return True, f'{joint} is already {word}' + if enabled: + self.disabled.discard(joint) + else: + counts = self.full_counts() + if counts is not None: + self.last_angle[joint] = self.map.to_positions(counts)[joint] + self.disabled.add(joint) + # A hold from before the switch must not move a drive that was left alone meanwhile, + # and a stop that a missing drive never took is no longer anyone's concern. + for index, joints in enumerate(self.drive_joints): + if joint in joints: + self.held[index], self.hold_until[index] = None, -math.inf + self.stopping.difference_update(self.idle) + self.get_logger().info(f'{joint} is {word}') + self.publish_joint_control() + return True, f'{joint} is {word}' + + def on_set_enabled(self, joint, request, response): + response.success, response.message = self.set_joint_enabled(joint, request.data) + return response + + def publish_joint_control(self): + counts = self.full_counts() + positions = self.map.to_positions(counts) if counts is not None else {} + statuses = [] + for joint in sorted({*self.map.joints, *self.locked}): + if joint in self.locked: + angle = self.locked[joint] + state, drives = joint_control.NO_DRIVE, [] + text = f'no drive fitted: locked at {math.degrees(angle):+.1f} deg' + else: + drives = [drive.name for drive, joints in zip(self.map.drives, self.drive_joints) + if joint in joints] + if joint in self.disabled: + angle = self.last_angle.get(joint, positions.get(joint, 0.0)) + state = joint_control.DISABLED + text = f'disabled: held at {math.degrees(angle):+.1f} deg' + else: + angle = positions.get(joint, self.last_angle.get(joint, 0.0)) + state, text = joint_control.ENABLED, 'enabled' + statuses.append(joint_control.joint_status(joint, state, drives, angle, text)) + message = DiagnosticArray(status=statuses) + message.header.stamp = self.get_clock().now().to_msg() + self.joint_control_publisher.publish(message) def on_test_fault_parameter(self, parameters): """Apply a simulator-only ``drive_name:fault`` parameter or clear with ``none``.""" From 9440c7d9fc3fbc9782a9161296bdca0d68798550 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:12:55 -0600 Subject: [PATCH 10/31] Hold the arm when a joint is switched off under teleop xbox_teleop follows arm/joint_control: joints the drive node reports as disabled are passed to ArmTeleop, also when the report arrives before the robot description. If the set changes while the arm is enabled, teleop disables and holds the measured pose, and the next Start enables only the joints that are left. The teleop.state row names the joints that are off. --- .../test/test_xbox_teleop_node.py | 57 ++++++++++++++++++- .../waybionic_teleop/xbox_teleop_node.py | 27 ++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/waybionic_teleop/test/test_xbox_teleop_node.py b/waybionic_teleop/test/test_xbox_teleop_node.py index 61eb8e13..a8b568c0 100644 --- a/waybionic_teleop/test/test_xbox_teleop_node.py +++ b/waybionic_teleop/test/test_xbox_teleop_node.py @@ -4,13 +4,14 @@ from pathlib import Path import time +from diagnostic_msgs.msg import DiagnosticArray import pytest import rclpy from rclpy.parameter import Parameter from sensor_msgs.msg import JointState, Joy from std_msgs.msg import Bool, String -from waybionic_teleop import xbox_teleop_node +from waybionic_teleop import joint_control, xbox_teleop_node from waybionic_teleop.gamepad import AXES, BUTTONS from waybionic_teleop.sim_arm_drives_node import SimArmDrives from waybionic_teleop.xbox_teleop_node import XboxTeleop @@ -281,3 +282,57 @@ def gate_report(): assert node.summary(True).endswith('DISABLED\nPRESS-MENU') finally: drives.destroy_node() + + +def joint_control_report(*disabled): + names = ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'tool_grip'] + return DiagnosticArray(status=[ + joint_control.joint_status( + joint, joint_control.DISABLED if joint in disabled else joint_control.ENABLED, + [], 0.0, 'disabled' if joint in disabled else 'enabled') + for joint in names]) + + +def test_a_joint_switched_off_while_enabled_holds_the_arm(node, monkeypatch): + enabled, commands = [], [] + monkeypatch.setattr(node.enable_publisher, 'publish', enabled.append) + monkeypatch.setattr(node.command_publisher, 'publish', commands.append) + ready(node) + # A report that changes nothing leaves the arm enabled. + node.on_joint_control(joint_control_report()) + assert node.teleop.enabled + node.measured['joint_3'] = 0.3 + node.on_joint_control(joint_control_report('joint_3')) + assert not node.teleop.enabled and node.teleop.disabled == {'joint_3'} + assert 'Joint enable changed' in node.teleop.note + assert enabled[-1].data is False and not any(commands[-1].velocity) + assert dict(zip(commands[-1].name, commands[-1].position))['joint_3'] == pytest.approx(0.3) + # Start holds it where it is, and its stick does nothing. + tick(node) + tick(node, 'start') + for _ in range(20): + tick(node, right_y=-1.0) + assert node.teleop.enabled and node.teleop.targets['joint_3'] == pytest.approx(0.3) + assert node.teleop.blocked == [] + + +def test_a_joint_reported_off_before_the_description_still_applies(node): + node.on_joint_control(joint_control_report('joint_3')) + assert node.teleop is None + node.load(String(data=URDF)) + assert node.teleop.disabled == {'joint_3'} + # The same report again, as the drive node repeats it, changes nothing. + node.on_joint_control(joint_control_report('joint_3')) + assert node.teleop.disabled == {'joint_3'} + node.on_joint_control(joint_control_report()) + assert node.teleop.disabled == set() + + +def test_the_state_row_names_the_joints_that_are_off(node, monkeypatch): + diagnostics = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', diagnostics.append) + node.load(String(data=URDF)) + node.on_joint_control(joint_control_report('joint_3', 'joint_1')) + node.report() + row = next(item for item in diagnostics[-1].status if item.name == 'teleop.state') + assert row.message.startswith('Joints off: joint_1, joint_3; ') diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index 9a5cc3d4..afb1b429 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -2,7 +2,8 @@ Drive the arm from an Xbox controller: /joy in, /joint_commands out. Mapping and limits come from config/xbox_teleop.yaml and the robot_description joint limits; -a joint the arm profile (``arm_profile``) locks stays at its angle. The logic lives in +a joint the arm profile (``arm_profile``) locks stays at its angle, and so does one the drive +node reports switched off on ``arm/joint_control``. The logic lives in :mod:`waybionic_teleop.teleop`. The node also reports its state on /diagnostics and draws a placeholder end effector and a status label in RViz. """ @@ -19,6 +20,7 @@ from std_msgs.msg import Bool, String from visualization_msgs.msg import Marker, MarkerArray +from waybionic_teleop import joint_control from waybionic_teleop.arm_profile import load_profile from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS @@ -70,6 +72,8 @@ def __init__(self, **kwargs): self.table_height = float(params.get('table_height', 0.0)) self.clearance = float(params.get('collision_clearance', 0.01)) self.locked = load_profile(params.get('arm_profile', '')).locked_joints + # Joints the drive node says are switched off, even before there is a teleop to tell. + self.disabled = set() self.teleop = None self.problem = 'Waiting for robot_description' self.joy = None @@ -82,6 +86,8 @@ def __init__(self, **kwargs): self.create_subscription(String, 'robot_description', self.load, latched) self.create_subscription(Joy, 'joy', self.on_joy, 10) self.create_subscription(JointState, 'joint_states', self.on_joint_states, 10) + self.create_subscription(DiagnosticArray, joint_control.TOPIC, self.on_joint_control, + latched) self.command_publisher = self.create_publisher(JointState, 'joint_commands', 10) self.enable_publisher = self.create_publisher(Bool, 'teleop_enabled', latched) # game_controller_node rumbles a local controller; joy_udp_receiver passes it on. @@ -135,6 +141,7 @@ def load(self, message): self.get_logger().error(f'Teleop disabled: {error}') return self.problem = '' + self.apply_disabled() self.get_logger().info('Xbox teleop ready (press Start to enable): ' + '; '.join( f'{group.name}: {group.describe()}' for group in self.teleop.groups)) @@ -153,6 +160,22 @@ def on_joy(self, message): self.joy, self.joy_time = message, time.monotonic() self.joy_count += 1 + def on_joint_control(self, message): + self.disabled = joint_control.disabled_joints(message) + self.apply_disabled() + + def apply_disabled(self): + if self.teleop is None: + return + was_enabled = self.teleop.enabled + changed = self.teleop.set_disabled( + self.disabled, self.recent_measurement(time.monotonic())) + if changed and was_enabled: + # Hold the arm where it is until the operator presses Start again. + self.publish_enabled(False) + self.publish_command() + self.get_logger().warning('Joint enable changed: teleop disabled, arm held') + def on_joint_states(self, message): now = time.monotonic() for name, position in zip(message.name, message.position): @@ -318,6 +341,8 @@ def report(self): 'Y switches once the tool is withdrawn') note = teleop.note or ('At limit: ' + ', '.join(teleop.blocked) if teleop.blocked else ('LB moves along one axis; ' if cartesian else '') + hint) + if teleop.disabled: + note = f'Joints off: {", ".join(sorted(teleop.disabled))}; {note}' speed = (f'{1000.0 * teleop.linear_speed:.1f} mm/s' if group.mode != 'joint' else f'{math.degrees(teleop.speed):.0f} deg/s') low, high = self.config.tool_limits From 49c66f0243ec893cb224389b9c7c58367f97e597 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:15:31 -0600 Subject: [PATCH 11/31] Add a start-up guide that says what to do next Starting the real arm took knowing which row of the diagnostics to look at: carrier, each drive, the controller, the zero. The setup_guide node reads those rows and publishes five steps on a latched arm/setup topic (carrier, drives, controller, zero, ready), each with an instruction, a state and, for the zero, an action the RViz panel can offer. It judges a step only when the ones it needs are done, forgets rows that stop arriving, and says each change in the terminal. It only reads and reports. The zero stays the drive node's own service. The launch file starts it with teleop. --- .../launch/ground_station.launch.py | 9 +- waybionic_teleop/setup.py | 1 + waybionic_teleop/test/test_setup_guide.py | 209 ++++++++++++++++ .../waybionic_teleop/setup_guide.py | 230 ++++++++++++++++++ 4 files changed, 448 insertions(+), 1 deletion(-) create mode 100644 waybionic_teleop/test/test_setup_guide.py create mode 100644 waybionic_teleop/waybionic_teleop/setup_guide.py diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index 10134382..14322479 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -332,6 +332,12 @@ def generate_launch_description(): arm_profile, sim_time] ) + # Tells the operator what to do next to start the arm (see waybionic_teleop/setup_guide.py). + setup_guide_node = Node( + package='waybionic_teleop', executable='setup_guide', name='setup_guide', + condition=IfCondition(teleop), parameters=[diagnostics_topic, sim_time] + ) + drives_node = Node( package='waybionic_teleop', executable='sim_arm_drives', name='sim_arm_drives', output='screen', condition=IfCondition(teleop), @@ -406,6 +412,7 @@ def generate_launch_description(): camera_bind_arg, camera_log_arg, launch_rviz_arg, rviz_maximized_arg, rviz_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node, - joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, camera_follower_node, + joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, setup_guide_node, + camera_follower_node, temp_diag_pub_node, camera_launch, rviz_node ]) diff --git a/waybionic_teleop/setup.py b/waybionic_teleop/setup.py index a5943eff..2a4fcda2 100644 --- a/waybionic_teleop/setup.py +++ b/waybionic_teleop/setup.py @@ -31,6 +31,7 @@ 'mks_drive_sim = waybionic_teleop.mks_drive_sim:main', 'mks_setup = waybionic_teleop.mks_setup:main', 'autoplay = waybionic_teleop.autoplay_node:main', + 'setup_guide = waybionic_teleop.setup_guide:main', 'joy_udp_receiver = waybionic_teleop.joy_udp_receiver:main', ], }, diff --git a/waybionic_teleop/test/test_setup_guide.py b/waybionic_teleop/test/test_setup_guide.py new file mode 100644 index 00000000..d86809be --- /dev/null +++ b/waybionic_teleop/test/test_setup_guide.py @@ -0,0 +1,209 @@ +"""The guided start-up steps: what the operator has to do next, from the /diagnostics rows.""" + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue +import pytest +import rclpy +from rclpy.parameter import Parameter + +from waybionic_teleop import setup_guide +from waybionic_teleop.setup_guide import BLOCKED, OK, SetupGuide, TODO, WORKING + +OK_LEVEL, WARN, ERROR, STALE = (DiagnosticStatus.OK, DiagnosticStatus.WARN, + DiagnosticStatus.ERROR, DiagnosticStatus.STALE) + + +def row(name, level=OK_LEVEL, message='', value='', **values): + items = {'value': value, **values} + return DiagnosticStatus(name=name, level=level, message=message, values=[ + KeyValue(key=key, value=str(item)) for key, item in items.items()]) + + +def table(*rows): + return {item.name: item for item in rows} + + +def drive(name, can_id, text='ready', level=OK_LEVEL): + return row(f'drive.{name}', level, f'CAN ID {can_id}: {text}', '0.000', can_id=can_id) + + +CARRIER = row('can.carrier', value='released') +GATE = row('arm.command_gate', WARN, 'Teleop disabled', 'stopped') +DRIVES = [drive('base_yaw', 1), drive('elbow', 3), drive('wrist_left', 4), + drive('wrist_right', 5)] +JOINTS = [row(f'arm.joint_{number}', value='+0.0', unit='deg') for number in range(1, 6)] +CONTROLLER = row('teleop.input', value='120') + + +def ready_rows(**changes): + rows = table(CARRIER, GATE, *DRIVES, *JOINTS, CONTROLLER, + row('can.bus', value='500', interface='slcan'), + row('teleop.state', value='disabled', message='Press Start to enable')) + rows.update(changes) + return {name: item for name, item in rows.items() if item is not None} + + +def states(rows): + return {step.name: step.state for step in setup_guide.evaluate(rows)} + + +def step(rows, name): + return next(item for item in setup_guide.evaluate(rows) if item.name == name) + + +def test_the_steps_come_in_the_order_the_operator_does_them(): + steps = setup_guide.evaluate({}) + assert [item.name for item in steps] == ['carrier', 'drives', 'controller', 'zero', 'ready'] + assert [item.title for item in steps] == ['Carrier', 'Drives', 'Controller', 'Zero', 'Ready'] + + +def test_nothing_is_running_yet(): + found = states({}) + assert found == {'carrier': WORKING, 'drives': TODO, 'controller': WORKING, 'zero': TODO, + 'ready': TODO} + assert 'Waiting' in step({}, 'carrier').message + + +def test_everything_in_order_leaves_only_start(): + found = states(ready_rows()) + assert [found[name] for name in ('carrier', 'drives', 'controller', 'zero')] == [OK] * 4 + ready = step(ready_rows(), 'ready') + assert ready.state == TODO and 'Start' in ready.message + assert states(ready_rows(**{'teleop.state': row('teleop.state', value='enabled')}))[ + 'ready'] == OK + + +def test_the_current_step_is_the_first_that_is_not_done(): + assert setup_guide.current(setup_guide.evaluate(ready_rows())).name == 'ready' + done = ready_rows(**{'teleop.state': row('teleop.state', value='enabled')}) + assert setup_guide.current(setup_guide.evaluate(done)) is None + assert setup_guide.current(setup_guide.evaluate({})).name == 'carrier' + + +@pytest.mark.parametrize('carrier, state, words', [ + (row('can.carrier', ERROR, 'USB link lost', 'unplugged'), TODO, 'USB-C'), + (row('can.carrier', WARN, 'No status from the carrier', 'silent'), BLOCKED, 'firmware'), + (row('can.carrier', ERROR, 'E-stop pressed', 'pressed'), BLOCKED, 'E-stop'), +]) +def test_a_carrier_that_is_not_there_holds_up_the_drives_and_what_needs_them( + carrier, state, words): + rows = ready_rows(**{'can.carrier': carrier}) + assert step(rows, 'carrier').state == state and words in step(rows, 'carrier').message + # The controller does not depend on it. + assert states(rows) == {'carrier': state, 'drives': TODO, 'controller': OK, 'zero': TODO, + 'ready': TODO} + assert setup_guide.current(setup_guide.evaluate(rows)).name == 'carrier' + + +def test_a_simulated_or_other_bus_needs_no_carrier(): + simulated = ready_rows(**{'can.carrier': None, + 'can.bus': row('can.bus', value='500', interface='sim')}) + assert step(simulated, 'carrier').state == OK and 'Simulated' in step( + simulated, 'carrier').message + socketcan = ready_rows(**{'can.carrier': None, + 'can.bus': row('can.bus', value='500', interface='socketcan')}) + assert 'socketcan' in step(socketcan, 'carrier').message + + +def test_a_drive_that_does_not_answer_is_named_with_its_can_id(): + silent = drive('elbow', 3, 'no reply', ERROR) + rows = ready_rows(**{'drive.elbow': silent}) + found = step(rows, 'drives') + assert found.state == BLOCKED + assert 'elbow' in found.message and 'CAN 3' in found.message + assert 'Joint control' in found.message + assert step(rows, 'zero').state == TODO + + +def test_a_drive_whose_joint_is_switched_off_is_not_a_problem(): + off = drive('elbow', 3, 'disabled (no reply)', WARN) + found = step(ready_rows(**{'drive.elbow': off}), 'drives') + assert found.state == OK and '3 drives answer' in found.message + assert '1 switched off' in found.message + + +def test_a_drive_that_reports_a_fault_blocks_with_its_state(): + failed = drive('base_yaw', 1, 'run failed', ERROR) + found = step(ready_rows(**{'drive.base_yaw': failed}), 'drives') + assert found.state == BLOCKED and 'base_yaw' in found.message and 'run failed' in found.message + + +def test_drives_still_being_set_up_are_work_in_progress(): + pending = drive('base_yaw', 1, 'ready, setup 82h unconfirmed', WARN) + assert step(ready_rows(**{'drive.base_yaw': pending}), 'drives').state == WORKING + assert step(ready_rows(**{f'drive.{name}': None for name in ( + 'base_yaw', 'elbow', 'wrist_left', 'wrist_right')}), 'drives').state == WORKING + + +def test_the_controller_must_be_sending_input(): + quiet = row('teleop.input', STALE, 'No /joy input from a controller', '0') + found = step(ready_rows(**{'teleop.input': quiet}), 'controller') + assert found.state == TODO and 'Connect' in found.message + assert step(ready_rows(**{'teleop.input': None}), 'controller').state == WORKING + + +def test_zero_asks_for_the_zero_pose_and_offers_the_zero_action(): + rows = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Not zeroed.', 'no'), + **{f'arm.joint_{number}': None for number in range(1, 6)}}) + found = step(rows, 'zero') + assert found.state == TODO and found.action == 'zero' and 'zero pose' in found.message + assert step(ready_rows(), 'zero').action == '' + checking = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Checking', 'checking'), + **{f'arm.joint_{number}': None for number in range(1, 6)}}) + assert step(checking, 'zero').state == WORKING and step(checking, 'zero').action == '' + assert step(rows, 'ready').state == TODO and 'above' in step(rows, 'ready').message + + +def test_a_teleop_that_cannot_start_blocks_the_last_step(): + broken = row('teleop.state', ERROR, 'Waiting for robot_description', 'disabled') + found = step(ready_rows(**{'teleop.state': broken}), 'ready') + assert found.state == BLOCKED and 'robot_description' in found.message + + +@pytest.fixture +def guide(monkeypatch): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + node = SetupGuide(context=context, parameter_overrides=[ + Parameter('diagnostics_topic', value='/diagnostics')]) + yield node + node.destroy_node() + rclpy.try_shutdown(context=context) + + +def test_the_guide_publishes_each_step_latched(guide, monkeypatch): + published = [] + monkeypatch.setattr(guide.publisher, 'publish', published.append) + assert guide.publisher.qos_profile.durability == rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + guide.publish_steps() + message = published[-1] + assert [item.name for item in message.status] == [ + 'setup.carrier', 'setup.drives', 'setup.controller', 'setup.zero', 'setup.ready'] + values = [{item.key: item.value for item in found.values} for found in message.status] + assert [item['state'] for item in values] == [OK, OK, OK, OK, TODO] + assert [item['title'] for item in values] == [ + 'Carrier', 'Drives', 'Controller', 'Zero', 'Ready'] + assert [item['current'] for item in values] == ['false'] * 4 + ['true'] + assert [found.level for found in message.status] == [OK_LEVEL] * 4 + [WARN] + + +def test_rows_that_stop_arriving_are_forgotten(guide, monkeypatch): + clock = [100.0] + monkeypatch.setattr(setup_guide.time, 'monotonic', lambda: clock[0]) + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + assert states(guide.fresh_rows()) == states(ready_rows()) + clock[0] += setup_guide.ROW_TIMEOUT_S + 0.1 + assert step(guide.fresh_rows(), 'carrier').state == WORKING + # One row that keeps coming stays, whatever the rest do. + guide.on_diagnostics(DiagnosticArray(status=[CARRIER, GATE])) + assert set(guide.fresh_rows()) == {'can.carrier', 'arm.command_gate'} + + +def test_a_step_that_changes_is_logged_once(guide, monkeypatch): + messages = [] + monkeypatch.setattr(guide, 'announce', messages.append) + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + guide.publish_steps() + guide.publish_steps() + assert len(messages) == 1 and 'Ready' in messages[0] and 'Start' in messages[0] diff --git a/waybionic_teleop/waybionic_teleop/setup_guide.py b/waybionic_teleop/waybionic_teleop/setup_guide.py new file mode 100644 index 00000000..43cac172 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/setup_guide.py @@ -0,0 +1,230 @@ +""" +Walk the operator through starting the arm: what to do next, from the /diagnostics rows. + +The drive and teleop nodes already report the carrier, each drive, the controller and the zero +on /diagnostics. This node turns those rows into five steps, in the order the operator does +them: carrier, drives, controller, zero and ready. It publishes them on ``arm/setup`` (a latched +DiagnosticArray of ``setup.`` rows) for the RViz setup panel, and says each change in the +terminal. A row's message is the instruction, and its values are ``title``, ``state`` (OK, +TODO, BLOCKED or WORKING), ``action`` (``zero`` when the panel is to offer the zero button) and +``current`` (true for the first step that is not done). + +It only reads and reports. The zero is the drive node's own ``~/zero`` service. +""" + +from dataclasses import dataclass +import time + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue +import rclpy +from rclpy.executors import ExternalShutdownException +from rclpy.node import Node +from rclpy.qos import DurabilityPolicy, QoSProfile + +from waybionic_teleop.ros_shutdown import is_shutdown_error + +TOPIC = 'arm/setup' +OK, TODO, BLOCKED, WORKING = 'ok', 'todo', 'blocked', 'working' +LEVELS = {OK: DiagnosticStatus.OK, WORKING: DiagnosticStatus.OK, TODO: DiagnosticStatus.WARN, + BLOCKED: DiagnosticStatus.ERROR} +# The drive node reports twice a second; a row this old means whoever sent it has gone. +ROW_TIMEOUT_S = 3.0 +PUBLISH_PERIOD_S = 0.5 +TITLES = {'carrier': 'Carrier', 'drives': 'Drives', 'controller': 'Controller', + 'zero': 'Zero', 'ready': 'Ready'} +WAITS = 'Waits for the steps above' + + +@dataclass +class Step: + """One thing the operator has to get right, and what to do about it.""" + + name: str + state: str + message: str + action: str = '' + + @property + def title(self): + return TITLES[self.name] + + +def value(row, key='value'): + """Return one of a row's values, or '' if it has none.""" + if row is None: + return '' + return next((item.value for item in row.values if item.key == key), '') + + +def carrier_step(rows): + if 'arm.command_gate' not in rows: + return Step('carrier', WORKING, 'Waiting for the ground station to start...') + carrier = rows.get('can.carrier') + if carrier is None: + interface = value(rows.get('can.bus'), 'interface') + if interface == 'sim': + return Step('carrier', OK, 'Simulated drives, no hardware') + return Step('carrier', OK, f'Using the {interface or "CAN"} adapter') + state = value(carrier) + if state == 'unplugged': + return Step('carrier', TODO, "Plug the carrier's USB-C cable into this computer") + if state == 'silent': + return Step('carrier', BLOCKED, + 'The carrier is plugged in but silent: replug it, or flash its firmware ' + '(./scripts/macos.sh flash)') + if state == 'pressed': + return Step('carrier', BLOCKED, 'The E-stop is pressed: release it') + return Step('carrier', OK, 'Carrier connected') + + +def drives_step(rows): + drives = {name[len('drive.'):]: row for name, row in rows.items() + if name.startswith('drive.')} + if not drives: + return Step('drives', WORKING, 'Waiting for the drives...') + off = [name for name, row in drives.items() if 'disabled (' in row.message] + on = {name: row for name, row in drives.items() if name not in off} + missing = [f'{name} (CAN {value(row, "can_id")})' for name, row in on.items() + if 'no reply' in row.message] + if missing: + return Step('drives', BLOCKED, + f'No answer from {", ".join(missing)}: check its power and CAN wiring, or ' + 'switch its joint off in Joint control') + failed = [f'{name} ({row.message.split(": ", 1)[-1]})' for name, row in on.items() + if row.level == DiagnosticStatus.ERROR] + if failed: + return Step('drives', BLOCKED, f'Drive fault: {", ".join(failed)}') + if any('unconfirmed' in row.message for row in on.values()): + return Step('drives', WORKING, 'Setting up the drives...') + message = f'{len(on)} drives answer' + if off: + message += f', {len(off)} switched off' + return Step('drives', OK, message) + + +def controller_step(rows): + row = rows.get('teleop.input') + if row is None: + return Step('controller', WORKING, 'Waiting for teleop to start...') + if row.level == DiagnosticStatus.OK: + return Step('controller', OK, 'Controller connected') + return Step('controller', TODO, + 'Connect an Xbox controller (USB or Bluetooth) and press any button') + + +def zero_step(rows): + zero = rows.get('arm.zero') + if zero is not None: + if value(zero) == 'checking': + return Step('zero', WORKING, 'Checking whether the drives kept their saved zero...') + return Step('zero', TODO, + 'Put the arm in its zero pose (upright, as RViz shows it), then press Zero', + action='zero') + if any(name.startswith('arm.') and name not in ('arm.zero', 'arm.command_gate') + for name in rows): + return Step('zero', OK, 'Zeroed') + return Step('zero', WORKING, 'Reading the drives...') + + +def ready_step(rows): + state = rows.get('teleop.state') + if state is None: + return Step('ready', WORKING, 'Waiting for teleop to start...') + if state.level == DiagnosticStatus.ERROR: + return Step('ready', BLOCKED, state.message) + if value(state) == 'enabled': + return Step('ready', OK, 'Teleop is on: the sticks move the arm, B stops it') + message = 'Press Start (the Menu button) on the controller' + if state.level == DiagnosticStatus.WARN and state.message: + message = state.message + return Step('ready', TODO, message) + + +def evaluate(rows): + """ + Return the five steps for the fresh /diagnostics rows, {name: DiagnosticStatus}. + + The controller can be plugged in at any time. The others need what comes before them: the + drives are on the carrier's bus, and the zero and the Start press need drives that answer. + """ + carrier = carrier_step(rows) + drives = drives_step(rows) if carrier.state == OK else Step('drives', TODO, WAITS) + controller = controller_step(rows) + zero = zero_step(rows) if drives.state == OK else Step('zero', TODO, WAITS) + before = (carrier, drives, controller, zero) + ready = (ready_step(rows) if all(step.state == OK for step in before) + else Step('ready', TODO, WAITS)) + return [*before, ready] + + +def current(steps): + """Return the first step that is not done, or None once the arm is ready.""" + return next((step for step in steps if step.state != OK), None) + + +class SetupGuide(Node): + """Publish the start-up steps as the other nodes' rows change.""" + + def __init__(self, **kwargs): + super().__init__('setup_guide', automatically_declare_parameters_from_overrides=True, + **kwargs) + topic = (self.get_parameter('diagnostics_topic').value + if self.has_parameter('diagnostics_topic') else '/diagnostics') + self.rows = {} + self.announced = None + latched = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + self.publisher = self.create_publisher(DiagnosticArray, TOPIC, latched) + self.create_subscription(DiagnosticArray, topic, self.on_diagnostics, 10) + self.create_timer(PUBLISH_PERIOD_S, self.publish_steps) + + def on_diagnostics(self, message): + now = time.monotonic() + for row in message.status: + self.rows[row.name] = (row, now) + + def fresh_rows(self): + now = time.monotonic() + return {name: row for name, (row, seen) in self.rows.items() + if now - seen <= ROW_TIMEOUT_S} + + def announce(self, text): + self.get_logger().info(text) + + def publish_steps(self): + steps = evaluate(self.fresh_rows()) + first = current(steps) + statuses = [] + for step in steps: + statuses.append(DiagnosticStatus( + name=f'setup.{step.name}', level=LEVELS[step.state], message=step.message, + values=[KeyValue(key='title', value=step.title), + KeyValue(key='state', value=step.state), + KeyValue(key='action', value=step.action), + KeyValue(key='current', value=str(step is first).lower())])) + message = DiagnosticArray(status=statuses) + message.header.stamp = self.get_clock().now().to_msg() + self.publisher.publish(message) + summary = (first.name, first.state, first.message) if first else None + if summary != self.announced: + self.announced = summary + self.announce(f'Setup: {first.title} - {first.message}' if first + else 'Setup: ready, the arm can be operated') + + +def main(): + rclpy.init() + node = SetupGuide() + try: + rclpy.spin(node) + except (KeyboardInterrupt, ExternalShutdownException): + pass + except RuntimeError as error: + if not is_shutdown_error(error): + raise + finally: + node.destroy_node() + rclpy.try_shutdown() + + +if __name__ == '__main__': + main() From a4d11c12be19a87c0004f39871a782b6f58f776b Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:22:18 -0600 Subject: [PATCH 12/31] Start the station on a Mac by double-click "WayBionic Ground Station.app" is a launcher around scripts/macos.sh: it offers to run the first-time setup, waits for the carrier to be plugged in (or asks which USB device it is, or runs without the arm), then starts the station for the real arm and logs to ~/Library/Logs/WayBionic. Quitting it stops the station as Ctrl+C would, so the drives get their stop first, and an unexpected exit shows the log. `./scripts/macos.sh app` installs a copy in ~/Applications that knows where this folder is. The new exit_with_rviz launch argument ends every node when the RViz window is closed, which the app needs so that nothing is left holding the carrier. macos.sh also adds Homebrew and Miniforge to the PATH, which Finder does not give an app. The launcher's decisions (set up, carrier, simulation) are tested without a screen through a dry-run mode and canned dialog answers. --- scripts/macos.sh | 22 +++ .../launch/ground_station.launch.py | 23 ++- waybionic_bringup/test/test_launch_options.py | 18 ++- waybionic_bringup/test/test_macos_app.py | 142 ++++++++++++++++++ 4 files changed, 199 insertions(+), 6 deletions(-) create mode 100644 waybionic_bringup/test/test_macos_app.py diff --git a/scripts/macos.sh b/scripts/macos.sh index 9ef21c7e..acf503c1 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -7,6 +7,9 @@ ENV_FILE="$ROOT/robostack.yaml" MANAGER="" ENV_EXISTS=false +# Finder, cron and other bare environments have no Homebrew or Miniforge on the PATH. +export PATH="$PATH:/opt/homebrew/bin:/opt/homebrew/Caskroom/miniforge/base/bin:/usr/local/bin" + fail() { echo "error: $*" >&2 exit 1 @@ -25,6 +28,8 @@ Commands: (the R4's own CAN with a TJA1051T transceiver) 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 + app Install "WayBionic Ground Station.app" in ~/Applications (or the folder given), to + start the station by double-click run Run any command inside the ROS workspace The carrier is found as the only /dev/cu.usbmodem* port; set WAYBIONIC_CARRIER to choose. @@ -218,6 +223,20 @@ flash_carrier() { echo "Flashed $name" } +install_app() { + local source="$ROOT/packaging/macos/WayBionic Ground Station.app" + local destination="${1:-$HOME/Applications}/WayBionic Ground Station.app" + + [[ -d "$source" ]] || fail "the app bundle is missing: $source" + mkdir -p "$(dirname "$destination")" + rm -rf "$destination" + cp -R "$source" "$destination" + # The copy can live anywhere, so it is told where this folder is. + printf '%s\n' "$ROOT" > "$destination/Contents/Resources/repo_root" + echo "Installed $destination" + echo "Double-click it, or drag it to the Dock." +} + command_name="${1:-help}" if [[ $# -gt 0 ]]; then shift @@ -271,6 +290,9 @@ case "$command_name" in joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" \ arm_profile:="$profile" drive_zero_state:="$zero_state" "$@" ;; + app) + install_app "$@" + ;; run) [[ $# -gt 0 ]] || fail "run requires a command" prepare diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index 14322479..56b875b8 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -5,10 +5,11 @@ from launch import LaunchDescription from launch.actions import ( - DeclareLaunchArgument, IncludeLaunchDescription, LogInfo, OpaqueFunction, + DeclareLaunchArgument, EmitEvent, IncludeLaunchDescription, LogInfo, OpaqueFunction, RegisterEventHandler) from launch.conditions import IfCondition -from launch.event_handlers import OnShutdown +from launch.event_handlers import OnProcessExit, OnShutdown +from launch.events import Shutdown from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import ( AndSubstitution, Command, EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, @@ -26,6 +27,7 @@ BOOLEAN_OPTIONS = { 'launch_rviz': 'true', 'rviz_maximized': 'true', + 'exit_with_rviz': 'false', 'use_joint_state_publisher_gui': 'true', 'use_diagnostics': 'true', 'use_mock_diagnostics': 'true', @@ -131,7 +133,7 @@ def _launch_rviz(context): live_diagnostics = OrSubstitution( OrSubstitution(LaunchConfiguration('demo_mode'), LaunchConfiguration('teleop')), LaunchConfiguration('camera')) - return [Node( + rviz = Node( package='waybionic_rviz_plugins' if maximized else 'rviz2', executable='ground_station_rviz' if maximized else 'rviz2', name='rviz2', output='screen', @@ -144,7 +146,14 @@ def _launch_rviz(context): NotSubstitution(live_diagnostics))}, {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} ] - )] + ) + actions = [rviz] + if IfCondition(LaunchConfiguration('exit_with_rviz')).evaluate(context): + # Closing the window ends the session, so no node is left holding the carrier. + actions.append(RegisterEventHandler(OnProcessExit( + target_action=rviz, + on_exit=[EmitEvent(event=Shutdown(reason='RViz was closed'))]))) + return actions def generate_launch_description(): @@ -265,6 +274,10 @@ def generate_launch_description(): 'rviz_maximized', default_value='true', choices=BOOLEAN_CHOICES, description='Fill the screen with RViz while keeping its panels and controls visible') + exit_with_rviz_arg = DeclareLaunchArgument( + 'exit_with_rviz', default_value='false', choices=BOOLEAN_CHOICES, + description='Shut every node down when the RViz window is closed') + rviz_config_arg = DeclareLaunchArgument( 'rvizconfig', default_value=default_rviz_config_path, description='Absolute path to rviz config file') @@ -410,7 +423,7 @@ def generate_launch_description(): joy_source_arg, autoplay_arg, joy_udp_bind_arg, joy_udp_port_arg, follow_camera_arg, use_sim_time_arg, camera_arg, camera_bind_arg, camera_log_arg, - launch_rviz_arg, rviz_maximized_arg, rviz_config_arg, file_check, + launch_rviz_arg, rviz_maximized_arg, exit_with_rviz_arg, rviz_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node, joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, setup_guide_node, camera_follower_node, diff --git a/waybionic_bringup/test/test_launch_options.py b/waybionic_bringup/test/test_launch_options.py index 8802457a..d68f2c21 100644 --- a/waybionic_bringup/test/test_launch_options.py +++ b/waybionic_bringup/test/test_launch_options.py @@ -5,9 +5,11 @@ from unittest.mock import patch from launch import LaunchContext -from launch.actions import DeclareLaunchArgument, RegisterEventHandler +from launch.actions import DeclareLaunchArgument, EmitEvent, RegisterEventHandler from launch.conditions import IfCondition +from launch.event_handlers import OnProcessExit from launch.events import Shutdown +from launch.events.process import ProcessExited from launch_ros.actions import Node import pytest import yaml @@ -116,6 +118,20 @@ def test_rviz_keeps_live_diagnostics_selection(context, mock, mode): assert IfCondition(use_mock).evaluate(context) == (mock == 'true' and mode is None) +def test_rviz_exit_ends_the_launch_only_when_asked(context): + assert declarations()['exit_with_rviz'].default_value[0].text == 'false' + context.launch_configurations['exit_with_rviz'] = 'false' + assert [type(action) for action in MODULE._launch_rviz(context)] == [Node] + context.launch_configurations['exit_with_rviz'] = 'true' + rviz, handler = MODULE._launch_rviz(context) + assert isinstance(handler, RegisterEventHandler) + assert isinstance(handler.event_handler, OnProcessExit) + closed = ProcessExited(action=rviz, name='rviz2', cmd=['rviz2'], cwd=None, env=None, + pid=1, returncode=0) + assert any(isinstance(action, EmitEvent) + for action in handler.event_handler.handle(closed, context)) + + def test_default_window_geometry(): config = yaml.safe_load((ROOT / 'rviz/waybionic_unified.rviz').read_text()) geometry = config['Window Geometry'] diff --git a/waybionic_bringup/test/test_macos_app.py b/waybionic_bringup/test/test_macos_app.py new file mode 100644 index 00000000..b858e608 --- /dev/null +++ b/waybionic_bringup/test/test_macos_app.py @@ -0,0 +1,142 @@ +"""The double-click launcher for macOS decides what to do without needing a screen.""" + +import os +from pathlib import Path +import plistlib +import shutil +import subprocess + +import pytest + +APP = (Path(__file__).resolve().parents[2] / 'packaging' / 'macos' + / 'WayBionic Ground Station.app') +LAUNCHER = APP / 'Contents' / 'MacOS' / 'WayBionicGroundStation' + + +@pytest.fixture +def station(tmp_path): + """Return (run, root): run the app copied beside a made-up repository, set up or not.""" + root = tmp_path / 'repo' + (root / 'scripts').mkdir(parents=True) + (root / 'scripts' / 'macos.sh').write_text('#!/bin/bash\n', encoding='utf-8') + (root / 'scripts' / 'macos.sh').chmod(0o755) + app = tmp_path / 'Applications' / APP.name + shutil.copytree(APP, app) + (app / 'Contents' / 'Resources').mkdir(exist_ok=True) + (app / 'Contents' / 'Resources' / 'repo_root').write_text(f'{root}\n', encoding='utf-8') + ports = tmp_path / 'dev' + ports.mkdir() + + def run(*devices, answer=None, set_up=True, **environment): + for item in ports.iterdir(): + item.unlink() + for device in devices: + (ports / device).touch() + installed = root / 'install' / 'setup.bash' + if set_up: + installed.parent.mkdir(exist_ok=True) + installed.touch() + env = {'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', 'WAYBIONIC_APP_DRY_RUN': '1', + 'WAYBIONIC_APP_PORT_GLOB': str(ports / 'cu.usbmodem*'), **environment} + if answer is not None: + env['WAYBIONIC_APP_ANSWER'] = answer + return subprocess.run( + [str(app / 'Contents' / 'MacOS' / LAUNCHER.name)], env=env, capture_output=True, + text=True, timeout=30, check=False) + return run, root, ports + + +def test_the_bundle_describes_an_app_that_runs_the_launcher(): + info = plistlib.loads((APP / 'Contents' / 'Info.plist').read_bytes()) + assert info['CFBundlePackageType'] == 'APPL' + executable = APP / 'Contents' / 'MacOS' / info['CFBundleExecutable'] + assert executable == LAUNCHER and os.access(executable, os.X_OK) + + +def test_the_only_carrier_starts_the_arm(station): + run, root, ports = station + result = run('cu.usbmodem1101') + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == ( + f'would run in {root}: {root}/scripts/macos.sh arm (carrier: {ports}/cu.usbmodem1101)') + + +def test_a_carrier_chosen_in_the_environment_is_not_searched_for(station): + run, root, _ = station + result = run(WAYBIONIC_CARRIER='/dev/cu.mine') + assert result.stdout.strip().endswith('(carrier: /dev/cu.mine)') + + +@pytest.mark.parametrize('answer, wanted', [ + ('Without the arm', 'scripts/macos.sh launch teleop:=true (carrier: none)'), + ('Quit', None), +]) +def test_without_a_carrier_the_operator_chooses(station, answer, wanted): + run, root, _ = station + result = run(answer=answer) + assert result.returncode == 0 + if wanted is None: + assert 'would run' not in result.stdout + else: + assert result.stdout.strip() == f'would run in {root}: {root}/{wanted}' + + +def test_several_usb_devices_ask_which_is_the_carrier(station): + run, root, _ = station + result = run('cu.usbmodem1101', 'cu.usbmodem2201', answer='/dev/cu.usbmodem2201') + assert result.stdout.strip().endswith('(carrier: /dev/cu.usbmodem2201)') + + +@pytest.mark.parametrize('answer, runs_setup', [('Set up', True), ('Not now', False)]) +def test_a_station_that_was_never_set_up_offers_to_set_it_up(station, answer, runs_setup): + run, root, _ = station + result = run('cu.usbmodem1101', set_up=False, answer=answer) + assert result.returncode == 0 + assert ('would run in a Terminal: cd ' + str(root) + ' && ./scripts/macos.sh setup' + in result.stdout) == runs_setup + assert 'macos.sh arm' not in result.stdout + + +def test_an_app_that_lost_its_repository_says_so(station): + run, root, _ = station + (root / 'scripts' / 'macos.sh').unlink() + result = run('cu.usbmodem1101', answer='Quit') + assert result.returncode == 1 and 'would run' not in result.stdout + + +def test_run_from_inside_the_repository_it_finds_the_repository_without_help(tmp_path): + result = subprocess.run( + [str(LAUNCHER)], env={'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', + 'WAYBIONIC_APP_DRY_RUN': '1', 'WAYBIONIC_CARRIER': '/dev/cu.x', + 'WAYBIONIC_APP_ANSWER': 'Quit'}, + capture_output=True, text=True, timeout=30, check=False) + root = APP.parents[2] + if (root / 'install' / 'setup.bash').exists(): + assert result.stdout.strip() == ( + f'would run in {root}: {root}/scripts/macos.sh arm (carrier: /dev/cu.x)') + else: + assert 'would run' not in result.stdout + + +def test_the_app_command_installs_a_copy_that_knows_the_repository(tmp_path): + script = APP.parents[2] / 'scripts' / 'macos.sh' + destination = tmp_path / 'Applications' + for _ in range(2): + result = subprocess.run( + ['bash', str(script), 'app', str(destination)], env={ + 'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin'}, + capture_output=True, text=True, timeout=30, check=False) + assert result.returncode == 0, result.stderr + installed = destination / APP.name + assert (installed / 'Contents' / 'Resources' / 'repo_root').read_text( + encoding='utf-8') == f'{APP.parents[2]}\n' + launcher = installed / 'Contents' / 'MacOS' / LAUNCHER.name + assert os.access(launcher, os.X_OK) + assert str(installed) in result.stdout + + +def test_the_app_command_is_in_the_usage(): + script = APP.parents[2] / 'scripts' / 'macos.sh' + result = subprocess.run(['bash', str(script), 'help'], capture_output=True, text=True, + timeout=30, check=False) + assert ' app ' in result.stdout From 081b8515085b4071abf4017b934a6448a870f73d Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:30:29 -0600 Subject: [PATCH 13/31] Commit the launcher bundle that .gitignore hid *.app is ignored for build results, so the bundle never made it into the previous commit and its tests could only pass in a working tree that had it. The bundle under packaging/macos is source and is now let through. A fresh clone also has no Resources folder, as git keeps no empty directories, so `macos.sh app` failed when it wrote the repository path there. It now creates the folder, and the test installs from a checkout made that way. --- .gitignore | 3 + .../Contents/Info.plist | 24 +++ .../Contents/MacOS/WayBionicGroundStation | 183 ++++++++++++++++++ scripts/macos.sh | 1 + waybionic_bringup/test/test_macos_app.py | 11 +- 5 files changed, 219 insertions(+), 3 deletions(-) create mode 100644 packaging/macos/WayBionic Ground Station.app/Contents/Info.plist create mode 100755 packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation diff --git a/.gitignore b/.gitignore index 8b0ab3b1..3e5e4b88 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,9 @@ ros2_aruco/ *.exe *.out *.app +# The launcher bundle is source, not a build result. +!packaging/macos/*.app +!packaging/macos/*.app/** ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. diff --git a/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist b/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist new file mode 100644 index 00000000..0077ce83 --- /dev/null +++ b/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleName + WayBionic Ground Station + CFBundleDisplayName + WayBionic Ground Station + CFBundleIdentifier + org.waybionic.groundstation + CFBundleExecutable + WayBionicGroundStation + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.1 + CFBundleVersion + 1 + LSMinimumSystemVersion + 13.0 + NSHighResolutionCapable + + + diff --git a/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation new file mode 100755 index 00000000..8f14550a --- /dev/null +++ b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation @@ -0,0 +1,183 @@ +#!/bin/bash +# Double-click launcher for the WayBionic ground station on a Mac. +# +# It checks that the station is set up and that the carrier is plugged in, then starts the +# station for the real arm (scripts/macos.sh arm). Whatever it cannot fix itself becomes a +# dialog that says what to do. The station's output goes to ~/Library/Logs/WayBionic. See the +# operator guide, "Starting the station by double-click". +# +# Without a screen: WAYBIONIC_APP_DRY_RUN=1 prints the command instead of running it, and +# WAYBIONIC_APP_ANSWER is the answer every dialog gets. + +set -u + +TITLE="WayBionic Ground Station" +APP="$(cd "$(dirname "$0")/../.." && pwd)" +LOG_DIR="$HOME/Library/Logs/WayBionic" +KEEP_LOGS=10 + +# Finder starts apps with a bare PATH, without Homebrew or Miniforge. +export PATH="/opt/homebrew/bin:/opt/homebrew/Caskroom/miniforge/base/bin:/usr/local/bin:$PATH" + +# ask TEXT BUTTON...: show a dialog, print the button that was pressed (nothing if it was closed). +ask() { + if [[ -n "${WAYBIONIC_APP_ANSWER:-}" ]]; then + printf '%s\n' "$WAYBIONIC_APP_ANSWER" + return + fi + osascript - "$TITLE" "$@" <<'APPLESCRIPT' 2>/dev/null +on run argv + set theTitle to item 1 of argv + set theText to item 2 of argv + set theButtons to items 3 thru -1 of argv + try + set answer to display dialog theText with title theTitle buttons theButtons default button (last item of theButtons) with icon note + return button returned of answer + on error + return "" + end try +end run +APPLESCRIPT +} + +# pick TEXT ITEM...: show a list, print the item that was chosen (nothing if it was closed). +pick() { + if [[ -n "${WAYBIONIC_APP_ANSWER:-}" ]]; then + printf '%s\n' "$WAYBIONIC_APP_ANSWER" + return + fi + osascript - "$TITLE" "$@" <<'APPLESCRIPT' 2>/dev/null +on run argv + set theTitle to item 1 of argv + set theText to item 2 of argv + set theItems to items 3 thru -1 of argv + set chosen to choose from list theItems with title theTitle with prompt theText + if chosen is false then return "" + return item 1 of chosen +end run +APPLESCRIPT +} + +find_root() { + local saved="$APP/Contents/Resources/repo_root" + if [[ -r "$saved" ]]; then + tr -d '\n' <"$saved" + else + # Opened from packaging/macos inside the repository. + (cd "$APP/../../.." 2>/dev/null && pwd) + fi +} + +in_terminal() { + osascript -e 'on run argv + tell application "Terminal" + activate + do script (item 1 of argv) + end tell + end run' "$1" >/dev/null 2>&1 +} + +# descendants PID: print the process IDs below a process. +# shellcheck disable=SC2329 # called by stop_station, which is called from a trap +descendants() { + local child + for child in $(pgrep -P "$1" 2>/dev/null); do + echo "$child" + descendants "$child" + done +} + +# Ask the station to shut down as Ctrl+C in Terminal would: the drives are stopped first. +# shellcheck disable=SC2329 # called from a trap +stop_station() { + local pid sent="" + for pid in $(descendants "$child"); do + if ps -o command= -p "$pid" 2>/dev/null | grep -q 'ros2 launch'; then + kill -INT "$pid" 2>/dev/null + sent=1 + fi + done + [[ -n "$sent" ]] || kill -INT "$child" 2>/dev/null +} + +carrier_ports() { + compgen -G "${WAYBIONIC_APP_PORT_GLOB:-/dev/cu.usbmodem*}" || true +} + +ROOT="$(find_root)" +if [[ -z "$ROOT" || ! -x "$ROOT/scripts/macos.sh" ]]; then + ask "I can't find the WayBionic folder. Run ./scripts/macos.sh app from inside it to set this app up again." "Quit" >/dev/null + exit 1 +fi + +if [[ ! -f "$ROOT/install/setup.bash" ]]; then + answer="$(ask "WayBionic has not been set up on this Mac yet. Setting up downloads a few GB and takes 30 to 60 minutes. Terminal shows its progress; open this app again when it finishes." "Not now" "Set up")" + if [[ "$answer" == "Set up" ]]; then + if [[ -n "${WAYBIONIC_APP_DRY_RUN:-}" ]]; then + echo "would run in a Terminal: cd $ROOT && ./scripts/macos.sh setup" + else + in_terminal "cd $(printf '%q' "$ROOT") && ./scripts/macos.sh setup" + fi + fi + exit 0 +fi + +command=("$ROOT/scripts/macos.sh" arm) +while [[ -z "${WAYBIONIC_CARRIER:-}" ]]; do + ports=() + while IFS= read -r port; do + [[ -n "$port" ]] && ports+=("$port") + done < <(carrier_ports) + case "${#ports[@]}" in + 1) + export WAYBIONIC_CARRIER="${ports[0]}" + ;; + 0) + answer="$(ask "The carrier is not plugged in. Connect the Arduino's USB-C cable to this Mac, then choose Try again." "Quit" "Without the arm" "Try again")" + case "$answer" in + "Try again") ;; + "Without the arm") + command=("$ROOT/scripts/macos.sh" launch teleop:=true) + break + ;; + *) exit 0 ;; + esac + ;; + *) + choice="$(pick "Several USB serial devices are connected. Which one is the carrier?" "${ports[@]}")" + [[ -n "$choice" ]] || exit 0 + export WAYBIONIC_CARRIER="$choice" + ;; + esac +done + +if [[ -n "${WAYBIONIC_APP_DRY_RUN:-}" ]]; then + echo "would run in $ROOT: ${command[*]} (carrier: ${WAYBIONIC_CARRIER:-none})" + exit 0 +fi + +mkdir -p "$LOG_DIR" +log="$LOG_DIR/station-$(date +%Y-%m-%d-%H%M%S).log" +# shellcheck disable=SC2012 +for old in $(ls -1t "$LOG_DIR"/station-*.log 2>/dev/null | tail -n +"$((KEEP_LOGS + 1))"); do + rm -f "$old" +done + +cd "$ROOT" || exit 1 +"${command[@]}" exit_with_rviz:=true >"$log" 2>&1 & +child=$! +stopping="" +trap 'stopping=1; stop_station' TERM INT HUP +status=0 +while kill -0 "$child" 2>/dev/null; do + wait "$child" + status=$? +done +trap - TERM INT HUP + +# Closing the window or Ctrl+C ends with 0 or 130; anything else is worth a look. +if [[ -z "$stopping" ]] && ((status != 0 && status != 130)); then + answer="$(ask "The ground station stopped (code $status). The log says why." "Close" "Show the log")" + [[ "$answer" == "Show the log" ]] && open "$log" +fi +exit 0 diff --git a/scripts/macos.sh b/scripts/macos.sh index acf503c1..06035273 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -232,6 +232,7 @@ install_app() { rm -rf "$destination" cp -R "$source" "$destination" # The copy can live anywhere, so it is told where this folder is. + mkdir -p "$destination/Contents/Resources" printf '%s\n' "$ROOT" > "$destination/Contents/Resources/repo_root" echo "Installed $destination" echo "Double-click it, or drag it to the Dock." diff --git a/waybionic_bringup/test/test_macos_app.py b/waybionic_bringup/test/test_macos_app.py index b858e608..e52d0f7e 100644 --- a/waybionic_bringup/test/test_macos_app.py +++ b/waybionic_bringup/test/test_macos_app.py @@ -119,17 +119,22 @@ def test_run_from_inside_the_repository_it_finds_the_repository_without_help(tmp def test_the_app_command_installs_a_copy_that_knows_the_repository(tmp_path): - script = APP.parents[2] / 'scripts' / 'macos.sh' + # A fresh clone has no empty Resources folder, as git does not keep one. + repo = tmp_path / 'checkout' + (repo / 'scripts').mkdir(parents=True) + shutil.copy(APP.parents[2] / 'scripts' / 'macos.sh', repo / 'scripts' / 'macos.sh') + shutil.copytree(APP, repo / 'packaging' / 'macos' / APP.name, + ignore=shutil.ignore_patterns('Resources')) destination = tmp_path / 'Applications' for _ in range(2): result = subprocess.run( - ['bash', str(script), 'app', str(destination)], env={ + ['bash', str(repo / 'scripts' / 'macos.sh'), 'app', str(destination)], env={ 'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin'}, capture_output=True, text=True, timeout=30, check=False) assert result.returncode == 0, result.stderr installed = destination / APP.name assert (installed / 'Contents' / 'Resources' / 'repo_root').read_text( - encoding='utf-8') == f'{APP.parents[2]}\n' + encoding='utf-8') == f'{repo}\n' launcher = installed / 'Contents' / 'MacOS' / LAUNCHER.name assert os.access(launcher, os.X_OK) assert str(installed) in result.stdout From a725a529babd2963178993e8ff88384da04e4d4a Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:40:44 -0600 Subject: [PATCH 14/31] Add RViz panels for the start-up steps and for switching joints Arm setup lists what is left before the arm can be operated, from the latched /arm/setup topic that setup_guide publishes (carrier, drives, controller, zero, ready), and offers a Zero button when the guide asks for it: after the operator confirms the arm is in its zero pose it calls the drive node's zero service. It shrinks to one line once every step is done. Joint control shows a checkbox per joint from the latched /arm/joint_control topic and calls /arm//set_enabled when one is clicked. The checkbox only ever shows what the topic says; a refusal (teleop still enabled, joint commands arriving) is shown and the box left alone. A joint with no drive is shown but cannot be switched. Both panels only read a topic and call services, and never send motion. ROS callbacks write into a mailbox and a Qt timer drains it, so no service call blocks the UI and no widget is touched off the Qt thread. Three seconds without the publisher greys a panel out as waiting. The parsing of each topic is a Qt-free unit with gtests over fabricated messages: states, ordering, labels and hostile input. RViz puts a panel its saved window state does not know in the left dock, so ground_station_rviz stacks Setup, Joint control and Diagnostics in the right-hand dock before maximizing. The panels are in waybionic_unified.rviz. --- waybionic_bringup/rviz/waybionic_unified.rviz | 8 + waybionic_rviz_plugins/CMakeLists.txt | 35 ++ waybionic_rviz_plugins/README.md | 43 +- .../joint_control_model.hpp | 79 +++ .../joint_control_panel.hpp | 130 +++++ .../waybionic_rviz_plugins/setup_model.hpp | 77 +++ .../waybionic_rviz_plugins/setup_panel.hpp | 120 +++++ waybionic_rviz_plugins/package.xml | 1 + waybionic_rviz_plugins/plugin_description.xml | 20 + .../src/ground_station_rviz.cpp | 39 ++ .../src/joint_control_model.cpp | 310 ++++++++++++ .../src/joint_control_panel.cpp | 443 +++++++++++++++++ waybionic_rviz_plugins/src/setup_model.cpp | 221 +++++++++ waybionic_rviz_plugins/src/setup_panel.cpp | 403 +++++++++++++++ .../test/test_joint_control_model.cpp | 459 ++++++++++++++++++ .../test/test_setup_model.cpp | 254 ++++++++++ 16 files changed, 2638 insertions(+), 4 deletions(-) create mode 100644 waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp create mode 100644 waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp create mode 100644 waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp create mode 100644 waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp create mode 100644 waybionic_rviz_plugins/src/joint_control_model.cpp create mode 100644 waybionic_rviz_plugins/src/joint_control_panel.cpp create mode 100644 waybionic_rviz_plugins/src/setup_model.cpp create mode 100644 waybionic_rviz_plugins/src/setup_panel.cpp create mode 100644 waybionic_rviz_plugins/test/test_joint_control_model.cpp create mode 100644 waybionic_rviz_plugins/test/test_setup_model.cpp diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz index 5b59a973..4172a445 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -28,6 +28,10 @@ Panels: Name: Time SyncMode: 0 SyncSource: "" + - Class: waybionic_rviz_plugins/SetupPanel + Name: SetupPanel + - Class: waybionic_rviz_plugins/JointControlPanel + Name: JointControlPanel - Class: waybionic_rviz_plugins/DiagnosticsPanel Diagnostics Topic: /diagnostics Name: DiagnosticsPanel @@ -208,6 +212,10 @@ Visualization Manager: Window Geometry: DiagnosticsPanel: collapsed: false + JointControlPanel: + collapsed: false + SetupPanel: + collapsed: false Displays: collapsed: false Height: 800 diff --git a/waybionic_rviz_plugins/CMakeLists.txt b/waybionic_rviz_plugins/CMakeLists.txt index 50a6f8f1..9fb1c5ea 100644 --- a/waybionic_rviz_plugins/CMakeLists.txt +++ b/waybionic_rviz_plugins/CMakeLists.txt @@ -15,6 +15,7 @@ find_package(Qt5 REQUIRED COMPONENTS Widgets) find_package(rclcpp REQUIRED) find_package(rviz_common REQUIRED) find_package(rviz_default_plugins REQUIRED) +find_package(std_srvs REQUIRED) set(THIS_PACKAGE_INCLUDE_DEPENDS diagnostic_msgs @@ -22,17 +23,26 @@ set(THIS_PACKAGE_INCLUDE_DEPENDS rclcpp rviz_common rviz_default_plugins + std_srvs ) add_library(${PROJECT_NAME} SHARED include/waybionic_rviz_plugins/diagnostics_source.hpp include/waybionic_rviz_plugins/diagnostics_panel.hpp + include/waybionic_rviz_plugins/joint_control_model.hpp + include/waybionic_rviz_plugins/joint_control_panel.hpp include/waybionic_rviz_plugins/motion_test_panel.hpp include/waybionic_rviz_plugins/ros_diagnostics_source.hpp + include/waybionic_rviz_plugins/setup_model.hpp + include/waybionic_rviz_plugins/setup_panel.hpp src/diagnostics_panel.cpp + src/joint_control_model.cpp + src/joint_control_panel.cpp src/mock_diagnostics_source.cpp src/ros_diagnostics_source.cpp src/motion_test_panel.cpp + src/setup_model.cpp + src/setup_panel.cpp ) target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17) @@ -134,6 +144,31 @@ if(BUILD_TESTING) rclcpp ) endif() + + # The joint control model parses messages without Qt or RViz, so it is built on its own. + ament_add_gtest(test_joint_control_model + test/test_joint_control_model.cpp + src/joint_control_model.cpp + TIMEOUT 60 + ) + if(TARGET test_joint_control_model) + target_include_directories(test_joint_control_model PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + ament_target_dependencies(test_joint_control_model diagnostic_msgs) + endif() + + ament_add_gtest(test_setup_model + test/test_setup_model.cpp + src/setup_model.cpp + TIMEOUT 60 + ) + if(TARGET test_setup_model) + target_include_directories(test_setup_model PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + ament_target_dependencies(test_setup_model diagnostic_msgs) + endif() endif() ament_export_targets(export_${PROJECT_NAME} HAS_LIBRARY_TARGET) diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index ba759dab..aac97720 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -1,16 +1,16 @@ # WayBionic RViz2 Diagnostics Plugin -RViz2-native diagnostics and monitoring UI for WayBionic. This package is diagnostics-only: it provides the engineer monitoring panel, mock/live diagnostics switching, and a temporary `/diagnostics` publisher for local validation. +RViz2-native diagnostics and monitoring UI for WayBionic. This package provides the engineer monitoring panel, mock/live diagnostics switching, and a temporary `/diagnostics` publisher for local validation. Two small operator panels sit beside it, the arm setup guide and joint control (see [Operator panels](#operator-panels)); they only read topics and call services, and never send motion. It also provides `ground_station_rviz`, the ground station's RViz entry point. It uses RViz's normal application initialization and then maximizes the window with Qt, rather than entering RViz's panel-hiding fullscreen mode. It accepts the normal RViz and ROS arguments and does not send motor commands. -Monitoring-only scope: +Monitoring scope: - No motor commands from this package. -- No robot control or safety-critical logic. +- No robot control or safety-critical logic. The operator panels ask the drive node to hold or release a joint, or to zero, over services; the drive node decides and refuses while the arm is enabled. - No camera or doctor/surgeon UI in this PR (handled separately later). - Mock diagnostics for validation while backend `/diagnostics` is not ready. @@ -34,13 +34,38 @@ colcon test --packages-select waybionic_rviz_plugins colcon test-result --verbose ``` +## Operator panels + +Both panels are in the ground station's right-hand dock, above the diagnostics panel +(`ground_station_rviz` stacks them; a plain `rviz2` leaves them wherever the layout puts them). + +**Arm setup** (`waybionic_rviz_plugins/SetupPanel`) lists the start-up steps the `setup_guide` +node publishes on the latched `/arm/setup` topic (a DiagnosticArray of `setup.` rows: +carrier, drives, controller, zero, ready). Each row's message is what to do next and its values +are `title`, `state` (`ok`, `todo`, `blocked` or `working`), `action` (`zero` or empty) and +`current`. When the guide asks for a zero, the panel offers a Zero button; after the operator +confirms the arm is in its zero pose it calls the drive node's `/sim_arm_drives/zero` +(`std_srvs/Trigger`) and shows the answer. Once every step is done the panel shrinks to one line. + +**Joint control** (`waybionic_rviz_plugins/JointControlPanel`) shows a checkbox per joint, +J1 to J5 and the tool. It reads the latched `/arm/joint_control` topic (a DiagnosticArray with +one row per joint: `state` is `enabled`, `disabled` or `no_drive`, plus `drives` and `angle`) +and calls `/arm//set_enabled` (`std_srvs/SetBool`) when a box is clicked. A joint that +is off is held by the drive node, which refuses a change while the arm is enabled; the panel +shows that refusal and leaves the box as the topic says. A joint with no drive is shown but +cannot be switched. + +Both publishers repeat their message every 0.5 s, so three seconds of silence greys a panel out +as waiting. The parsing of each topic lives in a Qt-free unit (`joint_control_model.*`, +`setup_model.*`) with gtests that build fabricated messages. + ## Package Layout ```text waybionic_rviz_plugins/ CMakeLists.txt # Builds the shared RViz plugin library + tests package.xml # Generic deps only; no Annin/AR4 exec deps - plugin_description.xml # Registers DiagnosticsPanel + plugin_description.xml # Registers DiagnosticsPanel, SetupPanel, JointControlPanel, MotionTestPanel scripts/ temporary_diagnostics_publisher.py diagnostics_recorder.py @@ -48,12 +73,20 @@ waybionic_rviz_plugins/ diagnostics_contract.hpp # Normalized DiagnosticMessage model diagnostics_source.hpp # DiagnosticsSource interface diagnostics_panel.hpp # Engineer monitoring panel + joint_control_model.hpp # Qt-free parsing of /arm/joint_control + joint_control_panel.hpp # Joint on/off checkboxes mock_diagnostics_source.hpp ros_diagnostics_source.hpp + setup_model.hpp # Qt-free parsing of /arm/setup + setup_panel.hpp # Start-up steps and the Zero button src/ diagnostics_panel.cpp + joint_control_model.cpp + joint_control_panel.cpp mock_diagnostics_source.cpp ros_diagnostics_source.cpp + setup_model.cpp + setup_panel.cpp config/ engineer_monitoring_view.rviz # Generic engineer layout (default) launch/ @@ -61,7 +94,9 @@ waybionic_rviz_plugins/ temporary_diagnostics_publisher.launch.py test/ test_package_metadata.py + test_joint_control_model.cpp # /arm/joint_control parsing test_ros_diagnostics_source.cpp # Live/mock source handoff stress tests + test_setup_model.cpp # /arm/setup parsing docs/ DIAGNOSTICS_CONTRACT.md DIAGNOSTICS_SOURCE_LIFECYCLE.md diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp new file mode 100644 index 00000000..8015cfc1 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp @@ -0,0 +1,79 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ + +#include +#include +#include +#include + +#include + +namespace waybionic_rviz_plugins +{ + +/// Latched topic on which the drive node reports the enable state of every joint. +constexpr const char * kJointControlTopic = "/arm/joint_control"; + +/// The drive node republishes every 0.5 s and on every state change, so this long +/// without a message means the node is gone. +constexpr std::chrono::milliseconds kDriveNodeQuietAfter{3000}; + +enum class JointState +{ + Enabled, + Disabled, + NoDrive +}; + +struct JointRow +{ + std::string joint_name; + std::string label; + JointState state{JointState::NoDrive}; + std::vector drives; + double angle_rad{0.0}; + std::string message; + /// True when the drive node offers a set_enabled service for this joint. + bool serviceable{false}; + /// False when the status broke the contract; `problem` then says how. + bool valid{false}; + std::string problem; +}; + +struct JointControlSnapshot +{ + /// True only when the array is non-empty and every row is valid. + bool valid{false}; + /// Rows in display order: the known joints first, then any others as received. + std::vector rows; + /// Summary of the first problem; empty when the snapshot is valid. + std::string error; +}; + +/// Reads one /arm/joint_control message. Never throws: malformed statuses are +/// reported through `valid`, `problem` and `error` so the caller can keep showing +/// the last good snapshot. +JointControlSnapshot parseJointControl(const diagnostic_msgs::msg::DiagnosticArray & array); + +/// Names of the joints the drive node normally reports, in display order. +std::vector knownJointNames(); + +/// Short display label: joint_1..joint_5 are J1..J5 and tool_grip is Tool. +/// Other names are returned unchanged. +std::string jointLabel(const std::string & joint_name); + +/// Name of the SetBool service that enables or disables a joint. +std::string setEnabledServiceName(const std::string & joint_name); + +/// Word shown for a state: "enabled", "disabled" or "no drive". +const char * stateWord(JointState state); + +/// True when the drive node should be treated as gone: nothing has been received, +/// or the last message is at least kDriveNodeQuietAfter old. +bool driveNodeQuiet( + const std::optional & last_message, + std::chrono::steady_clock::time_point now); + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp new file mode 100644 index 00000000..88be5397 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp @@ -0,0 +1,130 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +class QCheckBox; +class QGridLayout; +class QLabel; +class QScrollArea; +class QTimer; +class QWidget; + +namespace waybionic_rviz_plugins +{ + +struct JointControlMailbox; + +/// Lets the operator hold or release arm joints. +/// +/// The drive node latches the state of every joint on /arm/joint_control and +/// offers a SetBool service per joint. The panel only ever calls those services; +/// it never publishes motion commands or any other topic. The published state is +/// the single source of truth: a checkbox changes only when the topic reports a +/// change, never because it was clicked. +/// +/// Threading: RViz spins its node from the Qt thread, but nothing here relies on +/// that. ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer +/// drains it, so all widget and bookkeeping state is touched by the Qt thread +/// alone and no service call ever blocks it. +class JointControlPanel : public rviz_common::Panel +{ + Q_OBJECT + +public: + explicit JointControlPanel(QWidget * parent = nullptr); + ~JointControlPanel() override; + + void onInitialize() override; + + /// Subscribes to the joint states and prepares the service clients on `node`. + /// onInitialize() calls this with RViz's node; it is public so the panel can + /// also be driven by another node. Calling it again replaces the connection. + void connectToNode(rclcpp::Node::SharedPtr node); + +private: + using SetBool = std_srvs::srv::SetBool; + using SetBoolClient = rclcpp::Client; + + struct RowWidgets + { + QCheckBox * checkbox{nullptr}; + QLabel * state{nullptr}; + QLabel * detail{nullptr}; + QString state_style; + }; + + struct PendingCall + { + std::uint64_t token{0}; + std::int64_t request_id{0}; + bool enable{false}; + std::chrono::steady_clock::time_point sent; + }; + + void buildUi(); + void rebuildRows(const std::vector & joint_names); + void clearRows(); + void disconnectFromNode(); + + void poll(); + void applyMailbox(); + void applySnapshot(JointControlSnapshot snapshot); + void expirePendingCalls(std::chrono::steady_clock::time_point now); + void requestToggle(const std::string & joint_name); + SetBoolClient::SharedPtr clientFor(const std::string & joint_name); + void forgetCall(const std::string & joint_name, const PendingCall & call); + void showStatus(const QString & text); + void render(); + + const JointRow * findRow(const std::string & joint_name) const; + + rclcpp::Node::SharedPtr node_; + rclcpp::Subscription::SharedPtr subscription_; + std::map clients_; + std::shared_ptr mailbox_; + + // The last valid message, kept only while the drive node keeps talking. + JointControlSnapshot snapshot_; + bool has_snapshot_{false}; + std::optional last_message_; + + std::map pending_; + std::uint64_t next_token_{0}; + + QString status_text_; + std::chrono::steady_clock::time_point status_expires_; + + std::vector row_names_; + std::vector row_widgets_; + QString connection_style_; + + QTimer * poll_timer_{nullptr}; + QLabel * connection_label_{nullptr}; + QLabel * status_label_{nullptr}; + QScrollArea * rows_scroll_{nullptr}; + QWidget * rows_widget_{nullptr}; + QGridLayout * rows_layout_{nullptr}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp new file mode 100644 index 00000000..133dc4e0 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp @@ -0,0 +1,77 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ + +#include +#include +#include +#include + +#include + +namespace waybionic_rviz_plugins +{ + +/// Latched topic on which setup_guide publishes the start-up steps. +constexpr const char * kSetupTopic = "/arm/setup"; + +/// The drive node's zero service (std_srvs/Trigger): the setup panel's Zero button calls it. +constexpr const char * kZeroServiceName = "/sim_arm_drives/zero"; + +/// setup_guide publishes every 0.5 s, so this long without a message means it is gone. +constexpr std::chrono::milliseconds kSetupGuideQuietAfter{3000}; + +enum class StepState +{ + Ok, + Todo, + Blocked, + Working +}; + +struct SetupStep +{ + /// "carrier", "drives", "controller", "zero" or "ready": the row name without "setup.". + std::string name; + std::string title; + StepState state{StepState::Todo}; + /// What the operator is to do, or what is going on. + std::string message; + /// "zero" when the panel is to offer the Zero button; empty otherwise. + std::string action; + /// True for the first step that is not done. + bool current{false}; + bool valid{false}; + std::string problem; +}; + +struct SetupSnapshot +{ + /// True only when the array is non-empty and every step is valid. + bool valid{false}; + /// Known steps in the order the operator does them, then any others as received. + std::vector steps; + /// Summary of the first problem; empty when the snapshot is valid. + std::string error; + + /// True when there is at least one step and every one is done. + bool ready() const; + /// The step marked current, or nullptr once everything is done. + const SetupStep * currentStep() const; +}; + +/// Reads one /arm/setup message. Never throws: malformed statuses are reported through +/// `valid`, `problem` and `error` so the caller can keep showing the last good snapshot. +SetupSnapshot parseSetup(const diagnostic_msgs::msg::DiagnosticArray & array); + +/// Word shown for a state: "done", "to do", "blocked" or "working". +const char * stepStateWord(StepState state); + +/// True when setup_guide should be treated as gone: nothing has been received, or the last +/// message is at least kSetupGuideQuietAfter old. +bool setupGuideQuiet( + const std::optional & last_message, + std::chrono::steady_clock::time_point now); + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp new file mode 100644 index 00000000..6c3ffb2d --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp @@ -0,0 +1,120 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "waybionic_rviz_plugins/setup_model.hpp" + +class QLabel; +class QGridLayout; +class QPushButton; +class QTimer; +class QWidget; + +namespace waybionic_rviz_plugins +{ + +struct SetupMailbox; + +/// Walks the operator through starting the arm: carrier, drives, controller, zero, ready. +/// +/// The setup_guide node turns the other nodes' diagnostics into those steps and latches them +/// on /arm/setup. The panel shows them, and offers one button, Zero, when the guide asks for +/// it: that calls the drive node's own zero service after the operator confirms the arm is in +/// its zero pose. It never publishes anything, and never moves the arm. +/// +/// Threading: ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer drains it, +/// so all widget and bookkeeping state is touched by the Qt thread alone and no service call +/// ever blocks it. +class SetupPanel : public rviz_common::Panel +{ + Q_OBJECT + +public: + explicit SetupPanel(QWidget * parent = nullptr); + ~SetupPanel() override; + + void onInitialize() override; + + /// Subscribes to the setup steps and prepares the zero client on `node`. onInitialize() + /// calls this with RViz's node. Calling it again replaces the connection. + void connectToNode(rclcpp::Node::SharedPtr node); + +private: + using Trigger = std_srvs::srv::Trigger; + using TriggerClient = rclcpp::Client; + + struct RowWidgets + { + QLabel * icon{nullptr}; + QLabel * title{nullptr}; + QLabel * message{nullptr}; + }; + + struct PendingZero + { + std::uint64_t token{0}; + std::int64_t request_id{0}; + std::chrono::steady_clock::time_point sent; + }; + + void buildUi(); + void rebuildRows(const std::vector & step_names); + void clearRows(); + void disconnectFromNode(); + + void poll(); + void applyMailbox(); + void applySnapshot(SetupSnapshot snapshot); + void expirePendingZero(std::chrono::steady_clock::time_point now); + void requestZero(); + void showStatus(const QString & text, bool success); + void render(); + + bool zeroOffered() const; + + rclcpp::Node::SharedPtr node_; + rclcpp::Subscription::SharedPtr subscription_; + TriggerClient::SharedPtr zero_client_; + std::shared_ptr mailbox_; + + // The last valid message, kept only while the guide keeps talking. + SetupSnapshot snapshot_; + bool has_snapshot_{false}; + std::optional last_message_; + + std::optional pending_zero_; + std::uint64_t next_token_{0}; + + QString status_text_; + bool status_success_{false}; + std::chrono::steady_clock::time_point status_expires_; + + std::vector row_names_; + std::vector row_widgets_; + + QTimer * poll_timer_{nullptr}; + QLabel * summary_label_{nullptr}; + QLabel * status_label_{nullptr}; + QPushButton * zero_button_{nullptr}; + QWidget * rows_widget_{nullptr}; + QGridLayout * rows_layout_{nullptr}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ diff --git a/waybionic_rviz_plugins/package.xml b/waybionic_rviz_plugins/package.xml index 63bbb2d2..84245655 100644 --- a/waybionic_rviz_plugins/package.xml +++ b/waybionic_rviz_plugins/package.xml @@ -14,6 +14,7 @@ rclcpp sensor_msgs std_msgs + std_srvs rviz_common rviz_default_plugins diff --git a/waybionic_rviz_plugins/plugin_description.xml b/waybionic_rviz_plugins/plugin_description.xml index d6dc67dd..728a1308 100644 --- a/waybionic_rviz_plugins/plugin_description.xml +++ b/waybionic_rviz_plugins/plugin_description.xml @@ -8,6 +8,26 @@ + + + Start-up steps for the arm: carrier, drives, controller, zero and ready, with a Zero + button that asks the drive node to zero. This panel sends no motion commands. + + + + + + Switch arm joints on or off. The drive node holds a joint that is off; this panel + sends no motion commands. + + + #include +#include +#include +#include +#include #include "rclcpp/rclcpp.hpp" #include "rviz_common/logging.hpp" @@ -13,6 +17,40 @@ #include "rviz_common/visualization_frame.hpp" #include "rviz_common/visualizer_app.hpp" +namespace +{ + +// The station's own panels, from the top of the right-hand dock down, with the share of its +// height each gets. RViz puts a panel its saved window state does not know in the left dock, so +// they are stacked here whatever the layout file says. Panels that are not loaded are skipped. +void stackRightDock(QMainWindow * frame) +{ + struct Entry + { + const char * name; + int weight; + }; + const Entry order[] = {{"SetupPanel", 2}, {"JointControlPanel", 2}, {"DiagnosticsPanel", 5}}; + QList docks; + QList weights; + for (const auto & entry : order) { + if (auto * dock = frame->findChild(QString::fromLatin1(entry.name))) { + docks.append(dock); + weights.append(entry.weight); + } + } + if (docks.isEmpty()) { + return; + } + frame->addDockWidget(Qt::RightDockWidgetArea, docks.first()); + for (int index = 1; index < docks.size(); ++index) { + frame->splitDockWidget(docks[index - 1], docks[index], Qt::Vertical); + } + frame->resizeDocks(docks, weights, Qt::Vertical); +} + +} // namespace + int main(int argc, char ** argv) { auto arguments = rclcpp::remove_ros_arguments(argc, argv); @@ -52,6 +90,7 @@ int main(int argc, char ** argv) } for (auto * widget : QApplication::topLevelWidgets()) { if (auto * frame = qobject_cast(widget)) { + stackRightDock(frame); frame->showMaximized(); return application.exec(); } diff --git a/waybionic_rviz_plugins/src/joint_control_model.cpp b/waybionic_rviz_plugins/src/joint_control_model.cpp new file mode 100644 index 00000000..6da6c1b6 --- /dev/null +++ b/waybionic_rviz_plugins/src/joint_control_model.cpp @@ -0,0 +1,310 @@ +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +struct KnownJoint +{ + const char * name; + const char * label; +}; + +constexpr KnownJoint kKnownJoints[] = { + {"joint_1", "J1"}, + {"joint_2", "J2"}, + {"joint_3", "J3"}, + {"joint_4", "J4"}, + {"joint_5", "J5"}, + {"tool_grip", "Tool"}, +}; + +std::size_t displayOrder(const std::string & joint_name) +{ + for (std::size_t index = 0; index < std::size(kKnownJoints); ++index) { + if (joint_name == kKnownJoints[index].name) { + return index; + } + } + return std::size(kKnownJoints); +} + +// The name becomes part of a service name, so it must be a valid ROS name token. +bool isValidJointName(const std::string & name) +{ + if (name.empty()) { + return false; + } + for (std::size_t index = 0; index < name.size(); ++index) { + const char character = name[index]; + const bool letter = + (character >= 'a' && character <= 'z') || + (character >= 'A' && character <= 'Z') || character == '_'; + const bool digit = character >= '0' && character <= '9'; + if (!letter && !(digit && index > 0)) { + return false; + } + } + return true; +} + +std::string trim(const std::string & text) +{ + const auto first = text.find_first_not_of(" \t"); + if (first == std::string::npos) { + return {}; + } + const auto last = text.find_last_not_of(" \t"); + return text.substr(first, last - first + 1); +} + +// Problem texts quote the offending message, which ends up in the status line, so +// keep them short and printable whatever the message contains. +std::string shorten(const std::string & text) +{ + constexpr std::size_t kMaxLength = 32; + std::string result = text.substr(0, kMaxLength); + for (auto & character : result) { + const auto byte = static_cast(character); + if (byte < 0x20 || byte >= 0x7f) { + character = '?'; + } + } + if (text.size() > kMaxLength) { + result += "..."; + } + return result; +} + +std::vector splitDrives(const std::string & text) +{ + std::vector drives; + std::size_t start = 0; + while (start <= text.size()) { + const auto end = text.find(',', start); + const auto drive = trim(text.substr(start, end == std::string::npos ? end : end - start)); + if (!drive.empty()) { + drives.push_back(drive); + } + if (end == std::string::npos) { + break; + } + start = end + 1; + } + return drives; +} + +bool parseState(const std::string & text, JointState * state) +{ + if (text == "enabled") { + *state = JointState::Enabled; + } else if (text == "disabled") { + *state = JointState::Disabled; + } else if (text == "no_drive") { + *state = JointState::NoDrive; + } else { + return false; + } + return true; +} + +// Plain decimal numbers only. Hex floats, "nan" and "inf" are rejected up front +// because stream parsing of them differs between standard libraries. +bool parseDecimal(const std::string & text, double * value) +{ + if (text.empty() || text.find_first_not_of("0123456789+-.eE") != std::string::npos) { + return false; + } + std::istringstream stream(text); + stream.imbue(std::locale::classic()); + double parsed = 0.0; + stream >> parsed; + if (stream.fail() || !stream.eof() || !std::isfinite(parsed)) { + return false; + } + *value = parsed; + return true; +} + +// Returns the value stored under `key`, or nullptr. `duplicate` is set when the +// key appears more than once, because the intended value is then ambiguous. +const std::string * findValue( + const diagnostic_msgs::msg::DiagnosticStatus & status, const char * key, bool * duplicate) +{ + const std::string * found = nullptr; + *duplicate = false; + for (const auto & item : status.values) { + if (item.key != key) { + continue; + } + if (found != nullptr) { + *duplicate = true; + } else { + found = &item.value; + } + } + return found; +} + +JointRow parseRow(const diagnostic_msgs::msg::DiagnosticStatus & status) +{ + JointRow row; + row.joint_name = status.name; + row.label = jointLabel(status.name); + row.message = status.message; + + // Only the first problem is kept; it is enough to find the fault. + const auto fail = [&row](const std::string & problem) { + if (row.problem.empty()) { + row.problem = problem; + } + }; + + if (status.name.empty()) { + fail("status without a joint name"); + } else if (!isValidJointName(status.name)) { + fail("invalid joint name '" + shorten(status.name) + "'"); + } + + bool duplicate = false; + const auto * state_text = findValue(status, "state", &duplicate); + if (duplicate) { + fail("duplicate 'state' value"); + } else if (state_text == nullptr) { + fail("missing 'state' value"); + } else if (!parseState(*state_text, &row.state)) { + fail("unknown state '" + shorten(*state_text) + "'"); + } + + const auto * angle_text = findValue(status, "angle", &duplicate); + if (duplicate) { + fail("duplicate 'angle' value"); + } else if (angle_text == nullptr) { + fail("missing 'angle' value"); + } else if (!parseDecimal(*angle_text, &row.angle_rad)) { + fail("angle '" + shorten(*angle_text) + "' is not a number"); + } + + // The drive names are informational, so a status without them is still usable. + const auto * drives_text = findValue(status, "drives", &duplicate); + if (drives_text != nullptr) { + row.drives = splitDrives(*drives_text); + } + + row.valid = row.problem.empty(); + row.serviceable = row.valid && row.state != JointState::NoDrive; + return row; +} + +std::string describeProblem(const JointRow & row, const std::size_t position) +{ + const auto subject = + row.joint_name.empty() ? "status " + std::to_string(position + 1) : shorten(row.joint_name); + return subject + ": " + row.problem; +} + +} // namespace + +JointControlSnapshot parseJointControl(const diagnostic_msgs::msg::DiagnosticArray & array) +{ + JointControlSnapshot snapshot; + snapshot.rows.reserve(array.status.size()); + for (const auto & status : array.status) { + snapshot.rows.push_back(parseRow(status)); + } + + std::set seen; + for (auto & row : snapshot.rows) { + if (!seen.insert(row.joint_name).second) { + row.valid = false; + row.serviceable = false; + if (row.problem.empty()) { + row.problem = "duplicate joint name"; + } + } + } + + if (snapshot.rows.empty()) { + snapshot.error = "no joint statuses"; + } else { + std::size_t problems = 0; + for (std::size_t position = 0; position < snapshot.rows.size(); ++position) { + const auto & row = snapshot.rows[position]; + if (row.valid) { + continue; + } + if (problems == 0) { + snapshot.error = describeProblem(row, position); + } + ++problems; + } + if (problems > 1) { + snapshot.error += " (and " + std::to_string(problems - 1) + " more)"; + } + } + snapshot.valid = snapshot.error.empty(); + + std::stable_sort( + snapshot.rows.begin(), snapshot.rows.end(), [](const JointRow & left, const JointRow & right) { + return displayOrder(left.joint_name) < displayOrder(right.joint_name); + }); + return snapshot; +} + +std::vector knownJointNames() +{ + std::vector names; + for (const auto & joint : kKnownJoints) { + names.emplace_back(joint.name); + } + return names; +} + +std::string jointLabel(const std::string & joint_name) +{ + for (const auto & joint : kKnownJoints) { + if (joint_name == joint.name) { + return joint.label; + } + } + return joint_name; +} + +std::string setEnabledServiceName(const std::string & joint_name) +{ + return "/arm/" + joint_name + "/set_enabled"; +} + +const char * stateWord(const JointState state) +{ + switch (state) { + case JointState::Enabled: + return "enabled"; + case JointState::Disabled: + return "disabled"; + case JointState::NoDrive: + return "no drive"; + } + return "unknown"; +} + +bool driveNodeQuiet( + const std::optional & last_message, + const std::chrono::steady_clock::time_point now) +{ + return !last_message.has_value() || now - *last_message >= kDriveNodeQuietAfter; +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/joint_control_panel.cpp b/waybionic_rviz_plugins/src/joint_control_panel.cpp new file mode 100644 index 00000000..abccb72b --- /dev/null +++ b/waybionic_rviz_plugins/src/joint_control_panel.cpp @@ -0,0 +1,443 @@ +#include "waybionic_rviz_plugins/joint_control_panel.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr int kPollIntervalMs = 100; +constexpr std::chrono::seconds kServiceTimeout{5}; +constexpr std::chrono::seconds kStatusLifetime{8}; + +constexpr const char * kPanelStyle = R"( +QWidget { + background-color: #071019; + color: #e8f1f8; + font-family: "Segoe UI", "Ubuntu", sans-serif; + font-size: 12px; +} +QLabel#PanelTitle { + font-size: 15px; + font-weight: 700; +} +QLabel#Muted { + color: #8ea3b1; +} +QLabel#Warning { + color: #ffb84d; + font-weight: 700; +} +QCheckBox { + font-weight: 700; + spacing: 8px; +} +QCheckBox:disabled { + color: #5d7282; +} +QScrollArea { + border: none; +} +)"; + +constexpr const char * kEnabledStyle = "color: #3ddc84; font-weight: 700;"; +constexpr const char * kDisabledStyle = "color: #ffb84d; font-weight: 700;"; +constexpr const char * kNoDriveStyle = "color: #8ea3b1;"; +constexpr const char * kWaitingStyle = "color: #5d7282;"; + +const char * styleFor(const JointState state) +{ + switch (state) { + case JointState::Enabled: + return kEnabledStyle; + case JointState::Disabled: + return kDisabledStyle; + case JointState::NoDrive: + return kNoDriveStyle; + } + return kWaitingStyle; +} + +} // namespace + +/// What the ROS threads hand to the Qt thread. Callbacks only ever write here. +struct JointControlMailbox +{ + struct Reply + { + std::string joint_name; + std::uint64_t token{0}; + bool success{false}; + std::string message; + }; + + std::mutex mutex; + std::optional snapshot; + std::optional received_at; + std::deque replies; +}; + +JointControlPanel::JointControlPanel(QWidget * parent) +: rviz_common::Panel(parent), mailbox_(std::make_shared()) +{ + buildUi(); + poll_timer_ = new QTimer(this); + connect(poll_timer_, &QTimer::timeout, this, [this]() {poll();}); + poll_timer_->start(kPollIntervalMs); + render(); +} + +JointControlPanel::~JointControlPanel() +{ + if (poll_timer_ != nullptr) { + poll_timer_->stop(); + } + disconnectFromNode(); +} + +void JointControlPanel::onInitialize() +{ + if (auto ros_node_abstraction = getDisplayContext()->getRosNodeAbstraction().lock()) { + connectToNode(ros_node_abstraction->get_raw_node()); + } +} + +void JointControlPanel::connectToNode(rclcpp::Node::SharedPtr node) +{ + disconnectFromNode(); + node_ = std::move(node); + if (!node_) { + return; + } + { + std::lock_guard lock(mailbox_->mutex); + mailbox_->snapshot.reset(); + mailbox_->received_at.reset(); + mailbox_->replies.clear(); + } + subscription_ = node_->create_subscription( + kJointControlTopic, rclcpp::QoS(1).reliable().transient_local(), + [mailbox = mailbox_](diagnostic_msgs::msg::DiagnosticArray::ConstSharedPtr message) { + auto snapshot = parseJointControl(*message); + std::lock_guard lock(mailbox->mutex); + mailbox->snapshot = std::move(snapshot); + mailbox->received_at = std::chrono::steady_clock::now(); + }); +} + +void JointControlPanel::disconnectFromNode() +{ + subscription_.reset(); + for (const auto & [joint_name, call] : pending_) { + const auto client = clients_.find(joint_name); + if (client != clients_.end()) { + client->second->remove_pending_request(call.request_id); + } + } + pending_.clear(); + clients_.clear(); + node_.reset(); + has_snapshot_ = false; + snapshot_ = JointControlSnapshot{}; + last_message_.reset(); +} + +void JointControlPanel::buildUi() +{ + setStyleSheet(kPanelStyle); + setMinimumWidth(320); + + auto * root_layout = new QVBoxLayout(this); + root_layout->setContentsMargins(10, 10, 10, 10); + root_layout->setSpacing(6); + + auto * title = new QLabel("Joint control"); + title->setObjectName("PanelTitle"); + root_layout->addWidget(title); + + auto * hint = new QLabel( + "A checked joint moves with the sticks. An unchecked joint is held where it is. " + "Switch joints with teleop stopped."); + hint->setObjectName("Muted"); + hint->setWordWrap(true); + root_layout->addWidget(hint); + + connection_label_ = new QLabel(); + connection_label_->setObjectName("Muted"); + connection_label_->setWordWrap(true); + root_layout->addWidget(connection_label_); + + rows_scroll_ = new QScrollArea(); + rows_scroll_->setWidgetResizable(true); + rows_scroll_->setMinimumHeight(200); + rows_widget_ = new QWidget(); + rows_layout_ = new QGridLayout(rows_widget_); + rows_layout_->setContentsMargins(0, 0, 0, 0); + rows_layout_->setHorizontalSpacing(12); + rows_layout_->setVerticalSpacing(6); + rows_layout_->setColumnStretch(2, 1); + rows_scroll_->setWidget(rows_widget_); + root_layout->addWidget(rows_scroll_, 1); + + status_label_ = new QLabel(); + status_label_->setObjectName("Warning"); + status_label_->setWordWrap(true); + root_layout->addWidget(status_label_); +} + +void JointControlPanel::clearRows() +{ + // A checkbox may be running its own click handler, so the widgets go when Qt is done. + for (auto & row : row_widgets_) { + for (QWidget * widget : {static_cast(row.checkbox), + static_cast(row.state), static_cast(row.detail)}) + { + rows_layout_->removeWidget(widget); + widget->hide(); + widget->deleteLater(); + } + } + row_widgets_.clear(); + row_names_.clear(); +} + +void JointControlPanel::rebuildRows(const std::vector & joint_names) +{ + clearRows(); + row_names_ = joint_names; + int line = 0; + for (const auto & joint_name : joint_names) { + RowWidgets row; + row.checkbox = new QCheckBox(QString::fromStdString(jointLabel(joint_name))); + row.state = new QLabel(); + row.detail = new QLabel(); + row.detail->setObjectName("Muted"); + row.detail->setWordWrap(true); + connect(row.checkbox, &QCheckBox::clicked, this, [this, joint_name](bool) { + // The checkbox follows the published state, not the click: the click only asks. + requestToggle(joint_name); + render(); + }); + rows_layout_->addWidget(row.checkbox, line, 0); + rows_layout_->addWidget(row.state, line, 1); + rows_layout_->addWidget(row.detail, line, 2); + row_widgets_.push_back(row); + ++line; + } + rows_layout_->setRowStretch(line, 1); +} + +const JointRow * JointControlPanel::findRow(const std::string & joint_name) const +{ + const auto found = std::find_if( + snapshot_.rows.begin(), snapshot_.rows.end(), + [&joint_name](const JointRow & row) {return row.joint_name == joint_name;}); + return found == snapshot_.rows.end() ? nullptr : &*found; +} + +void JointControlPanel::poll() +{ + applyMailbox(); + expirePendingCalls(std::chrono::steady_clock::now()); + render(); +} + +void JointControlPanel::applyMailbox() +{ + std::optional snapshot; + std::optional received_at; + std::deque replies; + { + std::lock_guard lock(mailbox_->mutex); + snapshot.swap(mailbox_->snapshot); + received_at = mailbox_->received_at; + replies.swap(mailbox_->replies); + } + if (received_at.has_value()) { + last_message_ = received_at; + } + if (snapshot.has_value()) { + applySnapshot(std::move(*snapshot)); + } + for (const auto & reply : replies) { + const auto call = pending_.find(reply.joint_name); + if (call == pending_.end() || call->second.token != reply.token) { + continue; // Answers a call that already timed out. + } + pending_.erase(call); + if (!reply.success) { + const auto * row = findRow(reply.joint_name); + const auto label = row != nullptr ? row->label : reply.joint_name; + showStatus(QString::fromStdString(label + ": " + reply.message)); + } + } +} + +void JointControlPanel::applySnapshot(JointControlSnapshot snapshot) +{ + if (!snapshot.valid) { + // Keep showing the last good report, and say that this one was ignored. + showStatus(QString::fromStdString("Ignoring a malformed joint report: " + snapshot.error)); + return; + } + snapshot_ = std::move(snapshot); + has_snapshot_ = true; +} + +void JointControlPanel::expirePendingCalls(const std::chrono::steady_clock::time_point now) +{ + std::vector expired; + for (const auto & [joint_name, call] : pending_) { + if (now - call.sent > kServiceTimeout) { + expired.push_back(joint_name); + } + } + for (const auto & joint_name : expired) { + const auto call = pending_.at(joint_name); + forgetCall(joint_name, call); + const auto * row = findRow(joint_name); + const auto label = row != nullptr ? row->label : joint_name; + showStatus(QString::fromStdString("No answer from the drive node for " + label)); + } +} + +void JointControlPanel::forgetCall(const std::string & joint_name, const PendingCall & call) +{ + const auto client = clients_.find(joint_name); + if (client != clients_.end()) { + client->second->remove_pending_request(call.request_id); + } + pending_.erase(joint_name); +} + +JointControlPanel::SetBoolClient::SharedPtr JointControlPanel::clientFor( + const std::string & joint_name) +{ + const auto found = clients_.find(joint_name); + if (found != clients_.end()) { + return found->second; + } + auto client = node_->create_client(setEnabledServiceName(joint_name)); + clients_[joint_name] = client; + return client; +} + +void JointControlPanel::requestToggle(const std::string & joint_name) +{ + if (!node_ || !has_snapshot_ || pending_.count(joint_name) > 0 || + driveNodeQuiet(last_message_, std::chrono::steady_clock::now())) + { + return; + } + const auto * row = findRow(joint_name); + if (row == nullptr || !row->serviceable) { + return; + } + const auto client = clientFor(joint_name); + if (!client->service_is_ready()) { + showStatus(QString::fromStdString(row->label + ": drive node not available")); + return; + } + auto request = std::make_shared(); + request->data = row->state != JointState::Enabled; + PendingCall call; + call.token = ++next_token_; + call.enable = request->data; + call.sent = std::chrono::steady_clock::now(); + const auto sent = client->async_send_request( + request, + [mailbox = mailbox_, joint_name, token = call.token](SetBoolClient::SharedFuture future) { + const auto response = future.get(); + std::lock_guard lock(mailbox->mutex); + mailbox->replies.push_back({joint_name, token, response->success, response->message}); + }); + call.request_id = sent.request_id; + pending_[joint_name] = call; +} + +void JointControlPanel::showStatus(const QString & text) +{ + status_text_ = text; + status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; +} + +void JointControlPanel::render() +{ + const auto now = std::chrono::steady_clock::now(); + const bool quiet = driveNodeQuiet(last_message_, now); + const bool shown = has_snapshot_ && !quiet; + + if (quiet) { + connection_label_->setText("Waiting for the drive node (sim_arm_drives)..."); + } else if (!has_snapshot_) { + connection_label_->setText("Waiting for a valid joint report..."); + } else { + connection_label_->setText("Drive node connected"); + } + + std::vector names = knownJointNames(); + if (has_snapshot_) { + names.clear(); + for (const auto & row : snapshot_.rows) { + names.push_back(row.joint_name); + } + } + if (names != row_names_) { + rebuildRows(names); + } + + for (std::size_t index = 0; index < row_names_.size(); ++index) { + auto & widgets = row_widgets_[index]; + const auto * row = shown ? findRow(row_names_[index]) : nullptr; + const QSignalBlocker blocker(widgets.checkbox); + if (row == nullptr) { + widgets.checkbox->setChecked(false); + widgets.checkbox->setEnabled(false); + widgets.state->setText(QString::fromUtf8("\xE2\x80\x94")); + widgets.state->setStyleSheet(kWaitingStyle); + widgets.detail->setText(QString()); + continue; + } + const auto call = pending_.find(row->joint_name); + const bool waiting = call != pending_.end(); + widgets.checkbox->setChecked(row->state == JointState::Enabled); + widgets.checkbox->setEnabled(row->serviceable && !waiting); + QString word = QString::fromUtf8(stateWord(row->state)); + if (waiting) { + word = call->second.enable ? "enabling..." : "disabling..."; + } + widgets.state->setText(word); + const QString style = QString::fromUtf8(styleFor(row->state)); + if (widgets.state_style != style) { + widgets.state->setStyleSheet(style); + widgets.state_style = style; + } + const auto detail = QString::fromStdString(row->message); + widgets.detail->setText(detail); + widgets.checkbox->setToolTip(detail); + } + + status_label_->setText(now < status_expires_ ? status_text_ : QString()); +} + +} // namespace waybionic_rviz_plugins + +PLUGINLIB_EXPORT_CLASS(waybionic_rviz_plugins::JointControlPanel, rviz_common::Panel) diff --git a/waybionic_rviz_plugins/src/setup_model.cpp b/waybionic_rviz_plugins/src/setup_model.cpp new file mode 100644 index 00000000..0efcc6c2 --- /dev/null +++ b/waybionic_rviz_plugins/src/setup_model.cpp @@ -0,0 +1,221 @@ +#include "waybionic_rviz_plugins/setup_model.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr const char * kPrefix = "setup."; +constexpr const char * kKnownSteps[] = {"carrier", "drives", "controller", "zero", "ready"}; + +std::size_t displayOrder(const std::string & name) +{ + for (std::size_t index = 0; index < std::size(kKnownSteps); ++index) { + if (name == kKnownSteps[index]) { + return index; + } + } + return std::size(kKnownSteps); +} + +// Problem texts quote the offending message, which ends up in the panel, so keep them short +// and printable whatever the message contains. +std::string shorten(const std::string & text) +{ + constexpr std::size_t kMaxLength = 32; + std::string result = text.substr(0, kMaxLength); + for (auto & character : result) { + const auto byte = static_cast(character); + if (byte < 0x20 || byte >= 0x7f) { + character = '?'; + } + } + if (text.size() > kMaxLength) { + result += "..."; + } + return result; +} + +// Returns the value stored under `key`, or nullptr. `duplicate` is set when the key appears +// more than once, because the intended value is then ambiguous. +const std::string * findValue( + const diagnostic_msgs::msg::DiagnosticStatus & status, const char * key, bool * duplicate) +{ + const std::string * found = nullptr; + *duplicate = false; + for (const auto & item : status.values) { + if (item.key != key) { + continue; + } + if (found != nullptr) { + *duplicate = true; + } else { + found = &item.value; + } + } + return found; +} + +bool parseState(const std::string & text, StepState * state) +{ + if (text == "ok") { + *state = StepState::Ok; + } else if (text == "todo") { + *state = StepState::Todo; + } else if (text == "blocked") { + *state = StepState::Blocked; + } else if (text == "working") { + *state = StepState::Working; + } else { + return false; + } + return true; +} + +SetupStep parseStep(const diagnostic_msgs::msg::DiagnosticStatus & status) +{ + SetupStep step; + step.message = status.message; + + // Only the first problem is kept; it is enough to find the fault. + const auto fail = [&step](const std::string & problem) { + if (step.problem.empty()) { + step.problem = problem; + } + }; + + const std::string prefix = kPrefix; + if (status.name.compare(0, prefix.size(), prefix) != 0 || status.name.size() == prefix.size()) { + fail("not a setup step"); + step.name = status.name; + } else { + step.name = status.name.substr(prefix.size()); + } + step.title = step.name; + + bool duplicate = false; + const auto * title = findValue(status, "title", &duplicate); + if (title != nullptr && !duplicate && !title->empty()) { + step.title = *title; + } + + const auto * state_text = findValue(status, "state", &duplicate); + if (duplicate) { + fail("duplicate 'state' value"); + } else if (state_text == nullptr) { + fail("missing 'state' value"); + } else if (!parseState(*state_text, &step.state)) { + fail("unknown state '" + shorten(*state_text) + "'"); + } + + // Only the zero action exists; an unknown one must not become a button that does something else. + const auto * action = findValue(status, "action", &duplicate); + if (duplicate) { + fail("duplicate 'action' value"); + } else if (action != nullptr && !action->empty()) { + if (*action == "zero") { + step.action = *action; + } else { + fail("unknown action '" + shorten(*action) + "' (only zero)"); + } + } + + const auto * current = findValue(status, "current", &duplicate); + step.current = !duplicate && current != nullptr && *current == "true"; + + step.valid = step.problem.empty(); + return step; +} + +} // namespace + +bool SetupSnapshot::ready() const +{ + return valid && !steps.empty() && + std::all_of(steps.begin(), steps.end(), [](const SetupStep & step) { + return step.state == StepState::Ok; + }); +} + +const SetupStep * SetupSnapshot::currentStep() const +{ + const auto found = std::find_if( + steps.begin(), steps.end(), [](const SetupStep & step) {return step.current;}); + return found == steps.end() ? nullptr : &*found; +} + +SetupSnapshot parseSetup(const diagnostic_msgs::msg::DiagnosticArray & array) +{ + SetupSnapshot snapshot; + snapshot.steps.reserve(array.status.size()); + for (const auto & status : array.status) { + snapshot.steps.push_back(parseStep(status)); + } + + std::set seen; + for (auto & step : snapshot.steps) { + if (!seen.insert(step.name).second) { + step.valid = false; + if (step.problem.empty()) { + step.problem = "duplicate step"; + } + } + } + + if (snapshot.steps.empty()) { + snapshot.error = "no setup steps"; + } else { + std::size_t problems = 0; + for (const auto & step : snapshot.steps) { + if (step.valid) { + continue; + } + if (problems == 0) { + snapshot.error = shorten(step.name) + ": " + step.problem; + } + ++problems; + } + if (problems > 1) { + snapshot.error += " (and " + std::to_string(problems - 1) + " more)"; + } + } + snapshot.valid = snapshot.error.empty(); + + std::stable_sort( + snapshot.steps.begin(), snapshot.steps.end(), [](const SetupStep & left, const SetupStep & right) { + return displayOrder(left.name) < displayOrder(right.name); + }); + return snapshot; +} + +const char * stepStateWord(const StepState state) +{ + switch (state) { + case StepState::Ok: + return "done"; + case StepState::Todo: + return "to do"; + case StepState::Blocked: + return "blocked"; + case StepState::Working: + return "working"; + } + return "unknown"; +} + +bool setupGuideQuiet( + const std::optional & last_message, + const std::chrono::steady_clock::time_point now) +{ + return !last_message.has_value() || now - *last_message >= kSetupGuideQuietAfter; +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/setup_panel.cpp b/waybionic_rviz_plugins/src/setup_panel.cpp new file mode 100644 index 00000000..fa103cbb --- /dev/null +++ b/waybionic_rviz_plugins/src/setup_panel.cpp @@ -0,0 +1,403 @@ +#include "waybionic_rviz_plugins/setup_panel.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr int kPollIntervalMs = 100; +// The drive node waits up to half a second for the drives' replies before it answers. +constexpr std::chrono::seconds kZeroTimeout{10}; +constexpr std::chrono::seconds kStatusLifetime{10}; + +constexpr const char * kPanelStyle = R"( +QWidget { + background-color: #071019; + color: #e8f1f8; + font-family: "Segoe UI", "Ubuntu", sans-serif; + font-size: 12px; +} +QLabel#PanelTitle { + font-size: 15px; + font-weight: 700; +} +QLabel#Muted { + color: #8ea3b1; +} +QLabel#Ready { + color: #3ddc84; + font-weight: 700; +} +QPushButton { + background-color: #101d2a; + border: 1px solid #43a6ff; + border-radius: 6px; + color: #e8f1f8; + font-weight: 700; + padding: 6px; +} +QPushButton:disabled { + border-color: #284052; + color: #5d7282; +} +)"; + +struct StepLook +{ + const char * icon; + const char * color; +}; + +StepLook lookFor(const StepState state) +{ + switch (state) { + case StepState::Ok: + return {"\xE2\x9C\x93", "#3ddc84"}; // check mark + case StepState::Working: + return {"\xE2\x80\xA6", "#43a6ff"}; // ellipsis + case StepState::Todo: + return {"\xE2\x97\x8F", "#ffb84d"}; // black circle + case StepState::Blocked: + return {"\xE2\x9C\x97", "#ff4d5e"}; // ballot x + } + return {"?", "#8ea3b1"}; +} + +} // namespace + +/// What the ROS threads hand to the Qt thread. Callbacks only ever write here. +struct SetupMailbox +{ + struct ZeroReply + { + std::uint64_t token{0}; + bool success{false}; + std::string message; + }; + + std::mutex mutex; + std::optional snapshot; + std::optional received_at; + std::optional zero_reply; +}; + +SetupPanel::SetupPanel(QWidget * parent) +: rviz_common::Panel(parent), mailbox_(std::make_shared()) +{ + buildUi(); + poll_timer_ = new QTimer(this); + connect(poll_timer_, &QTimer::timeout, this, [this]() {poll();}); + poll_timer_->start(kPollIntervalMs); + render(); +} + +SetupPanel::~SetupPanel() +{ + if (poll_timer_ != nullptr) { + poll_timer_->stop(); + } + disconnectFromNode(); +} + +void SetupPanel::onInitialize() +{ + if (auto ros_node_abstraction = getDisplayContext()->getRosNodeAbstraction().lock()) { + connectToNode(ros_node_abstraction->get_raw_node()); + } +} + +void SetupPanel::connectToNode(rclcpp::Node::SharedPtr node) +{ + disconnectFromNode(); + node_ = std::move(node); + if (!node_) { + return; + } + { + std::lock_guard lock(mailbox_->mutex); + mailbox_->snapshot.reset(); + mailbox_->received_at.reset(); + mailbox_->zero_reply.reset(); + } + subscription_ = node_->create_subscription( + kSetupTopic, rclcpp::QoS(1).reliable().transient_local(), + [mailbox = mailbox_](diagnostic_msgs::msg::DiagnosticArray::ConstSharedPtr message) { + auto snapshot = parseSetup(*message); + std::lock_guard lock(mailbox->mutex); + mailbox->snapshot = std::move(snapshot); + mailbox->received_at = std::chrono::steady_clock::now(); + }); + zero_client_ = node_->create_client(kZeroServiceName); +} + +void SetupPanel::disconnectFromNode() +{ + subscription_.reset(); + if (pending_zero_.has_value() && zero_client_) { + zero_client_->remove_pending_request(pending_zero_->request_id); + } + pending_zero_.reset(); + zero_client_.reset(); + node_.reset(); + has_snapshot_ = false; + snapshot_ = SetupSnapshot{}; + last_message_.reset(); +} + +void SetupPanel::buildUi() +{ + setStyleSheet(kPanelStyle); + setMinimumWidth(320); + + auto * root_layout = new QVBoxLayout(this); + root_layout->setContentsMargins(10, 10, 10, 10); + root_layout->setSpacing(6); + + auto * title = new QLabel("Arm setup"); + title->setObjectName("PanelTitle"); + root_layout->addWidget(title); + + summary_label_ = new QLabel(); + summary_label_->setObjectName("Muted"); + summary_label_->setWordWrap(true); + root_layout->addWidget(summary_label_); + + rows_widget_ = new QWidget(); + rows_layout_ = new QGridLayout(rows_widget_); + rows_layout_->setContentsMargins(0, 0, 0, 0); + rows_layout_->setHorizontalSpacing(8); + rows_layout_->setVerticalSpacing(6); + rows_layout_->setColumnStretch(2, 1); + root_layout->addWidget(rows_widget_); + + zero_button_ = new QPushButton("Zero the arm"); + zero_button_->setToolTip( + "Makes the arm's present position the zero of every drive. Only with the arm in its zero " + "pose and teleop stopped."); + connect(zero_button_, &QPushButton::clicked, this, [this]() {requestZero();}); + root_layout->addWidget(zero_button_); + + status_label_ = new QLabel(); + status_label_->setWordWrap(true); + root_layout->addWidget(status_label_); + root_layout->addStretch(1); +} + +void SetupPanel::clearRows() +{ + // The widgets go when Qt is done with any handler that is running. + for (auto & row : row_widgets_) { + for (QWidget * widget : {static_cast(row.icon), + static_cast(row.title), static_cast(row.message)}) + { + rows_layout_->removeWidget(widget); + widget->hide(); + widget->deleteLater(); + } + } + row_widgets_.clear(); + row_names_.clear(); +} + +void SetupPanel::rebuildRows(const std::vector & step_names) +{ + clearRows(); + row_names_ = step_names; + int line = 0; + for (std::size_t index = 0; index < step_names.size(); ++index) { + RowWidgets row; + row.icon = new QLabel(); + row.title = new QLabel(); + row.message = new QLabel(); + row.message->setWordWrap(true); + rows_layout_->addWidget(row.icon, line, 0, Qt::AlignTop); + rows_layout_->addWidget(row.title, line, 1, Qt::AlignTop); + rows_layout_->addWidget(row.message, line, 2); + row_widgets_.push_back(row); + ++line; + } +} + +void SetupPanel::poll() +{ + applyMailbox(); + expirePendingZero(std::chrono::steady_clock::now()); + render(); +} + +void SetupPanel::applyMailbox() +{ + std::optional snapshot; + std::optional received_at; + std::optional reply; + { + std::lock_guard lock(mailbox_->mutex); + snapshot.swap(mailbox_->snapshot); + received_at = mailbox_->received_at; + reply.swap(mailbox_->zero_reply); + } + if (received_at.has_value()) { + last_message_ = received_at; + } + if (snapshot.has_value()) { + applySnapshot(std::move(*snapshot)); + } + if (reply.has_value() && pending_zero_.has_value() && pending_zero_->token == reply->token) { + pending_zero_.reset(); + showStatus(QString::fromStdString(reply->message), reply->success); + } +} + +void SetupPanel::applySnapshot(SetupSnapshot snapshot) +{ + if (!snapshot.valid) { + // Keep showing the last good steps, and say that this message was ignored. + showStatus(QString::fromStdString("Ignoring a malformed setup report: " + snapshot.error), false); + return; + } + snapshot_ = std::move(snapshot); + has_snapshot_ = true; +} + +void SetupPanel::expirePendingZero(const std::chrono::steady_clock::time_point now) +{ + if (pending_zero_.has_value() && now - pending_zero_->sent > kZeroTimeout) { + if (zero_client_) { + zero_client_->remove_pending_request(pending_zero_->request_id); + } + pending_zero_.reset(); + showStatus("No answer from the drive node to the zero request", false); + } +} + +bool SetupPanel::zeroOffered() const +{ + return has_snapshot_ && std::any_of( + snapshot_.steps.begin(), snapshot_.steps.end(), [](const SetupStep & step) { + return step.action == "zero" && step.state != StepState::Ok; + }); +} + +void SetupPanel::requestZero() +{ + if (!node_ || !zero_client_ || pending_zero_.has_value() || !zeroOffered() || + setupGuideQuiet(last_message_, std::chrono::steady_clock::now())) + { + return; + } + const auto answer = QMessageBox::question( + this, "Zero the arm", + "Is the arm in its zero pose, upright as RViz shows it, with teleop stopped?\n\n" + "Zeroing makes the arm's present position the zero of every drive.", + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + if (answer != QMessageBox::Yes) { + return; + } + if (!zero_client_->service_is_ready()) { + showStatus("Drive node not available", false); + return; + } + PendingZero call; + call.token = ++next_token_; + call.sent = std::chrono::steady_clock::now(); + const auto sent = zero_client_->async_send_request( + std::make_shared(), + [mailbox = mailbox_, token = call.token](TriggerClient::SharedFuture future) { + const auto response = future.get(); + std::lock_guard lock(mailbox->mutex); + mailbox->zero_reply = SetupMailbox::ZeroReply{token, response->success, response->message}; + }); + call.request_id = sent.request_id; + pending_zero_ = call; + render(); +} + +void SetupPanel::showStatus(const QString & text, const bool success) +{ + status_text_ = text; + status_success_ = success; + status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; +} + +void SetupPanel::render() +{ + const auto now = std::chrono::steady_clock::now(); + const bool quiet = setupGuideQuiet(last_message_, now); + const bool shown = has_snapshot_ && !quiet; + const bool ready = shown && snapshot_.ready(); + + if (!shown) { + summary_label_->setObjectName("Muted"); + summary_label_->setText( + quiet ? "Waiting for the setup guide (setup_guide)..." : "Waiting for a valid setup report..."); + } else if (ready) { + summary_label_->setObjectName("Ready"); + summary_label_->setText(QString::fromUtf8("\xE2\x9C\x93 Ready: the arm can be operated")); + } else { + summary_label_->setObjectName("Muted"); + const auto * current = snapshot_.currentStep(); + summary_label_->setText( + current != nullptr ? QString::fromStdString("Next: " + current->title) : QString()); + } + // The object name picks the style, so it has to be applied again. + summary_label_->style()->unpolish(summary_label_); + summary_label_->style()->polish(summary_label_); + + std::vector names; + if (shown && !ready) { + for (const auto & step : snapshot_.steps) { + names.push_back(step.name); + } + } + if (names != row_names_) { + rebuildRows(names); + } + rows_widget_->setVisible(!names.empty()); + + for (std::size_t index = 0; index < row_names_.size(); ++index) { + const auto & step = snapshot_.steps[index]; + auto & widgets = row_widgets_[index]; + const auto look = lookFor(step.state); + widgets.icon->setText(QString::fromUtf8(look.icon)); + widgets.icon->setStyleSheet(QString("color: %1; font-weight: 700;").arg(look.color)); + widgets.title->setText(QString::fromStdString(step.title)); + widgets.title->setStyleSheet(step.current ? "font-weight: 700;" : "color: #8ea3b1;"); + widgets.message->setText(QString::fromStdString(step.message)); + widgets.message->setStyleSheet(step.current ? "" : "color: #8ea3b1;"); + } + + const bool offered = shown && zeroOffered(); + zero_button_->setVisible(offered); + zero_button_->setEnabled(offered && !pending_zero_.has_value()); + zero_button_->setText(pending_zero_.has_value() ? "Zeroing..." : "Zero the arm"); + + if (now < status_expires_) { + status_label_->setStyleSheet( + status_success_ ? "color: #3ddc84; font-weight: 700;" : "color: #ffb84d; font-weight: 700;"); + status_label_->setText(status_text_); + } else { + status_label_->setText(QString()); + } +} + +} // namespace waybionic_rviz_plugins + +PLUGINLIB_EXPORT_CLASS(waybionic_rviz_plugins::SetupPanel, rviz_common::Panel) diff --git a/waybionic_rviz_plugins/test/test_joint_control_model.cpp b/waybionic_rviz_plugins/test/test_joint_control_model.cpp new file mode 100644 index 00000000..0b98f8ed --- /dev/null +++ b/waybionic_rviz_plugins/test/test_joint_control_model.cpp @@ -0,0 +1,459 @@ +// Tests for the Qt-free parsing of /arm/joint_control. They build fabricated +// DiagnosticArray messages, so no drive node or ROS graph is needed. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +using diagnostic_msgs::msg::DiagnosticArray; +using diagnostic_msgs::msg::DiagnosticStatus; +using diagnostic_msgs::msg::KeyValue; +using namespace std::chrono_literals; + +KeyValue keyValue(const std::string & key, const std::string & value) +{ + KeyValue item; + item.key = key; + item.value = value; + return item; +} + +DiagnosticStatus makeStatus( + const std::string & name, const std::string & state, const std::string & angle = "0.0", + const std::string & drives = "", const std::string & message = "") +{ + DiagnosticStatus status; + status.name = name; + status.message = message; + status.values.push_back(keyValue("state", state)); + status.values.push_back(keyValue("drives", drives)); + status.values.push_back(keyValue("angle", angle)); + return status; +} + +DiagnosticArray makeArray(const std::vector & statuses) +{ + DiagnosticArray array; + array.status = statuses; + return array; +} + +// The array the drive node publishes for an arm with J2 and the tool unfitted. +DiagnosticArray healthyArray() +{ + return makeArray( + { + makeStatus("joint_1", "enabled", "0.1", "base_yaw", "enabled"), + makeStatus("joint_2", "no_drive", "0.0", "", "no drive fitted: locked at 0.0 deg"), + makeStatus("joint_3", "disabled", "0.2146755", "elbow", "disabled: held at +12.3 deg"), + makeStatus("joint_4", "enabled", "-0.3490658503988659", "wrist_left, wrist_right", "enabled"), + makeStatus("joint_5", "enabled", "0.0", "wrist_left,wrist_right", "enabled"), + makeStatus("tool_grip", "no_drive", "0.0", "", "no drive fitted: locked at 0.0 deg"), + }); +} + +std::vector names(const JointControlSnapshot & snapshot) +{ + std::vector result; + for (const auto & row : snapshot.rows) { + result.push_back(row.joint_name); + } + return result; +} + +const JointRow & rowFor(const JointControlSnapshot & snapshot, const std::string & name) +{ + for (const auto & row : snapshot.rows) { + if (row.joint_name == name) { + return row; + } + } + ADD_FAILURE() << "no row for " << name; + static const JointRow missing; + return missing; +} + +TEST(JointControlModel, ParsesAllThreeStates) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_TRUE(snapshot.error.empty()); + ASSERT_EQ(snapshot.rows.size(), 6u); + + const auto & enabled = rowFor(snapshot, "joint_1"); + EXPECT_EQ(enabled.state, JointState::Enabled); + EXPECT_TRUE(enabled.valid); + EXPECT_EQ(enabled.message, "enabled"); + EXPECT_DOUBLE_EQ(enabled.angle_rad, 0.1); + + const auto & disabled = rowFor(snapshot, "joint_3"); + EXPECT_EQ(disabled.state, JointState::Disabled); + EXPECT_EQ(disabled.message, "disabled: held at +12.3 deg"); + EXPECT_DOUBLE_EQ(disabled.angle_rad, 0.2146755); + + const auto & no_drive = rowFor(snapshot, "joint_2"); + EXPECT_EQ(no_drive.state, JointState::NoDrive); + EXPECT_EQ(no_drive.message, "no drive fitted: locked at 0.0 deg"); + EXPECT_DOUBLE_EQ(no_drive.angle_rad, 0.0); +} + +TEST(JointControlModel, ReadsNegativeAnglesWithFullPrecision) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_DOUBLE_EQ(rowFor(snapshot, "joint_4").angle_rad, -0.3490658503988659); +} + +TEST(JointControlModel, SplitsAndTrimsDriveNames) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_1").drives, std::vector{"base_yaw"}); + EXPECT_EQ( + rowFor(snapshot, "joint_4").drives, (std::vector{"wrist_left", "wrist_right"})); + EXPECT_EQ( + rowFor(snapshot, "joint_5").drives, (std::vector{"wrist_left", "wrist_right"})); + EXPECT_TRUE(rowFor(snapshot, "joint_2").drives.empty()); +} + +TEST(JointControlModel, DropsEmptyDriveNames) +{ + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled", "0.0", " ,base_yaw,, ")})); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(snapshot.rows.front().drives, std::vector{"base_yaw"}); +} + +TEST(JointControlModel, ToleratesAMissingDrivesEntry) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.erase(status.values.begin() + 1); // "drives" + const auto snapshot = parseJointControl(makeArray({status})); + + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_TRUE(snapshot.rows.front().drives.empty()); +} + +TEST(JointControlModel, KeepsTheKnownJointOrderWhateverTheArrivalOrder) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("tool_grip", "no_drive"), + makeStatus("joint_5", "enabled"), + makeStatus("joint_3", "enabled"), + makeStatus("joint_1", "enabled"), + makeStatus("joint_4", "enabled"), + makeStatus("joint_2", "no_drive"), + })); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ( + names(snapshot), + (std::vector{"joint_1", "joint_2", "joint_3", "joint_4", "joint_5", "tool_grip"})); +} + +TEST(JointControlModel, PutsUnknownJointsLastInArrivalOrder) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("wrist_roll", "enabled"), + makeStatus("tool_grip", "no_drive"), + makeStatus("joint_6", "disabled"), + makeStatus("joint_1", "enabled"), + })); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ( + names(snapshot), + (std::vector{"joint_1", "tool_grip", "wrist_roll", "joint_6"})); +} + +TEST(JointControlModel, LabelsKnownJointsAndKeepsRawNamesOtherwise) +{ + EXPECT_EQ(jointLabel("joint_1"), "J1"); + EXPECT_EQ(jointLabel("joint_2"), "J2"); + EXPECT_EQ(jointLabel("joint_3"), "J3"); + EXPECT_EQ(jointLabel("joint_4"), "J4"); + EXPECT_EQ(jointLabel("joint_5"), "J5"); + EXPECT_EQ(jointLabel("tool_grip"), "Tool"); + EXPECT_EQ(jointLabel("joint_6"), "joint_6"); + EXPECT_EQ(jointLabel("wrist_roll"), "wrist_roll"); + + const auto snapshot = parseJointControl( + makeArray({makeStatus("joint_3", "enabled"), makeStatus("wrist_roll", "enabled")})); + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_3").label, "J3"); + EXPECT_EQ(rowFor(snapshot, "wrist_roll").label, "wrist_roll"); +} + +TEST(JointControlModel, ListsTheKnownJointsInDisplayOrder) +{ + EXPECT_EQ( + knownJointNames(), + (std::vector{"joint_1", "joint_2", "joint_3", "joint_4", "joint_5", "tool_grip"})); +} + +TEST(JointControlModel, OnlyEnabledAndDisabledJointsAreServiceable) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_TRUE(rowFor(snapshot, "joint_1").serviceable); + EXPECT_FALSE(rowFor(snapshot, "joint_2").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_3").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_4").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_5").serviceable); + EXPECT_FALSE(rowFor(snapshot, "tool_grip").serviceable); +} + +TEST(JointControlModel, IgnoresTheDiagnosticLevel) +{ + auto status = makeStatus("joint_1", "enabled"); + status.level = DiagnosticStatus::ERROR; + auto locked = makeStatus("joint_2", "disabled"); + locked.level = DiagnosticStatus::OK; + const auto snapshot = parseJointControl(makeArray({status, locked})); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_1").state, JointState::Enabled); + EXPECT_EQ(rowFor(snapshot, "joint_2").state, JointState::Disabled); +} + +TEST(JointControlModel, IgnoresEntriesItDoesNotKnow) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.push_back(keyValue("firmware", "1.2")); + const auto snapshot = parseJointControl(makeArray({status})); + + EXPECT_TRUE(snapshot.valid) << snapshot.error; +} + +TEST(JointControlModel, MissingStateInvalidatesTheArray) +{ + auto broken = makeStatus("joint_3", "enabled"); + broken.values.erase(broken.values.begin()); // "state" + const auto snapshot = parseJointControl(makeArray({makeStatus("joint_1", "enabled"), broken})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_3"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("state"), std::string::npos) << snapshot.error; + EXPECT_TRUE(rowFor(snapshot, "joint_1").valid); + const auto & row = rowFor(snapshot, "joint_3"); + EXPECT_FALSE(row.valid); + EXPECT_FALSE(row.serviceable); + EXPECT_FALSE(row.problem.empty()); +} + +TEST(JointControlModel, UnknownStateInvalidatesTheArray) +{ + for (const std::string bad : {"faulted", "Enabled", "ENABLED", "no drive", "", " enabled"}) { + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled"), makeStatus("joint_2", bad)})); + + EXPECT_FALSE(snapshot.valid) << "state '" << bad << "' was accepted"; + EXPECT_FALSE(rowFor(snapshot, "joint_2").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_2").serviceable); + EXPECT_NE(snapshot.error.find("joint_2"), std::string::npos) << snapshot.error; + } +} + +TEST(JointControlModel, DuplicateJointNamesInvalidateTheArray) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("joint_1", "enabled"), + makeStatus("joint_3", "enabled"), + makeStatus("joint_3", "disabled"), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_3"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("duplicate"), std::string::npos) << snapshot.error; + ASSERT_EQ(snapshot.rows.size(), 3u); + EXPECT_TRUE(snapshot.rows[0].valid); + EXPECT_TRUE(snapshot.rows[1].valid); + EXPECT_FALSE(snapshot.rows[2].valid); +} + +TEST(JointControlModel, NonNumericAngleInvalidatesTheRow) +{ + const std::vector bad_angles = { + "", "abc", "nan", "inf", "-inf", "1.5x", "0x10", " 1.0", "1.0 ", "1,5", "1e999", "--1", "1.2.3", + "e5", "+", "."}; + for (const auto & bad : bad_angles) { + const auto snapshot = parseJointControl( + makeArray({makeStatus("joint_1", "enabled"), makeStatus("joint_4", "enabled", bad)})); + + EXPECT_FALSE(snapshot.valid) << "angle '" << bad << "' was accepted"; + EXPECT_TRUE(rowFor(snapshot, "joint_1").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_4").valid); + EXPECT_NE(snapshot.error.find("joint_4"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("angle"), std::string::npos) << snapshot.error; + } +} + +TEST(JointControlModel, AcceptsPlainDecimalAngles) +{ + const std::vector> good_angles = { + {"0.0", 0.0}, {"-0.3490658503988659", -0.3490658503988659}, {"1.5707963267948966", + 1.5707963267948966}, {"+0.5", 0.5}, {"-3", -3.0}, {"2.", 2.0}, {".25", 0.25}, {"1e-3", 0.001}, + {"-1.5E2", -150.0}}; + for (const auto & [text, expected] : good_angles) { + const auto snapshot = parseJointControl(makeArray({makeStatus("joint_1", "enabled", text)})); + + ASSERT_TRUE(snapshot.valid) << "angle '" << text << "' was rejected: " << snapshot.error; + EXPECT_DOUBLE_EQ(snapshot.rows.front().angle_rad, expected); + } +} + +TEST(JointControlModel, MissingAngleInvalidatesTheRow) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.pop_back(); // "angle" + const auto snapshot = parseJointControl(makeArray({status})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("angle"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, RepeatedStateOrAngleEntriesAreAmbiguous) +{ + auto twice_state = makeStatus("joint_1", "enabled"); + twice_state.values.push_back(keyValue("state", "disabled")); + auto twice_angle = makeStatus("joint_2", "enabled"); + twice_angle.values.push_back(keyValue("angle", "1.0")); + const auto snapshot = parseJointControl(makeArray({twice_state, twice_angle})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_FALSE(rowFor(snapshot, "joint_1").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_2").valid); +} + +TEST(JointControlModel, JointNamesMustBeUsableInAServiceName) +{ + for (const std::string bad : {"", "arm/joint_1", "/joint_1", "1joint", "joint 1", "joint-1"}) { + const auto snapshot = parseJointControl(makeArray({makeStatus(bad, "enabled")})); + + EXPECT_FALSE(snapshot.valid) << "name '" << bad << "' was accepted"; + EXPECT_FALSE(snapshot.rows.front().serviceable); + } +} + +TEST(JointControlModel, AnEmptyArrayIsInvalid) +{ + const auto snapshot = parseJointControl(DiagnosticArray()); + + EXPECT_FALSE(snapshot.valid); + EXPECT_TRUE(snapshot.rows.empty()); + EXPECT_FALSE(snapshot.error.empty()); +} + +TEST(JointControlModel, ReportsTheFirstProblemAndCountsTheRest) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("joint_1", "enabled"), + makeStatus("joint_2", "bogus"), + makeStatus("joint_3", "enabled", "x"), + makeStatus("joint_4", "enabled", "y"), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_2"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("2 more"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, NamesAnonymousStatusesByPosition) +{ + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled"), makeStatus("", "enabled")})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("status 2"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, SurvivesHostileStrings) +{ + const std::string long_text(100000, 'x'); + const std::string with_nul("1.0\0junk", 8); + auto hostile = makeStatus(long_text, long_text, long_text, long_text, long_text); + hostile.values.push_back(keyValue(long_text, long_text)); + hostile.values.push_back(keyValue("", "")); + const auto snapshot = parseJointControl( + makeArray( + { + hostile, + makeStatus(std::string("joint_1\0x", 9), "enabled", with_nul), + makeStatus("joint_2", with_nul), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.rows.size(), 3u); + for (const auto & row : snapshot.rows) { + EXPECT_FALSE(row.valid); + EXPECT_FALSE(row.serviceable); + } +} + +TEST(JointControlModel, ServiceNamesFollowTheContract) +{ + EXPECT_EQ(setEnabledServiceName("joint_3"), "/arm/joint_3/set_enabled"); + EXPECT_EQ(setEnabledServiceName("tool_grip"), "/arm/tool_grip/set_enabled"); + EXPECT_STREQ(kJointControlTopic, "/arm/joint_control"); +} + +TEST(JointControlModel, StateWordsAreForTheOperator) +{ + EXPECT_STREQ(stateWord(JointState::Enabled), "enabled"); + EXPECT_STREQ(stateWord(JointState::Disabled), "disabled"); + EXPECT_STREQ(stateWord(JointState::NoDrive), "no drive"); +} + +TEST(JointControlModel, DriveNodeIsQuietWithoutAnyMessage) +{ + EXPECT_TRUE(driveNodeQuiet(std::nullopt, std::chrono::steady_clock::now())); +} + +TEST(JointControlModel, DriveNodeIsQuietFromThreeSecondsWithoutAMessage) +{ + const auto last = std::chrono::steady_clock::now(); + + EXPECT_FALSE(driveNodeQuiet(last, last)); + EXPECT_FALSE(driveNodeQuiet(last, last + 500ms)); + EXPECT_FALSE(driveNodeQuiet(last, last + 2999ms)); + EXPECT_TRUE(driveNodeQuiet(last, last + 3000ms)); + EXPECT_TRUE(driveNodeQuiet(last, last + 10s)); +} + +TEST(JointControlModel, AMessageFromTheFutureIsNotQuiet) +{ + const auto now = std::chrono::steady_clock::now(); + + EXPECT_FALSE(driveNodeQuiet(now + 1s, now)); +} + +} // namespace +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/test/test_setup_model.cpp b/waybionic_rviz_plugins/test/test_setup_model.cpp new file mode 100644 index 00000000..d8436292 --- /dev/null +++ b/waybionic_rviz_plugins/test/test_setup_model.cpp @@ -0,0 +1,254 @@ +// Tests for the Qt-free parsing of /arm/setup. They build fabricated DiagnosticArray +// messages, so no setup_guide node or ROS graph is needed. + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/setup_model.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +using diagnostic_msgs::msg::DiagnosticArray; +using diagnostic_msgs::msg::DiagnosticStatus; +using diagnostic_msgs::msg::KeyValue; +using namespace std::chrono_literals; + +KeyValue keyValue(const std::string & key, const std::string & value) +{ + KeyValue item; + item.key = key; + item.value = value; + return item; +} + +DiagnosticStatus makeStep( + const std::string & name, const std::string & title, const std::string & state, + const std::string & message, const std::string & action = "", + const std::string & current = "false") +{ + DiagnosticStatus status; + status.name = name; + status.message = message; + status.values.push_back(keyValue("title", title)); + status.values.push_back(keyValue("state", state)); + status.values.push_back(keyValue("action", action)); + status.values.push_back(keyValue("current", current)); + return status; +} + +DiagnosticArray makeArray(const std::vector & statuses) +{ + DiagnosticArray array; + array.status = statuses; + return array; +} + +// What setup_guide publishes while the arm waits to be zeroed. +DiagnosticArray zeroingArray() +{ + return makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", "Carrier connected"), + makeStep("setup.drives", "Drives", "ok", "4 drives answer"), + makeStep("setup.controller", "Controller", "ok", "Controller connected"), + makeStep( + "setup.zero", "Zero", "todo", + "Put the arm in its zero pose (upright, as RViz shows it), then press Zero", "zero", + "true"), + makeStep("setup.ready", "Ready", "todo", "Waits for the steps above"), + }); +} + +DiagnosticArray readyArray() +{ + return makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", "Carrier connected"), + makeStep("setup.drives", "Drives", "ok", "4 drives answer"), + makeStep("setup.controller", "Controller", "ok", "Controller connected"), + makeStep("setup.zero", "Zero", "ok", "Zeroed"), + makeStep("setup.ready", "Ready", "ok", "Teleop is on"), + }); +} + +} // namespace + +TEST(SetupModel, ParsesTheFiveStepsInOrder) +{ + const auto snapshot = parseSetup(zeroingArray()); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + ASSERT_EQ(5u, snapshot.steps.size()); + EXPECT_EQ("carrier", snapshot.steps[0].name); + EXPECT_EQ("Carrier", snapshot.steps[0].title); + EXPECT_EQ(StepState::Ok, snapshot.steps[0].state); + EXPECT_EQ("zero", snapshot.steps[3].name); + EXPECT_EQ(StepState::Todo, snapshot.steps[3].state); + EXPECT_EQ("zero", snapshot.steps[3].action); + EXPECT_TRUE(snapshot.steps[3].current); + EXPECT_FALSE(snapshot.steps[4].current); + EXPECT_EQ("Waits for the steps above", snapshot.steps[4].message); +} + +TEST(SetupModel, ReadsEveryState) +{ + const auto snapshot = parseSetup( + makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", ""), + makeStep("setup.drives", "Drives", "todo", ""), + makeStep("setup.controller", "Controller", "blocked", ""), + makeStep("setup.zero", "Zero", "working", ""), + })); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ(StepState::Ok, snapshot.steps[0].state); + EXPECT_EQ(StepState::Todo, snapshot.steps[1].state); + EXPECT_EQ(StepState::Blocked, snapshot.steps[2].state); + EXPECT_EQ(StepState::Working, snapshot.steps[3].state); +} + +TEST(SetupModel, KnowsWhenEverythingIsReady) +{ + EXPECT_FALSE(parseSetup(zeroingArray()).ready()); + EXPECT_TRUE(parseSetup(readyArray()).ready()); + EXPECT_FALSE(parseSetup(DiagnosticArray()).ready()); +} + +TEST(SetupModel, FindsTheCurrentStep) +{ + const auto snapshot = parseSetup(zeroingArray()); + ASSERT_NE(nullptr, snapshot.currentStep()); + EXPECT_EQ("zero", snapshot.currentStep()->name); + EXPECT_EQ(nullptr, parseSetup(readyArray()).currentStep()); +} + +TEST(SetupModel, OnlyTheZeroActionIsKnown) +{ + auto array = zeroingArray(); + array.status[3].values[2].value = "reboot"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("action")); + EXPECT_NE(std::string::npos, snapshot.error.find("zero")); +} + +TEST(SetupModel, AMissingActionMeansNone) +{ + auto array = zeroingArray(); + array.status[3].values.erase(array.status[3].values.begin() + 2); + const auto snapshot = parseSetup(array); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ("", snapshot.steps[3].action); +} + +TEST(SetupModel, AMissingTitleFallsBackToTheStepName) +{ + auto array = zeroingArray(); + array.status[1].values.erase(array.status[1].values.begin()); + const auto snapshot = parseSetup(array); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ("drives", snapshot.steps[1].title); +} + +TEST(SetupModel, UnknownOrMissingStatesInvalidateTheSnapshot) +{ + auto array = zeroingArray(); + array.status[0].values[1].value = "fine"; + auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("carrier")); + EXPECT_NE(std::string::npos, snapshot.error.find("fine")); + + array = zeroingArray(); + array.status[0].values.erase(array.status[0].values.begin() + 1); + snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("state")); +} + +TEST(SetupModel, StepsMustBeNamedSetupSomething) +{ + auto array = zeroingArray(); + array.status[2].name = "controller"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("controller")); +} + +TEST(SetupModel, DuplicateStepsInvalidateTheSnapshot) +{ + auto array = zeroingArray(); + array.status[1].name = "setup.carrier"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("duplicate")); +} + +TEST(SetupModel, AnEmptyArrayIsInvalid) +{ + const auto snapshot = parseSetup(DiagnosticArray()); + EXPECT_FALSE(snapshot.valid); + EXPECT_FALSE(snapshot.error.empty()); +} + +TEST(SetupModel, KeepsKnownStepsInOrderAndUnknownOnesLast) +{ + const auto snapshot = parseSetup( + makeArray( + { + makeStep("setup.extra", "Extra", "ok", ""), + makeStep("setup.ready", "Ready", "todo", ""), + makeStep("setup.carrier", "Carrier", "ok", ""), + })); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + ASSERT_EQ(3u, snapshot.steps.size()); + EXPECT_EQ("carrier", snapshot.steps[0].name); + EXPECT_EQ("ready", snapshot.steps[1].name); + EXPECT_EQ("extra", snapshot.steps[2].name); +} + +TEST(SetupModel, SurvivesHostileStrings) +{ + auto array = zeroingArray(); + array.status[0].message = std::string("a\0b\xff\n", 5); + array.status[1].values[0].value = std::string(10000, 'x'); + array.status[2].values[1].value = std::string("\x01\x02", 2); + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_LT(snapshot.error.size(), 200u); +} + +TEST(SetupModel, StateWordsAreForTheOperator) +{ + EXPECT_STREQ("done", stepStateWord(StepState::Ok)); + EXPECT_STREQ("to do", stepStateWord(StepState::Todo)); + EXPECT_STREQ("blocked", stepStateWord(StepState::Blocked)); + EXPECT_STREQ("working", stepStateWord(StepState::Working)); +} + +TEST(SetupModel, TheGuideIsQuietFromThreeSecondsWithoutAMessage) +{ + const auto now = std::chrono::steady_clock::now(); + EXPECT_TRUE(setupGuideQuiet(std::nullopt, now)); + EXPECT_FALSE(setupGuideQuiet(now - 2900ms, now)); + EXPECT_TRUE(setupGuideQuiet(now - 3000ms, now)); + EXPECT_FALSE(setupGuideQuiet(now + 1s, now)); +} + +TEST(SetupModel, TheZeroServiceIsTheDriveNodes) +{ + EXPECT_STREQ("/sim_arm_drives/zero", kZeroServiceName); + EXPECT_STREQ("/arm/setup", kSetupTopic); +} + +} // namespace waybionic_rviz_plugins From 3a9c5db37d3db141aa6e16b573dc7e7d923f4012 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:40:44 -0600 Subject: [PATCH 15/31] Document the start-up guide, switching joints off and the app The operator guide gets the double-click app, the Arm setup steps and what to do when one is not done, and Joint control: what switching a joint off does (the drive holds it, nothing releases it), why a change waits until teleop stops, that the wrist drives are shared, that the state is not saved, and how to fit the shoulder drive later through the arm profile. --- docs/operator_guide.md | 92 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 599be972..4ab30614 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -380,6 +380,35 @@ then run these from the repository root. each joint a known angle, such as 10 degrees in RViz, and measure it on the arm; a different angle means its `gear_ratio` is wrong. +### Starting by double-click (Mac) + +After the [macOS setup](../BuildInstructions.md#macos-native-ros-with-robostack), install +the app once from the repository root: + +```bash +./scripts/macos.sh app +``` + +This puts **WayBionic Ground Station** in `~/Applications`; drag it to the Dock. The +copy in `packaging/macos/` also opens in place. Then, to start the arm: + +1. Plug in the carrier, the controller (USB or Bluetooth) and power the drives. +2. Double-click the app. The first time, it offers to run the setup in Terminal, which + takes 30 to 60 minutes; open the app again when that finishes. +3. If the carrier is not plugged in, a dialog says so: plug it in and choose *Try again*, + or choose *Without the arm* to run the simulation. With several USB serial devices + connected, it asks which one is the carrier. +4. It then starts the station exactly as `./scripts/macos.sh arm` does (the arm profile + and the saved zero included), with RViz filling the screen. The Arm setup panel there + walks through what is left: the controller, the zero pose, Start. + +Closing the RViz window, or quitting the app from the Dock, stops the station the way +Ctrl+C does, so each drive gets its stop first. The station's output goes to +`~/Library/Logs/WayBionic/` (the last 10 sessions are kept), and if it stops unexpectedly +the app offers to open the log. The app is not signed: if you download the repository as +a zip instead of cloning it, macOS asks you to confirm opening it once (right-click, then +Open). + ### Remote operator The controller can stay with an operator on another computer. On the operator's @@ -431,7 +460,8 @@ and zero as below. CI runs `waybionic_teleop/test/test_can_drives.py` over `vcan 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 run: +(the pose RViz shows before anything moves), leave teleop disabled, and press **Zero the +arm** in the Arm setup panel (see [Start-up guide](#start-up-guide)), or run: ```bash ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger @@ -490,6 +520,66 @@ service waits. A refused stop frame is sent again on every tick, and Start is refused until it has gone out. After any stop, disable teleop and press Start again. +### Start-up guide + +The **Arm setup** panel (top of RViz's right-hand dock) lists what is left to do before the +arm can be operated, one thing at a time. The `setup_guide` node builds the list from the +same diagnostics the station already publishes, and also says each change in the terminal. + +| Step | Done when | If it isn't | +| --- | --- | --- | +| Carrier | the carrier reports on USB and its E-stop is not pressed | plug in its USB-C cable; if it is plugged in but silent, replug it or flash it | +| Drives | every drive that is switched on answers | the panel names the drive and its CAN ID: check its power and wiring, or switch its joint off (below) | +| Controller | `/joy` input is arriving | connect an Xbox controller (USB or Bluetooth) and press a button | +| Zero | every drive that is switched on is zeroed or kept its saved zero | put the arm in its zero pose and press **Zero the arm** (it asks you to confirm) | +| Ready | teleop is enabled | press Start (the Menu button) on the controller | + +The controller needs no other step: the guide shows it as connected once input arrives. When +every step is done the panel shrinks to one line. If the guide itself is not running, the panel +says it is waiting for it. Nothing in the panel moves the arm. + +### Switching joints off + +The **Joint control** panel, below Arm setup, has a checkbox for each joint (J1 to J5 and the +tool). Unchecking one switches that joint off: + +- The drive stays powered and holds where it is. It is not released, so the joint does not + fall or move by itself. +- The sticks and triggers that were mapped to it do nothing, so the controller no longer + vibrates when you push a stick that needs a joint you don't want. The Cartesian and + incision groups need every joint, so they are left out of the group cycle while any joint + is off or unfitted. +- A drive whose joints are all off may be faulty or missing: it no longer stops the arm, + keeps the zero service from succeeding or keeps the arm from being enabled. The two wrist + drives move both wrist joints together, so switching off only J4 or only J5 still needs both + drives, which then hold that joint; switch off both to ignore a wrist drive. + +A change is only taken while teleop is stopped and no joint command has arrived for a second, +as for zeroing. Otherwise the panel shows why, and the box stays as it was. Turning a joint +back on needs its drive answering and zeroed before the arm can be enabled again, so after +fitting or repairing a drive, put the arm in the zero pose and zero it. + +The state is not saved: after a restart every fitted joint is on. A joint that has no drive +at all, such as the shoulder (J2) and the tool on the bench arm, is shown as *no drive* and +cannot be switched here. It comes from the arm profile (`~/.waybionic/arm_profile.yaml`): + +```yaml +# Bench arm: the shoulder is fixed upright and has no drive, and there is no tool. +fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] +locked_joints: {joint_2: 0.0, tool_grip: 0.0} +``` + +To fit the shoulder drive later, give it CAN ID 2 (`./scripts/macos.sh drives set-id 1 2` +with only that drive on the bus), add `shoulder` to `fitted_drives`, delete `joint_2` from +`locked_joints`, restart the station and zero. J2 then has a checkbox like the others. + +Without the panel, from a terminal: + +```bash +ros2 service call /arm/joint_3/set_enabled std_srvs/srv/SetBool "{data: false}" +ros2 topic echo /arm/joint_control +``` + ### Powered hand-guiding Powered hand-guiding is not enabled yet. A stopped drive holds position; disabling From e8555953bfbc9f907c53bcf8bc337d97331c7609 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:44:33 -0600 Subject: [PATCH 16/31] Wait a few seconds before the start-up guide reports a problem After a start the carrier reboots and the drives take a moment to answer, so the drives step said "no answer" in red every time even with the wiring fine. A blocked step now shows as still being checked until it has lasted five seconds, and the wait starts over once it clears. --- waybionic_teleop/test/test_setup_guide.py | 29 +++++++++++++++++++ .../waybionic_teleop/setup_guide.py | 10 +++++++ 2 files changed, 39 insertions(+) diff --git a/waybionic_teleop/test/test_setup_guide.py b/waybionic_teleop/test/test_setup_guide.py index d86809be..67ee9883 100644 --- a/waybionic_teleop/test/test_setup_guide.py +++ b/waybionic_teleop/test/test_setup_guide.py @@ -207,3 +207,32 @@ def test_a_step_that_changes_is_logged_once(guide, monkeypatch): guide.publish_steps() guide.publish_steps() assert len(messages) == 1 and 'Ready' in messages[0] and 'Start' in messages[0] + + +def test_a_problem_is_only_reported_once_it_has_lasted(guide, monkeypatch): + # The drives and the carrier take a few seconds to answer after a start; saying 'no answer' + # at once would blame wiring that is fine. + clock = [100.0] + monkeypatch.setattr(setup_guide.time, 'monotonic', lambda: clock[0]) + published = [] + monkeypatch.setattr(guide.publisher, 'publish', published.append) + + def drives(*changes): + # The other nodes report every half second, so the rows stay fresh. + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows(**dict(changes)).values()))) + guide.publish_steps() + found = next(item for item in published[-1].status if item.name == 'setup.drives') + return {item.key: item.value for item in found.values}['state'], found.message + + silent = ('drive.elbow', drive('elbow', 3, 'no reply', ERROR)) + state, message = drives(silent) + assert state == WORKING and 'elbow' not in message + clock[0] += setup_guide.BLOCK_GRACE_S - 0.5 + assert drives(silent)[0] == WORKING + clock[0] += 1.0 + state, message = drives(silent) + assert state == BLOCKED and 'elbow' in message + # Once it clears, the next problem starts the wait again. + assert drives()[0] == OK + clock[0] += 0.5 + assert drives(silent)[0] == WORKING diff --git a/waybionic_teleop/waybionic_teleop/setup_guide.py b/waybionic_teleop/waybionic_teleop/setup_guide.py index 43cac172..a086c678 100644 --- a/waybionic_teleop/waybionic_teleop/setup_guide.py +++ b/waybionic_teleop/waybionic_teleop/setup_guide.py @@ -30,6 +30,9 @@ # The drive node reports twice a second; a row this old means whoever sent it has gone. ROW_TIMEOUT_S = 3.0 PUBLISH_PERIOD_S = 0.5 +# The carrier and the drives need a few seconds to answer after a start, so a problem is only +# reported once it has lasted this long; until then the step is still being checked. +BLOCK_GRACE_S = 5.0 TITLES = {'carrier': 'Carrier', 'drives': 'Drives', 'controller': 'Controller', 'zero': 'Zero', 'ready': 'Ready'} WAITS = 'Waits for the steps above' @@ -171,6 +174,7 @@ def __init__(self, **kwargs): topic = (self.get_parameter('diagnostics_topic').value if self.has_parameter('diagnostics_topic') else '/diagnostics') self.rows = {} + self.blocked_since = {} self.announced = None latched = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) self.publisher = self.create_publisher(DiagnosticArray, TOPIC, latched) @@ -191,7 +195,13 @@ def announce(self, text): self.get_logger().info(text) def publish_steps(self): + now = time.monotonic() steps = evaluate(self.fresh_rows()) + for step in steps: + if step.state != BLOCKED: + self.blocked_since.pop(step.name, None) + elif now - self.blocked_since.setdefault(step.name, now) < BLOCK_GRACE_S: + step.state, step.message = WORKING, f'Checking the {step.title.lower()}...' first = current(steps) statuses = [] for step in steps: From 40439453e25beccb63b6859c214dd084618ac1f8 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:52:36 -0600 Subject: [PATCH 17/31] Save the new panels in the unified layout's window state The layout test requires every panel in the file to be named once in the saved QMainWindow State, as RViz would not place one it does not know. CI caught that the Arm setup and Joint control panels were not. The state was rebuilt with Qt rather than by hand: the old state was restored into a window with the same dock and toolbar names, the two panels were stacked above Diagnostics in the right-hand dock, and the result saved. Restoring the new state into a fresh window brings the same layout back, and each name appears once. --- waybionic_bringup/rviz/waybionic_unified.rviz | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz index 4172a445..ab1ed498 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -221,7 +221,7 @@ Window Geometry: Height: 800 Hide Left Dock: false Hide Right Dock: false - QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002d9fc0200000001fc00000014000002d90000003a01000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000001600fffffffb0000000a005600690065007700730100000000ffffffff0000001600fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000001600fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000001600ffffff00000001000001b8000002d9fc0200000001fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000014000002d90000001600ffffff00000003000005000000002dfc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002d900000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002b4fc0200000001fc00000014000002b40000007601000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000005200fffffffb0000000a005600690065007700730100000000ffffffff0000005200fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000005200fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000005200ffffff00000001000001b8000002b4fc0200000003fb000000140053006500740075007000500061006e0065006c0100000014000000970000005200fffffffb00000022004a006f0069006e00740043006f006e00740072006f006c00500061006e0065006c01000000b1000000970000005200fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c010000014e0000017a0000005200ffffff000000030000050000000052fc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002b400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: From 7abccab914b84e4435caa53ebcda41239e47662d Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:53:36 -0600 Subject: [PATCH 18/31] Press Start again in the Cartesian launch test when the drives stop The test failed on CI runners three times, once with the tip off the line by 0.64 mm and once with the tip not moving at all. The drives stop and want Start pressed afresh whenever the host stalls for half a second, which a busy runner can do, and the test never looked at the drives' gate, so it measured a cut that could not move. It now presses Start until both teleop and the drive gate report enabled, as an operator would after a stop, and repeats the cut if the gate closed during it. The failure message says what the gate and teleop reported, so a flake that is not this one explains itself. The assertions on the line are unchanged. --- .../test/test_cartesian_launch.py | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/waybionic_bringup/test/test_cartesian_launch.py b/waybionic_bringup/test/test_cartesian_launch.py index 3231f02f..219a1e93 100644 --- a/waybionic_bringup/test/test_cartesian_launch.py +++ b/waybionic_bringup/test/test_cartesian_launch.py @@ -73,6 +73,25 @@ def hold(seconds, *pressed, record=False, **axes): if record: samples.append(tip()) + def gate(): + row = diagnostics.get('arm.command_gate') + return row.values[0].value if row is not None else 'missing' + + def teleop_state(): + row = diagnostics.get('teleop.state') + return row.values[0].value if row is not None else 'missing' + + def enable(): + # The drives stop, and want Start pressed afresh, if the host stalls for half a + # second, as a busy CI runner can. An operator would press Start again. + for _ in range(6): + hold(0.2, 'start') + # Diagnostics are reported every 0.5 s. + hold(0.6) + if gate() == 'enabled' and teleop_state() == 'enabled': + return + self.fail(f'the drives never accepted Start: {diagnostics["arm.command_gate"]}') + try: deadline = time.monotonic() + 30.0 # Press Start only once teleop has loaded the robot description (the group row @@ -82,22 +101,32 @@ def hold(seconds, *pressed, record=False, **axes): and diagnostics['teleop.input'].level == DiagnosticStatus.OK and buffer.can_transform('base_link', 'tool_link', Time())): hold(0.1) - hold(0.2, 'start') + enable() hold(0.3, 'y') # Bend the shoulder, elbow and wrist away from the upright pose. hold(1.0, left_x=1.0, left_y=1.0, right_y=1.0) hold(0.5) hold(0.3, 'y') - # Diagnostics are reported every 0.5 s. hold(0.6) - self.assertEqual(diagnostics['teleop.state'].values[0].value, 'enabled') + if gate() != 'enabled' or teleop_state() != 'enabled': + enable() self.assertEqual(diagnostics['teleop.group'].values[0].value, 'cartesian') - start, tilt = tip() - hold(1.5, 'left_bumper', record=True, left_x=1.0) - hold(0.5, record=True) + for _ in range(3): + samples.clear() + start, tilt = tip() + hold(1.5, 'left_bumper', record=True, left_x=1.0) + hold(0.5, record=True) + if gate() == 'enabled': + break + # The drives stopped during the cut, so it says nothing about the line. + enable() travel = samples[-1][0][1] - start[1] worst = max(math.hypot(x - start[0], z - start[2]) for (x, y, z), _ in samples) - self.assertGreater(travel, 0.025, 'the tool tip did not move sideways') + self.assertGreater( + travel, 0.025, + f'the tool tip did not move sideways (drives {gate()}: ' + f'{diagnostics["arm.command_gate"].message!r}; teleop: ' + f'{diagnostics["teleop.state"].message!r})') self.assertLess(worst, 0.0005, f'the tip left the line by {worst * 1000:.2f} mm') self.assertLess(max(abs(value - tilt) for _, value in samples), 0.005) finally: From 90b17d6c61e7161c6de296c4b2b412c5372033ff Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:08:45 -0600 Subject: [PATCH 19/31] Keep the incision group while the tool is through the incision point Switching a joint off made the incision group unusable, and teleop moved the operator to another group while the tool was still through the incision point. A joint that is switched off now keeps the group the operator is in as long as the tool is inserted, with a warning, and the group cannot be left by group change. Teleop refuses to start in a group that has nothing to move. --- waybionic_teleop/test/test_incision.py | 36 +++++++++++++++ waybionic_teleop/waybionic_teleop/teleop.py | 50 +++++++++++++++------ 2 files changed, 72 insertions(+), 14 deletions(-) diff --git a/waybionic_teleop/test/test_incision.py b/waybionic_teleop/test/test_incision.py index 529a2ce2..8bc97cdc 100644 --- a/waybionic_teleop/test/test_incision.py +++ b/waybionic_teleop/test/test_incision.py @@ -323,3 +323,39 @@ def test_a_new_incision_point_clears_only_the_incision_warning(teleop): run(teleop, 0.1) assert teleop.incision is not None assert teleop.warning and teleop.note == 'Controller lost; press Start (Menu) to enable' + + +def test_switching_a_joint_off_with_the_tool_through_the_incision_keeps_the_group(teleop): + run(teleop, 1.0, left_y=1.0) + run(teleop, 0.3) + first, inserted = teleop.incision, dict(teleop.targets) + assert teleop.set_disabled({'joint_5'}, inserted) + # Leaving the group would let the other groups, and going home, drag the tool sideways + # inside the incision, as Y and A are refused for. + assert not teleop.enabled and teleop.active_group.name == 'incision' + assert teleop.incision == first and teleop.warning and 'switch it back on' in teleop.note + press(teleop, 'start') + assert not teleop.enabled and 'switch it back on' in teleop.note + run(teleop, 0.5, 'a') + assert teleop.targets == inserted + # With the joint back on, the group moves again. + assert teleop.set_disabled(set(), inserted) + press(teleop, 'start') + assert teleop.enabled and teleop.active_group.name == 'incision' + assert teleop.incision == pytest.approx(first, abs=1e-12) + + +def test_a_tool_that_is_out_of_the_incision_lets_the_group_go_and_is_remembered(teleop, arm): + run(teleop, 1.0, left_y=1.0) + run(teleop, 0.3) + first = teleop.incision + # While teleop is off the tool ends up beside the incision point, still deep. + beside = shifted(arm, teleop.targets, 0.02) + teleop.disable(beside, 'moved') + assert teleop.set_disabled({'joint_5'}, beside) + assert teleop.active_group.name == 'base' and not teleop.withdrawn + teleop.set_disabled(set(), beside) + # Choosing the incision group again must not take the tool tip for the new incision point. + for _ in range(len(teleop.groups) - 1): + press(teleop, 'y') + assert teleop.active_group.name == 'incision' and teleop.incision == first diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index 267650b1..f9847984 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -16,6 +16,8 @@ INCISION_LOST = ('The tool is off the incision point; press Y, withdraw it in another group, ' 'then choose the incision group again') INCISION_HELD = 'The tool is inserted; withdraw it to the incision point before pressing Y' +INCISION_JOINT_OFF = ('A joint is switched off with the tool through the incision point; switch ' + 'it back on in Joint control to withdraw the tool') def clamp(value, low, high): @@ -196,14 +198,23 @@ def movable(self, joint): """Return whether the sticks can move this joint: it is neither locked nor disabled.""" return joint not in self.locked and joint not in self.disabled - def usable_groups(self): - """Return the groups with something to move: a Cartesian solve needs every joint.""" - def usable(group): - if group.mode in MOVES: - return all(self.movable(joint) for joint in group.joints) - return any(self.movable(joint) for joint in group.joints) - return [group for group in self.configured_groups if usable(group)] or [ - self.configured_groups[0]] + def group_usable(self, group): + """Return whether a group has something to move: a Cartesian solve needs every joint.""" + if group.mode in MOVES: + return all(self.movable(joint) for joint in group.joints) + return any(self.movable(joint) for joint in group.joints) + + def usable_groups(self, keep=None): + """Return the groups with something to move, and keep, which is not left for one.""" + return [group for group in self.configured_groups + if group is keep or self.group_usable(group)] or [self.configured_groups[0]] + + def inserted(self): + """Return whether the tool is through the incision point, which groups may not leave.""" + if self.active_group.mode != 'incision' or self.incision is None or not self.targets: + return False + miss, depth = self.incision_offset(self.targets) + return miss <= INCISION_TOLERANCE and depth > INSERTED def set_disabled(self, joints, measured): """ @@ -219,13 +230,22 @@ def set_disabled(self, joints, measured): if self.enabled: self.disable(measured, 'Joint enable changed; press Start (Xbox Menu button) to ' 'enable') + previous = self.active_group + # The other groups, and going home, could drag the tool sideways in the incision, which + # Y and A are refused for, so a tool that is through it stays in its group, unable to move + # until the joint is switched back on. + keep = previous if self.inserted() else None self.disabled = joints self.disabled_angles = {joint: angle for joint, angle in self.disabled_angles.items() if joint in joints} - name = self.active_group.name - self.groups = self.usable_groups() + self.groups = self.usable_groups(keep) self.group = next((index for index, group in enumerate(self.groups) - if group.name == name), 0) + if group.name == previous.name), 0) + if self.active_group is not previous and previous.mode == 'incision' and ( + self.incision is not None): + self.withdrawn = self.incision_offset(self.targets)[1] <= INSERTED + if keep is not None and not self.group_usable(keep): + self.note, self.warning = INCISION_JOINT_OFF, True return True @property @@ -268,12 +288,11 @@ def update(self, axes, buttons, measured, dt): def change_group(self): """Select the next group, unless the tool is inserted through the incision point.""" if self.active_group.mode == 'incision' and self.incision is not None: - miss, depth = self.incision_offset(self.targets) - if miss <= INCISION_TOLERANCE and depth > INSERTED: + if self.inserted(): # The other groups, and going home, could drag the tool sideways in the incision. self.note, self.warning = INCISION_HELD, True return - self.withdrawn = depth <= INSERTED + self.withdrawn = self.incision_offset(self.targets)[1] <= INSERTED self.group = (self.group + 1) % len(self.groups) self.stop_cartesian() self.velocities = dict.fromkeys(self.limits, 0.0) @@ -305,6 +324,9 @@ def enable(self, measured, axes): self.note = 'No joint is enabled; switch one on in the Joint control panel' self.warning = True return + if not self.group_usable(self.active_group): + self.note, self.warning = INCISION_JOINT_OFF, True + return if self.motion_input_held(axes): # A stuck or held input must never start moving the arm the moment it is enabled. self.note = 'Center the sticks and release the triggers and buttons, then press Start' From 156b04a0bb42d484291a62957feed6257a308f3f Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:08:45 -0600 Subject: [PATCH 20/31] Do not offer the zero again once it has succeeded The start-up guide kept the "arm.zero" row from before the zero was saved, so the Zero step stayed on offer. A joint row and the arm.zero row now replace each other, so the guide follows whichever the drive node reported last. --- waybionic_teleop/test/test_setup_guide.py | 16 ++++++++++++++++ waybionic_teleop/waybionic_teleop/setup_guide.py | 11 +++++++++++ 2 files changed, 27 insertions(+) diff --git a/waybionic_teleop/test/test_setup_guide.py b/waybionic_teleop/test/test_setup_guide.py index 67ee9883..514d7ef7 100644 --- a/waybionic_teleop/test/test_setup_guide.py +++ b/waybionic_teleop/test/test_setup_guide.py @@ -236,3 +236,19 @@ def drives(*changes): assert drives()[0] == OK clock[0] += 0.5 assert drives(silent)[0] == WORKING + + +def test_a_zero_that_succeeded_is_not_offered_again(guide): + # The drive node reports arm.zero or the joints' positions, never both, so one appearing + # ends the other even though its last row is still fresh. + joints = {f'arm.joint_{number}': None for number in range(1, 6)} + unzeroed = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Not zeroed.', 'no'), **joints}) + guide.on_diagnostics(DiagnosticArray(status=list(unzeroed.values()))) + assert step(guide.fresh_rows(), 'zero').action == 'zero' + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + assert 'arm.zero' not in guide.fresh_rows() + assert step(guide.fresh_rows(), 'zero').state == OK + # And when the arm loses its zero, the old positions are no longer true. + guide.on_diagnostics(DiagnosticArray(status=list(unzeroed.values()))) + assert not any(name.startswith('arm.joint_') for name in guide.fresh_rows()) + assert step(guide.fresh_rows(), 'zero').action == 'zero' diff --git a/waybionic_teleop/waybionic_teleop/setup_guide.py b/waybionic_teleop/waybionic_teleop/setup_guide.py index a086c678..2a86fa6a 100644 --- a/waybionic_teleop/waybionic_teleop/setup_guide.py +++ b/waybionic_teleop/waybionic_teleop/setup_guide.py @@ -183,6 +183,17 @@ def __init__(self, **kwargs): def on_diagnostics(self, message): now = time.monotonic() + names = {row.name for row in message.status} + positions = [name for name in names + if name.startswith('arm.') and name not in ('arm.zero', 'arm.command_gate')] + # The drive node reports arm.zero or the joints' positions, never both, so one appearing + # ends the other, though its last row would count as fresh for a few seconds more. + if 'arm.zero' in names: + for name in [name for name in self.rows if name.startswith('arm.') + and name not in ('arm.zero', 'arm.command_gate')]: + del self.rows[name] + elif positions: + self.rows.pop('arm.zero', None) for row in message.status: self.rows[row.name] = (row, now) From c67b86bb85136c73237a57413aeae0cd345cfc59 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:08:45 -0600 Subject: [PATCH 21/31] End a station that is still starting when the app is quit The launcher only sent SIGINT to a "ros2 launch" process, and a background job of a script ignores SIGINT, so quitting while the station was still setting itself up (or before the launch process existed) did nothing. It now ends the station and everything below it with SIGTERM when no launch process exists yet. The trap is installed before the station is started, so a quit that arrives while it starts is carried out too. Tests run the real launcher over a made-up macos.sh for both cases. --- .../Contents/MacOS/WayBionicGroundStation | 16 ++- waybionic_bringup/test/test_macos_app.py | 100 ++++++++++++++++++ 2 files changed, 113 insertions(+), 3 deletions(-) diff --git a/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation index 8f14550a..33900a7e 100755 --- a/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation +++ b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation @@ -97,7 +97,13 @@ stop_station() { sent=1 fi done - [[ -n "$sent" ]] || kill -INT "$child" 2>/dev/null + if [[ -z "$sent" ]]; then + # Still setting itself up: nothing to shut down gracefully yet, and a background job of + # this script ignores SIGINT, so end it with TERM. + for pid in $(descendants "$child") "$child"; do + kill -TERM "$pid" 2>/dev/null + done + fi } carrier_ports() { @@ -164,10 +170,14 @@ for old in $(ls -1t "$LOG_DIR"/station-*.log 2>/dev/null | tail -n +"$((KEEP_LOG done cd "$ROOT" || exit 1 +# The trap comes first so that a quit during start-up is not lost; one that arrives before the +# station has a process ID is carried out right after it is started. +child="" +stopping="" +trap 'stopping=1; [[ -n "$child" ]] && stop_station' TERM INT HUP "${command[@]}" exit_with_rviz:=true >"$log" 2>&1 & child=$! -stopping="" -trap 'stopping=1; stop_station' TERM INT HUP +[[ -z "$stopping" ]] || stop_station status=0 while kill -0 "$child" 2>/dev/null; do wait "$child" diff --git a/waybionic_bringup/test/test_macos_app.py b/waybionic_bringup/test/test_macos_app.py index e52d0f7e..f03769e0 100644 --- a/waybionic_bringup/test/test_macos_app.py +++ b/waybionic_bringup/test/test_macos_app.py @@ -3,8 +3,12 @@ import os from pathlib import Path import plistlib +import shlex import shutil +import signal import subprocess +import sys +import time import pytest @@ -145,3 +149,99 @@ def test_the_app_command_is_in_the_usage(): result = subprocess.run(['bash', str(script), 'help'], capture_output=True, text=True, timeout=30, check=False) assert ' app ' in result.stdout + + +def written(path, timeout=10): + """Wait for a made-up macos.sh to finish writing a line into path; return the line.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + text = path.read_text(encoding='utf-8') if path.exists() else '' + if text.endswith('\n'): + return text.strip() + time.sleep(0.02) + raise AssertionError(f'{path.name} was never written') + + +def gone(pid, timeout=10): + """Return whether the process has ended (a zombie nobody reaped yet counts as ended).""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + state = subprocess.run(['ps', '-o', 'stat=', '-p', str(pid)], capture_output=True, + text=True, check=False).stdout.strip() + if not state or state.startswith('Z'): + return True + time.sleep(0.05) + return False + + +@pytest.fixture +def running(station, tmp_path): + """ + Start the launcher for real over a made-up macos.sh. + + Return (start, pids): start(script) runs the launcher and returns its process, and the + made-up macos.sh reports the processes it starts by writing "$PIDS/". + """ + _, root, _ = station + pids = tmp_path / 'pids' + pids.mkdir() + started = [] + + def start(script): + (root / 'scripts' / 'macos.sh').write_text(f'#!/bin/bash\n{script}', encoding='utf-8') + (root / 'install').mkdir(exist_ok=True) + (root / 'install' / 'setup.bash').touch() + app = next((tmp_path / 'Applications').iterdir()) + process = subprocess.Popen( + [str(app / 'Contents' / 'MacOS' / LAUNCHER.name)], env={ + 'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', 'PIDS': str(pids), + 'WAYBIONIC_CARRIER': '/dev/cu.x', 'WAYBIONIC_APP_ANSWER': 'Close'}, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started.append(process) + return process + yield start, pids + for report in pids.glob('*'): + try: + os.kill(int(report.read_text(encoding='utf-8')), signal.SIGKILL) + except (OSError, ValueError): + pass + for process in started: + if process.poll() is None: + process.kill() + process.wait() + + +def test_quitting_before_the_launch_exists_stops_the_station_that_is_starting(running): + start, pids = running + # A background job of a script ignores SIGINT, so only TERM ends a station that has no + # launch process yet. The script dies with TERM and would leave its child behind. + process = start('echo $$ >"$PIDS/script"\nsleep 60 &\necho $! >"$PIDS/sleep"\nwait\n') + script, sleeper = int(written(pids / 'script')), int(written(pids / 'sleep')) + process.send_signal(signal.SIGTERM) + assert process.wait(timeout=10) == 0 + assert gone(script) + assert gone(sleeper) + + +def test_quitting_asks_the_running_launch_to_shut_down_as_ctrl_c_does(running, tmp_path): + start, pids = running + marker, ready = tmp_path / 'got_sigint', tmp_path / 'ready' + # Like the real launch process, it sets up its own SIGINT handler, and its command line + # holds "ros2 launch". + code = ( + 'import signal, sys, time\n' + 'def stop(*_):\n' + f' open({str(marker)!r}, "w").write("SIGINT\\n")\n' + ' sys.exit(0)\n' + 'signal.signal(signal.SIGINT, stop)\n' + f'open({str(ready)!r}, "w").write("ready\\n")\n' + 'time.sleep(60)\n') + process = start( + 'echo $$ >"$PIDS/script"\n' + f'{shlex.quote(sys.executable)} -c {shlex.quote(code)} ros2 launch fake &\n' + 'echo $! >"$PIDS/launch"\nwait\n') + written(ready) + process.send_signal(signal.SIGTERM) + assert process.wait(timeout=10) == 0 + assert marker.exists(), 'the launch process was not asked to shut down with SIGINT' + assert gone(int(written(pids / 'launch'))) From a25c83f62d8445087d07a4ca3acb16452212abc3 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:14:59 -0600 Subject: [PATCH 22/31] Read a burst of replies in one pass through a relay's socket port pyserial's socket:// port reports at most one byte waiting, so reading in_waiting bytes took a control tick per byte. Read a chunk instead. A socket port also ignored write_timeout, which would have held the control loop for five seconds while the relay stopped reading, so give its socket the write timeout. --- waybionic_teleop/test/test_slcan_bus.py | 52 +++++++++++++++++++ .../waybionic_teleop/slcan_bus.py | 22 ++++++-- 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index 92a68121..cae6648a 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -2,10 +2,12 @@ import os import shutil +import socket import subprocess import time import pytest +import serial from waybionic_teleop import carrier, mks_can, slcan_bus from waybionic_teleop.slcan_bus import SlcanBus @@ -295,3 +297,53 @@ def wait_for(done, seconds=2.0): finally: sim.terminate() sim.wait() + + +@pytest.fixture +def relay_end(): + """The far end of a socket:// port, as a carrier relay presents the carrier: (server, url).""" + server = socket.create_server(('127.0.0.1', 0)) + server.settimeout(2.0) + yield server, f'socket://127.0.0.1:{server.getsockname()[1]}' + server.close() + + +def test_a_burst_of_frames_through_a_relay_is_read_in_one_pass(relay_end): + # pyserial's socket port reports at most one byte waiting, so a read of what is waiting + # would take a control tick for every byte and leave the replies far behind. + server, url = relay_end + bus = SlcanBus(url, 500000, baudrate=115200) + peer, _ = server.accept() + try: + peer.sendall(VERSION + b'\r\r\r') + for _ in range(200): + bus.receive() + if not bus.syncing: + break + time.sleep(0.001) + assert not bus.syncing + peer.sendall(b't0013F501F7\r' * 100) + time.sleep(0.05) + frames = [] + while (frame := bus.receive()) is not None: + frames.append(frame) + assert frames == [(1, bytes.fromhex('F501F7'))] * 100 + assert bus.errors == 0 + finally: + peer.close() + bus.shutdown() + + +def test_a_relay_that_stops_reading_fails_the_write_instead_of_stalling_the_loop(relay_end): + server, url = relay_end + link = slcan_bus.open_link(url, 115200) + peer, _ = server.accept() + started = time.monotonic() + try: + with pytest.raises(serial.SerialException): + while time.monotonic() - started < 10.0: + link.write(b'x' * 65536) + assert time.monotonic() - started < 2.0 + finally: + peer.close() + link.close() diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 04d2abcc..554c34bb 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -50,6 +50,22 @@ ANSWER_TIMEOUT_S = 0.5 BELL = 0x07 CR = 0x0D +# One read takes whatever has arrived, up to this much. A socket:// port, which is how a carrier +# relay presents the carrier, only ever reports one byte waiting, so asking for that many would +# take a read, and a control tick, for every byte. +READ_CHUNK = 4096 + + +def open_link(port, baudrate): + """Open the carrier's serial port, or a relay's socket:// URL, so no read or write blocks.""" + link = serial.serial_for_url(port, baudrate=baudrate, timeout=0, + write_timeout=WRITE_TIMEOUT_S) + # A socket:// port ignores write_timeout and would hold the control loop for five seconds + # while the relay is not reading. + relay = getattr(link, '_socket', None) + if relay is not None: + relay.settimeout(WRITE_TIMEOUT_S) + return link def parse_line(line): @@ -74,9 +90,7 @@ 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, - write_timeout=WRITE_TIMEOUT_S)) + self.open_port = open_port or (lambda: open_link(port, baudrate)) self.frames = self.bits = self.errors = self.refused = self.reopens = 0 self.problem = '' self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() @@ -208,7 +222,7 @@ def _read(self): if self.serial is None: return try: - chunk = self.serial.read(self.serial.in_waiting or 1) + chunk = self.serial.read(READ_CHUNK) except (serial.SerialException, OSError) as error: self._lost(error) return From 2fd630acd612cdc33fb92a8b42e9a7d42aa862eb Mon Sep 17 00:00:00 2001 From: Harold Kim Date: Sat, 17 Oct 2026 15:01:34 -0600 Subject: [PATCH 23/31] Fix scripts affecting how files are run --- compose.yaml | 18 ++ scripts/windows-arm.cmd | 3 + scripts/windows-arm.ps1 | 102 +++++++++ waybionic_teleop/test/test_carrier_relay.py | 101 +++++++++ .../waybionic_teleop/carrier_relay.py | 193 ++++++++++++++++++ 5 files changed, 417 insertions(+) create mode 100644 scripts/windows-arm.cmd create mode 100644 scripts/windows-arm.ps1 create mode 100644 waybionic_teleop/test/test_carrier_relay.py create mode 100644 waybionic_teleop/waybionic_teleop/carrier_relay.py diff --git a/compose.yaml b/compose.yaml index e15d0c3b..ef5540b5 100644 --- a/compose.yaml +++ b/compose.yaml @@ -191,3 +191,21 @@ services: - joy_source:=udp - joy_udp_bind:=0.0.0.0 - autoplay:=true + + # The real arm from Windows. The carrier relay (waybionic_teleop.carrier_relay) runs on + # Windows and the drive node connects out to it, so the carrier needs no published port. + wslg-arm: + <<: *wslg + profiles: [wslg-arm] + ports: + - 127.0.0.1:47300:47300/udp + command: + - ros2 + - launch + - waybionic_bringup + - ground_station.launch.py + - teleop:=true + - joy_source:=udp + - joy_udp_bind:=0.0.0.0 + - drive_interface:=slcan + - drive_channel:=socket://host.docker.internal:47320 diff --git a/scripts/windows-arm.cmd b/scripts/windows-arm.cmd new file mode 100644 index 00000000..c04c8a63 --- /dev/null +++ b/scripts/windows-arm.cmd @@ -0,0 +1,3 @@ +@echo off +rem Drives the real arm from Windows. Plug in the carrier, then double-click this file or run it from a terminal. +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0windows-arm.ps1" \ No newline at end of file diff --git a/scripts/windows-arm.ps1 b/scripts/windows-arm.ps1 new file mode 100644 index 00000000..b30db357 --- /dev/null +++ b/scripts/windows-arm.ps1 @@ -0,0 +1,102 @@ +# Drives the real arm from Windows in one step: Docker Desktop, the carrier bridge, the +# controller bridge and the ground station. Docker Desktop cannot open COM ports, so the +# carrier bridge relays the carrier's port to 127.0.0.1:47320 and the drive node connects to it. +# Run windows-arm.cmd, or: powershell -ExecutionPolicy Bypass -File scripts\windows-arm.ps1 + +$root = Split-Path -Parent $PSScriptRoot +$teleop = Join-Path $root 'waybionic_teleop' +$carrierPort = 47320 + +$docker = Join-Path $env:LOCALAPPDATA 'Programs\DockerDesktop\resources\bin\docker.exe' +if (-not (Test-Path $docker)) { + $command = Get-Command docker -ErrorAction SilentlyContinue + if (-not $command) { + Write-Error 'Docker Desktop is not installed; see BuildInstructions.md.' + exit 1 + } + $docker = $command.Source +} + +& $docker info *> $null +if ($LASTEXITCODE -ne 0) { + $app = @( + (Join-Path $env:LOCALAPPDATA 'Programs\DockerDesktop\Docker Desktop.exe'), + (Join-Path $env:ProgramFiles 'Docker\Docker\Docker Desktop.exe') + ) | Where-Object { Test-Path $_ } | Select-Object -First 1 + if (-not $app) { + Write-Error 'Docker is not running and Docker Desktop was not found.' + exit 1 + } + Write-Host 'Starting Docker Desktop...' + Start-Process $app + $deadline = (Get-Date).AddMinutes(3) + do { + Start-Sleep -Seconds 3 + & $docker info *> $null + } until ($LASTEXITCODE -eq 0 -or (Get-Date) -gt $deadline) + if ($LASTEXITCODE -ne 0) { + Write-Error 'Docker Desktop did not start within 3 minutes.' + exit 1 + } +} + +$python = $null +$pythonArguments = @() +foreach ($name in 'python', 'python3', 'py') { + $command = Get-Command $name -ErrorAction SilentlyContinue + if (-not $command) { + continue + } + $prefix = if ($command.Name -eq 'py.exe') { @('-3') } else { @() } + & $command.Source @prefix -c 'import sys; sys.exit(sys.version_info[0] != 3)' *> $null + if ($LASTEXITCODE -eq 0) { + $python, $pythonArguments = $command, $prefix + break + } +} +if (-not $python) { + Write-Error 'The real arm needs Python 3 on Windows for the carrier bridge.' + exit 1 +} +& $python.Source @pythonArguments -c 'import serial' *> $null +if ($LASTEXITCODE -ne 0) { + Write-Error 'The carrier bridge needs pyserial: python -m pip install pyserial' + exit 1 +} + +$carrier = $null +$controller = $null +try { + $carrier = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop ` + -ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.carrier_relay')) + + Write-Host 'Waiting for the carrier...' + $deadline = (Get-Date).AddSeconds(15) + do { + Start-Sleep -Milliseconds 500 + $listening = Get-NetTCPConnection -LocalPort $carrierPort -State Listen ` + -ErrorAction SilentlyContinue + } until ($listening -or $carrier.HasExited -or (Get-Date) -gt $deadline) + if (-not $listening) { + Write-Error ('The carrier bridge is not ready. Plug in only the carrier, or run ' + + 'python -m waybionic_teleop.carrier_relay from waybionic_teleop to see why.') + exit 1 + } + + $controller = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop ` + -ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.xinput_bridge')) + + Push-Location $root + try { + Write-Host 'Starting the ground station; press Ctrl+C here to stop.' + & $docker compose run --rm --build --service-ports wslg-arm + } finally { + Pop-Location + } +} finally { + foreach ($process in $controller, $carrier) { + if ($process -and -not $process.HasExited) { + Stop-Process -Id $process.Id + } + } +} \ No newline at end of file diff --git a/waybionic_teleop/test/test_carrier_relay.py b/waybionic_teleop/test/test_carrier_relay.py new file mode 100644 index 00000000..bd6999f6 --- /dev/null +++ b/waybionic_teleop/test/test_carrier_relay.py @@ -0,0 +1,101 @@ +import socket +import threading + +import pytest +import serial + +from waybionic_teleop import carrier_relay + + +class LostCarrier: + """A carrier that has just been unplugged.""" + + in_waiting = 0 + + def read(self, size=1): + raise serial.SerialException('device unplugged') + + def write(self, data): + raise serial.SerialException('device unplugged') + + +def loop_carrier(): + return serial.serial_for_url('loop://', timeout=carrier_relay.POLL_S) + + +def start(link): + """Run relay() in a thread; return our end of the connection, stop, thread and result.""" + ours, theirs = socket.socketpair() + ours.settimeout(2.0) + stop = threading.Event() + result = [] + thread = threading.Thread( + target=lambda: result.append(carrier_relay.relay(link, theirs, stop)), daemon=True) + thread.start() + return ours, stop, thread, result + + +def test_frames_pass_both_ways(): + link = loop_carrier() + ours, stop, thread, result = start(link) + frame = b't00121234\r' + ours.sendall(frame) + echoed = b'' + while len(echoed) < len(frame): + echoed += ours.recv(64) + assert echoed == frame + stop.set() + thread.join(2.0) + assert result == ['stopped'] + ours.close() + link.close() + + +def test_lost_carrier_closes_the_connection(): + ours, stop, thread, result = start(LostCarrier()) + assert ours.recv(64) == b'' + thread.join(2.0) + assert result == ['serial'] + ours.close() + + +def test_stopping_closes_the_connection(): + link = loop_carrier() + ours, stop, thread, result = start(link) + stop.set() + assert ours.recv(64) == b'' + thread.join(2.0) + assert result == ['stopped'] + ours.close() + link.close() + + +def test_ground_station_disconnect_keeps_the_carrier_open(): + link = loop_carrier() + ours, stop, thread, result = start(link) + ours.close() + thread.join(2.0) + assert result == ['client'] + assert link.is_open + link.close() + + +def test_no_connection_while_the_carrier_is_unplugged(): + probe = socket.create_server(('127.0.0.1', 0)) + tcp_port = probe.getsockname()[1] + probe.close() + stop = threading.Event() + + def unplugged(): + raise serial.SerialException('could not open port') + + thread = threading.Thread( + target=carrier_relay.serve, + args=(unplugged, '127.0.0.1', tcp_port, stop, lambda message: None), daemon=True) + thread.start() + try: + with pytest.raises(OSError): + socket.create_connection(('127.0.0.1', tcp_port), timeout=1.0) + finally: + stop.set() + thread.join(2.0) diff --git a/waybionic_teleop/waybionic_teleop/carrier_relay.py b/waybionic_teleop/waybionic_teleop/carrier_relay.py new file mode 100644 index 00000000..6732ff1f --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/carrier_relay.py @@ -0,0 +1,193 @@ +""" +Relay the WayBionic carrier's COM port to a local TCP port for the drive node in Docker. + +Docker Desktop cannot open Windows COM ports, but the drive node opens the carrier with +pyserial's serial_for_url, so it accepts socket://host.docker.internal:PORT as its +drive_channel. This passes bytes both ways unchanged, as soon as they arrive. If the carrier +is unplugged or the bridge stops, the connection closes, so the drive node loses the carrier +exactly as it does when the USB cable is pulled on a Mac or Linux. Needs pyserial. Run from +the waybionic_teleop directory: + + python -m waybionic_teleop.carrier_relay --port COM5 +""" + +import argparse +import socket +import threading + +import serial +from serial.tools import list_ports + +ARDUINO_VID = 0x2341 +DEFAULT_BAUDRATE = 1000000 +DEFAULT_TCP_PORT = 47320 +REOPEN_EVERY_S = 1.0 +# How often blocking calls wake up to check whether to stop. +POLL_S = 0.05 +CHUNK = 4096 + + +def find_carrier(): + """Return the only Arduino COM port, or None if there are none or several.""" + ports = [info.device for info in list_ports.comports() if info.vid == ARDUINO_VID] + return ports[0] if len(ports) == 1 else None + + +def relay(link, client, stop): + """ + Pass bytes both ways between the carrier and one TCP client until either side fails. + + Return 'client' if the client disconnected, 'serial' if the carrier was lost, or + 'stopped' once stop is set. Always closes the client; never closes the carrier. + """ + try: + # Send each frame at once instead of waiting to fill a packet. + client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass # Not a TCP socket, as in the tests. + client.settimeout(POLL_S) + done = threading.Event() + lock = threading.Lock() + reasons = [] + + def finish(reason): + with lock: + if not done.is_set(): + reasons.append(reason) + done.set() + + def to_client(): + while not done.is_set(): + try: + data = link.read(link.in_waiting or 1) + except (serial.SerialException, OSError): + finish('serial') + return + if not data: + continue + try: + client.sendall(data) + except OSError: + finish('client') + return + + def to_carrier(): + while not done.is_set(): + try: + data = client.recv(CHUNK) + except socket.timeout: + continue + except OSError: + finish('client') + return + if not data: + finish('client') + return + try: + link.write(data) + except (serial.SerialException, OSError): + finish('serial') + return + + threads = [threading.Thread(target=pump, daemon=True) for pump in (to_client, to_carrier)] + for thread in threads: + thread.start() + try: + while not done.wait(POLL_S): + if stop.is_set(): + finish('stopped') + finally: + done.set() + for thread in threads: + thread.join() + client.close() + return reasons[0] if reasons else 'stopped' + + +def _carrier_alive(link): + """Discard what the carrier sent with nobody connected; return False if it is gone.""" + try: + link.reset_input_buffer() + except (serial.SerialException, OSError): + return False + return True + + +def _close(thing): + if thing is not None: + try: + thing.close() + except (serial.SerialException, OSError): + pass + return None + + +def serve(open_port, bind, tcp_port, stop, log=print): + """ + Relay the carrier to one client at a time until stop is set. + + Listen only while the carrier is open, so the drive node's connection is refused, as an + unplugged port would be, until the carrier is back. + """ + link = server = None + problem = None + try: + while not stop.is_set(): + if link is None: + try: + link = open_port() + except (serial.SerialException, OSError) as error: + if str(error) != problem: + problem = str(error) + log(f'Carrier unavailable, retrying every second: {error}') + stop.wait(REOPEN_EVERY_S) + continue + problem = None + server = socket.create_server((bind, tcp_port)) + server.settimeout(POLL_S) + log('Carrier open; waiting for the ground station') + try: + client, address = server.accept() + except socket.timeout: + reason = None if _carrier_alive(link) else 'serial' + else: + log(f'Ground station connected from {address[0]}') + reason = relay(link, client, stop) + if reason == 'serial': + log('Carrier lost; connection closed') + server = _close(server) + link = _close(link) + elif reason == 'client': + log('Ground station disconnected; waiting for it to reconnect') + finally: + _close(server) + _close(link) + + +def main(): + parser = argparse.ArgumentParser(description='Relay the carrier COM port to the arm.') + parser.add_argument('--port', + help='carrier COM port, such as COM5 (default: the only Arduino)') + parser.add_argument('--baudrate', type=int, default=DEFAULT_BAUDRATE) + parser.add_argument('--bind', default='127.0.0.1', + help='listen address; keep it local, this drives the arm') + parser.add_argument('--tcp-port', type=int, default=DEFAULT_TCP_PORT) + args = parser.parse_args() + port = args.port or find_carrier() + if port is None: + found = ', '.join(info.device for info in list_ports.comports()) or 'none' + raise SystemExit(f'Plug in only the carrier, or pass --port. COM ports found: {found}') + print(f'Relaying {port} to {args.bind}:{args.tcp_port} (Ctrl+C to stop)') + print(f'Ground station: drive_channel:=socket://host.docker.internal:{args.tcp_port}') + stop = threading.Event() + try: + serve(lambda: serial.Serial(port, args.baudrate, timeout=POLL_S), + args.bind, args.tcp_port, stop) + except KeyboardInterrupt: + pass + finally: + stop.set() + + +if __name__ == '__main__': + main() From 94616fdf564fa23d1b5c37c25c10a095e5c5fd59 Mon Sep 17 00:00:00 2001 From: Harold Kim Date: Sat, 24 Oct 2026 12:45:02 -0600 Subject: [PATCH 24/31] Add short message when port in already in use --- waybionic_teleop/test/test_carrier_relay.py | 11 +++++++++++ waybionic_teleop/waybionic_teleop/carrier_relay.py | 7 ++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/waybionic_teleop/test/test_carrier_relay.py b/waybionic_teleop/test/test_carrier_relay.py index bd6999f6..5a20790a 100644 --- a/waybionic_teleop/test/test_carrier_relay.py +++ b/waybionic_teleop/test/test_carrier_relay.py @@ -99,3 +99,14 @@ def unplugged(): finally: stop.set() thread.join(2.0) + + +def test_port_in_use_exits_with_a_message(): + taken = socket.create_server(('127.0.0.1', 0)) + tcp_port = taken.getsockname()[1] + stop = threading.Event() + try: + with pytest.raises(SystemExit, match='already in use'): + carrier_relay.serve(loop_carrier, '127.0.0.1', tcp_port, stop, lambda message: None) + finally: + taken.close() diff --git a/waybionic_teleop/waybionic_teleop/carrier_relay.py b/waybionic_teleop/waybionic_teleop/carrier_relay.py index 6732ff1f..ae7664be 100644 --- a/waybionic_teleop/waybionic_teleop/carrier_relay.py +++ b/waybionic_teleop/waybionic_teleop/carrier_relay.py @@ -143,7 +143,12 @@ def serve(open_port, bind, tcp_port, stop, log=print): stop.wait(REOPEN_EVERY_S) continue problem = None - server = socket.create_server((bind, tcp_port)) + try: + server = socket.create_server((bind, tcp_port)) + except OSError as error: + raise SystemExit( + f'Port {tcp_port} is already in use ({error}).' + 'Another carrier bridge may still be running, close it first.') from None server.settimeout(POLL_S) log('Carrier open; waiting for the ground station') try: From f32335e5c9e371b5f688bf3801624f17c8c79f34 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:17:04 -0600 Subject: [PATCH 25/31] Test the simulated carrier through a carrier relay The Windows path carries the carrier's port over TCP to the drive node, so run the simulated carrier through the relay and SlcanBus's socket:// port, as the existing test does through a pty. --- waybionic_teleop/test/test_slcan_bus.py | 72 ++++++++++++++++++------- 1 file changed, 53 insertions(+), 19 deletions(-) diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index cae6648a..4b18bbcc 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -4,12 +4,13 @@ import shutil import socket import subprocess +import threading import time import pytest import serial -from waybionic_teleop import carrier, mks_can, slcan_bus +from waybionic_teleop import carrier, carrier_relay, mks_can, slcan_bus from waybionic_teleop.slcan_bus import SlcanBus # The carrier's answer to V, which comes before the answers to C, Sn and O. @@ -268,6 +269,27 @@ def slcan_sim(): return path if path and os.access(path, os.X_OK) else None +def check_the_simulated_carrier_answers(bus): + 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() + + @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'], @@ -275,26 +297,38 @@ def test_the_simulated_carrier_answers_through_the_real_bridge_code(): try: port = sim.stdout.readline().strip() # A pty ignores the baud rate, and macOS refuses a custom rate such as 1000000 on one. - bus = SlcanBus(port, 500000, baudrate=115200) - frames = [] + check_the_simulated_carrier_answers(SlcanBus(port, 500000, baudrate=115200)) + finally: + sim.terminate() + sim.wait() - 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() + +@pytest.mark.skipif(slcan_sim() is None, reason='waybionic_can slcan_sim is not built') +def test_the_simulated_carrier_answers_through_a_carrier_relay(): + # The Windows path: the relay carries the carrier's port over TCP to the drive node. + sim = subprocess.Popen([slcan_sim(), '--ids', '1', '--move-ms', '100'], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + stop = threading.Event() + try: + port = sim.stdout.readline().strip() + with socket.create_server(('127.0.0.1', 0)) as probe: + tcp_port = probe.getsockname()[1] + relay = threading.Thread(target=carrier_relay.serve, daemon=True, args=( + lambda: serial.Serial(port, 115200, timeout=carrier_relay.POLL_S), + '127.0.0.1', tcp_port, stop, lambda message: None)) + relay.start() + deadline = time.monotonic() + 3.0 + while True: + try: + bus = SlcanBus(f'socket://127.0.0.1:{tcp_port}', 500000, baudrate=115200) + break + except serial.SerialException: + assert time.monotonic() < deadline, 'the relay never listened' + time.sleep(0.02) + check_the_simulated_carrier_answers(bus) finally: + stop.set() + relay.join(3.0) sim.terminate() sim.wait() From e2e3aca5dbe9c2e67098923375118ec355ee131b Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:20:35 -0600 Subject: [PATCH 26/31] Ship the profile of the arm as built The shoulder is wired now, so J1 to J5 each have a drive and only the tool has none. A profile in the repository lets a launcher that has no home directory to read, such as the Windows container's, start the arm without waiting for a tool drive that does not exist. A test keeps it valid for the arm map. --- waybionic_teleop/config/arm_profile_bench.yaml | 7 +++++++ waybionic_teleop/test/test_arm_profile.py | 11 +++++++++++ waybionic_teleop/test/test_slcan_bus.py | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 waybionic_teleop/config/arm_profile_bench.yaml diff --git a/waybionic_teleop/config/arm_profile_bench.yaml b/waybionic_teleop/config/arm_profile_bench.yaml new file mode 100644 index 00000000..3cf4f420 --- /dev/null +++ b/waybionic_teleop/config/arm_profile_bench.yaml @@ -0,0 +1,7 @@ +# The bench arm as it is built now: a drive on each of J1 to J5 (CAN IDs 1 to 5) and no tool +# drive. The Windows launcher (compose.yaml, wslg-arm) uses this file, as a Mac uses +# ~/.waybionic/arm_profile.yaml; waybionic_teleop/arm_profile.py describes the format. +# When the tool drive (CAN ID 6) is fitted, add `tool` to fitted_drives and delete tool_grip +# from locked_joints. +fitted_drives: [base_yaw, shoulder, elbow, wrist_left, wrist_right] +locked_joints: {tool_grip: 0.0} diff --git a/waybionic_teleop/test/test_arm_profile.py b/waybionic_teleop/test/test_arm_profile.py index 1d8c39a1..2457b3c7 100644 --- a/waybionic_teleop/test/test_arm_profile.py +++ b/waybionic_teleop/test/test_arm_profile.py @@ -1,5 +1,7 @@ """An arm profile says which drives one arm has and holds still the joints it lacks.""" +from pathlib import Path + import pytest from waybionic_teleop.arm_profile import ( @@ -25,6 +27,15 @@ def test_the_bench_profile_runs_four_drives_and_holds_the_shoulder(parameters, b assert params['drives'][1] == 'shoulder' +def test_the_shipped_bench_profile_fits_the_arm_as_built(parameters): + # The Windows launcher passes this file, so it has to stay valid for the arm map. + shipped = Path(__file__).resolve().parent.parent / 'config' / 'arm_profile_bench.yaml' + profile = load_profile(shipped) + assert profile.locked_joints == {'tool_grip': 0.0} + fitted = fit_drive_parameters(parameters('arm_drives.yaml', 'sim_arm_drives'), profile) + assert fitted['drives'] == ['base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right'] + + @pytest.mark.parametrize('data, message', [ ([], 'must be a mapping'), ({'fitted': ['base_yaw']}, 'unknown keys'), diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index 4b18bbcc..38741677 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -335,7 +335,7 @@ def test_the_simulated_carrier_answers_through_a_carrier_relay(): @pytest.fixture def relay_end(): - """The far end of a socket:// port, as a carrier relay presents the carrier: (server, url).""" + """Listen as a carrier relay does, yielding (server, url) for a socket:// port.""" server = socket.create_server(('127.0.0.1', 0)) server.settimeout(2.0) yield server, f'socket://127.0.0.1:{server.getsockname()[1]}' From 571bf57e6afee1226269aa2f7ca9701fcf5435a0 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:20:35 -0600 Subject: [PATCH 27/31] Start the real arm from Windows with the setup panel Pass the bench profile and close the station with RViz, build the image without running the unit tests (CI has, and they are timing-sensitive), point the one-step script at the Arm setup panel for the zero, and document the Windows steps next to the Mac's. The guide also named a 1 Mbit/s CAN rate and an older carrier that this arm does not use. --- compose.yaml | 12 +++++ docs/operator_guide.md | 100 ++++++++++++++++++++++++++++++++-------- scripts/windows-arm.ps1 | 2 + 3 files changed, 95 insertions(+), 19 deletions(-) diff --git a/compose.yaml b/compose.yaml index ef5540b5..799227b0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -194,9 +194,19 @@ services: # The real arm from Windows. The carrier relay (waybionic_teleop.carrier_relay) runs on # Windows and the drive node connects out to it, so the carrier needs no published port. + # arm_profile_bench.yaml says the arm has no tool drive; closing RViz ends the station. + # Launching the arm shouldn't depend on the unit tests passing on this machine, which are + # timing-sensitive, so this image stops at the build stage; CI has run the tests. wslg-arm: <<: *wslg profiles: [wslg-arm] + image: waybionic_ground_station:arm + build: + context: . + dockerfile: docker/Dockerfile + target: build + cache_from: + - ghcr.io/waybionic/waybionic_ground_station:jazzy ports: - 127.0.0.1:47300:47300/udp command: @@ -209,3 +219,5 @@ services: - joy_udp_bind:=0.0.0.0 - drive_interface:=slcan - drive_channel:=socket://host.docker.internal:47320 + - arm_profile:=/waybionic_ws/install/waybionic_teleop/share/waybionic_teleop/config/arm_profile_bench.yaml + - exit_with_rviz:=true diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 4ab30614..94680387 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -300,12 +300,12 @@ bridge needs `python3-opencv`. The controller plugs into the computer, not the Arduino. The computer runs teleop, the Cartesian moves, the joint limits and collision checks, the RViz twin and the -monitor, then sends MKS frames through the carrier board: 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. +monitor, then sends MKS frames through the carrier board: a UNO R4 with an MCP2515 CAN +module running `waybionic_can/arduino/carrier_bridge_mcp2515`. The carrier only passes +frames between USB and the CAN bus, and reports its own status. ```text -controller -> computer (ROS 2) -> USB, 1 Mbaud -> carrier -> CAN, 1 Mbit/s -> 5 MKS drives +controller -> computer (ROS 2) -> USB -> carrier -> CAN, 500 kbit/s -> 5 MKS drives ``` `waybionic_teleop/config/arm_drives.yaml` maps the joints to the drives: CAN IDs 1 @@ -323,8 +323,9 @@ unloaded, and keep the E-stop within reach. The computer running ROS needs the carrier or a USB CAN adapter. Docker Desktop on Windows and macOS can't reach USB devices, so use native ROS on macOS -([RoboStack](../BuildInstructions.md#macos-native-ros-with-robostack)) or Linux, or -Docker on Linux with `--network host` for a SocketCAN adapter. +([RoboStack](../BuildInstructions.md#macos-native-ros-with-robostack)), the +[carrier relay on Windows](#on-windows) or Linux, or Docker on Linux with +`--network host` for a SocketCAN adapter. ### On a Mac @@ -344,14 +345,12 @@ then run these from the repository root. ``` 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. + as 1). Leave them at the factory 500 kbit/s, the most the arm's MCP2515 carrier + runs. Then 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 + ./scripts/macos.sh drives scan --ids 1 2 3 4 5 ``` 3. **Start the ground station.** With `tool` removed from `drives` in @@ -428,6 +427,66 @@ On the Mac, listen on the network: The receiver takes controller packets from any computer that can reach its port, so do this only on a private network. +### On Windows + +Docker Desktop can't open COM ports, so a small program on Windows, `carrier_relay`, +passes the carrier's port through `127.0.0.1:47320`, and the drive node in the container +connects to it as `socket://host.docker.internal:47320`. Besides +[Docker Desktop with WSLg](../BuildInstructions.md#windows-wslg), as for the other Windows +demos, it needs Python 3 on Windows and pyserial: + +```powershell +python -m pip install pyserial +``` + +Flash the carrier first, as in step 1 of [On a Mac](#on-a-mac) (from a Mac, or with the +Arduino IDE). + +**In one step:** plug in only the carrier, connect an Xbox controller and double-click +`scripts\windows-arm.cmd`. It starts Docker Desktop, the carrier bridge and the controller +bridge, then the ground station with `waybionic_teleop/config/arm_profile_bench.yaml` +(J1 to J5 driven, no tool). The first start builds the image, which takes a while. The Arm +setup panel in RViz then walks through what is left: put the arm in its zero pose, press +**Zero the arm**, then press Start on the controller. The zero is not kept between runs on +Windows, so do this every time. Closing RViz, or Ctrl+C in the script's window, stops the +ground station first, so each drive gets its stop, then the bridges. + +**Step by step,** from the repository root. The bridge serves one connection at a time, so +let each command finish before the next. If `docker` is not recognized, see +[its troubleshooting](../BuildInstructions.md#docker-is-not-recognized-on-windows). + +1. Start the bridge in its own PowerShell window and leave it running. It finds the + carrier as the only Arduino COM port; otherwise pass `--port COM5`. Wait for + `Carrier open; waiting for the ground station`: the drive node stops at start-up if + nothing is listening. + + ```powershell + cd waybionic_teleop + python -m waybionic_teleop.carrier_relay + ``` + +2. Scan the drives from a second window: + + ```powershell + docker compose run --rm --build wslg-arm ros2 run waybionic_teleop mks_setup --channel socket://host.docker.internal:47320 scan --ids 1 2 3 4 5 + ``` + +3. Start the controller bridge in a third window, then the ground station: + + ```powershell + cd waybionic_teleop + python -m waybionic_teleop.xinput_bridge + ``` + + ```powershell + docker compose run --rm --build --service-ports wslg-arm + ``` + +Stopping the bridge or unplugging the carrier closes the connection, so the drive node +loses the carrier as it does when the USB cable is pulled on a Mac: every drive stops and +the arm must be zeroed again. The bridge listens only on `127.0.0.1`; keep it local, +because anything that connects to it can drive the arm. + ### On Linux With the carrier, set up the drives as in step 2 above, with `mks_setup`, then @@ -560,18 +619,21 @@ back on needs its drive answering and zeroed before the arm can be enabled again fitting or repairing a drive, put the arm in the zero pose and zero it. The state is not saved: after a restart every fitted joint is on. A joint that has no drive -at all, such as the shoulder (J2) and the tool on the bench arm, is shown as *no drive* and -cannot be switched here. It comes from the arm profile (`~/.waybionic/arm_profile.yaml`): +at all, such as the tool on the bench arm, is shown as *no drive* and cannot be switched +here. It comes from the arm profile (`~/.waybionic/arm_profile.yaml` on a Mac, +`waybionic_teleop/config/arm_profile_bench.yaml` for the Windows launcher): ```yaml -# Bench arm: the shoulder is fixed upright and has no drive, and there is no tool. -fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] -locked_joints: {joint_2: 0.0, tool_grip: 0.0} +# Bench arm: J1 to J5 have a drive (CAN IDs 1 to 5), and there is no tool. +fitted_drives: [base_yaw, shoulder, elbow, wrist_left, wrist_right] +locked_joints: {tool_grip: 0.0} ``` -To fit the shoulder drive later, give it CAN ID 2 (`./scripts/macos.sh drives set-id 1 2` -with only that drive on the bus), add `shoulder` to `fitted_drives`, delete `joint_2` from -`locked_joints`, restart the station and zero. J2 then has a checkbox like the others. +To fit another drive later, give it its CAN ID (`./scripts/macos.sh drives set-id 1 6` with +only that drive on the bus), add it to `fitted_drives`, delete its joint from +`locked_joints`, restart the station and zero. Its joint then has a checkbox like the +others. A drive that isn't wired is left out of `fitted_drives` and its joints are locked, as +the shoulder's were before it was wired: `locked_joints: {joint_2: 0.0, tool_grip: 0.0}`. Without the panel, from a terminal: diff --git a/scripts/windows-arm.ps1 b/scripts/windows-arm.ps1 index b30db357..5c863a09 100644 --- a/scripts/windows-arm.ps1 +++ b/scripts/windows-arm.ps1 @@ -89,6 +89,8 @@ try { Push-Location $root try { Write-Host 'Starting the ground station; press Ctrl+C here to stop.' + Write-Host ('When RViz opens, follow its Arm setup panel: put the arm in its zero pose, ' + + 'press Zero the arm, then press Start (Menu) on the controller. Close RViz to stop.') & $docker compose run --rm --build --service-ports wslg-arm } finally { Pop-Location From 96e9d7713118fe3c50ceaeb268b6849944367935 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:39:04 -0600 Subject: [PATCH 28/31] Look for the carrier's COM port each time the relay opens it The relay chose the Arduino's COM port once and exited when none was listed, so a carrier that was still enumerating, or that came back under another COM number after a replug, was never found. It now looks again on every open and waits, saying what it sees. The launcher waits up to a minute for it instead of 15 seconds. --- docs/operator_guide.md | 9 +- scripts/windows-arm.ps1 | 5 +- waybionic_teleop/test/test_carrier_relay.py | 100 ++++++++++++++++++ .../waybionic_teleop/carrier_relay.py | 49 ++++++--- 4 files changed, 144 insertions(+), 19 deletions(-) diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 94680387..7c04ca96 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -455,10 +455,11 @@ ground station first, so each drive gets its stop, then the bridges. let each command finish before the next. If `docker` is not recognized, see [its troubleshooting](../BuildInstructions.md#docker-is-not-recognized-on-windows). -1. Start the bridge in its own PowerShell window and leave it running. It finds the - carrier as the only Arduino COM port; otherwise pass `--port COM5`. Wait for - `Carrier open; waiting for the ground station`: the drive node stops at start-up if - nothing is listening. +1. Start the bridge in its own PowerShell window and leave it running. It looks for the + Arduino's COM port each time it opens the carrier, so plugging the carrier in after it + starts, or replugging it under another COM number, is fine; with several Arduinos plugged + in, pass `--port COM5`. Wait for `Carrier open; waiting for the ground station`: the + drive node stops at start-up if nothing is listening. ```powershell cd waybionic_teleop diff --git a/scripts/windows-arm.ps1 b/scripts/windows-arm.ps1 index 5c863a09..23b64d4e 100644 --- a/scripts/windows-arm.ps1 +++ b/scripts/windows-arm.ps1 @@ -70,8 +70,9 @@ try { $carrier = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop ` -ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.carrier_relay')) - Write-Host 'Waiting for the carrier...' - $deadline = (Get-Date).AddSeconds(15) + Write-Host ('Waiting for the carrier (up to a minute): plug it in if you have not; the ' + + 'bridge window says what it sees...') + $deadline = (Get-Date).AddSeconds(60) do { Start-Sleep -Milliseconds 500 $listening = Get-NetTCPConnection -LocalPort $carrierPort -State Listen ` diff --git a/waybionic_teleop/test/test_carrier_relay.py b/waybionic_teleop/test/test_carrier_relay.py index 5a20790a..d812def1 100644 --- a/waybionic_teleop/test/test_carrier_relay.py +++ b/waybionic_teleop/test/test_carrier_relay.py @@ -1,5 +1,7 @@ import socket import threading +import time +from types import SimpleNamespace import pytest import serial @@ -110,3 +112,101 @@ def test_port_in_use_exits_with_a_message(): carrier_relay.serve(loop_carrier, '127.0.0.1', tcp_port, stop, lambda message: None) finally: taken.close() + + +class ComPorts: + """The COM ports Windows lists, which a test changes as the carrier is plugged in.""" + + def __init__(self, *devices): + self.devices, self.opened = list(devices), [] + + def arduino(self, device): + return SimpleNamespace(device=device, vid=carrier_relay.ARDUINO_VID) + + def listed(self): + return [self.arduino(device) if device.startswith('COM') else + SimpleNamespace(device=device, vid=0x1A86) for device in self.devices] + + def open_serial(self, name, baudrate, timeout): + self.opened.append((name, baudrate)) + return name + + +def opener(ports, port=None): + return carrier_relay.carrier_opener( + port, 1000000, open_serial=ports.open_serial, list_com_ports=ports.listed, + log=lambda message: None) + + +def test_a_carrier_plugged_in_after_the_relay_started_is_found(): + ports = ComPorts() + open_carrier = opener(ports) + with pytest.raises(serial.SerialException, match='no Arduino COM port found.*plug in'): + open_carrier() + ports.devices.append('COM5') + assert open_carrier() == 'COM5' + assert ports.opened == [('COM5', 1000000)] + + +def test_a_replugged_carrier_is_found_under_its_new_com_number(): + ports = ComPorts('COM5') + open_carrier = opener(ports) + assert open_carrier() == 'COM5' + ports.devices[:] = ['COM7'] + assert open_carrier() == 'COM7' + + +def test_other_serial_devices_are_not_mistaken_for_the_carrier(): + ports = ComPorts('/dev/ttyUSB0') + with pytest.raises(serial.SerialException, match='no Arduino COM port found'): + opener(ports)() + assert ports.opened == [] + + +def test_the_relay_does_not_guess_between_several_arduinos(): + ports = ComPorts('COM3', 'COM5') + with pytest.raises(serial.SerialException, match=r'COM3, COM5.*--port'): + opener(ports)() + assert ports.opened == [] + + +def test_a_port_that_is_given_is_opened_without_looking_for_it(): + ports = ComPorts() + assert opener(ports, port='COM9')() == 'COM9' + + +def test_the_relay_starts_listening_once_the_carrier_is_plugged_in(): + probe = socket.create_server(('127.0.0.1', 0)) + tcp_port = probe.getsockname()[1] + probe.close() + ports = ComPorts() + messages, stop = [], threading.Event() + opener_with_loop = carrier_relay.carrier_opener( + None, 1000000, open_serial=lambda name, baudrate, timeout: loop_carrier(), + list_com_ports=ports.listed, log=messages.append) + thread = threading.Thread( + target=carrier_relay.serve, daemon=True, + args=(opener_with_loop, '127.0.0.1', tcp_port, stop, messages.append)) + thread.start() + try: + time.sleep(0.2) + with pytest.raises(OSError): + socket.create_connection(('127.0.0.1', tcp_port), timeout=0.5) + assert any('plug in the carrier' in message for message in messages) + ports.devices.append('COM5') + deadline = time.monotonic() + 4.0 + while True: + try: + client = socket.create_connection(('127.0.0.1', tcp_port), timeout=0.5) + break + except OSError: + assert time.monotonic() < deadline, 'the relay never listened' + time.sleep(0.05) + client.settimeout(2.0) + client.sendall(b't00121234\r') + assert client.recv(64) == b't00121234\r' + client.close() + assert 'Carrier on COM5' in messages + finally: + stop.set() + thread.join(3.0) diff --git a/waybionic_teleop/waybionic_teleop/carrier_relay.py b/waybionic_teleop/waybionic_teleop/carrier_relay.py index ae7664be..e458fb06 100644 --- a/waybionic_teleop/waybionic_teleop/carrier_relay.py +++ b/waybionic_teleop/waybionic_teleop/carrier_relay.py @@ -8,7 +8,11 @@ exactly as it does when the USB cable is pulled on a Mac or Linux. Needs pyserial. Run from the waybionic_teleop directory: - python -m waybionic_teleop.carrier_relay --port COM5 + python -m waybionic_teleop.carrier_relay + +It looks for the Arduino's COM port each time it opens the carrier, so a carrier plugged in +after it starts, or replugged under another COM number, is found. With several Arduinos plugged +in, name the carrier's: --port COM5. """ import argparse @@ -27,10 +31,33 @@ CHUNK = 4096 -def find_carrier(): - """Return the only Arduino COM port, or None if there are none or several.""" - ports = [info.device for info in list_ports.comports() if info.vid == ARDUINO_VID] - return ports[0] if len(ports) == 1 else None +def carrier_opener(port, baudrate, open_serial=serial.Serial, list_com_ports=list_ports.comports, + log=print): + """ + Return the open_port that serve() calls whenever it needs the carrier. + + With no port it looks for the only Arduino COM port every time, because the carrier may be + plugged in after the relay starts, still be enumerating, or come back under another COM + number. It never guesses between several Arduinos. + """ + def open_carrier(): + name = port + if name is None: + infos = list_com_ports() + arduinos = sorted(info.device for info in infos if info.vid == ARDUINO_VID) + if not arduinos: + listed = ', '.join(sorted(info.device for info in infos)) or 'none' + raise serial.SerialException( + f'no Arduino COM port found (COM ports: {listed}); plug in the carrier') + if len(arduinos) > 1: + raise serial.SerialException( + f'several Arduino COM ports ({", ".join(arduinos)}); plug in only the ' + 'carrier, or pass --port') + name = arduinos[0] + link = open_serial(name, baudrate, timeout=POLL_S) + log(f'Carrier on {name}') + return link + return open_carrier def relay(link, client, stop): @@ -172,22 +199,18 @@ def serve(open_port, bind, tcp_port, stop, log=print): def main(): parser = argparse.ArgumentParser(description='Relay the carrier COM port to the arm.') parser.add_argument('--port', - help='carrier COM port, such as COM5 (default: the only Arduino)') + help='carrier COM port, such as COM5 (default: the only Arduino, ' + 'looked for again whenever the carrier is opened)') parser.add_argument('--baudrate', type=int, default=DEFAULT_BAUDRATE) parser.add_argument('--bind', default='127.0.0.1', help='listen address; keep it local, this drives the arm') parser.add_argument('--tcp-port', type=int, default=DEFAULT_TCP_PORT) args = parser.parse_args() - port = args.port or find_carrier() - if port is None: - found = ', '.join(info.device for info in list_ports.comports()) or 'none' - raise SystemExit(f'Plug in only the carrier, or pass --port. COM ports found: {found}') - print(f'Relaying {port} to {args.bind}:{args.tcp_port} (Ctrl+C to stop)') + print(f'Relaying the carrier to {args.bind}:{args.tcp_port} (Ctrl+C to stop)') print(f'Ground station: drive_channel:=socket://host.docker.internal:{args.tcp_port}') stop = threading.Event() try: - serve(lambda: serial.Serial(port, args.baudrate, timeout=POLL_S), - args.bind, args.tcp_port, stop) + serve(carrier_opener(args.port, args.baudrate), args.bind, args.tcp_port, stop) except KeyboardInterrupt: pass finally: From d439c11588705f067107c44f9f7e97dc945e9963 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:34:19 -0600 Subject: [PATCH 29/31] Close the setup panel when the arm is ready and reopen it for a problem Once every step is done and the arm has stayed ready for four seconds the panel closes its dock, so the other panels get the room, and it opens again when a step before Ready is to do or blocked, or the drives stopped the arm. A step that is only being checked, and teleop merely being stopped, change nothing. The policy is Qt-free and tested without a display, and it was watched in a real RViz window: shown while Start is waiting, hidden seven seconds after Start, shown again when the controller was unplugged and hidden again after Start. When no guide is running the panel now says why (the plain viewer never starts one) instead of waiting for it forever, and the panel asks for the height its wrapped instructions need, because a long one was squeezed over the row below it. --- docs/operator_guide.md | 15 +- .../waybionic_rviz_plugins/setup_model.hpp | 50 +++++++ .../waybionic_rviz_plugins/setup_panel.hpp | 17 +++ waybionic_rviz_plugins/src/setup_model.cpp | 59 ++++++++ waybionic_rviz_plugins/src/setup_panel.cpp | 78 +++++++++- .../test/test_setup_model.cpp | 138 ++++++++++++++++++ 6 files changed, 352 insertions(+), 5 deletions(-) diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 7c04ca96..53b87e43 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -594,9 +594,18 @@ same diagnostics the station already publishes, and also says each change in the | Zero | every drive that is switched on is zeroed or kept its saved zero | put the arm in its zero pose and press **Zero the arm** (it asks you to confirm) | | Ready | teleop is enabled | press Start (the Menu button) on the controller | -The controller needs no other step: the guide shows it as connected once input arrives. When -every step is done the panel shrinks to one line. If the guide itself is not running, the panel -says it is waiting for it. Nothing in the panel moves the arm. +The controller needs no other step: the guide shows it as connected once input arrives. Once +every step is done, including Start, and the arm has stayed ready for four seconds, the panel +closes so the other panels get its room. It opens again when something needs you: a step +before Ready is to do or blocked, such as the controller dropping out, a drive losing its zero +or the carrier being unplugged, or Ready is blocked because the drives stopped the arm. A step +that is only being checked does not open it, and neither does stopping teleop (B or Start), +which leaves only Start to press. The panel's close button, or Panels > SetupPanel, shows or +hides it by hand, and it is not hidden again until the arm next becomes ready. + +If the guide itself is not running, the panel says so. A station started without the arm, such +as the plain `wslg` viewer, has no guide: the arm launchers (`scripts\windows-arm.cmd`, +`./scripts/macos.sh arm`) start it with `teleop:=true`. Nothing in the panel moves the arm. ### Switching joints off diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp index 133dc4e0..472f971c 100644 --- a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp @@ -20,6 +20,9 @@ constexpr const char * kZeroServiceName = "/sim_arm_drives/zero"; /// setup_guide publishes every 0.5 s, so this long without a message means it is gone. constexpr std::chrono::milliseconds kSetupGuideQuietAfter{3000}; +/// How long the arm has to stay ready before the setup panel puts itself away. +constexpr std::chrono::milliseconds kSetupHideAfter{4000}; + enum class StepState { Ok, @@ -55,6 +58,10 @@ struct SetupSnapshot /// True when there is at least one step and every one is done. bool ready() const; + /// True when the operator has something to do or fix: a step is blocked, or a step before + /// Ready is still to do. A step that is only being checked does not count, and neither does + /// Ready being to do, which is teleop stopped with only Start left to press. + bool needsAttention() const; /// The step marked current, or nullptr once everything is done. const SetupStep * currentStep() const; }; @@ -72,6 +79,49 @@ bool setupGuideQuiet( const std::optional & last_message, std::chrono::steady_clock::time_point now); +/// What the panel says while it has no report to show. `seen_guide` is whether a valid report +/// has ever arrived, and `guide_quiet` is setupGuideQuiet(). +std::string setupWaitingMessage(bool seen_guide, bool guide_quiet); + +/// What the setup panel's dock is to do about its own visibility. +enum class DockAction +{ + None, + Show, + Hide +}; + +/// How the latest setup report bears on the dock. +enum class SetupDockInput +{ + /// Nothing to act on: no report yet, a step being checked, or only Start left to press. + Waiting, + /// The operator has something to do or fix; see SetupSnapshot::needsAttention. + NeedsAttention, + /// Every step is done. + Ready +}; + +/// Puts the setup panel away once the arm has stayed ready for a while, and brings it back when +/// something needs the operator, so it takes room only while it is useful. It acts on changes +/// only: it shows the panel once when a problem appears, so that closing the panel by hand sticks +/// until the next one, and hides it once per ready period, so that a panel opened by hand while +/// ready stays open. A report that is neither (a step being checked, or only Start left) changes +/// nothing, except that it ends the ready period. +class SetupDockPolicy +{ +public: + explicit SetupDockPolicy(std::chrono::steady_clock::duration hide_after = kSetupHideAfter); + + DockAction update(SetupDockInput input, std::chrono::steady_clock::time_point now); + +private: + std::chrono::steady_clock::duration hide_after_; + SetupDockInput last_{SetupDockInput::Waiting}; + std::chrono::steady_clock::time_point ready_since_; + bool hidden_{false}; +}; + } // namespace waybionic_rviz_plugins #endif // WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp index 6c3ffb2d..471acd45 100644 --- a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp @@ -19,9 +19,11 @@ #include "waybionic_rviz_plugins/setup_model.hpp" +class QDockWidget; class QLabel; class QGridLayout; class QPushButton; +class QResizeEvent; class QTimer; class QWidget; @@ -37,6 +39,10 @@ struct SetupMailbox; /// it: that calls the drive node's own zero service after the operator confirms the arm is in /// its zero pose. It never publishes anything, and never moves the arm. /// +/// Once the arm has stayed ready for a few seconds the panel closes its dock, so the other +/// panels get the room, and it opens again when something needs the operator, such as the +/// controller dropping out or a drive losing its zero. The Panels menu opens it by hand. +/// /// Threading: ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer drains it, /// so all widget and bookkeeping state is touched by the Qt thread alone and no service call /// ever blocks it. @@ -54,6 +60,9 @@ class SetupPanel : public rviz_common::Panel /// calls this with RViz's node. Calling it again replaces the connection. void connectToNode(rclcpp::Node::SharedPtr node); +protected: + void resizeEvent(QResizeEvent * event) override; + private: using Trigger = std_srvs::srv::Trigger; using TriggerClient = rclcpp::Client; @@ -84,6 +93,10 @@ class SetupPanel : public rviz_common::Panel void requestZero(); void showStatus(const QString & text, bool success); void render(); + void fitHeight(); + QDockWidget * dock() const; + SetupDockInput dockInput(bool quiet) const; + void applyDockAction(DockAction action); bool zeroOffered() const; @@ -95,7 +108,11 @@ class SetupPanel : public rviz_common::Panel // The last valid message, kept only while the guide keeps talking. SetupSnapshot snapshot_; bool has_snapshot_{false}; + // True once a valid report has arrived, so that a guide that has gone quiet is told from one + // that has not started yet. + bool seen_guide_{false}; std::optional last_message_; + SetupDockPolicy dock_policy_; std::optional pending_zero_; std::uint64_t next_token_{0}; diff --git a/waybionic_rviz_plugins/src/setup_model.cpp b/waybionic_rviz_plugins/src/setup_model.cpp index 0efcc6c2..fd4083d3 100644 --- a/waybionic_rviz_plugins/src/setup_model.cpp +++ b/waybionic_rviz_plugins/src/setup_model.cpp @@ -15,6 +15,8 @@ namespace constexpr const char * kPrefix = "setup."; constexpr const char * kKnownSteps[] = {"carrier", "drives", "controller", "zero", "ready"}; +// The last step: it is to do while teleop is stopped, which is not a fault. +constexpr const char * kReadyStep = "ready"; std::size_t displayOrder(const std::string & name) { @@ -152,6 +154,17 @@ const SetupStep * SetupSnapshot::currentStep() const return found == steps.end() ? nullptr : &*found; } +bool SetupSnapshot::needsAttention() const +{ + return valid && std::any_of( + steps.begin(), steps.end(), [](const SetupStep & step) { + if (step.state == StepState::Blocked) { + return true; + } + return step.state == StepState::Todo && step.name != kReadyStep; + }); +} + SetupSnapshot parseSetup(const diagnostic_msgs::msg::DiagnosticArray & array) { SetupSnapshot snapshot; @@ -218,4 +231,50 @@ bool setupGuideQuiet( return !last_message.has_value() || now - *last_message >= kSetupGuideQuietAfter; } +std::string setupWaitingMessage(const bool seen_guide, const bool guide_quiet) +{ + if (!guide_quiet) { + return "Waiting for a valid setup report..."; + } + if (seen_guide) { + return "The setup guide (setup_guide) has stopped reporting."; + } + return "Waiting for the setup guide. It runs when the station is started for the arm " + "(teleop:=true), as windows-arm.cmd and ./scripts/macos.sh arm do."; +} + +SetupDockPolicy::SetupDockPolicy(const std::chrono::steady_clock::duration hide_after) +: hide_after_(hide_after) +{ +} + +DockAction SetupDockPolicy::update( + const SetupDockInput input, const std::chrono::steady_clock::time_point now) +{ + DockAction action = DockAction::None; + switch (input) { + case SetupDockInput::NeedsAttention: + if (last_ != SetupDockInput::NeedsAttention) { + action = DockAction::Show; + } + hidden_ = false; + break; + case SetupDockInput::Ready: + if (last_ != SetupDockInput::Ready) { + ready_since_ = now; + hidden_ = false; + } + if (!hidden_ && now - ready_since_ >= hide_after_) { + action = DockAction::Hide; + hidden_ = true; + } + break; + case SetupDockInput::Waiting: + hidden_ = false; + break; + } + last_ = input; + return action; +} + } // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/setup_panel.cpp b/waybionic_rviz_plugins/src/setup_panel.cpp index fa103cbb..1d48c21c 100644 --- a/waybionic_rviz_plugins/src/setup_panel.cpp +++ b/waybionic_rviz_plugins/src/setup_panel.cpp @@ -6,10 +6,12 @@ #include #include +#include #include #include #include #include +#include #include #include #include @@ -24,6 +26,8 @@ namespace { constexpr int kPollIntervalMs = 100; +// The most height the panel asks of its dock for its text; a dock that is shorter scrolls it. +constexpr int kMaxFittedHeight = 420; // The drive node waits up to half a second for the drives' replies before it answers. constexpr std::chrono::seconds kZeroTimeout{10}; constexpr std::chrono::seconds kStatusLifetime{10}; @@ -158,8 +162,10 @@ void SetupPanel::disconnectFromNode() zero_client_.reset(); node_.reset(); has_snapshot_ = false; + seen_guide_ = false; snapshot_ = SetupSnapshot{}; last_message_.reset(); + dock_policy_ = SetupDockPolicy(); } void SetupPanel::buildUi() @@ -275,6 +281,7 @@ void SetupPanel::applySnapshot(SetupSnapshot snapshot) } snapshot_ = std::move(snapshot); has_snapshot_ = true; + seen_guide_ = true; } void SetupPanel::expirePendingZero(const std::chrono::steady_clock::time_point now) @@ -337,17 +344,82 @@ void SetupPanel::showStatus(const QString & text, const bool success) status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; } +SetupDockInput SetupPanel::dockInput(const bool quiet) const +{ + if (quiet) { + // A guide that was there and has gone is a fault; one that has not started yet is not. + return seen_guide_ ? SetupDockInput::NeedsAttention : SetupDockInput::Waiting; + } + if (!has_snapshot_) { + return SetupDockInput::Waiting; + } + if (snapshot_.needsAttention()) { + return SetupDockInput::NeedsAttention; + } + return snapshot_.ready() ? SetupDockInput::Ready : SetupDockInput::Waiting; +} + +QDockWidget * SetupPanel::dock() const +{ + // The dock may hold the panel through a scroll area. + for (QWidget * widget = parentWidget(); widget != nullptr; widget = widget->parentWidget()) { + if (auto * found = qobject_cast(widget)) { + return found; + } + } + return nullptr; +} + +void SetupPanel::applyDockAction(const DockAction action) +{ + // RViz keeps every panel in a dock of its own. Hiding it is what the dock's close button does, + // and the Panels menu shows it again. + auto * panel_dock = dock(); + if (panel_dock == nullptr || action == DockAction::None) { + return; + } + if (action == DockAction::Hide) { + panel_dock->hide(); + } else { + panel_dock->show(); + panel_dock->raise(); + } +} + +void SetupPanel::resizeEvent(QResizeEvent * event) +{ + rviz_common::Panel::resizeEvent(event); + fitHeight(); +} + +// A word-wrapped label reports a one-line minimum height, and a dock gives its panel no height +// for its width, so a long message was squeezed over the row below it. Asking for the height the +// layout needs at this width keeps the text readable: a dock or scroll area that is shorter +// scrolls the panel instead. +void SetupPanel::fitHeight() +{ + // Before the dock has laid the panel out it is far narrower than it will be, so the height it + // would need there is meaningless, and as a minimum it would stop the window from maximizing. + if (layout() == nullptr || width() < minimumWidth()) { + return; + } + const int needed = std::min(layout()->totalHeightForWidth(width()), kMaxFittedHeight); + if (needed > 0 && needed != minimumHeight()) { + setMinimumHeight(needed); + } +} + void SetupPanel::render() { const auto now = std::chrono::steady_clock::now(); const bool quiet = setupGuideQuiet(last_message_, now); const bool shown = has_snapshot_ && !quiet; const bool ready = shown && snapshot_.ready(); + applyDockAction(dock_policy_.update(dockInput(quiet), now)); if (!shown) { summary_label_->setObjectName("Muted"); - summary_label_->setText( - quiet ? "Waiting for the setup guide (setup_guide)..." : "Waiting for a valid setup report..."); + summary_label_->setText(QString::fromStdString(setupWaitingMessage(seen_guide_, quiet))); } else if (ready) { summary_label_->setObjectName("Ready"); summary_label_->setText(QString::fromUtf8("\xE2\x9C\x93 Ready: the arm can be operated")); @@ -389,6 +461,8 @@ void SetupPanel::render() zero_button_->setEnabled(offered && !pending_zero_.has_value()); zero_button_->setText(pending_zero_.has_value() ? "Zeroing..." : "Zero the arm"); + fitHeight(); + if (now < status_expires_) { status_label_->setStyleSheet( status_success_ ? "color: #3ddc84; font-weight: 700;" : "color: #ffb84d; font-weight: 700;"); diff --git a/waybionic_rviz_plugins/test/test_setup_model.cpp b/waybionic_rviz_plugins/test/test_setup_model.cpp index d8436292..c59d3fcd 100644 --- a/waybionic_rviz_plugins/test/test_setup_model.cpp +++ b/waybionic_rviz_plugins/test/test_setup_model.cpp @@ -2,6 +2,7 @@ // messages, so no setup_guide node or ROS graph is needed. #include +#include #include #include #include @@ -245,6 +246,143 @@ TEST(SetupModel, TheGuideIsQuietFromThreeSecondsWithoutAMessage) EXPECT_FALSE(setupGuideQuiet(now + 1s, now)); } +namespace +{ + +// The array with one step replaced, as when the controller drops out of a ready arm. +DiagnosticArray withStep( + DiagnosticArray array, const std::size_t index, const DiagnosticStatus & step) +{ + array.status[index] = step; + return array; +} + +// Seconds after an arbitrary start, on the clock the panel uses. +std::chrono::steady_clock::time_point at(const int seconds) +{ + return std::chrono::steady_clock::time_point{} + std::chrono::hours(1) + + std::chrono::seconds(seconds); +} + +} // namespace + +TEST(SetupModel, ASetupStepBeforeReadyThatIsNotDoneNeedsTheOperator) +{ + EXPECT_TRUE(parseSetup(zeroingArray()).needsAttention()); + EXPECT_FALSE(parseSetup(readyArray()).needsAttention()); + EXPECT_FALSE(parseSetup(DiagnosticArray()).needsAttention()); + + const auto no_controller = withStep( + readyArray(), 2, + makeStep("setup.controller", "Controller", "todo", "Connect an Xbox controller")); + EXPECT_TRUE(parseSetup(no_controller).needsAttention()); + + const auto no_answer = withStep( + readyArray(), 1, makeStep("setup.drives", "Drives", "blocked", "No answer from elbow")); + EXPECT_TRUE(parseSetup(no_answer).needsAttention()); +} + +TEST(SetupModel, AStepBeingCheckedDoesNotNeedTheOperatorYet) +{ + const auto checking = withStep( + readyArray(), 1, makeStep("setup.drives", "Drives", "working", "Checking the drives...")); + EXPECT_FALSE(parseSetup(checking).needsAttention()); +} + +TEST(SetupModel, TeleopThatIsOnlyStoppedLeavesThePanelAlone) +{ + const auto paused = withStep( + readyArray(), 4, + makeStep("setup.ready", "Ready", "todo", "Press Start (the Menu button) on the controller")); + EXPECT_FALSE(parseSetup(paused).needsAttention()); + EXPECT_FALSE(parseSetup(paused).ready()); + + const auto stopped_by_a_fault = withStep( + readyArray(), 4, + makeStep("setup.ready", "Ready", "blocked", "DRIVES-STOPPED: following error")); + EXPECT_TRUE(parseSetup(stopped_by_a_fault).needsAttention()); +} + +TEST(SetupDock, ShowsOnceWhenSomethingNeedsTheOperator) +{ + SetupDockPolicy policy(4s); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(0))); + EXPECT_EQ(DockAction::Show, policy.update(SetupDockInput::NeedsAttention, at(1))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::NeedsAttention, at(2))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::NeedsAttention, at(60))); +} + +TEST(SetupDock, HidesOnceAfterTheArmHasBeenReadyForTheDelay) +{ + SetupDockPolicy policy(4s); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(0))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // Opened again by hand while ready, it stays open. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(5))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(600))); +} + +TEST(SetupDock, ANewProblemShowsItAgainAndReadyHidesItAgain) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + ASSERT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // The controller drops out and comes back, straight from ready to a problem and back. + EXPECT_EQ(DockAction::Show, policy.update(SetupDockInput::NeedsAttention, at(10))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(12))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(15))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(16))); +} + +TEST(SetupDock, AStepBeingCheckedRestartsTheCountdown) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(3))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(4))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(7))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(8))); +} + +TEST(SetupDock, PausingTeleopNeitherShowsNorHidesThePanel) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + ASSERT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // B stops teleop: only Start is left to press. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(10))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(100))); + // Start again: a new ready period, so it is hidden again after the delay. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(101))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(105))); +} + +TEST(SetupDock, TheDefaultDelayIsFourSeconds) +{ + EXPECT_EQ(std::chrono::milliseconds(4000), kSetupHideAfter); + SetupDockPolicy policy; + policy.update(SetupDockInput::Ready, at(0)); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); +} + +TEST(SetupModel, SaysWhyThereIsNoSetupGuide) +{ + // A station started without the arm, such as the plain viewer, never runs the guide. + const auto never = setupWaitingMessage(false, true); + EXPECT_NE(std::string::npos, never.find("teleop:=true")); + EXPECT_NE(std::string::npos, never.find("windows-arm")); + EXPECT_NE(std::string::npos, never.find("macos.sh arm")); + // One that was running and has gone is a fault, not a missing launch option. + const auto gone = setupWaitingMessage(true, true); + EXPECT_NE(std::string::npos, gone.find("stopped")); + EXPECT_EQ(std::string::npos, gone.find("teleop:=true")); + // Reports that arrive but are all malformed. + EXPECT_NE(std::string::npos, setupWaitingMessage(false, false).find("valid setup report")); +} + TEST(SetupModel, TheZeroServiceIsTheDriveNodes) { EXPECT_STREQ("/sim_arm_drives/zero", kZeroServiceName); From b2208aafd4028966c050706e8674fa34af4b2791 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:34:19 -0600 Subject: [PATCH 30/31] Keep the right-hand panels inside the screen The setup, joint control and diagnostics panels together asked for more height than a laptop screen has, so RViz opened 1315 points tall on a 949 point screen with its bottom cut off. The joint control and diagnostics panels now scroll in their docks, and the setup panel, which has to be readable while it is open, asks for exactly the height its text needs. RViz now opens 1512 by 949 on that screen. --- waybionic_rviz_plugins/README.md | 8 ++++- .../src/ground_station_rviz.cpp | 29 ++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index aac97720..41fcd0fb 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -38,6 +38,9 @@ colcon test-result --verbose Both panels are in the ground station's right-hand dock, above the diagnostics panel (`ground_station_rviz` stacks them; a plain `rviz2` leaves them wherever the layout puts them). +It also puts the joint control and diagnostics panels in scroll areas, so that the three together +do not make the window taller than a laptop screen; the setup panel asks for the height its text +needs and does not scroll. **Arm setup** (`waybionic_rviz_plugins/SetupPanel`) lists the start-up steps the `setup_guide` node publishes on the latched `/arm/setup` topic (a DiagnosticArray of `setup.` rows: @@ -45,7 +48,10 @@ carrier, drives, controller, zero, ready). Each row's message is what to do next are `title`, `state` (`ok`, `todo`, `blocked` or `working`), `action` (`zero` or empty) and `current`. When the guide asks for a zero, the panel offers a Zero button; after the operator confirms the arm is in its zero pose it calls the drive node's `/sim_arm_drives/zero` -(`std_srvs/Trigger`) and shows the answer. Once every step is done the panel shrinks to one line. +(`std_srvs/Trigger`) and shows the answer. Once every step is done the panel shrinks to one line, +and four seconds later (`kSetupHideAfter`) it closes its dock; `SetupDockPolicy` opens it again, once, +when a step before ready needs the operator (`SetupSnapshot::needsAttention`) and again hides it once +the arm is next ready. Teleop merely being stopped changes nothing. **Joint control** (`waybionic_rviz_plugins/JointControlPanel`) shows a checkbox per joint, J1 to J5 and the tool. It reads the latched `/arm/joint_control` topic (a DiagnosticArray with diff --git a/waybionic_rviz_plugins/src/ground_station_rviz.cpp b/waybionic_rviz_plugins/src/ground_station_rviz.cpp index db521c47..6b3de6c1 100644 --- a/waybionic_rviz_plugins/src/ground_station_rviz.cpp +++ b/waybionic_rviz_plugins/src/ground_station_rviz.cpp @@ -7,8 +7,10 @@ #include #include #include +#include #include #include +#include #include #include "rclcpp/rclcpp.hpp" @@ -20,21 +22,46 @@ namespace { +// A panel asks for the height of everything in it. The three stacked below ask for more than a +// laptop screen has between them, which made the window taller than the screen and cut off its +// bottom. In a scroll area a dock can be shorter than its panel, and the panel scrolls. +void scrollInDock(QDockWidget * dock) +{ + QWidget * panel = dock->widget(); + if (panel == nullptr || qobject_cast(panel) != nullptr) { + return; + } + auto * scroll = new QScrollArea(); + scroll->setFrameShape(QFrame::NoFrame); + scroll->setWidgetResizable(true); + // Giving the dock another widget hides the panel, so put it in the scroll area and show it. + dock->setWidget(scroll); + scroll->setWidget(panel); + panel->show(); +} + // The station's own panels, from the top of the right-hand dock down, with the share of its // height each gets. RViz puts a panel its saved window state does not know in the left dock, so // they are stacked here whatever the layout file says. Panels that are not loaded are skipped. +// The setup panel never scrolls: it asks for exactly the height its text needs, and it is the +// one the operator has to read while it is open. void stackRightDock(QMainWindow * frame) { struct Entry { const char * name; int weight; + bool scrolls; }; - const Entry order[] = {{"SetupPanel", 2}, {"JointControlPanel", 2}, {"DiagnosticsPanel", 5}}; + const Entry order[] = { + {"SetupPanel", 2, false}, {"JointControlPanel", 2, true}, {"DiagnosticsPanel", 5, true}}; QList docks; QList weights; for (const auto & entry : order) { if (auto * dock = frame->findChild(QString::fromLatin1(entry.name))) { + if (entry.scrolls) { + scrollInDock(dock); + } docks.append(dock); weights.append(entry.weight); } From a3800b29ed7b8c636a0ee871877c1e08ac9f15a6 Mon Sep 17 00:00:00 2001 From: Yassin Soliman <108886216+yassinsolim@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:37:28 -0600 Subject: [PATCH 31/31] Say what a drive's health check found in the setup guide A drive whose health check fails (following error, stalled, disabled) has an error row whose message only carries the move status, so the guide said 'Drive fault: base_yaw (run complete; ...)' with no reason, the kind of unexplained alarm that sent a bring-up chasing wiring. It now names the check and how far off the target the drive is. --- docs/operator_guide.md | 2 +- waybionic_teleop/test/test_setup_guide.py | 26 +++++++++++++++++++ .../waybionic_teleop/setup_guide.py | 19 +++++++++++++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 53b87e43..14fa9e08 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -589,7 +589,7 @@ same diagnostics the station already publishes, and also says each change in the | Step | Done when | If it isn't | | --- | --- | --- | | Carrier | the carrier reports on USB and its E-stop is not pressed | plug in its USB-C cable; if it is plugged in but silent, replug it or flash it | -| Drives | every drive that is switched on answers | the panel names the drive and its CAN ID: check its power and wiring, or switch its joint off (below) | +| Drives | every drive that is switched on answers and passes its health check | the panel names the drive and what is wrong: no answer (with its CAN ID, so check its power and wiring, or switch its joint off, below), a failed move, or the health check, such as `following error: 6.3 deg off its target` | | Controller | `/joy` input is arriving | connect an Xbox controller (USB or Bluetooth) and press a button | | Zero | every drive that is switched on is zeroed or kept its saved zero | put the arm in its zero pose and press **Zero the arm** (it asks you to confirm) | | Ready | teleop is enabled | press Start (the Menu button) on the controller | diff --git a/waybionic_teleop/test/test_setup_guide.py b/waybionic_teleop/test/test_setup_guide.py index 514d7ef7..786a69d6 100644 --- a/waybionic_teleop/test/test_setup_guide.py +++ b/waybionic_teleop/test/test_setup_guide.py @@ -127,6 +127,32 @@ def test_a_drive_that_reports_a_fault_blocks_with_its_state(): assert found.state == BLOCKED and 'base_yaw' in found.message and 'run failed' in found.message +def test_a_drive_that_fails_its_health_check_says_what_it_found(): + # The drive node raises the row's level for its health state but its message only has the + # move status, so the guide has to say what the health check found. + behind = row('drive.base_yaw', ERROR, 'CAN ID 1: run complete; last 001#F5000000000000F6', + '0.000', can_id=1, state='FOLLOWING_ERROR', target_encoder_error_deg='-6.300') + found = step(ready_rows(**{'drive.base_yaw': behind}), 'drives') + assert found.state == BLOCKED + assert 'base_yaw (following error: 6.3 deg off its target)' in found.message + assert 'run complete' not in found.message + + stalled = row('drive.elbow', ERROR, 'CAN ID 3: running', '0.000', can_id=3, state='STALLED', + target_encoder_error_deg='2.000') + assert 'elbow (stalled: 2.0 deg off its target)' in step( + ready_rows(**{'drive.elbow': stalled}), 'drives').message + + disabled = row('drive.elbow', ERROR, 'CAN ID 3: ready', '0.000', can_id=3, state='DISABLED') + assert 'elbow (disabled)' in step(ready_rows(**{'drive.elbow': disabled}), 'drives').message + + +def test_a_drive_that_fails_its_move_keeps_its_own_status_when_it_is_healthy(): + failed = row('drive.base_yaw', ERROR, 'CAN ID 1: run failed', '0.000', can_id=1, state='OK', + target_encoder_error_deg='0.100') + assert 'base_yaw (run failed)' in step( + ready_rows(**{'drive.base_yaw': failed}), 'drives').message + + def test_drives_still_being_set_up_are_work_in_progress(): pending = drive('base_yaw', 1, 'ready, setup 82h unconfirmed', WARN) assert step(ready_rows(**{'drive.base_yaw': pending}), 'drives').state == WORKING diff --git a/waybionic_teleop/waybionic_teleop/setup_guide.py b/waybionic_teleop/waybionic_teleop/setup_guide.py index 2a86fa6a..c580c4a6 100644 --- a/waybionic_teleop/waybionic_teleop/setup_guide.py +++ b/waybionic_teleop/waybionic_teleop/setup_guide.py @@ -80,6 +80,23 @@ def carrier_step(rows): return Step('carrier', OK, 'Carrier connected') +def fault(name, row): + """Say why a drive's row is an error: its health check, or else its move status.""" + # The drive node raises the row's level for a failed health check, but its message only has + # the move status, such as "run complete", so the reason is in the row's state value. + health = value(row, 'state') + if health and health != 'OK': + text = health.lower().replace('_', ' ') + if health in ('FOLLOWING_ERROR', 'STALLED'): + try: + error = abs(float(value(row, 'target_encoder_error_deg'))) + text += f': {error:.1f} deg off its target' + except ValueError: + pass + return f'{name} ({text})' + return f'{name} ({row.message.split(": ", 1)[-1]})' + + def drives_step(rows): drives = {name[len('drive.'):]: row for name, row in rows.items() if name.startswith('drive.')} @@ -93,7 +110,7 @@ def drives_step(rows): return Step('drives', BLOCKED, f'No answer from {", ".join(missing)}: check its power and CAN wiring, or ' 'switch its joint off in Joint control') - failed = [f'{name} ({row.message.split(": ", 1)[-1]})' for name, row in on.items() + failed = [fault(name, row) for name, row in on.items() if row.level == DiagnosticStatus.ERROR] if failed: return Step('drives', BLOCKED, f'Drive fault: {", ".join(failed)}')