Skip to content

Commit 1935e04

Browse files
committed
Integrate published simulated-drive safety with Cartesian teleop
2 parents 6e3bafa + f7b7f64 commit 1935e04

11 files changed

Lines changed: 309 additions & 27 deletions

File tree

‎BuildInstructions.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,14 @@ CAN map is not a powered-arm safety case. Do not change a wrist bound or operate
331331
motors until Mechanical identifies the URDF joint and measures signed travel from upright
332332
zero, including any cable or gear stop.
333333

334+
In simulation, a zero-velocity joint command (including B and controller timeout)
335+
sends an MKS F5 frame with zero speed and zero acceleration to each moving drive.
336+
An out-of-range encoder target stops all drives instead of updating only part of
337+
the arm. The placeholder drive speed is capped at 300 RPM; the MKS manual warns
338+
against immediate software stops above 1000 RPM. This checks simulated behavior
339+
only. Do not connect powered drives or treat it as a hardware E-stop test; drive
340+
identities, wiring, zeroing and electrical safety still need hardware verification.
341+
334342
The RViz camera follows the tool as the arm moves; drag to orbit and scroll to zoom
335343
as usual, or add `follow_camera:=false` to the launch command for a fixed view.
336344

‎waybionic_bringup/scripts/camera_follower.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from geometry_msgs.msg import TransformStamped
77
import rclpy
8+
from rclpy._rclpy_pybind11 import RCLError
89
from rclpy.executors import ExternalShutdownException
910
from rclpy.node import Node
1011
from rclpy.time import Time
@@ -65,6 +66,16 @@ def main():
6566
rclpy.spin(node)
6667
except (KeyboardInterrupt, ExternalShutdownException):
6768
pass
69+
except RCLError as error:
70+
# SIGINT can shut down the context before spin recreates its wait set.
71+
if rclpy.ok() or 'the given context is not valid' not in str(error):
72+
raise
73+
except RuntimeError as error:
74+
# A TF subscription can surface this Jazzy binding error if its ROS context is
75+
# already invalidated during SIGINT. Other runtime errors must still fail.
76+
if (rclpy.ok() or not str(error).startswith(
77+
"Unable to convert call argument '0' to Python object")):
78+
raise
6879
finally:
6980
node.destroy_node()
7081
rclpy.try_shutdown()

‎waybionic_bringup/test/test_teleop_launch.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import rclpy
1717
from sensor_msgs.msg import JointState
1818

19-
from waybionic_teleop import gamepad
19+
from waybionic_teleop import gamepad, mks_can
2020

2121
PORT = 47391
2222

@@ -91,9 +91,18 @@ def hold(seconds, *pressed, **axes):
9191
self.assertGreater(joints['tool_grip'], 0.3)
9292
hold(0.2, 'b')
9393
pitch = joints['joint_4']
94-
hold(0.5, right_y=1.0)
94+
hold(0.75, right_y=1.0)
9595
self.assertAlmostEqual(joints['joint_4'], pitch, places=2, msg='moved after B')
9696
self.assertEqual(diagnostics['teleop.state'].values[0].value, 'disabled')
97+
for drive in ('base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right', 'tool'):
98+
values = {item.key: item.value for item in diagnostics[f'drive.{drive}'].values}
99+
can_id = int(values['can_id'])
100+
stop = mks_can.hex_frame(can_id, mks_can.absolute_axis(can_id, 0, 0, 0))
101+
self.assertEqual(values['last_command'], stop, f'{drive} did not stop')
102+
hold(0.2, 'start')
103+
hold(0.9, right_y=1.0)
104+
self.assertGreater(joints['joint_4'], pitch + 0.05, 'Start did not re-arm')
105+
self.assertEqual(diagnostics['teleop.state'].values[0].value, 'enabled')
97106
self.assertEqual(diagnostics['can.bus'].level, b'\x00')
98107
self.assertEqual(diagnostics['drive.wrist_left'].level, b'\x00')
99108
finally:

