Skip to content

Commit 6575a85

Browse files
Add PS5 DualSense controller support on Windows (#26)
Adds a PS5 DualSense controller on Windows through an SDL/Pygame bridge that maps it onto the existing teleop layout (Options to Start, Circle to B, Triangle to Y, Cross to A, L2/R2 to the triggers). The bridge needs neutral controls to connect or reconnect, and sends a disconnected state when the controller is lost.
1 parent 24ac04c commit 6575a85

5 files changed

Lines changed: 506 additions & 7 deletions

File tree

‎BuildInstructions.md‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -292,9 +292,9 @@ Qt may report a default `XDG_RUNTIME_DIR`, and RViz may report that stereo is no
292292
supported; neither prevented this demo from starting. On Ctrl+C, the joint GUI
293293
can report exit code `-2`, indicating the requested SIGINT interruption.
294294

295-
## Xbox Controller (Simulated Arm)
295+
## Xbox and PS5 Controllers (Simulated Arm)
296296

297-
`teleop:=true` drives the arm with an Xbox controller through simulated CAN drives;
297+
`teleop:=true` drives the arm with a controller through simulated CAN drives;
298298
nothing is sent to hardware unless you choose a drive bus, as described in
299299
[Real MKS drives over CAN](#real-mks-drives-over-can). The controller mapping is in
300300
`waybionic_teleop/config/xbox_teleop.yaml`, and the placeholder joint-to-drive map
@@ -319,6 +319,36 @@ python -m waybionic_teleop.xinput_bridge
319319
The bridge sends the controller state to the container on `127.0.0.1:47300/udp`.
320320
Press **Ctrl+C** in each window to stop.
321321

322+
**PS5 DualSense on Windows:** pair the controller in Windows Bluetooth settings or
323+
connect it by USB, then use the same `wslg-teleop` command above. In the second
324+
PowerShell window, use Python 3.13 or older, install Pygame once, and start the SDL
325+
bridge:
326+
327+
```powershell
328+
python -m pip install pygame==2.6.1
329+
cd waybionic_teleop
330+
python -m waybionic_teleop.sdl_bridge
331+
```
332+
333+
To enable Bluetooth rumble, restart the bridge with:
334+
335+
```powershell
336+
python -m waybionic_teleop.sdl_bridge --bluetooth-rumble
337+
```
338+
339+
This opt-in uses SDL extended reports. It can temporarily stop non-SDL
340+
DirectInput apps from using the controller; power-cycle the controller to restore
341+
normal DirectInput behavior. USB rumble does not need this option.
342+
343+
Run only one Windows bridge at a time; the
344+
[self-running demo](#self-running-demo) opens the Xbox bridge, so close its window
345+
before starting the SDL bridge. The SDL bridge uses the first recognized
346+
controller by default; use `--index 1` (or another SDL index) if multiple controllers
347+
are connected. It waits for all controls to be released when the controller first
348+
connects or reconnects. Windows must show the controller as connected, and the bridge
349+
must print `Controller ready` before Options can enable teleoperation. If Pygame
350+
cannot see the controller over Bluetooth, try USB and report which connection worked.
351+
322352
**Linux (native ROS):** with the controller plugged in, run
323353
`ros2 launch waybionic_bringup ground_station.launch.py teleop:=true`.
324354

@@ -351,6 +381,15 @@ Bluetooth controllers are not listed in `/dev/input/by-id`; connect the controll
351381
| D-pad up/down | Speed: 10, 25, 50 or 100% of 60 deg/s, or of 50 mm/s and 30 deg/s of tilt in the Cartesian and incision groups |
352382
| A (hold) | Return to the zero pose (not in the incision group) |
353383

384+
On PS5 DualSense, **Options** replaces Start/Menu, **Circle** replaces B,
385+
**Triangle** replaces Y, **Cross** replaces A, and the left/right triggers are
386+
L2/R2. The sticks, D-pad, and shoulder buttons keep the same positions. After
387+
connecting, test each row above with those names, and check that the controller
388+
rumbles when a move stops at a limit. Turn the controller off while
389+
teleoperation is enabled: the arm should hold its pose and show disabled. After
390+
reconnecting, teleoperation must remain disabled until you release the controls
391+
and press Options again.
392+
354393
Start is refused until the sticks are centred and the triggers and motion buttons released;
355394
after Y changes groups with motion held, the new group waits until the controls are neutral.
356395
Stick and trigger movement inside the 15% deadzone is ignored, so a trigger that does not
@@ -367,7 +406,7 @@ RViz label also turns red and names the cause, for example `STOPPED-joint_3` or
367406
`OUT-OF-REACH`. If the drives stop the arm while teleop is still enabled, for example after
368407
rejecting a target or losing encoder feedback, the label shows `DRIVES-STOPPED` and the
369408
drives' reason, and the controller rumbles once; press B, then Start, to continue. Rumble
370-
works with a controller plugged into the ground station and through the Windows bridge.
409+
works with a controller plugged into the ground station and through either Windows bridge.
371410

372411
When the bridge reports that the controller disconnected, every control is released once,
373412
so the arm slows to a stop. After 0.5 s without controller input, teleop disables and holds
@@ -442,8 +481,8 @@ updating the controller. The bridge keeps sending the last state it read, so the
442481
controller cannot stop the arm, not even with B. Press **Ctrl+C** in the bridge
443482
window; with no controller input, teleop disables and holds the arm after the
444483
0.5 s input timeout. Turn the controller off and on (or unplug and replug it),
445-
start the bridge again and press Start. Real drives need a stop that does not
446-
depend on the controller.
484+
start the bridge again and press Start/Options. Real drives need a stop that does
485+
not depend on the controller.
447486

448487
### Self-Running Demo
449488

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Currently, this repository contains the clean foundation and the SolidWorks-expo
1111
- **`waybionic_bringup`**
1212
Launch files and RViz configurations to bring up the robot state and visualization.
1313
- **`waybionic_teleop`**
14-
Xbox controller teleoperation of the arm through placeholder MKS SERVO CAN drives, simulated until the real drives are connected.
14+
Xbox and PS5 DualSense controller teleoperation of the arm through placeholder MKS SERVO CAN drives, simulated until the real drives are connected.
1515
- **`waybionic_rviz_plugins`**
1616
Engineer diagnostics panel, mock/live diagnostics sources, and a temporary diagnostics publisher.
1717

‎waybionic_teleop/setup.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
maintainer='Yassin Soliman',
2020
maintainer_email='solimanyassin@gmail.com',
2121
description=(
22-
'Xbox controller teleoperation and MKS CAN joint drives, simulated or real, for the '
22+
'Controller teleoperation and MKS CAN joint drives, simulated or real, for the '
2323
'WayBionic arm.'
2424
),
2525
license='Apache-2.0',
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
"""DualSense input must match the teleop layout and fail safe on reconnect."""
2+
3+
import socket
4+
import sys
5+
import time
6+
from types import SimpleNamespace
7+
8+
import pytest
9+
10+
from waybionic_teleop import gamepad, sdl_bridge
11+
12+
13+
class FakeController:
14+
"""An SDL controller whose input can change during a test."""
15+
16+
def __init__(self):
17+
"""Start with neutral controls and a connected device."""
18+
self.axes = {}
19+
self.buttons = {}
20+
self.connected = True
21+
self.rumbles = []
22+
23+
def get_axis(self, index):
24+
"""Return a simulated SDL axis."""
25+
return self.axes.get(index, 0)
26+
27+
def get_button(self, index):
28+
"""Return a simulated SDL button."""
29+
return self.buttons.get(index, False)
30+
31+
def attached(self):
32+
"""Report whether the simulated device is connected."""
33+
return self.connected
34+
35+
def rumble(self, low, high, duration):
36+
"""Record a simulated SDL rumble request."""
37+
self.rumbles.append((low, high, duration))
38+
return True
39+
40+
def stop_rumble(self):
41+
"""Record a simulated SDL rumble stop."""
42+
self.rumbles.append('stop')
43+
44+
def quit(self): # noqa: A003
45+
"""Match the SDL controller cleanup API."""
46+
pass
47+
48+
49+
class FakeSDL:
50+
"""Expose the controller constants used by the production bridge."""
51+
52+
def __init__(self):
53+
"""Assign test constants and start without devices."""
54+
self.devices = []
55+
for index, name in enumerate(sdl_bridge.AXIS_NAMES):
56+
setattr(self, 'CONTROLLER_AXIS_' + name, index)
57+
for index, name in enumerate(sdl_bridge.BUTTON_NAMES.values()):
58+
setattr(self, 'CONTROLLER_BUTTON_' + name, index)
59+
60+
def get_count(self):
61+
"""Return the current SDL device count."""
62+
return len(self.devices)
63+
64+
def is_controller(self, index):
65+
"""Mark every test device as an SDL controller."""
66+
return True
67+
68+
def Controller(self, index):
69+
"""Open one simulated SDL controller."""
70+
return self.devices[index]
71+
72+
def name_forindex(self, index):
73+
"""Name the test controller like a DualSense."""
74+
return 'DualSense Wireless Controller'
75+
76+
77+
def pressed(buttons):
78+
"""List normalized names of pressed buttons."""
79+
return [name for name, value in zip(gamepad.BUTTONS, buttons) if value]
80+
81+
82+
def fake_pygame(sdl):
83+
"""Expose SDL constants where Pygame 2.6 publishes them."""
84+
pygame = SimpleNamespace(event=SimpleNamespace(pump=lambda: None))
85+
for name in sdl_bridge.AXIS_NAMES:
86+
setattr(pygame, 'CONTROLLER_AXIS_' + name,
87+
getattr(sdl, 'CONTROLLER_AXIS_' + name))
88+
for name in sdl_bridge.BUTTON_NAMES.values():
89+
setattr(pygame, 'CONTROLLER_BUTTON_' + name,
90+
getattr(sdl, 'CONTROLLER_BUTTON_' + name))
91+
return pygame
92+
93+
94+
def test_dualsense_controls_match_existing_teleop_layout():
95+
"""Keep DualSense axes and buttons compatible with teleop packets."""
96+
sdl = FakeSDL()
97+
pad = FakeController()
98+
pad.axes = {sdl.CONTROLLER_AXIS_LEFTX: -32768,
99+
sdl.CONTROLLER_AXIS_LEFTY: -32768,
100+
sdl.CONTROLLER_AXIS_RIGHTX: 16384,
101+
sdl.CONTROLLER_AXIS_RIGHTY: 32767,
102+
sdl.CONTROLLER_AXIS_TRIGGERLEFT: 32768}
103+
pad.buttons = {sdl.CONTROLLER_BUTTON_A: True, # Cross
104+
sdl.CONTROLLER_BUTTON_B: True, # Circle
105+
sdl.CONTROLLER_BUTTON_Y: True, # Triangle
106+
sdl.CONTROLLER_BUTTON_START: True, # Options
107+
sdl.CONTROLLER_BUTTON_DPAD_UP: True}
108+
axes, buttons = sdl_bridge.to_joy(pad, sdl)
109+
assert axes == pytest.approx([1.0, 1.0, -0.5, -32767 / 32768, -1.0, 0.0])
110+
assert pressed(buttons) == ['a', 'b', 'y', 'start', 'dpad_up']
111+
_, connected, unpacked_axes, unpacked_buttons = gamepad.unpack(
112+
gamepad.pack(1, axes, buttons))
113+
assert connected
114+
assert unpacked_axes == pytest.approx(axes)
115+
assert unpacked_buttons == buttons
116+
117+
118+
def test_disconnect_sends_neutral_and_reconnect_requires_release():
119+
"""Do not expose controls until a new device has been released."""
120+
sdl = FakeSDL()
121+
first = FakeController()
122+
sdl.devices = [first]
123+
bridge = sdl_bridge.SDLBridge(fake_pygame(sdl), sdl)
124+
assert bridge.poll(0.0)[2] is False # neutral reset
125+
assert bridge.poll(0.01)[2] is True
126+
first.buttons[sdl.CONTROLLER_BUTTON_START] = True
127+
assert 'start' in pressed(bridge.poll(0.02)[1])
128+
129+
first.connected = False
130+
axes, buttons, connected, _ = bridge.poll(0.03)
131+
assert not connected and (axes, buttons) == sdl_bridge.NEUTRAL
132+
133+
second = FakeController()
134+
second.buttons[sdl.CONTROLLER_BUTTON_START] = True
135+
sdl.devices = [second]
136+
# Held Options cannot enable teleop on reconnect.
137+
assert bridge.poll(1.04)[2] is False
138+
second.buttons.clear()
139+
assert bridge.poll(1.05)[2] is False # wait for a fresh Options press
140+
assert bridge.poll(1.06)[2] is True
141+
second.buttons[sdl.CONTROLLER_BUTTON_START] = True
142+
assert 'start' in pressed(bridge.poll(1.07)[1])
143+
144+
145+
def test_trigger_or_stick_held_blocks_connection():
146+
"""A held control must block the reset after connection."""
147+
sdl = FakeSDL()
148+
pad = FakeController()
149+
pad.axes[sdl.CONTROLLER_AXIS_TRIGGERLEFT] = 20000
150+
sdl.devices = [pad]
151+
bridge = sdl_bridge.SDLBridge(fake_pygame(sdl), sdl)
152+
assert bridge.poll(0.0)[2] is False
153+
pad.axes.clear()
154+
pad.axes[sdl.CONTROLLER_AXIS_LEFTX] = 20000
155+
assert bridge.poll(0.01)[2] is False
156+
pad.axes.clear()
157+
assert bridge.poll(0.02)[2] is False
158+
assert bridge.poll(0.03)[2] is True
159+
160+
161+
def test_missing_controller_reports_a_useful_status():
162+
"""Tell the operator when the bridge is running without a controller."""
163+
sdl = FakeSDL()
164+
bridge = sdl_bridge.SDLBridge(fake_pygame(sdl), sdl)
165+
166+
axes, buttons, connected, message = bridge.poll(0.0)
167+
168+
assert not connected and (axes, buttons) == sdl_bridge.NEUTRAL
169+
assert message == ('No controller detected; connect a PS5 DualSense '
170+
'controller')
171+
assert bridge.poll(0.5)[3] is None
172+
173+
174+
def test_rumble_reaches_only_an_open_controller():
175+
"""Rumble for a second per request like the Xbox bridge; zero stops it."""
176+
sdl = FakeSDL()
177+
bridge = sdl_bridge.SDLBridge(fake_pygame(sdl), sdl)
178+
assert bridge.rumble(1.0) is False
179+
pad = FakeController()
180+
sdl.devices = [pad]
181+
bridge.poll(0.0)
182+
assert bridge.rumble(0.5) is True
183+
assert bridge.rumble(0.0) is True
184+
assert pad.rumbles == [(0.5, 0.5, 1000), 'stop']
185+
pad.rumble = lambda low, high, duration: False
186+
assert bridge.rumble(0.5) is False
187+
188+
189+
@pytest.mark.parametrize('bluetooth_rumble', [False, True])
190+
def test_rumble_replies_do_not_interrupt_the_controller_packets(
191+
monkeypatch, bluetooth_rumble):
192+
"""Only the ground station's replies rumble; the bridge keeps sending."""
193+
sdl = FakeSDL()
194+
pad = FakeController()
195+
sdl.devices = [pad]
196+
197+
def init():
198+
expected = '1' if bluetooth_rumble else None
199+
assert sdl_bridge.os.environ.get('SDL_JOYSTICK_HIDAPI_PS5_RUMBLE') == expected
200+
sdl.init = init
201+
sdl.quit = lambda: None
202+
pygame = fake_pygame(sdl)
203+
pygame.HIDDEN = 0
204+
pygame.display = SimpleNamespace(
205+
init=lambda: None, set_mode=lambda size, flags: None,
206+
quit=lambda: None)
207+
monkeypatch.setitem(sys.modules, 'pygame', pygame)
208+
monkeypatch.setitem(sys.modules, 'pygame._sdl2',
209+
SimpleNamespace(controller=sdl))
210+
monkeypatch.setenv('SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS', '1')
211+
monkeypatch.delenv('SDL_JOYSTICK_HIDAPI_PS5_RUMBLE', raising=False)
212+
station = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
213+
stranger = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
214+
station.bind(('127.0.0.1', 0))
215+
station.settimeout(2.0)
216+
packets = []
217+
218+
def sleep(seconds):
219+
data, address = station.recvfrom(64)
220+
packets.append(gamepad.unpack(data))
221+
if len(packets) == 3:
222+
stranger.sendto(gamepad.pack_rumble(1.0), address)
223+
station.sendto(gamepad.pack_rumble(0.5), address)
224+
elif len(packets) == 6:
225+
raise KeyboardInterrupt
226+
227+
monkeypatch.setattr(sdl_bridge, 'time', SimpleNamespace(
228+
monotonic=time.monotonic, sleep=sleep))
229+
arguments = ['sdl_bridge', '--port', str(station.getsockname()[1])]
230+
if bluetooth_rumble:
231+
arguments.append('--bluetooth-rumble')
232+
monkeypatch.setattr(sys, 'argv', arguments)
233+
try:
234+
sdl_bridge.main()
235+
finally:
236+
station.close()
237+
stranger.close()
238+
assert [packet[1] for packet in packets] == [False] + [True] * 5
239+
assert pad.rumbles == [(0.5, 0.5, 1000), 'stop']

0 commit comments

Comments
 (0)