puck_sniffer.ino 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. // puck_sniffer.ino -- PASSIVE 2.4GHz sniffer for the Valve SC2 puck <-> controller link.
  2. //
  3. // Flash this onto a SECOND nRF52840 board (NOT the one emulating a puck). It never transmits, so it cannot
  4. // disturb the real puck<->controller pairing -- it only listens. It reuses OpenPuck's CRC-validated radio
  5. // config (radio.cpp): PHY Ble_2Mbit, ENDIAN=Big, no whitening, CRC16 0x11021/0xFFFF, 5-byte ESB address.
  6. //
  7. // HOW IT FINDS THE SESSION
  8. // The puck and controller talk on a per-puck SESSION address/channel. The puck advertises those in its E1
  9. // host-frame beacon, which it sends on the SHARED discovery rendezvous ("ibex" / prefix 0x10 / channel 2).
  10. // So the sniffer: (1) ACQUIRE -- listen on ibex/ch2, catch an E1, read session base/prefix/channel from it;
  11. // (2) CAPTURE -- retune to that session address/channel and receive every frame both ways. E1 keepalives on
  12. // the session address re-advertise the channel, so a QoS channel-hop is followed; a stall re-acquires.
  13. //
  14. // Frame in RAM after RX (PCNF0 S0=0/LF=8/S1=3): rfrx[0]=LENGTH(payload bytes), rfrx[1]=S1, rfrx[2..]=payload.
  15. // payload[0] (rfrx[2]) is the opcode: 0xE? = puck->controller, 0xF? = controller->puck.
  16. //
  17. // STREAM (over WebUSB bulk IN), little-endian:
  18. // packet: C0 DE [N] [t_us:4] [ch] [flags] [rssi] [match] [N raw bytes] flags bit0=CRC ok; match=RXMATCH pipe
  19. // status: C1 DE [state][curCh][b0 b1 b2 b3][prefix][cap][rxLo rxHi][advCh][ab0 ab1 ab2 ab3][apfx][lastMatch]
  20. // (state 0=acquire 1=capture; adv* = session params last parsed out of an E1 host frame; 19 bytes)
  21. // COMMANDS (WebUSB bulk OUT):
  22. // 01 start | 02 stop | 03 re-acquire (back to ibex/ch2) | 04 <ch> pin channel (keep current address)
  23. // 05 <b0 b1 b2 b3 pfx ch> pin a full session: force this exact base/prefix/channel (use after reading a real
  24. // E1 by eye -- the surest way to camp on the session when auto-acquire's fixed E1 offsets are wrong)
  25. //
  26. // Build (Adafruit nRF52 core, same flags as OpenPuck):
  27. // arduino-cli compile -b adafruit:nrf52:feather52840 \
  28. // --build-property "build.extra_flags=-DNRF52840_XXAA {build.flags.usb}" puck_sniffer
  29. #include <Adafruit_TinyUSB.h>
  30. #include <Arduino.h>
  31. #include "radio.h"
  32. Adafruit_USBD_WebUSB usb_web;
  33. // ---- capture ring (single producer + consumer, both loop context -> no locking) ----
  34. struct Cap {
  35. uint32_t t;
  36. uint8_t ch, flags, rssi, match, n;
  37. uint8_t b[96];
  38. };
  39. #define RINGN 512
  40. static Cap g_ring[RINGN];
  41. static volatile uint16_t g_head = 0, g_tail = 0;
  42. static inline uint16_t rnext(uint16_t i)
  43. {
  44. return (uint16_t)((i + 1) % RINGN);
  45. }
  46. static void rxArmInit();
  47. static void tuneDiscovery();
  48. static void tuneSession();
  49. static bool g_streaming = false; // app sent START -> emit packet frames
  50. static uint8_t g_state = 0; // 0=ACQUIRE (ibex/ch2), 1=CAPTURE (session)
  51. static uint8_t g_curCh = 2;
  52. static uint8_t g_sBase[4] = { 0x69, 0x62, 0x65, 0x78 };
  53. static uint8_t g_sPrefix = 0x10;
  54. static uint8_t g_forceCh =
  55. 0; // !=0 -> user pinned a channel (skip auto-acquire retune)
  56. static bool g_pinSession =
  57. false; // user pinned a FULL session (cmd 05): never auto-retune addr/ch
  58. // cmd 06: stay on ibex/ch2 and stream EVERY E1 beacon, never auto-lock
  59. // (so you can see how many pucks/slots are advertising + their bases)
  60. static bool g_survey = false;
  61. // cmd 07: lock ONLY the E1 whose ibex_uuid (E1 payload bytes, = rfrx[7..10], LE) matches -- the puck beacons one
  62. // E1 per bonded slot and we must pick the CONNECTED controller's. Read its uuid from pairtui (e.g. 0xEF7171B4).
  63. static bool g_haveTarget = false;
  64. static uint8_t g_targetIbex[4] = { 0, 0, 0, 0 };
  65. static unsigned long g_lastRx = 0; // for stall -> sweep/re-acquire
  66. static uint8_t g_lastMatch =
  67. 0; // RXMATCH pipe of the most recent frame (diagnostic)
  68. // What the last E1 host frame ADVERTISED (parsed by the assumed offsets). Reported in status EVEN IF we don't
  69. // lock, so the panel can show whether those offsets are sane (channel in range, address non-degenerate) -- the
  70. // fastest way to tell if auto-acquire is mis-reading the real puck's E1.
  71. static uint8_t g_advCh = 0, g_advBase[4] = { 0, 0, 0, 0 }, g_advPfx = 0;
  72. // CAPTURE-mode stall sweep: instead of jumping straight back to discovery (which abandons the session and
  73. // strands us on ch2 seeing only E1/E2), step through clean candidate channels KEEPING the learned address --
  74. // this follows a QoS channel hop. Only after a couple of fully-dry sweeps do we fall back to discovery.
  75. static const uint8_t SWEEP_CH[] = { 18, 46, 76, 22, 68, 2, 80, 52, 55, 56, 57 };
  76. static uint8_t g_sweepIdx = 0, g_sweepDry = 0;
  77. // Gazell session-hunt: the puck's 5Hz E1/E2 keepalive trickles in on the primary channel even when the
  78. // controller isn't being actively polled, so "no packets" never fires the sweep. The ACTIVE session (E3 poll +
  79. // 0xF* controller reply) rides a ~3-channel set {primary,2,80} derived from the per-session address. So HUNT on
  80. // "no 0xF* reply" instead: dwell briefly on each of {primary,2,80,+clean candidates} until the controller's
  81. // replies appear, then PARK there. g_lastFrx = last controller (0xF*) frame; g_primaryCh = E1-advertised channel.
  82. static const uint8_t HUNT_CH[] = { 2, 80, 18, 46, 76, 22, 68, 52 };
  83. static uint8_t g_primaryCh = 78, g_huntIdx = 0;
  84. static unsigned long g_lastFrx = 0, g_huntMs = 0;
  85. #define HUNT_DWELL_MS 350u
  86. #define HUNT_NOFRX_MS 1000u
  87. static void tuneDiscovery()
  88. {
  89. g_state = 0;
  90. g_curCh = 2;
  91. rfConfig(2);
  92. rfSetAddr(PAIR_BASE, 0x10);
  93. rxArmInit();
  94. }
  95. // Session RX listens across all 8 pipes on the learned base (rfSetAddrMulti) so a same-base/other-prefix
  96. // controller reply is still caught; RXMATCH tells us which pipe each frame used.
  97. static void tuneSession()
  98. {
  99. g_state = 1;
  100. rfConfig(g_curCh);
  101. rfSetAddrMulti(g_sBase, g_sPrefix);
  102. rxArmInit();
  103. }
  104. // Continuous (gapless) RX: READY->START and END->START keep the radio receiving; ADDRESS->RSSISTART samples
  105. // signal strength for each packet. We poll EVENTS_END and copy rfrx before the next packet can overwrite it.
  106. static void rxArmInit()
  107. {
  108. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  109. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  110. RADIO_SHORTS_END_START_Msk |
  111. RADIO_SHORTS_ADDRESS_RSSISTART_Msk |
  112. RADIO_SHORTS_DISABLED_RSSISTOP_Msk;
  113. NRF_RADIO->EVENTS_END = 0;
  114. NRF_RADIO->EVENTS_ADDRESS = 0;
  115. NRF_RADIO->TASKS_RXEN = 1;
  116. }
  117. static void ringPush(uint32_t t, uint8_t ch, bool crcok, uint8_t rssi,
  118. uint8_t match, const uint8_t *b, uint8_t n)
  119. {
  120. uint16_t h = g_head, nx = rnext(h);
  121. if (nx == g_tail)
  122. g_tail = rnext(g_tail); // full -> drop oldest
  123. Cap &c = g_ring[h];
  124. c.t = t;
  125. c.ch = ch;
  126. c.flags = crcok ? 1 : 0;
  127. c.rssi = rssi;
  128. c.match = match;
  129. c.n = n;
  130. memcpy(c.b, b, n);
  131. g_head = nx;
  132. }
  133. // Drain the radio: copy every completed RX frame into the ring. Called very often from loop() so the tight
  134. // poll->reply exchange is caught. RSSISAMPLE/CRCSTATUS belong to the frame whose END we just saw.
  135. static void rxPump()
  136. {
  137. for (int guard = 0; guard < 8 && NRF_RADIO->EVENTS_END; guard++) {
  138. NRF_RADIO->EVENTS_END = 0;
  139. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  140. uint8_t rssi = (uint8_t)(NRF_RADIO->RSSISAMPLE & 0x7F);
  141. // which logical address (pipe) the frame hit
  142. uint8_t match = (uint8_t)(NRF_RADIO->RXMATCH & 0x7);
  143. g_lastMatch = match;
  144. uint8_t len = rfrx[0];
  145. uint16_t n = (uint16_t)(2 + len);
  146. if (n > 96)
  147. n = 96; // LENGTH + S1 + payload, clamped
  148. ringPush(micros(), g_curCh, crcok, rssi, match, rfrx,
  149. (uint8_t)n);
  150. g_lastRx = millis();
  151. if (g_state == 1)
  152. // any frame on the session resets the dry-sweep count
  153. g_sweepDry = 0;
  154. if (crcok && len >= 1 && (rfrx[2] & 0xF0) == 0xF0)
  155. // controller reply = ACTIVE session here -> stop hunting, park
  156. g_lastFrx = millis();
  157. // Parse the session params advertised in an E1 host-frame (payload[0]=0xE1) by the ASSUMED offsets, and
  158. // always record them for the status report -- so the panel shows what auto-acquire would lock onto even
  159. // when we choose not to (lets us eyeball whether the real puck's offsets match ours).
  160. if (crcok && len >= 18 && rfrx[2] == 0xE1) {
  161. g_advCh = rfrx[11];
  162. g_advBase[0] = rfrx[15];
  163. g_advBase[1] = rfrx[16];
  164. g_advBase[2] = rfrx[17];
  165. g_advBase[3] = rfrx[18];
  166. g_advPfx = rfrx[19];
  167. if (g_pinSession || g_survey)
  168. // pinned / survey -> never auto-retune (just record adv)
  169. continue;
  170. // Target a specific bonded slot by its ibex_uuid (E1 bytes rfrx[7..10]): the puck beacons one E1 per slot,
  171. // so skip any E1 that isn't the CONNECTED controller's -- otherwise we lock an idle slot's keepalive.
  172. if (g_haveTarget &&
  173. memcmp(rfrx + 7, g_targetIbex, 4) != 0)
  174. continue;
  175. // ACQUIRE: lock onto the advertised session. CAPTURE: a different advertised channel = QoS hop -> follow.
  176. if (g_advCh >= 1 && g_advCh <= 80) {
  177. if (g_state == 0) {
  178. memcpy(g_sBase, g_advBase, 4);
  179. g_sPrefix = g_advPfx;
  180. g_primaryCh = g_advCh;
  181. g_curCh = g_forceCh ? g_forceCh :
  182. g_advCh;
  183. g_huntIdx = 0;
  184. g_lastFrx = millis();
  185. tuneSession();
  186. return;
  187. } else if (!g_forceCh && g_advCh != g_curCh) {
  188. g_curCh = g_advCh;
  189. tuneSession();
  190. return;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. // ---- WebUSB stream out ----
  197. static void emitPacket(const Cap &c)
  198. {
  199. uint8_t f[11 + 96];
  200. f[0] = 0xC0;
  201. f[1] = 0xDE;
  202. f[2] = c.n;
  203. f[3] = (uint8_t)c.t;
  204. f[4] = (uint8_t)(c.t >> 8);
  205. f[5] = (uint8_t)(c.t >> 16);
  206. f[6] = (uint8_t)(c.t >> 24);
  207. f[7] = c.ch;
  208. f[8] = c.flags;
  209. f[9] = c.rssi;
  210. f[10] = c.match;
  211. memcpy(f + 11, c.b, c.n);
  212. usb_web.write(f, (uint32_t)(11 + c.n));
  213. }
  214. static void emitStatus()
  215. {
  216. static unsigned long last = 0;
  217. if (millis() - last < 250)
  218. return;
  219. last = millis();
  220. static uint16_t rx = 0;
  221. rx++;
  222. uint8_t f[19] = { 0xC1, 0xDE,
  223. g_state, g_curCh,
  224. g_sBase[0], g_sBase[1],
  225. g_sBase[2], g_sBase[3],
  226. g_sPrefix, (uint8_t)(g_streaming ? 1 : 0),
  227. (uint8_t)rx, (uint8_t)(rx >> 8),
  228. g_advCh, g_advBase[0],
  229. g_advBase[1], g_advBase[2],
  230. g_advBase[3], g_advPfx,
  231. g_lastMatch };
  232. usb_web.write(f, sizeof f);
  233. usb_web.flush();
  234. }
  235. static void drainToHost()
  236. {
  237. if (!usb_web.connected())
  238. return;
  239. // bound per-call so RX stays responsive; the ring covers bursts
  240. uint16_t budget = 64;
  241. while (budget-- && g_tail != g_head) {
  242. if (g_streaming)
  243. emitPacket(g_ring[g_tail]);
  244. g_tail = rnext(g_tail);
  245. }
  246. usb_web.flush();
  247. emitStatus();
  248. }
  249. static void handleCmd()
  250. {
  251. while (usb_web.available()) {
  252. int c = usb_web.read();
  253. if (c < 0)
  254. break;
  255. if (c == 0x01) {
  256. g_streaming = true;
  257. g_head = g_tail = 0;
  258. } // START (flush stale ring)
  259. else if (c == 0x02) {
  260. g_streaming = false;
  261. } // STOP
  262. else if (c == 0x03) {
  263. g_forceCh = 0;
  264. g_pinSession = false;
  265. g_survey = false;
  266. tuneDiscovery();
  267. } // re-acquire from ibex/ch2
  268. else if (c == 0x06) {
  269. g_survey = !g_survey;
  270. g_forceCh = 0;
  271. g_pinSession = false;
  272. tuneDiscovery();
  273. } // survey: list all E1 beacons on ch2, no lock
  274. // target ibex_uuid: lock only the matching slot's E1
  275. else if (c == 0x07) {
  276. int u0 = usb_web.read(), u1 = usb_web.read(),
  277. u2 = usb_web.read(), u3 = usb_web.read();
  278. if (u0 >= 0 && u1 >= 0 && u2 >= 0 && u3 >= 0) {
  279. g_targetIbex[0] = u0;
  280. g_targetIbex[1] = u1;
  281. g_targetIbex[2] = u2;
  282. g_targetIbex[3] = u3;
  283. g_haveTarget = true;
  284. g_survey = false;
  285. g_forceCh = 0;
  286. g_pinSession = false;
  287. tuneDiscovery();
  288. }
  289. } else if (c == 0x04) {
  290. int ch = usb_web.read();
  291. if (ch >= 1 && ch <= 80) {
  292. g_forceCh = (uint8_t)ch;
  293. g_curCh = (uint8_t)ch;
  294. tuneSession();
  295. }
  296. } // pin channel, keep addr
  297. else if (c == 0x05) { // pin a FULL session: b0 b1 b2 b3 pfx ch
  298. int b0 = usb_web.read(), b1 = usb_web.read(),
  299. b2 = usb_web.read(), b3 = usb_web.read(),
  300. pf = usb_web.read(), ch = usb_web.read();
  301. if (b0 >= 0 && b1 >= 0 && b2 >= 0 && b3 >= 0 &&
  302. pf >= 0 && ch >= 1 && ch <= 80) {
  303. g_sBase[0] = b0;
  304. g_sBase[1] = b1;
  305. g_sBase[2] = b2;
  306. g_sBase[3] = b3;
  307. g_sPrefix = (uint8_t)pf;
  308. g_curCh = (uint8_t)ch;
  309. g_forceCh = (uint8_t)ch;
  310. g_pinSession = true;
  311. tuneSession();
  312. }
  313. }
  314. }
  315. }
  316. void setup()
  317. {
  318. // Standard Adafruit WebUSB setup (keep the default CDC composite; just add the WebUSB vendor interface). No
  319. // landing page -> no Chrome "open <url>" notification. No detach/clearConfiguration: that's OpenPuck-specific
  320. // endpoint juggling and can leave the WebUSB stream un-enabled.
  321. // 'SN' -- distinct PID so the host doesn't confuse it with a puck
  322. USBDevice.setID(0x28DE, 0x534E);
  323. USBDevice.setManufacturerDescriptor("Valve Software");
  324. USBDevice.setProductDescriptor("OpenPuck Sniffer");
  325. usb_web.begin();
  326. Serial.begin(115200);
  327. for (int i = 0; i < 200 && !USBDevice.mounted(); i++)
  328. delay(10);
  329. // harmless (we never TX); leaves the radio tunables at their validated defaults
  330. rfGenSessionAddr();
  331. tuneDiscovery();
  332. g_lastRx = millis();
  333. }
  334. void loop()
  335. {
  336. rxPump();
  337. handleCmd();
  338. // pump again around the (fast, buffered) USB work to catch tight poll->reply pairs
  339. rxPump();
  340. drainToHost();
  341. // Session HUNT (Gazell). A pinned session (cmd 04/05) is never disturbed. Otherwise: while we're NOT seeing the
  342. // controller's 0xF* replies (the ACTIVE session), the keepalive trickles in on the primary but the real E3/F1
  343. // exchange is on another channel of the per-session set -> hunt {primary,2,80,+candidates}, dwelling briefly on
  344. // each, KEEPING the learned address. The instant a 0xF* arrives (g_lastFrx) we stop and park there. After two
  345. // full dry passes (no replies anywhere -> session address likely changed on a reconnect) fall back to discovery
  346. // to re-read an E1. Hunting only runs when there are no replies, so an active capture is never disturbed.
  347. if (g_state == 1 && !g_forceCh && !g_pinSession &&
  348. millis() - g_lastFrx > HUNT_NOFRX_MS &&
  349. millis() - g_huntMs > HUNT_DWELL_MS) {
  350. g_huntMs = millis();
  351. uint8_t ch =
  352. (g_huntIdx == 0) ?
  353. g_primaryCh :
  354. HUNT_CH[(g_huntIdx - 1) % (sizeof HUNT_CH)];
  355. g_huntIdx++;
  356. if (g_huntIdx > 1 + 2 * (uint8_t)sizeof HUNT_CH) {
  357. g_huntIdx = 0;
  358. tuneDiscovery();
  359. g_lastFrx = millis();
  360. g_huntMs = millis();
  361. return;
  362. }
  363. g_curCh = ch;
  364. rfConfig(g_curCh);
  365. rfSetAddrMulti(g_sBase, g_sPrefix);
  366. rxArmInit();
  367. }
  368. }