‎waybionic_teleop/test/test_mks_can.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
(mks_can.absolute_axis(1, 0x28000, 300, 2), 'F5012C02028000A7'),
1212
(mks_can.absolute_axis(1, 0x7F8000, 300, 2), 'F5012C027F800024'),
1313
(mks_can.absolute_axis(1, 0, 0, 4), 'F5000004000000FA'),
14+
(mks_can.absolute_axis(1, 0, 0, 0), 'F5000000000000F6'),
1415
(mks_can.read_encoder(1), '3132'),
1516
(mks_can.set_mode(1), '820588'),
1617
(mks_can.enable(1), 'F301F5'),
@@ -28,6 +29,14 @@ def test_encoder_reply_decodes_negative_values():
2829
assert mks_can.encoder_value(arguments) == -16
2930

3031

32+
@pytest.mark.parametrize('raw, expected', [
33+
('800000000000', -(1 << 47)),
34+
('7FFFFFFFFFFF', (1 << 47) - 1),
35+
])
36+
def test_encoder_reply_preserves_the_signed_int48_limits(raw, expected):
37+
assert mks_can.encoder_value(bytes.fromhex(raw)) == expected
38+
39+
3140
@pytest.mark.parametrize('can_id, data', [
3241
(1, bytes.fromhex('3133')),
3342
(1, b'\x31'),
@@ -39,7 +48,8 @@ def test_parse_rejects_bad_checksums_and_lengths(can_id, data):
3948

4049

4150
@pytest.mark.parametrize('axis, speed, acc', [
42-
(0x800000, 100, 2), (-0x800001, 100, 2), (0, 3001, 2), (0, 100, 256)])
51+
(0x800000, 100, 2), (-0x800001, 100, 2), (0, -1, 2),
52+
(0, 3001, 2), (0, 100, 256)])
4353
def test_absolute_axis_rejects_out_of_range_arguments(axis, speed, acc):
4454
with pytest.raises(ValueError):
4555
mks_can.absolute_axis(1, axis, speed, acc)

‎waybionic_teleop/test/test_sim_arm_drives_node.py‎

Lines changed: 158 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,40 @@
11
"""Exercise the ROS command gate and MKS frames without a hardware CAN interface."""
22

3+
import importlib.util
34
import math
45
from pathlib import Path
56
import time
7+
from unittest.mock import MagicMock
68

79
import pytest
810
import rclpy
11+
from rclpy._rclpy_pybind11 import RCLError
912
from rclpy.parameter import Parameter
1013
from sensor_msgs.msg import JointState
1114
from std_msgs.msg import Bool, String
1215

13-
from waybionic_teleop import mks_can
16+
from waybionic_teleop import joy_udp_receiver, mks_can, sim_arm_drives_node, xbox_teleop_node
1417
from waybionic_teleop.sim_arm_drives_node import REPLY_TIMEOUT_S, SimArmDrives
1518

1619
URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf'
1720
/ 'waybionic_arm.urdf').read_text(encoding='utf-8')
21+
CAMERA_PATH = (Path(__file__).resolve().parents[2] / 'waybionic_bringup'
22+
/ 'scripts' / 'camera_follower.py')
23+
_camera_spec = importlib.util.spec_from_file_location('waybionic_camera_shutdown', CAMERA_PATH)
24+
camera_module = importlib.util.module_from_spec(_camera_spec)
25+
_camera_spec.loader.exec_module(camera_module)
26+
27+
POSE = {'joint_1': 0.8, 'joint_2': -0.8, 'joint_3': 0.8,
28+
'joint_4': 0.8, 'joint_5': 0.25, 'tool_grip': 0.8}
29+
RATES = {'joint_1': 0.2, 'joint_2': -0.2, 'joint_3': 0.2,
30+
'joint_4': 0.2, 'joint_5': 0.05, 'tool_grip': 0.2}
31+
32+
SHUTDOWN_NODES = [
33+
(xbox_teleop_node, 'XboxTeleop'),
34+
(sim_arm_drives_node, 'SimArmDrives'),
35+
(joy_udp_receiver, 'JoyUdpReceiver'),
36+
(camera_module, 'CameraFollower'),
37+
]
1838

1939

