pairtui.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #!/usr/bin/env python3
  2. """pairtui — steamless pairing manager for the Steam Controller 2 ("Triton") puck / copycat.
  3. Reads the 4 bond slots over USB-HID (0xA3 on control interface --up 1 --idx 0..3, the same way Steam
  4. reads dongle slots — one bond per interface). Pair / unpair go via ./scmd over USB-HID; live connection
  5. state (CONNECTED/CONNECTING/IDLE) is read from the real puck's `dongle~$` CDC shell when present.
  6. scmd: 0xA2 puck slot write/clear, 0xEE/0xEF controller esb/bond, 0x95 reboot-to-wireless, 0xAD pairing.
  7. Build scmd: clang -framework IOKit -framework CoreFoundation -o scmd scmd.c
  8. Run: python3 pairtui.py (pure stdlib: curses + termios)
  9. """
  10. import curses, subprocess, re, os, glob, termios, time, select
  11. HERE = os.path.dirname(os.path.abspath(__file__))
  12. SCMD = os.path.join(HERE, "scmd")
  13. PUCK_PID = "1304" # Valve puck / copycat
  14. CTRL_PIDS = ("1301", "1302", "1303", "1205") # Steam Controller variants (NOT a puck)
  15. def scmd(args, timeout=30):
  16. try:
  17. return subprocess.run([SCMD] + args, capture_output=True, text=True, timeout=timeout).stdout
  18. except Exception as e:
  19. return "ERR %s" % e
  20. def _list_devices():
  21. """Parse `scmd list` -> dedup dict {serial: {pid, product}}. One entry per physical device."""
  22. out = scmd(["list"], timeout=8)
  23. devs = {}
  24. for m in re.finditer(r"Valve 28DE:([0-9A-Fa-f]+)\b.*?serial=(\S+)\s+product=(.+?)\s+manufacturer", out):
  25. pid, ser, prod = m.group(1).lower(), m.group(2), m.group(3).strip()
  26. if ser not in devs:
  27. devs[ser] = {"pid": pid, "product": prod}
  28. return devs
  29. def find_pucks():
  30. """[(serial, cdc_port)] for PID-1304 PUCKS ONLY (a controller is PID 1302 and is excluded)."""
  31. res = []
  32. for ser, d in _list_devices().items():
  33. if d["pid"] != PUCK_PID:
  34. continue
  35. port = (glob.glob("/dev/cu.usbmodem%s*" % ser) or [None])[0]
  36. res.append((ser, port))
  37. return res
  38. def find_controllers():
  39. """[(pid, serial)] of docked Valve controllers (anything that is NOT a puck)."""
  40. res = []
  41. for ser, d in _list_devices().items():
  42. if d["pid"] == PUCK_PID or "Puck" in d["product"]:
  43. continue
  44. if ser.startswith("FX"):
  45. res.append((d["pid"], ser))
  46. return res
  47. class Shell:
  48. """Talk to the real puck's CDC debug shell (dongle~$). Used only for live `connection` state."""
  49. def __init__(self, port): self.port = port; self.fd = None
  50. def open(self):
  51. self.fd = os.open(self.port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)
  52. a = termios.tcgetattr(self.fd); a[4] = a[5] = termios.B115200
  53. a[3] &= ~(termios.ICANON | termios.ECHO | termios.ISIG | termios.IEXTEN)
  54. a[0] &= ~(termios.IXON | termios.ICRNL); a[1] &= ~termios.OPOST
  55. termios.tcsetattr(self.fd, termios.TCSANOW, a)
  56. self.cmd("", 0.3)
  57. def close(self):
  58. if self.fd is not None:
  59. try: os.close(self.fd)
  60. except Exception: pass
  61. self.fd = None
  62. def cmd(self, c, wait=0.8):
  63. os.write(self.fd, (c + "\r\n").encode()); out = b""; t0 = time.time()
  64. while time.time() - t0 < wait:
  65. if select.select([self.fd], [], [], 0.1)[0]:
  66. try: out += os.read(self.fd, 8192)
  67. except Exception: pass
  68. return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", out.decode("ascii", "replace"))
  69. def shell_connection(port):
  70. """Return {slot_idx: STATE} from the real puck's `connection` command, or {} otherwise.
  71. SAFETY: the copycat's CDC is a *different* command shell (single-letter cmds like 'c'=channel), so
  72. blindly sending "connection" there would be misread as a command and corrupt its state. We first
  73. probe with a harmless newline and ONLY proceed if the reply shows the real puck's `dongle~$` prompt."""
  74. if not port:
  75. return {}
  76. sh = Shell(port)
  77. try:
  78. sh.open()
  79. probe = sh.cmd("", 0.3) # bare newline — harmless on any shell
  80. if "dongle" not in probe and "~$" not in probe:
  81. return {} # not the dongle shell (e.g. the copycat): hands off
  82. txt = sh.cmd("connection", 0.7)
  83. except Exception:
  84. return {}
  85. finally:
  86. sh.close()
  87. states = {}
  88. for m in re.finditer(r"ibex(\d)_state\s*:\s*(\w+)", txt):
  89. states[int(m.group(1))] = m.group(2).upper()
  90. return states
  91. def ctrl_read(puck_serial, idx):
  92. """Read 0xA3 (bond/status) from control interface --up 1 --idx; return (serial, raw_record_hex)."""
  93. out = scmd([PUCK_PID, "--serial", puck_serial, "--up", "1", "--idx", str(idx), "A3"], timeout=8)
  94. m = re.search(r"ascii:.*?(FX[A-Z0-9]{6,})", out)
  95. serial = m.group(1) if m else ""
  96. rm = re.search(r"02 A3 [0-9A-Fa-f]{2} ([0-9A-Fa-f ]+)", out)
  97. return serial, (rm.group(1).strip() if rm else "")
  98. def _ser16(serial):
  99. b = serial.encode()[:16]; b += b"\x00" * (16 - len(b))
  100. return ["%02x" % x for x in b]
  101. def pair_full(puck_serial, puck_slot, ctrl_pid, ctrl_serial):
  102. """Steamless pair (controller must be USB-docked). Fresh 8-byte uuid; writes the puck slot
  103. (0xA2 [uuids][ctrl_serial]) and the controller (0xEE esb/bond [uuids][puck_serial] + 0xEF commit),
  104. then 0x95 reboots the controller to wireless. Undock to connect. Returns the uuids hex string."""
  105. uuids = ["%02x" % x for x in os.urandom(8)]
  106. key = ["%02x" % x for x in b"esb/bond\x00"]
  107. scmd([PUCK_PID, "--serial", puck_serial, "--up", "1", "--idx", str(puck_slot), "A2"]
  108. + uuids + _ser16(ctrl_serial))
  109. scmd([ctrl_pid, "--serial", ctrl_serial, "--up", "1", "EE"] + key + uuids + _ser16(puck_serial))
  110. scmd([ctrl_pid, "--serial", ctrl_serial, "--up", "1", "EF"] + key)
  111. scmd([ctrl_pid, "--serial", ctrl_serial, "--up", "1", "95", "52", "af", "27", "a4"])
  112. return "".join(uuids)
  113. def usb_slots(puck_serial):
  114. """Read all 4 bond slots over USB (0xA3, --up 1 --idx 0..3). Works for real puck and copycat.
  115. Record = [4B proteus_uuid LE][4B ibex_uuid LE][16B controller serial]."""
  116. slots = []
  117. for i in range(4):
  118. _, rec = ctrl_read(puck_serial, i)
  119. b = bytes(int(x, 16) for x in rec.split()[:24]) if rec else b""
  120. used = len(b) >= 24 and any(b[0:8])
  121. slots.append({
  122. "idx": i,
  123. "puuid": "0x%08X" % int.from_bytes(b[0:4], "little") if used else "",
  124. "iuuid": "0x%08X" % int.from_bytes(b[4:8], "little") if used else "",
  125. "serial": b[8:24].split(b"\x00")[0].decode("latin1") if used else "",
  126. "state": "BONDED" if used else "empty",
  127. })
  128. return slots
  129. # ───────────────────────────── UI ─────────────────────────────
  130. CP_TITLE, CP_OK, CP_CONN, CP_WARN, CP_DIM, CP_SEL, CP_KEY, CP_HDR = range(1, 9)
  131. STATE_STYLE = {
  132. "CONNECTED": (CP_CONN, "●"), "CONNECTING": (CP_WARN, "◐"),
  133. "BONDED": (CP_OK, "●"), "IDLE": (CP_DIM, "○"), "empty": (CP_DIM, "·"),
  134. }
  135. class TUI:
  136. def __init__(self, scr):
  137. self.scr = scr; self.pucks = []; self.pi = 0; self.slot_i = 0
  138. self.slots = []; self.conn = {}; self.log = ["ready"]
  139. self.rescan()
  140. def msg(self, m):
  141. self.log.append("%s %s" % (time.strftime("%H:%M:%S"), m)); self.log = self.log[-300:]
  142. def cur(self):
  143. return self.pucks[self.pi] if self.pucks else None
  144. def rescan(self):
  145. self.pucks = find_pucks(); self.pi = min(self.pi, max(0, len(self.pucks) - 1))
  146. self.msg("found %d puck(s), %d controller(s)" % (len(self.pucks), len(find_controllers())))
  147. self.refresh()
  148. def refresh(self):
  149. p = self.cur()
  150. if not p:
  151. self.slots = []; self.conn = {}; return
  152. try:
  153. self.slots = usb_slots(p[0])
  154. self.conn = shell_connection(p[1]) # {} unless it's a real puck dongle shell
  155. n = sum(1 for s in self.slots if s["serial"])
  156. self.msg("%s: %d bonded%s" % (p[0], n, " (live state)" if self.conn else ""))
  157. except Exception as e:
  158. self.msg("read err: %s" % e); self.slots = []
  159. def slot_state(self, i):
  160. """Prefer live connection state from the shell; fall back to the bonded/empty USB read."""
  161. sl = self.slots[i] if i < len(self.slots) else {"state": "empty", "serial": "", "iuuid": ""}
  162. st = self.conn.get(i, sl["state"])
  163. if st == "IDLE" and not sl["serial"]:
  164. st = "empty"
  165. return st, sl
  166. # ---- drawing helpers ----
  167. def _cs(self, cp):
  168. return curses.color_pair(cp) if curses.has_colors() else 0
  169. def draw(self):
  170. s = self.scr; s.erase(); h, w = s.getmaxyx(); W = max(40, w)
  171. def ln(y, x, t, a=0):
  172. if 0 <= y < h: s.addnstr(y, x, t, max(0, w - x - 1), a)
  173. def rule(y, label=""):
  174. if 0 <= y < h:
  175. s.hline(y, 0, curses.ACS_HLINE, w - 1)
  176. if label: ln(y, 3, " %s " % label, self._cs(CP_HDR) | curses.A_BOLD)
  177. # title bar
  178. title = " ⬡ TRITON · steamless pairing manager "
  179. ln(0, 0, title.ljust(w - 1), self._cs(CP_TITLE) | curses.A_BOLD)
  180. # device line
  181. p = self.cur()
  182. if p:
  183. anyconn = any(v in ("CONNECTED", "CONNECTING") for v in self.conn.values())
  184. badge = "● live" if self.conn else "○ usb"
  185. ln(2, 2, "PUCK", self._cs(CP_KEY) | curses.A_BOLD)
  186. ln(2, 8, "%d/%d" % (self.pi + 1, len(self.pucks)), curses.A_DIM)
  187. ln(2, 14, p[0], curses.A_BOLD)
  188. ln(2, 14 + len(p[0]) + 3, badge, self._cs(CP_CONN if anyconn else CP_DIM))
  189. if p[1]:
  190. ln(2, w - len(p[1]) - 3, p[1].split("/")[-1], curses.A_DIM)
  191. else:
  192. ln(2, 2, "no puck found — plug in the copycat / dongle, press [r]", self._cs(CP_WARN))
  193. # slot table
  194. rule(4, "bond slots")
  195. ln(5, 2, " %-4s %-12s %-18s %-12s" % ("SLOT", "STATE", "CONTROLLER", "IBEX UUID"),
  196. self._cs(CP_DIM) | curses.A_BOLD)
  197. for i in range(4):
  198. st, sl = self.slot_state(i)
  199. cp, glyph = STATE_STYLE.get(st, (CP_DIM, "·"))
  200. sel = (i == self.slot_i)
  201. who = sl["serial"] or "—"
  202. cursor = "▶" if sel else " "
  203. base_a = self._cs(CP_SEL) | curses.A_BOLD if sel else 0
  204. ln(6 + i, 1, "%s ibex%d %s %-11s %-18s %-12s"
  205. % (cursor, i, glyph, st.lower(), who, sl.get("iuuid", "")), base_a)
  206. # controllers available
  207. rule(11, "docked controllers")
  208. ctrls = find_controllers()
  209. ln(12, 2, " ".join("%s" % c[1] for c in ctrls) or "(none docked)",
  210. self._cs(CP_OK) if ctrls else self._cs(CP_DIM))
  211. # log
  212. rule(14, "log")
  213. for i, m in enumerate(self.log[-(h - 18):]):
  214. ln(15 + i, 2, m, curses.A_DIM)
  215. # footer key bar
  216. keys = [("↑↓", "slot"), ("p", "pair"), ("u", "unpair"), ("F", "wipe"),
  217. ("P", "puck"), ("r", "rescan"), ("i", "refresh"), ("q", "quit")]
  218. x = 1
  219. for k, lbl in keys:
  220. seg = " %s " % k
  221. if x + len(seg) + len(lbl) + 2 < w:
  222. s.addnstr(h - 1, x, seg, len(seg), self._cs(CP_KEY) | curses.A_REVERSE | curses.A_BOLD)
  223. x += len(seg)
  224. s.addnstr(h - 1, x, " %s " % lbl, len(lbl) + 2, self._cs(CP_DIM))
  225. x += len(lbl) + 2
  226. s.refresh()
  227. def prompt(self, msg, color=CP_WARN):
  228. h, w = self.scr.getmaxyx(); curses.echo()
  229. self.scr.addnstr(h - 1, 0, (msg + " ").ljust(w - 1), w - 1,
  230. self._cs(color) | curses.A_REVERSE | curses.A_BOLD)
  231. self.scr.refresh()
  232. try: v = self.scr.getstr(h - 1, len(msg) + 1, 60).decode().strip()
  233. except Exception: v = ""
  234. curses.noecho(); return v
  235. def do_pair(self):
  236. p = self.cur(); i = self.slot_i
  237. if not p: return
  238. if i < len(self.slots) and self.slots[i]["serial"]:
  239. self.msg("slot %d occupied — pick a vacant slot or unpair first" % i); return
  240. ctrls = find_controllers()
  241. if not ctrls:
  242. self.msg("no USB-docked controller found — plug one in to pair"); return
  243. pid, cser = ctrls[0]
  244. if len(ctrls) > 1:
  245. pick = self.prompt("controllers %s — serial to pair:" % ",".join(c[1] for c in ctrls)).strip()
  246. for cp, cs in ctrls:
  247. if cs == pick: pid, cser = cp, cs; break
  248. if self.prompt("pair %s -> ibex%d ? type YES:" % (cser, i)) != "YES":
  249. self.msg("pair cancelled"); return
  250. uu = pair_full(p[0], i, pid, cser)
  251. self.msg("paired %s -> ibex%d (uuid %s) — UNDOCK controller to connect" % (cser, i, uu))
  252. time.sleep(1); self.refresh()
  253. def do_unpair(self):
  254. p = self.cur(); i = self.slot_i
  255. if not p or i >= len(self.slots) or not self.slots[i]["serial"]:
  256. self.msg("slot %d empty" % i); return
  257. target = self.slots[i]["serial"]
  258. if self.prompt("clear ibex%d (%s) ? type YES:" % (i, target)) != "YES":
  259. self.msg("unpair cancelled"); return
  260. scmd([PUCK_PID, "--serial", p[0], "--up", "1", "--idx", str(i), "A2"] + ["00"] * 24, timeout=12)
  261. self.msg("forget sent (slot %d)" % i); time.sleep(0.3); self.refresh()
  262. def do_factory(self):
  263. p = self.cur()
  264. if not p: return
  265. if self.prompt("wipe ALL slots ? type WIPE:") != "WIPE":
  266. self.msg("wipe cancelled"); return
  267. for i in range(4):
  268. scmd([PUCK_PID, "--serial", p[0], "--up", "1", "--idx", str(i), "A2"] + ["00"] * 24, timeout=12)
  269. self.msg("wiped all slots"); time.sleep(0.5); self.refresh()
  270. def run(self):
  271. while True:
  272. self.draw(); k = self.scr.getch()
  273. if k in (ord("q"), 27): break
  274. elif k in (curses.KEY_UP, ord("k")): self.slot_i = (self.slot_i - 1) % 4
  275. elif k in (curses.KEY_DOWN, ord("j")): self.slot_i = (self.slot_i + 1) % 4
  276. elif k == ord("P") and self.pucks:
  277. self.pi = (self.pi + 1) % len(self.pucks); self.refresh()
  278. elif k == ord("p"): self.do_pair()
  279. elif k == ord("u"): self.do_unpair()
  280. elif k == ord("F"): self.do_factory()
  281. elif k == ord("i"): self.refresh()
  282. elif k == ord("r"): self.rescan()
  283. def main(scr):
  284. curses.curs_set(0); scr.keypad(True)
  285. if curses.has_colors():
  286. curses.start_color(); curses.use_default_colors()
  287. curses.init_pair(CP_TITLE, curses.COLOR_CYAN, -1)
  288. curses.init_pair(CP_OK, curses.COLOR_GREEN, -1)
  289. curses.init_pair(CP_CONN, curses.COLOR_GREEN, -1)
  290. curses.init_pair(CP_WARN, curses.COLOR_YELLOW, -1)
  291. curses.init_pair(CP_DIM, curses.COLOR_WHITE, -1)
  292. curses.init_pair(CP_SEL, curses.COLOR_CYAN, -1)
  293. curses.init_pair(CP_KEY, curses.COLOR_BLACK, curses.COLOR_CYAN)
  294. curses.init_pair(CP_HDR, curses.COLOR_MAGENTA, -1)
  295. TUI(scr).run()
  296. if __name__ == "__main__":
  297. if not os.path.exists(SCMD):
  298. raise SystemExit("build scmd: clang -framework IOKit -framework CoreFoundation -o scmd scmd.c")
  299. curses.wrapper(main)