openctrl.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #!/usr/bin/env python3
  2. """openctrl.py -- Steam Deck forwarder for the ReversePuck emulated Steam Controller 2.
  3. Runs on the Steam Deck (Desktop Mode). Opens the nRF (Valve 28DE:1302) CDC port, reads its STATUS
  4. stream (which bonded pucks are live), and shows a fullscreen touchscreen UI of tappable puck tiles.
  5. Tap an *available* puck -> the Deck's controls are grabbed (detached) and streamed to the nRF, which
  6. relays them over RF so the puck presents a Steam Controller 2 to its host. Tap again, or lose the RF
  7. link, and control returns to the Deck.
  8. python3 openctrl.py # fullscreen touchscreen UI
  9. python3 openctrl.py --debug # headless: print status, no UI (for bring-up)
  10. python3 openctrl.py --port /dev/ttyACM0 # override CDC port autodetect
  11. python3 openctrl.py --evdev # use the evdev fallback input source (lower fidelity)
  12. The dongle (nRF CDC) is hot-pluggable: launch with or without it, it appears/disappears live.
  13. Deps: pyserial + pygame (UI) + pyusb (input/USB detach). See README.md / the ./ReversePuck launcher.
  14. """
  15. import argparse
  16. import os
  17. import sys
  18. import time
  19. import frame
  20. import input_source as isrc
  21. VID = 0x28DE
  22. PID = 0x1302 # the ReversePuck emulated controller (nRF "dongle")
  23. PUCK_PID = 0x1304 # a puck's own CDC -- never grab this as the dongle
  24. INPUT_HZ = 250.0
  25. def find_port():
  26. try:
  27. from serial.tools import list_ports
  28. except Exception:
  29. return None
  30. for p in list_ports.comports():
  31. if (p.vid, p.pid) == (VID, PID):
  32. return p.device
  33. # fall back: any Valve CDC except a puck's (so a puck docked on the Deck isn't mistaken for it)
  34. for p in list_ports.comports():
  35. if p.vid == VID and p.pid != PUCK_PID:
  36. return p.device
  37. return None
  38. class App:
  39. def __init__(self, args):
  40. self.args = args
  41. import serial # imported here so --help works without pyserial
  42. self._serial = serial
  43. # The dongle (nRF CDC) is HOT-PLUGGABLE: we don't require it at launch and we re-open it
  44. # whenever it (re)appears, and tear down cleanly when it goes away.
  45. self.ser = None
  46. self.port_name = None
  47. self.reader = frame.Reader()
  48. self._last_open_try = 0.0
  49. self.input = None
  50. self.forwarding = False
  51. self.fwd_slot = None
  52. self.last_input = 0.0
  53. # model surfaced to the UI
  54. self.status = {"link_up": False, "link_slot": None, "sess_ch": 0,
  55. "bonds": [], "forwarding": False}
  56. self.note = "waiting for ReversePuck dongle (28DE:1302)…"
  57. self.log = [] # firmware '#' diagnostic lines (the in-app serial monitor)
  58. # file log: everything (firmware '#' lines + app events) with timestamps, for sharing.
  59. self.logf = None
  60. try:
  61. self.logf = open(args.logfile, "a", buffering=1) # line-buffered
  62. self._flog("==== openctrl start ====")
  63. except Exception as ex:
  64. print("logfile open failed (%s); continuing without it" % ex)
  65. def _flog(self, line):
  66. if self.logf:
  67. try:
  68. self.logf.write("%.3f %s\n" % (time.monotonic(), line))
  69. except Exception:
  70. pass
  71. @property
  72. def dongle_connected(self):
  73. return self.ser is not None
  74. # ---- serial I/O (hot-plug aware) ----
  75. def _open_serial(self):
  76. """Try to (re)open the dongle CDC port. Throttled to ~2 Hz. Sets self.ser on success."""
  77. if self.ser is not None:
  78. return
  79. now = time.monotonic()
  80. if now - self._last_open_try < 0.5:
  81. return
  82. self._last_open_try = now
  83. port = self.args.port or find_port()
  84. if not port:
  85. return
  86. try:
  87. self.ser = self._serial.Serial(port, 115200, timeout=0)
  88. self.port_name = port
  89. self.reader = frame.Reader() # fresh framer for the new connection
  90. # forget any stale link state from a previous dongle session
  91. self.status = {"link_up": False, "link_slot": None, "sess_ch": 0,
  92. "bonds": [], "forwarding": False}
  93. self.note = "dongle connected: %s" % port
  94. self._flog("dongle connected: %s" % port)
  95. except Exception:
  96. self.ser = None # e.g. permission / busy; will retry
  97. def _drop_serial(self, why):
  98. """Tear down on disconnect: close the port FIRST so we never try to write to a gone dongle, then
  99. release the grabbed pad locally and reset the model. (Closing first also makes send() a no-op, so
  100. there's no re-entrant _drop_serial via a failing write.)"""
  101. try:
  102. if self.ser:
  103. self.ser.close()
  104. except Exception:
  105. pass
  106. self.ser = None
  107. self.port_name = None
  108. self._release_local() # hand the pad back without trying to notify the dongle that's gone
  109. self.status = {"link_up": False, "link_slot": None, "sess_ch": 0,
  110. "bonds": [], "forwarding": False}
  111. self.note = "dongle disconnected (%s) — waiting…" % why
  112. self._flog("dongle disconnected: %s" % why)
  113. def pump_serial(self):
  114. if self.ser is None:
  115. self._open_serial()
  116. return
  117. # A yanked CDC often makes pyserial return b'' silently rather than raise, so the port node
  118. # disappearing is the reliable disconnect signal. Check it (throttled).
  119. now = time.monotonic()
  120. if now - self._last_open_try >= 0.5:
  121. self._last_open_try = now
  122. if self.port_name and not os.path.exists(self.port_name):
  123. self._drop_serial("unplugged")
  124. return
  125. try:
  126. data = self.ser.read(512)
  127. except Exception as ex:
  128. # device yanked / I/O error -> clean teardown, then we'll re-detect it
  129. self._drop_serial(str(ex) or "read error")
  130. return
  131. last_haptic = None
  132. for typ, payload in self.reader.feed(data):
  133. if typ == frame.T_STATUS:
  134. st = frame.parse_status(payload)
  135. if st:
  136. self.status = st
  137. elif typ == frame.T_HAPTIC:
  138. # coalesce a burst to the newest state -- replaying every frame is what lagged the rumble
  139. last_haptic = frame.parse_haptic(payload)
  140. elif typ == frame.T_TEXT:
  141. line = payload.decode("latin1", "replace").rstrip()
  142. if line:
  143. self.note = line
  144. self.log.append(line)
  145. self.log = self.log[-300:]
  146. self._flog(line)
  147. if self.args.debug:
  148. print(line) # stream the firmware log like a serial monitor
  149. # play only the newest haptic of this batch, and only while we're actually forwarding
  150. if last_haptic and self.forwarding and self.input:
  151. try:
  152. self.input.rumble(last_haptic["intensity"], last_haptic["left"],
  153. last_haptic["right"], last_haptic["lgain"],
  154. last_haptic["rgain"])
  155. except Exception:
  156. pass
  157. def send(self, b):
  158. if self.ser is None:
  159. return
  160. try:
  161. self.ser.write(b)
  162. except Exception:
  163. self._drop_serial("write error")
  164. # ---- forwarding control ----
  165. def _ensure_input(self):
  166. if self.input is None:
  167. # libusb DeckSource by default (detaches the pad from Steam + decodes the raw report
  168. # correctly); --evdev forces the lower-fidelity fallback.
  169. self.input = isrc.open_source(prefer_evdev=self.args.evdev,
  170. path=self.args.input)
  171. return self.input
  172. def start_forwarding(self, slot):
  173. try:
  174. self._ensure_input().grab()
  175. except Exception as ex:
  176. # roll back any partial interface claim so the pad is never left half-detached, and force a
  177. # clean rebuild of the source next time (the cached handle may be wedged).
  178. self._drop_input("grab failed: %s" % ex)
  179. self.note = "grab failed: %s" % ex
  180. return
  181. self.forwarding = True
  182. self.fwd_slot = slot
  183. self.send(frame.build_set_forwarding(True))
  184. self.note = "forwarding -> slot %s (%s)" % (slot, self.input.name)
  185. self._flog("APP forwarding START slot=%s input=%s" % (slot, self.input.name))
  186. def _release_local(self):
  187. """Clear forwarding state + ungrab the pad locally, WITHOUT notifying the dongle (used when the
  188. dongle or input device has gone away, so there's nothing to tell)."""
  189. self.forwarding = False
  190. self.fwd_slot = None
  191. if self.input:
  192. try:
  193. self.input.ungrab()
  194. except Exception:
  195. pass
  196. def stop_forwarding(self):
  197. """Clean, user-initiated stop: tell the firmware to stop forwarding, then release the pad."""
  198. if self.forwarding:
  199. self.send(frame.build_set_forwarding(False))
  200. self._release_local()
  201. self.note = "control returned to Deck"
  202. self._flog("APP forwarding STOP")
  203. def _drop_input(self, why):
  204. """Tear down the input source and force a rebuild on the next grab, so a transient USB hiccup on
  205. the Deck pad (or a failed grab) can't wedge the app behind a dead handle."""
  206. self._release_local()
  207. self.input = None
  208. self._flog("input dropped: %s" % why)
  209. def toggle(self, slot):
  210. """Tap handler: a tappable tile is one whose puck is live (alive)."""
  211. if self.forwarding:
  212. self.stop_forwarding()
  213. elif self.dongle_connected:
  214. self.start_forwarding(slot)
  215. def remove_bond(self, slot):
  216. """GUI "remove": un-bond a puck slot on the firmware. Refused while forwarding to it."""
  217. if self.forwarding and self.fwd_slot == slot:
  218. return
  219. self.send(frame.build_clear_bond(slot))
  220. # drop it from the local model immediately so the tile disappears without waiting for STATUS
  221. self.status["bonds"] = [b for b in self.status.get("bonds", []) if b["slot"] != slot]
  222. self._flog("APP remove bond slot=%s" % slot)
  223. def pump_input(self):
  224. if not self.forwarding or not self.input:
  225. return
  226. try:
  227. st = self.input.pump()
  228. except Exception as ex:
  229. # the pad raised (USB reset / yanked) mid-forward. Notify the firmware to stop (the dongle is
  230. # likely still up, so the puck doesn't freeze on the last frame), then drop the dead handle so
  231. # the next tap rebuilds it -- never let this bubble up and kill the loop.
  232. self._flog("input pump error: %s" % ex)
  233. self.stop_forwarding()
  234. self.input = None
  235. self.note = "input device error — control returned to Deck"
  236. return
  237. now = time.monotonic()
  238. if now - self.last_input >= 1.0 / INPUT_HZ:
  239. self.last_input = now
  240. self.send(frame.build_input(st))
  241. def auto_release_on_drop(self):
  242. """If the RF link drops while forwarding, hand control back to the Deck."""
  243. if self.forwarding and not self.status.get("link_up"):
  244. # only release if the slot we're forwarding to is no longer alive
  245. slot = self.fwd_slot
  246. bonds = self.status.get("bonds", [])
  247. alive = any(b["slot"] == slot and b["alive"] for b in bonds)
  248. if not alive:
  249. self.stop_forwarding()
  250. # ---- loops ----
  251. def run_debug(self):
  252. last = 0
  253. while True:
  254. try:
  255. self.pump_serial()
  256. self.pump_input()
  257. self.auto_release_on_drop()
  258. except Exception as ex:
  259. self._flog("debug loop error: %r" % ex)
  260. if time.monotonic() - last > 0.5:
  261. last = time.monotonic()
  262. s = self.status
  263. tiles = ", ".join(
  264. "[%d %s%s]" % (b["slot"], b["serial"] or "?", " LIVE" if b["alive"] else "")
  265. for b in s["bonds"]) or "(no bonds)"
  266. print("dongle=%s link=%s fwd=%s ch=%s %s | %s" %
  267. ("yes" if self.dongle_connected else "NO", s["link_up"],
  268. self.forwarding, s["sess_ch"], tiles, self.note))
  269. time.sleep(0.002)
  270. def run_ui(self):
  271. import ui
  272. ui.run(self)
  273. def main():
  274. ap = argparse.ArgumentParser(description="Steam Deck forwarder for ReversePuck")
  275. ap.add_argument("--port", help="CDC port (default: autodetect Valve 28DE:1302)")
  276. ap.add_argument("--input", help="force an evdev node, e.g. /dev/input/event12 (only with --evdev)")
  277. ap.add_argument("--evdev", action="store_true",
  278. help="use the evdev fallback instead of the libusb DeckSource (lower fidelity, "
  279. "no USB-level detach)")
  280. ap.add_argument("--debug", action="store_true", help="headless status print, no UI")
  281. ap.add_argument("--logfile", default="openctrl.log",
  282. help="append firmware log + app events here (default: openctrl.log in this dir)")
  283. args = ap.parse_args()
  284. app = App(args)
  285. try:
  286. if args.debug:
  287. app.run_debug()
  288. else:
  289. app.run_ui()
  290. except KeyboardInterrupt:
  291. pass
  292. finally:
  293. if app.forwarding:
  294. app.stop_forwarding()
  295. # belt-and-suspenders: never exit with the Deck pad still detached from Steam
  296. if app.input:
  297. try:
  298. app.input.ungrab()
  299. except Exception:
  300. pass
  301. if __name__ == "__main__":
  302. main()