2040
@pytest.fixture
@@ -44,25 +64,37 @@ def ready(node):
4464
assert node.description_valid and node.authorized
4565

4666

47-
def command(node, **changes):
67+
def command(node, velocities=None, **changes):
4868
targets = dict.fromkeys(node.map.joints, 0.0)
4969
targets.update(changes)
70+
if velocities is None:
71+
velocities = {name: math.copysign(0.2, value) if value else 0.0
72+
for name, value in targets.items()}
5073
return JointState(name=list(targets), position=list(targets.values()),
51-
velocity=[0.0] * len(targets))
74+
velocity=[velocities.get(name, 0.0) for name in targets])
75+
76+
77+
def sent_frame(node, index):
78+
drive = node.map.drives[index]
79+
can_id, hex_data = node.last_command[index].split('#')
80+
assert int(can_id, 16) == drive.can_id
81+
return mks_can.parse(drive.can_id, bytes.fromhex(hex_data))
5282

5383

5484
def assert_stopped(node):
55-
assert not node.authorized and all(servo.target is None for servo in node.bus.drives.values())
56-
for drive, frame in zip(node.map.drives, node.last_command):
57-
code, args = mks_can.parse(drive.can_id, bytes.fromhex(frame.split('#')[1]))
58-
assert code == mks_can.ABSOLUTE_AXIS and int.from_bytes(args[:2], 'big') == 0
85+
assert not node.authorized
86+
assert all(servo.enabled and servo.target is None and servo.rpm == 0.0
87+
for servo in node.bus.drives.values())
88+
assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6))
89+
for index in range(len(node.map.drives)))
5990

6091

6192
def test_a_valid_setpoint_reaches_the_simulated_bus_and_feedback(node):
6293
ready(node)
6394
requested = command(node, joint_1=0.5, joint_2=0.1)
6495
node.on_command(requested)
6596
advance(node)
97+
advance(node)
6698
assert node.bus.drives[1].target is not None
6799
assert node.bus.drives[1].axis > 0
68100
assert node.bus.drives[2].axis > 0
@@ -145,6 +177,17 @@ def test_int24_overflow_rejects_the_entire_coordinated_move(node):
145177
advance(node)
146178
assert node.rejected == 1
147179
assert_stopped(node)
180+
node.map.drives[0].gear_ratio = 1.0
181+
valid = command(node, joint_1=0.5)
182+
node.on_enabled(Bool(data=True))
183+
node.on_command(valid)
184+
advance(node)
185+
assert_stopped(node)
186+
node.on_enabled(Bool(data=False))
187+
node.on_enabled(Bool(data=True))
188+
node.on_command(valid)
189+
advance(node)
190+
assert node.authorized and node.bus.drives[1].target is not None
148191

149192

