haptics.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. #include "haptics.h"
  2. #include "bonds.h"
  3. #include "config.h"
  4. #include "rf_link.h"
  5. // USBDevice.suspended() -> autonomous controller power-off on host sleep
  6. #include <Adafruit_TinyUSB.h>
  7. #include <Arduino.h>
  8. #include <string.h>
  9. uint8_t g_relayOp = 0xE3; // E3 poll
  10. // relay sub-TLV TYPE byte. Vestigial: rfConnFlushRelay derives the on-air type from the report id (0x05 for
  11. // actuators/haptics <0x87, 0x01 for config/settings/LED >=0x87). Still exposed over WebUSB diagnostics.
  12. uint8_t g_relaySub = 0x05;
  13. volatile uint8_t g_testHaptic = 0;
  14. volatile uint8_t g_hapticStop = 0;
  15. // Per-slot reconnect block. 0 = idle; non-zero = drop haptics aimed at this slot until millis() catches up.
  16. unsigned long g_hapticBlockUntil[NSLOT] = { 0 };
  17. // Controller power-off. CONFIRMED from a real Windows USB capture of the Valve puck: Steam's "turn off
  18. // controller" is the single feature-0x01 command 0x9F with payload ASCII "off!" (6F 66 66 21). The dongle
  19. // forwards host feature reports verbatim, so the controller acts on report 0x9F directly -- we relay it the
  20. // same way (E3 SET sub-TLV). The wire relay is NO-ACK, so send a small burst: a single lost frame must not
  21. // leave the controller on.
  22. void hapticSendShutdown()
  23. {
  24. static const uint8_t OFF[4] = { 0x6f, 0x66, 0x66, 0x21 }; // "off!"
  25. // broadcast: every connected controller should power off, not just the slot the shutdown was triggered
  26. // from (the trigger can come from a Steam interface, the test button, or host-suspend -- any of which
  27. // "logically" means "all controllers off").
  28. for (uint8_t i = 0; i < HAPTIC_SHUTDOWN_SHOTS; i++)
  29. relayEnqueue(0x9F, OFF, sizeof OFF, 0xFF);
  30. }
  31. // millis of last 0x82 haptic OUTPUT relayed (Steam mode)
  32. static unsigned long g_haptic82Ms = 0;
  33. // a non-zero 0x82 haptic is currently active (awaiting host stop)
  34. static bool g_haptic82On = false;
  35. // millis of last translated host rumble (0x80), per-slot (4 XInput interfaces each have their own stream)
  36. static unsigned long g_rumble80Ms[NSLOT] = { 0 };
  37. // Steam/Triton rumble is latched on until an explicit zero report; tracked per-slot so each controller's
  38. // stuck-rumble watchdog is independent
  39. static bool g_rumble80On[NSLOT] = { false, false, false, false };
  40. // when to fire the next post-reconnect haptic re-init (0 = none scheduled)
  41. static unsigned long g_reinitAt = 0;
  42. // how many re-init shots remain in this connect window
  43. static uint8_t g_reinitLeft = 0;
  44. // haptic activity happened -> arm a clear once it goes idle (catches a
  45. // latch that engaged during/after use, even seconds after connect)
  46. static bool g_hapClearArmed = false;
  47. // ---- relay ring: multi-producer (USB ISR + loop-context console/xinput), single consumer (poll flush) ----
  48. // Producers serialize through a brief PRIMASK critical section (copy is <=62 bytes); the consumer only ever
  49. // touches the tail entry, which no producer writes while the ring isn't full -- so a flush can't be torn.
  50. struct RelayMsg {
  51. uint8_t rid, len, slot;
  52. uint8_t data[RELAY_MAXP];
  53. };
  54. // deep enough to hold a full Steam settings/LED transaction burst without loss
  55. #define RELAY_QLEN 32
  56. static RelayMsg g_rq[RELAY_QLEN];
  57. static volatile uint8_t
  58. g_rqHead = 0,
  59. g_rqTail = 0; // head=next write, tail=next read; empty when equal
  60. static inline uint8_t rqNext(uint8_t i)
  61. {
  62. return (uint8_t)((i + 1) % RELAY_QLEN);
  63. }
  64. bool relayPending()
  65. {
  66. return g_rqHead != g_rqTail;
  67. }
  68. bool relayEnqueue(uint8_t rid, const uint8_t *payload, uint8_t plen,
  69. uint8_t slot)
  70. {
  71. // 60B is the RF frame ceiling; longer can't be relayed
  72. if (plen > RELAY_MAXP)
  73. plen = RELAY_MAXP;
  74. uint32_t pm = __get_PRIMASK();
  75. __disable_irq();
  76. uint8_t h = g_rqHead, nx = rqNext(h);
  77. // Full -> evict the OLDEST entry, never the newest. Steam sends commands as bursts where the meaningful
  78. // frame comes LAST (a settings transaction ends with its commit; a haptic stream ends with its stop), so
  79. // dropping the oldest guarantees the most recent command (LED commit, haptic stop) always lands.
  80. if (nx == g_rqTail)
  81. g_rqTail = rqNext(g_rqTail);
  82. g_rq[h].rid = rid;
  83. g_rq[h].len = plen;
  84. g_rq[h].slot = slot;
  85. if (plen)
  86. memcpy(g_rq[h].data, payload, plen);
  87. g_rqHead = nx;
  88. // Any haptic relay (Steam OR Xbox rumble OR test) arms the idle-clear and refreshes its timer -- so the
  89. // during-use buzz gets cleared in EVERY USB mode. The re-init's own 0x81/0x87 deliberately don't match.
  90. if (rid == 0x82 || rid == 0x80) {
  91. g_haptic82Ms = millis();
  92. g_hapClearArmed = true;
  93. }
  94. __set_PRIMASK(pm);
  95. return true;
  96. }
  97. #if OPK_LOG
  98. // diagnostic capture: a ring of the last OUTPUT reports Steam sends (rid/slot/bytes/ms), dumped with 'H'.
  99. struct HapLog {
  100. uint32_t ms;
  101. uint8_t slot, rid, n, b[16];
  102. }; // 16 payload bytes: capture full 0x87 settings frames
  103. // Big always-on ring: log EVERYTHING from boot (Steam writes, our TX-to-controller, link edges) so a rare
  104. // reconnect-buzz can be caught after the fact -- the trigger happens moments after boot, while this RAM is
  105. // fresh, and we dump it once the panel reconnects. 4096 * 20B ~= 80KB.
  106. #define HAPLOG_N 4096
  107. static HapLog g_hapLog[HAPLOG_N];
  108. static uint16_t g_hapHead = 0;
  109. static uint16_t g_hapTail =
  110. 0; // live/dump drain cursor (loop-context reader; chases g_hapHead)
  111. void hapLogAdd(uint8_t slot, uint8_t rid, const uint8_t *b, uint16_t n)
  112. {
  113. // Written from the USB SET ISR (handleSet) AND loop context (relay flush / link edges) -> guard g_hapHead.
  114. // Special slot markers for the diagnostic capture: 0xFE = a frame WE transmitted to the controller (TX
  115. // relay); 0xFD = a link state edge (b[0]=1 up, 0 down). Real Steam writes use the interface index (0..3).
  116. uint32_t pm = __get_PRIMASK();
  117. __disable_irq();
  118. HapLog &e = g_hapLog[g_hapHead];
  119. e.ms = millis();
  120. e.slot = slot;
  121. e.rid = rid;
  122. e.n = (uint8_t)(n > 255 ? 255 : n);
  123. for (int i = 0; i < 16; i++)
  124. e.b[i] = (i < (int)n) ? b[i] : 0;
  125. g_hapHead = (uint8_t)((g_hapHead + 1) %
  126. (sizeof g_hapLog / sizeof g_hapLog[0]));
  127. __set_PRIMASK(pm);
  128. }
  129. void hapticDumpLog()
  130. {
  131. const uint16_t N = HAPLOG_N;
  132. uint32_t now = millis();
  133. Serial.printf("# --- capture history (now=%lu, curSlot=%d) ---\n",
  134. (unsigned long)now, g_curSlot);
  135. for (uint16_t i = 0; i < N; i++) {
  136. HapLog &e = g_hapLog[(uint16_t)((g_hapHead + i) % N)];
  137. if (!e.ms && !e.rid)
  138. continue;
  139. Serial.printf("# -%lums if%u rid=%02X n=%u:",
  140. (unsigned long)(now - e.ms), e.slot, e.rid, e.n);
  141. for (uint8_t j = 0; j < 16 && j < e.n; j++)
  142. Serial.printf(" %02X", e.b[j]);
  143. Serial.println();
  144. }
  145. Serial.println("# --- end ---");
  146. }
  147. // ---- drain cursor: stream entries to the WebUSB panel. resetDrain(false)=from "now" (live only);
  148. // resetDrain(true)=from the OLDEST entry (dump the whole ring from boot). pull skips empty slots. ----
  149. void hapLogResetDrain(bool fromBoot)
  150. {
  151. // oldest slot (the next-to-overwrite holds it)
  152. g_hapTail = fromBoot ? (uint16_t)((g_hapHead + 1) % HAPLOG_N) :
  153. // "now"
  154. g_hapHead;
  155. }
  156. bool hapLogPull(uint32_t *logMs, uint8_t *slot, uint8_t *rid, uint8_t *n,
  157. uint8_t bytes16[16])
  158. {
  159. while (g_hapTail != g_hapHead) {
  160. HapLog &e = g_hapLog[g_hapTail];
  161. g_hapTail = (uint16_t)((g_hapTail + 1) % HAPLOG_N);
  162. if (!e.ms && !e.rid)
  163. continue; // skip empty slot (ring not yet full)
  164. // Return the ABSOLUTE log time (millis since boot), not "age now". The panel drains in batches 100ms
  165. // apart, so an age computed here would jump between batches; the panel computes age vs the newest entry.
  166. *logMs = e.ms;
  167. *slot = e.slot;
  168. *rid = e.rid;
  169. *n = (e.n > 16) ? 16 : e.n;
  170. memcpy(bytes16, e.b, 16);
  171. return true;
  172. }
  173. return false;
  174. }
  175. #endif // OPK_LOG
  176. // Per-slot helpers. slot==-1 (default) checks the CURRENT poll slot (g_curSlot), used by flush-time code
  177. // paths that don't have a slot in hand. Callers with a real slot pass it in.
  178. bool hapticLinkUp(int slot)
  179. {
  180. int s = (slot >= 0) ? slot : g_curSlot;
  181. if (s < 0 || s >= NSLOT)
  182. return false;
  183. return g_slot[s].used && (millis() - g_connReplyMs[s]) < 300;
  184. }
  185. bool haptic82Blocked(int slot)
  186. {
  187. int s = (slot >= 0) ? slot : g_curSlot;
  188. if (s < 0 || s >= NSLOT)
  189. return true;
  190. return !hapticLinkUp(s) ||
  191. (g_hapticBlockUntil[s] &&
  192. (int32_t)(millis() - g_hapticBlockUntil[s]) < 0);
  193. }
  194. // "Is haptics from this USB interface's slot allowed through?" -- the slot must be currently connected.
  195. bool hapticRelaySlotOk(int slot)
  196. {
  197. return slot >= 0 && slot < NSLOT && hapticLinkUp(slot);
  198. }
  199. static bool haptic82PayloadOn(const uint8_t *p, uint16_t n)
  200. {
  201. if (n < 3)
  202. return false;
  203. for (uint16_t i = 2; i < n; i++)
  204. if (p[i])
  205. // observed form is [01 01 gain], but treat any trailing non-zero as active
  206. return true;
  207. return false;
  208. }
  209. static void hapticCancelPendingOn()
  210. {
  211. // void queued ON entries (stale Steam haptics / translated rumble across a reconnect)
  212. uint32_t pm = __get_PRIMASK();
  213. __disable_irq();
  214. for (uint8_t i = g_rqTail; i != g_rqHead; i = rqNext(i)) {
  215. RelayMsg &m = g_rq[i];
  216. if (m.rid == 0x82) {
  217. bool on = false;
  218. for (uint8_t j = 2; j < m.len; j++)
  219. if (m.data[j]) {
  220. on = true;
  221. break;
  222. }
  223. if (on)
  224. m.rid = 0;
  225. }
  226. if (m.rid == 0x80) {
  227. bool on = false;
  228. for (uint8_t j = 0; j < m.len; j++)
  229. if (m.data[j]) {
  230. on = true;
  231. break;
  232. }
  233. if (on)
  234. m.rid = 0;
  235. }
  236. }
  237. __set_PRIMASK(pm);
  238. }
  239. void haptic82HostReport(const uint8_t *p, uint16_t n, int slot)
  240. {
  241. // the on/off flag is global -- one relay stream keeps the watchdog armed across slots
  242. (void)slot;
  243. if (n < 3)
  244. return;
  245. g_haptic82Ms = millis();
  246. // any haptic activity arms a clear when it next goes idle (kills a latch from this use)
  247. g_hapClearArmed = true;
  248. // Track on/off only. Do NOT synthesize a stop burst: Steam's own stop is forwarded verbatim, and each extra
  249. // 0x82 is a discrete pad click -- the spurious end-of-movement "click"/buzz the real puck never produces.
  250. g_haptic82On = haptic82PayloadOn(p, n);
  251. }
  252. bool hapticSteamRumble(uint16_t lowFreq, uint16_t highFreq, uint8_t slot)
  253. {
  254. if (slot >= NSLOT)
  255. return false;
  256. // user rumble-strength scale (percent; 200 = double). Clamp to 16-bit.
  257. if (g_rumbleScale != 100) {
  258. uint32_t l = (uint32_t)lowFreq * g_rumbleScale / 100,
  259. h = (uint32_t)highFreq * g_rumbleScale / 100;
  260. lowFreq = (l > 0xFFFF) ? 0xFFFF : (uint16_t)l;
  261. highFreq = (h > 0xFFFF) ? 0xFFFF : (uint16_t)h;
  262. }
  263. bool on = lowFreq || highFreq;
  264. // Per-slot settle gate (the per-slot reconnect block + link-up check). 0x82 haptics in Steam mode use the
  265. // same gate; for XInput, the host only sends a stream while a controller is connected, so this also doubles
  266. // as "no controller here, no relay".
  267. if (on && haptic82Blocked(slot))
  268. return false;
  269. if (!on && !hapticLinkUp(slot))
  270. return false;
  271. // SDL's current Steam/Triton structs define output report 0x80 as:
  272. // type, uint16 intensity, {uint16 speed, int8 gain} left/right.
  273. // We map conventional gamepad low/high-frequency motors to left/right speeds and use max as intensity.
  274. uint16_t intensity = lowFreq > highFreq ? lowFreq : highFreq;
  275. uint8_t p[9];
  276. // haptic_type_t::HAPTIC_TYPE_RUMBLE; 0 is the off/zero report
  277. p[0] = on ? 0x04 : 0x00;
  278. p[1] = (uint8_t)(intensity & 0xFF);
  279. p[2] = (uint8_t)(intensity >> 8);
  280. p[3] = (uint8_t)(lowFreq & 0xFF);
  281. p[4] = (uint8_t)(lowFreq >> 8);
  282. p[5] = 0;
  283. p[6] = (uint8_t)(highFreq & 0xFF);
  284. p[7] = (uint8_t)(highFreq >> 8);
  285. p[8] = 0;
  286. if (!relayEnqueue(0x80, p, sizeof p, slot))
  287. return false;
  288. g_rumble80Ms[slot] = millis();
  289. g_rumble80On[slot] = on;
  290. return true;
  291. }
  292. // Queue a pending test-haptic / stop relay (runs inside the poll cadence -- never at raw loop rate). Test
  293. // haptics broadcast to all connected slots (slot 0xFF); the stop frame is broadcast too (a stuck latch can
  294. // affect any controller, and the haptic-engine clear-re-init is settings-only so it's harmless on healthy
  295. // ones).
  296. void rfConnQueueHapticRelay()
  297. {
  298. if (relayPending())
  299. return; // host relays first; injectables wait for an idle cycle
  300. static const uint8_t HAP_ON[3] = { 0x01, 0x01, 0xF7 };
  301. static const uint8_t HAP_OFF[3] = { 0x01, 0x01, 0x00 };
  302. if (g_testHaptic) {
  303. if (relayEnqueue(0x82, HAP_ON, 3, 0xFF))
  304. g_testHaptic--;
  305. } else if (g_hapticStop && !g_xbox) {
  306. if (relayEnqueue(0x82, HAP_OFF, 3, 0xFF))
  307. g_hapticStop--;
  308. }
  309. }
  310. // rfConnFlushRelay(ch, s1): scan the queue for the first entry that targets the CURRENT slot (g_curSlot),
  311. // or the broadcast sentinel 0xFF. Emit it on that slot's session address (so each controller only sees
  312. // its own relay). With 4 connected slots the per-slot relay rate is 1/4 of the per-cycle rate; sustained
  313. // buzz streams are still 1 packet/cycle/slot which the controller's haptic engine handles fine.
  314. void rfConnFlushRelay(uint8_t ch, uint8_t s1)
  315. {
  316. int cur = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  317. while (g_rqTail != g_rqHead) {
  318. RelayMsg &m = g_rq[g_rqTail];
  319. // rid 0 = entry voided by hapticCancelPendingOn -> skip, take the next
  320. if (m.rid) {
  321. // Only relay entries for the CURRENT slot (or broadcast 0xFF). If the entry is for
  322. // another slot, leave it in the queue -- its slot's turn will pick it up.
  323. if (m.slot != 0xFF && m.slot != cur) {
  324. // advance past it without consuming; the per-slot flush is the consumer
  325. g_rqTail = rqNext(g_rqTail);
  326. continue;
  327. }
  328. uint8_t rl = m.len;
  329. if (rl > RELAY_MAXP)
  330. rl = RELAY_MAXP;
  331. // On-air sub-TLV framing. CONFIRMED from real puck<->controller sniffs (puck_sniffer): a command LANDS on
  332. // the controller only with the type-01 + inner-len form E3 [2+rl][01][rid][innerlen][data]; with the legacy
  333. // form E3 [1+rl][05][rid][data] (no inner-len) the controller DISCARDS any 0x87+ command (it reads data[0]
  334. // as the length).
  335. //
  336. // WHITELIST the landing form to EXACTLY the two commands that need it; everything else keeps legacy form:
  337. // * LED brightness -- report 0x87 whose first register byte is 0x2D
  338. // * controller power-off -- report 0x9F ("off!")
  339. // Steam ALSO sends other 0x87 passthrough writes during play -- the haptic-config block (reg 0x30 =
  340. // IMU/subsystem enable, 0x34/0x35 = haptic amplitude). Landing those regresses BOTH: a landed 0x30 FREEZES
  341. // the IMU (gyro stops) and landed 0x34/0x35 = the connect buzz. So keep this list tight.
  342. bool land01 =
  343. (m.rid == 0x9F) ||
  344. (m.rid == 0x87 && rl >= 1 && m.data[0] == 0x2D);
  345. uint8_t p[5 + RELAY_MAXP], plen;
  346. if (land01) {
  347. p[0] = g_relayOp;
  348. p[1] = (uint8_t)(2 + rl);
  349. p[2] = 0x01;
  350. p[3] = m.rid;
  351. p[4] = rl;
  352. memcpy(p + 5, m.data, rl);
  353. plen = (uint8_t)(5 + rl);
  354. } else {
  355. p[0] = g_relayOp;
  356. p[1] = (uint8_t)(1 + rl);
  357. p[2] = 0x05;
  358. p[3] = m.rid;
  359. memcpy(p + 4, m.data, rl);
  360. plen = (uint8_t)(4 + rl);
  361. }
  362. // log what we actually TX to the controller (slot 0xFE) for the buzz hunt
  363. hapLogAdd(0xFE, m.rid, m.data, rl);
  364. // copied out -> release the slot before the TX
  365. g_rqTail = rqNext(g_rqTail);
  366. // s1 carries a PID distinct from the GET poll that follows (caller cycles it), so the controller's ESB
  367. // dedup never mistakes the GET for a retransmit of this relay. 80us RX window: the relay is NO-ACK, so
  368. // don't burn the full ~1.2ms reply window (that halves the poll rate during haptics).
  369. rfConnTx(ch, s1, p, plen, 80);
  370. // ONE relay per poll cycle (matches the real puck's pacing)
  371. return;
  372. }
  373. g_rqTail = rqNext(g_rqTail);
  374. }
  375. }
  376. // Haptic-subsystem RE-INIT: the exact sequence Steam sends (captured on hardware) when it (re)takes control,
  377. // which clears a stuck haptic script on the controller -- a 0x81 reset action plus 0x87 writes to the haptic
  378. // registers (30/07/08/31/52, 18/2e/34/35). Replayed to recover from the latched-buzz the controller falls
  379. // into across a reconnect. Brightness (0x87 reg 2d) is deliberately OMITTED so we don't stomp the LED.
  380. //
  381. // The 0x87 frames below go out on LEGACY (type-05) framing (the whitelist lands 0x87 only for brightness
  382. // 0x2D), so the controller DISCARDS them -- kept verbatim only to match the captured sequence. The effective
  383. // re-init is the three 0x81 frames. (Landing the 0x30 here would freeze the gyro.)
  384. //
  385. // slot defaults to 0xFF (broadcast to all connected) -- the clear re-init is a settings-only reset and
  386. // is harmless on healthy controllers, so it's worth re-initializing every slot the firmware knows about.
  387. void hapticReinit(uint8_t slot)
  388. {
  389. static const uint8_t H30[] = { 0x30, 0x00, 0x00, 0x07, 0x07,
  390. 0x00, 0x08, 0x07, 0x00, 0x31,
  391. 0x02, 0x00, 0x52, 0x03, 0x00 };
  392. static const uint8_t H18[] = { 0x18, 0x00, 0x00, 0x2e, 0x00,
  393. 0x00, 0x34, 0xff, 0xff, 0x35,
  394. 0xff, 0xff, 0x34, 0xff, 0xff };
  395. static const uint8_t H35[] = { 0x35, 0xff, 0xff, 0x2e, 0x00, 0x00 };
  396. static const uint8_t T81A[] = {
  397. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  398. };
  399. static const uint8_t T81B[] = {
  400. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  401. };
  402. // reset action (FUN_0001f554) -- Steam sends this first
  403. relayEnqueue(0x81, nullptr, 0, slot);
  404. relayEnqueue(0x87, H30, sizeof H30, slot);
  405. // haptic config (enabled/amplifier/gain): the part that clears a latch
  406. relayEnqueue(0x87, H18, sizeof H18, slot);
  407. relayEnqueue(0x87, H35, sizeof H35, slot);
  408. relayEnqueue(0x81, T81A, sizeof T81A, slot);
  409. relayEnqueue(0x81, T81B, sizeof T81B, slot);
  410. }
  411. void hapticInit()
  412. {
  413. g_rqHead = g_rqTail = 0;
  414. g_haptic82On = false;
  415. for (int s = 0; s < NSLOT; s++) {
  416. g_rumble80On[s] = false;
  417. g_rumble80Ms[s] = 0;
  418. }
  419. // boot: block stale Steam 0x82 until link stable (every slot)
  420. for (int s = 0; s < NSLOT; s++)
  421. g_hapticBlockUntil[s] = millis() + HAPTIC_RECONNECT_BLOCK_MS;
  422. // NO fabricated stop burst. USB capture proves Steam only ever sends 0x82 [01 01 f7] pulses -- never a
  423. // zero-gain [01 01 00] "stop". An invented stop frame at boot/connect is a likelier cause of the connect-time
  424. // buzz than a cure. Be a pure pass-through of Steam's haptics, like the real puck.
  425. g_hapticStop = 0;
  426. }
  427. // Arm the post-(re)connect haptic block + schedule the clearing re-init. Called from rf_link the moment a
  428. // controller reply arrives after a gap (the reliable reconnect signal), and as a backup on hapticTask's
  429. // link-up edge. Idempotent -- safe to call repeatedly. Per-slot: only the slot that just reconnected is
  430. // blocked, the other slots keep relaying. The scheduled re-init is global (broadcast) so any slot's
  431. // latch gets cleared.
  432. void hapticOnReconnect(int slot)
  433. {
  434. if (slot < 0 || slot >= NSLOT)
  435. return;
  436. // no haptics relayed for the next 3s (per-slot)
  437. g_hapticBlockUntil[slot] = millis() + HAPTIC_RECONNECT_BLOCK_MS;
  438. g_haptic82On = false;
  439. g_rumble80On[slot] = false;
  440. g_rumble80Ms[slot] = 0;
  441. // drop any haptic ON queued before the link came up
  442. hapticCancelPendingOn();
  443. // Re-init the haptic engine repeatedly across the settle window rather than waiting for the block to end: the
  444. // brief connect buzz engages early (during the block, controller-internal), so a single late shot misses it.
  445. // The re-init is settings only (no haptic play) and Steam haptics are blocked throughout, so it can't buzz.
  446. g_reinitAt = millis() + 200u; // first reset ~200ms after (re)connect
  447. // then every HAPTIC_REINIT_GAP_MS across the window
  448. g_reinitLeft = HAPTIC_REINIT_SHOTS;
  449. uint8_t mk = 2;
  450. // capture marker: RECONNECT detected (block+reinit armed)
  451. hapLogAdd(0xFD, 0xEE, &mk, 1);
  452. }
  453. void hapticTask()
  454. {
  455. // Per-slot link-edge detect: any slot going from "down" to "up" gets the haptic block + re-init
  456. // scheduled for that slot. The rf_link decode already calls hapticOnReconnect on the first F-reply
  457. // after a gap (reliable); this loop is a backup for slots whose link-up the decode didn't see directly
  458. // (e.g. a long gap followed by a quiet stretch).
  459. static bool wasHapticLinkUp[NSLOT] = { 0 };
  460. for (int s = 0; s < NSLOT; s++) {
  461. if (!g_slot[s].used)
  462. continue;
  463. bool up = hapticLinkUp(s);
  464. if (up && !wasHapticLinkUp[s]) {
  465. uint8_t mk = 1;
  466. hapLogAdd(0xFD, 0xEE, &mk, 1);
  467. hapticOnReconnect(s);
  468. }
  469. if (!up && wasHapticLinkUp[s]) {
  470. uint8_t mk = 0;
  471. hapLogAdd(0xFD, 0xEE, &mk, 1);
  472. }
  473. wasHapticLinkUp[s] = up;
  474. }
  475. // Proactive haptic re-init (scheduled at (re)connect by hapticOnReconnect): the re-init is
  476. // settings-only so broadcasting to all connected slots is fine, and it's the same per-slot
  477. // re-init the controller would have received on its own connect.
  478. if (g_reinitAt && anySlotLinkUp() &&
  479. (int32_t)(millis() - g_reinitAt) >=
  480. 0) { // proactive haptic re-init across the connect window
  481. hapticReinit();
  482. g_reinitAt = (g_reinitLeft && --g_reinitLeft) ?
  483. (millis() + HAPTIC_REINIT_GAP_MS) :
  484. 0;
  485. }
  486. // Controller power-off on host SLEEP: send the power-off command (0x9F "off!") the instant the USB bus
  487. // suspends, like the real puck. BUT only when USB power (VBUS) is still present -- i.e. a genuine host sleep,
  488. // NOT a cable unplug. Pulling the dongle ALSO trips the suspend edge (in the brief window it runs on residual
  489. // power), and we must NOT kill the controller then; it should only power off on a shutdown command or a real
  490. // host sleep. VBUSDETECT is 1 while the cable still delivers 5V, 0 once unplugged. wasSusp starts true so a
  491. // boot-into-suspended state never false-fires.
  492. static bool wasSusp = true;
  493. bool susp = USBDevice.suspended();
  494. bool vbus = (NRF_POWER->USBREGSTATUS &
  495. POWER_USBREGSTATUS_VBUSDETECT_Msk) != 0;
  496. if (susp && !wasSusp && vbus)
  497. hapticSendShutdown();
  498. wasSusp = susp;
  499. // Steam-mode: host went quiet -> mark the 0x82 stream inactive. Do NOT synthesize a stop: trackpad haptics
  500. // are one-shot pulses, so firing a 0x82-zero ~HAPTIC_QUIET_MS after a swipe ends is the extra end-of-movement
  501. // click the real puck doesn't make. Steam forwards its own stop for any sustained haptic.
  502. if (!g_xbox && g_haptic82On &&
  503. millis() - g_haptic82Ms > HAPTIC_QUIET_MS)
  504. g_haptic82On = false;
  505. // Per-slot stuck-rumble watchdog: if a controller's rumble stream has been "on" without a refresh for
  506. // 2.5s, force a zero report to clear the controller's latch. The previous single-stream watchdog
  507. // couldn't cover a 4-XInput scenario where only one slot is stuck (it would only fire when the
  508. // merged-flag went stale).
  509. for (int s = 0; s < NSLOT; s++) {
  510. if (g_rumble80On[s] && millis() - g_rumble80Ms[s] > 2500u)
  511. hapticSteamRumble(0, 0, (uint8_t)s);
  512. }
  513. // Haptic activity has gone idle for a while -> fire one re-init to clear any latch it left behind (the buzz
  514. // that engages during/after use and won't self-clear, incl. after a mode switch). Fires only after a quiet
  515. // gap, so it never interrupts active haptics; the brightness-less re-init is silent (settings, no play, no
  516. // LED). Runs in ALL modes (the controller-side latch is mode-independent).
  517. if (g_hapClearArmed &&
  518. (millis() - g_haptic82Ms) > HAPTIC_CLEAR_IDLE_MS) {
  519. g_hapClearArmed = false;
  520. hapticReinit();
  521. }
  522. }