150193
def test_encoder_outside_a_provisional_limit_may_move_only_toward_it(node):
@@ -177,3 +220,111 @@ def test_stale_encoder_feedback_stops_before_sending_another_position(node):
177220
node.on_command(command(node, joint_1=1.0))
178221
advance(node)
179222
assert node.authorized and node.bus.drives[1].target is not None
223+
224+
225+
def test_zero_speed_f5_stops_six_drives_and_negative_targets_rearm(node):
226+
ready(node)
227+
node.max_rpm = 5
228+
node.on_command(command(node, velocities=RATES, **POSE))
229+
advance(node)
230+
assert all(drive.target is not None for drive in node.bus.drives.values())
231+
advance(node, 0.1)
232+
assert all(drive.rpm != 0.0 for drive in node.bus.drives.values())
233+
234+
measured = node.map.to_positions(node.counts)
235+
node.on_command(command(node, velocities=dict.fromkeys(POSE, 0.0), **measured))
236+
advance(node)
237+
assert node.authorized
238+
assert all(drive.enabled and drive.target is None and drive.rpm == 0.0
239+
for drive in node.bus.drives.values())
240+
assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6))
241+
for index in range(len(node.map.drives)))
242+
held = [drive.axis for drive in node.bus.drives.values()]
243+
advance(node, 0.6)
244+
assert [drive.axis for drive in node.bus.drives.values()] == held
245+
assert_stopped(node)
246+
247+
node.on_enabled(Bool(data=False))
248+
node.on_enabled(Bool(data=True))
249+
reverse = dict.fromkeys(POSE, -0.4)
250+
reverse.update(joint_5=0.1, tool_grip=0.2)
251+
rates = dict.fromkeys(POSE, -0.2)
252+
rates.update(joint_5=0.05, tool_grip=0.2)
253+
node.on_command(command(node, velocities=rates, **reverse))
254+
advance(node)
255+
assert node.authorized
256+
assert [drive.target for drive in node.bus.drives.values()] == node.map.to_counts(reverse)
257+
assert all(drive.speed > 0 for drive in node.bus.drives.values())
258+
assert int.from_bytes(sent_frame(node, 0)[1][3:], 'big', signed=True) < 0
259+
260+
261+
def test_six_drive_host_pause_drops_pending_targets_until_fresh_start(node):
262+
ready(node)
263+
node.max_rpm = 5
264+
node.on_command(command(node, velocities=RATES, **POSE))
265+
advance(node)
266+
assert all(drive.target is not None for drive in node.bus.drives.values())
267+
next_pose = {joint: value * 1.1 for joint, value in POSE.items()}
268+
node.on_command(command(node, velocities=RATES, **next_pose))
269+
advance(node, 2.0)
270+
assert all(drive.heartbeat_stops == 1 for drive in node.bus.drives.values())
271+
assert_stopped(node)
272+
assert node.commanded != next_pose
273+
274+
node.on_enabled(Bool(data=True))
275+
node.on_command(command(node, velocities=RATES, **next_pose))
276+
advance(node)
277+
assert_stopped(node)
278+
node.on_enabled(Bool(data=False))
279+
node.on_enabled(Bool(data=True))
280+
node.on_command(command(node, velocities=RATES, **next_pose))
281+
advance(node)
282+
assert [drive.target for drive in node.bus.drives.values()] == node.map.to_counts(next_pose)
283+
advance(node, 2.0)
284+
assert all(drive.heartbeat_stops == 2 for drive in node.bus.drives.values())
285+
assert_stopped(node)
286+
287+
288+
@pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES)
289+
def test_shutdown_only_ignores_an_invalid_shutdown_context(module, class_name, monkeypatch):
290+
factory = MagicMock()
291+
spin = MagicMock(side_effect=RCLError('the given context is not valid'))
292+
monkeypatch.setattr(module, class_name, factory)
293+
monkeypatch.setattr(module.rclpy, 'init', MagicMock())
294+
monkeypatch.setattr(module.rclpy, 'try_shutdown', MagicMock())
295+
monkeypatch.setattr(module.rclpy, 'spin', spin)
296+
monkeypatch.setattr(module.rclpy, 'ok', lambda: False)
297+
module.main()
298+
299+
spin.side_effect = RCLError('unrelated ROS failure')
300+
with pytest.raises(RCLError, match='unrelated ROS failure'):
301+
module.main()
302+
monkeypatch.setattr(module.rclpy, 'ok', lambda: True)
303+
spin.side_effect = RCLError('the given context is not valid')
304+
with pytest.raises(RCLError, match='context is not valid'):
305+
module.main()
306+
assert spin.call_count == 3
307+
assert factory.return_value.destroy_node.call_count == 3
308+
309+
310+
@pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES)
311+
def test_binding_error_only_ignored_after_context_shutdown(module, class_name, monkeypatch):
312+
factory = MagicMock()
313+
error = RuntimeError("Unable to convert call argument '0' to Python object")
314+
spin = MagicMock(side_effect=error)
315+
monkeypatch.setattr(module, class_name, factory)
316+
monkeypatch.setattr(module.rclpy, 'init', MagicMock())
317+
monkeypatch.setattr(module.rclpy, 'try_shutdown', MagicMock())
318+
monkeypatch.setattr(module.rclpy, 'spin', spin)
319+
monkeypatch.setattr(module.rclpy, 'ok', lambda: False)
320+
module.main()
321+
322+
spin.side_effect = RuntimeError('unrelated subscription failure')
323+
with pytest.raises(RuntimeError, match='unrelated subscription failure'):
324+
module.main()
325+
monkeypatch.setattr(module.rclpy, 'ok', lambda: True)
326+
spin.side_effect = error
327+
with pytest.raises(RuntimeError, match='Unable to convert call argument'):
328+
module.main()
329+
assert spin.call_count == 3
330+
assert factory.return_value.destroy_node.call_count == 3

‎waybionic_teleop/test/test_sim_drives.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,21 @@ def test_a_long_pause_still_trips_the_heartbeat():
6969
assert servo.axis == pytest.approx(0.5 * mks_can.COUNTS_PER_REV, rel=0.05)
7070

7171

72+
def test_f5_stop_is_immediate_and_a_new_negative_target_rearms_the_drive():
73+
servo = ready_servo()
74+
assert servo.receive(mks_can.absolute_axis(1, 0x4000, 300, 0)) == [RUNNING]
75+
run(servo, 0.05)
76+
assert servo.rpm > 0.0 and servo.axis > 0.0
77+
held = servo.axis
78+
assert servo.receive(mks_can.absolute_axis(1, 0, 0, 0)) == [COMPLETE]
79+
assert servo.enabled and servo.target is None and servo.rpm == 0.0
80+
assert run(servo, 0.4) == []
81+
assert servo.axis == held
82+
assert servo.receive(mks_can.absolute_axis(1, -0x4000, 300, 0)) == [RUNNING]
83+
run(servo, 0.05)
84+
assert servo.target == -0x4000 and servo.rpm < 0.0 and servo.axis < held
85+
86+
7287
def test_bus_routes_replies_and_counts_bad_frames():
7388
bus = SimulatedBus([SimulatedServo(1), SimulatedServo(2)], 500000)
7489
bus.send(2, mks_can.read_encoder(2))

‎waybionic_teleop/test/test_teleop.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,23 @@ def test_b_holds_the_measured_pose_and_disables(teleop):
119119
assert not teleop.update(*sample(left_x=1.0), pose, DT)
120120

121121

122+
def test_b_stop_needs_a_fresh_start_with_centered_sticks_to_rearm(teleop):
123+
press(teleop, 'start')
124+
run(teleop, 0.4, left_x=1.0)
125+
pose = {**HOME, 'joint_1': 0.2}
126+
press(teleop, 'b', pose)
127+
run(teleop, 0.4, left_x=1.0)
128+
assert not teleop.enabled and teleop.targets['joint_1'] == 0.2
129+
130+
teleop.update(*sample('start', left_x=1.0), pose, DT)
131+
assert not teleop.enabled and teleop.warning
132+
teleop.update(*sample(), pose, DT)
133+
press(teleop, 'start', pose)
134+
assert teleop.enabled and teleop.targets == pose
135+
run(teleop, 0.4, left_x=-1.0)
136+
assert teleop.targets['joint_1'] < pose['joint_1']
137+
138+
122139
def test_joint_limits_stop_motion_and_are_reported(teleop):
123140
press(teleop, 'start')
124141
run(teleop, 6.0, left_y=1.0)

‎waybionic_teleop/waybionic_teleop/joy_udp_receiver.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
77
import rclpy
8+
from rclpy._rclpy_pybind11 import RCLError
89
from rclpy.executors import ExternalShutdownException
910
from rclpy.node import Node
1011
from sensor_msgs.msg import Joy
@@ -98,6 +99,15 @@ def main():
9899
rclpy.spin(node)
99100
except (KeyboardInterrupt, ExternalShutdownException):
100101
pass
102+
except RCLError as error:
103+
# SIGINT can shut down the context before spin recreates its wait set.
104+
if rclpy.ok() or 'the given context is not valid' not in str(error):
105+
raise
106+
except RuntimeError as error:
107+
# Jazzy may surface this binding error when SIGINT invalidates a subscription.
108+
if (rclpy.ok() or not str(error).startswith(
109+
"Unable to convert call argument '0' to Python object")):
110+
raise
101111
finally:
102112
node.socket.close()
103113
node.destroy_node()

0 commit comments

Comments
 (0)