haptics.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 rings: one per bond slot. Multi-producer (USB ISR + loop-context console/xinput), one consumer
  48. // per slot (rfConnFlushRelay on that slot's poll turn). Producers serialize under PRIMASK.
  49. struct RelayMsg {
  50. uint8_t rid, len;
  51. uint8_t data[RELAY_MAXP];
  52. };
  53. // deep enough to hold a full Steam settings/LED transaction burst without loss
  54. #define RELAY_QLEN 32
  55. static RelayMsg g_rq[NSLOT][RELAY_QLEN];
  56. static volatile uint8_t g_rqHead[NSLOT];
  57. static volatile uint8_t
  58. g_rqTail[NSLOT]; // head=next write, tail=next read; empty when equal
  59. static inline uint8_t rqNext(uint8_t i)
  60. {
  61. return (uint8_t)((i + 1) % RELAY_QLEN);
  62. }
  63. bool relayPending()
  64. {
  65. // check the current slot's queue; called from rfConnQueueHapticRelay which runs with g_curSlot set
  66. int cur = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  67. return g_rqHead[cur] != g_rqTail[cur];
  68. }
  69. bool relayEnqueue(uint8_t rid, const uint8_t *payload, uint8_t plen,
  70. uint8_t slot)
  71. {
  72. if (plen > RELAY_MAXP)
  73. plen = RELAY_MAXP;
  74. if (slot != 0xFF && slot >= NSLOT)
  75. return false;
  76. uint32_t pm = __get_PRIMASK();
  77. __disable_irq();
  78. // slot=0xFF: broadcast -- enqueue into every slot's ring.
  79. // Full queue: evict the oldest entry, never the newest. Steam bursts end with the commit/stop, so
  80. // dropping the oldest keeps the most-recent (meaningful) frame.
  81. uint8_t s0 = (slot == 0xFF) ? 0 : slot;
  82. uint8_t s1 = (slot == 0xFF) ? NSLOT : slot + 1;
  83. for (uint8_t s = s0; s < s1; s++) {
  84. uint8_t h = g_rqHead[s], nx = rqNext(h);
  85. if (nx == g_rqTail[s])
  86. g_rqTail[s] = rqNext(g_rqTail[s]);
  87. g_rq[s][h].rid = rid;
  88. g_rq[s][h].len = plen;
  89. if (plen)
  90. memcpy(g_rq[s][h].data, payload, plen);
  91. g_rqHead[s] = nx;
  92. }
  93. // Any haptic relay arms the idle-clear (so the during-use latch gets cleared in every mode).
  94. if (rid == 0x82 || rid == 0x80) {
  95. g_haptic82Ms = millis();
  96. g_hapClearArmed = true;
  97. }
  98. __set_PRIMASK(pm);
  99. return true;
  100. }
  101. #if OPK_LOG
  102. // diagnostic capture: a ring of the last OUTPUT reports Steam sends (rid/slot/bytes/ms), dumped with 'H'.
  103. struct HapLog {
  104. uint32_t ms;
  105. uint8_t slot, rid, n, b[16];
  106. }; // 16 payload bytes: capture full 0x87 settings frames
  107. // Big always-on ring: log EVERYTHING from boot (Steam writes, our TX-to-controller, link edges) so a rare
  108. // reconnect-buzz can be caught after the fact -- the trigger happens moments after boot, while this RAM is
  109. // fresh, and we dump it once the panel reconnects. 4096 * 20B ~= 80KB.
  110. #define HAPLOG_N 4096
  111. static HapLog g_hapLog[HAPLOG_N];
  112. static uint16_t g_hapHead = 0;
  113. static uint16_t g_hapTail =
  114. 0; // live/dump drain cursor (loop-context reader; chases g_hapHead)
  115. void hapLogAdd(uint8_t slot, uint8_t rid, const uint8_t *b, uint16_t n)
  116. {
  117. // Written from the USB SET ISR (handleSet) AND loop context (relay flush / link edges) -> guard g_hapHead.
  118. // Special slot markers for the diagnostic capture: 0xFE = a frame WE transmitted to the controller (TX
  119. // relay); 0xFD = a link state edge (b[0]=1 up, 0 down). Real Steam writes use the interface index (0..3).
  120. uint32_t pm = __get_PRIMASK();
  121. __disable_irq();
  122. HapLog &e = g_hapLog[g_hapHead];
  123. e.ms = millis();
  124. e.slot = slot;
  125. e.rid = rid;
  126. e.n = (uint8_t)(n > 255 ? 255 : n);
  127. for (int i = 0; i < 16; i++)
  128. e.b[i] = (i < (int)n) ? b[i] : 0;
  129. g_hapHead = (uint8_t)((g_hapHead + 1) %
  130. (sizeof g_hapLog / sizeof g_hapLog[0]));
  131. __set_PRIMASK(pm);
  132. }
  133. void hapticDumpLog()
  134. {
  135. const uint16_t N = HAPLOG_N;
  136. uint32_t now = millis();
  137. Serial.printf("# --- capture history (now=%lu, curSlot=%d) ---\n",
  138. (unsigned long)now, g_curSlot);
  139. for (uint16_t i = 0; i < N; i++) {
  140. HapLog &e = g_hapLog[(uint16_t)((g_hapHead + i) % N)];
  141. if (!e.ms && !e.rid)
  142. continue;
  143. Serial.printf("# -%lums if%u rid=%02X n=%u:",
  144. (unsigned long)(now - e.ms), e.slot, e.rid, e.n);
  145. for (uint8_t j = 0; j < 16 && j < e.n; j++)
  146. Serial.printf(" %02X", e.b[j]);
  147. Serial.println();
  148. }
  149. Serial.println("# --- end ---");
  150. }
  151. // ---- drain cursor: stream entries to the WebUSB panel. resetDrain(false)=from "now" (live only);
  152. // resetDrain(true)=from the OLDEST entry (dump the whole ring from boot). pull skips empty slots. ----
  153. void hapLogResetDrain(bool fromBoot)
  154. {
  155. // oldest slot (the next-to-overwrite holds it)
  156. g_hapTail = fromBoot ? (uint16_t)((g_hapHead + 1) % HAPLOG_N) :
  157. // "now"
  158. g_hapHead;
  159. }
  160. bool hapLogPull(uint32_t *logMs, uint8_t *slot, uint8_t *rid, uint8_t *n,
  161. uint8_t bytes16[16])
  162. {
  163. while (g_hapTail != g_hapHead) {
  164. HapLog &e = g_hapLog[g_hapTail];
  165. g_hapTail = (uint16_t)((g_hapTail + 1) % HAPLOG_N);
  166. if (!e.ms && !e.rid)
  167. continue; // skip empty slot (ring not yet full)
  168. // Return the ABSOLUTE log time (millis since boot), not "age now". The panel drains in batches 100ms
  169. // apart, so an age computed here would jump between batches; the panel computes age vs the newest entry.
  170. *logMs = e.ms;
  171. *slot = e.slot;
  172. *rid = e.rid;
  173. *n = (e.n > 16) ? 16 : e.n;
  174. memcpy(bytes16, e.b, 16);
  175. return true;
  176. }
  177. return false;
  178. }
  179. #endif // OPK_LOG
  180. // Per-slot helpers. slot==-1 (default) checks the CURRENT poll slot (g_curSlot), used by flush-time code
  181. // paths that don't have a slot in hand. Callers with a real slot pass it in.
  182. bool hapticLinkUp(int slot)
  183. {
  184. int s = (slot >= 0) ? slot : g_curSlot;
  185. if (s < 0 || s >= NSLOT)
  186. return false;
  187. return g_slot[s].used && (millis() - g_connReplyMs[s]) < 300;
  188. }
  189. bool haptic82Blocked(int slot)
  190. {
  191. int s = (slot >= 0) ? slot : g_curSlot;
  192. if (s < 0 || s >= NSLOT)
  193. return true;
  194. return !hapticLinkUp(s) ||
  195. (g_hapticBlockUntil[s] &&
  196. (int32_t)(millis() - g_hapticBlockUntil[s]) < 0);
  197. }
  198. // "Is haptics from this USB interface's slot allowed through?" -- the slot must be currently connected.
  199. bool hapticRelaySlotOk(int slot)
  200. {
  201. return slot >= 0 && slot < NSLOT && hapticLinkUp(slot);
  202. }
  203. static bool haptic82PayloadOn(const uint8_t *p, uint16_t n)
  204. {
  205. if (n < 3)
  206. return false;
  207. for (uint16_t i = 2; i < n; i++)
  208. if (p[i])
  209. // observed form is [01 01 gain], but treat any trailing non-zero as active
  210. return true;
  211. return false;
  212. }
  213. static void hapticCancelPendingOn()
  214. {
  215. // void queued ON entries across all slot queues (stale haptics / rumble across a reconnect)
  216. uint32_t pm = __get_PRIMASK();
  217. __disable_irq();
  218. for (int s = 0; s < NSLOT; s++) {
  219. for (uint8_t i = g_rqTail[s]; i != g_rqHead[s]; i = rqNext(i)) {
  220. RelayMsg &m = g_rq[s][i];
  221. if (m.rid == 0x82) {
  222. bool on = false;
  223. for (uint8_t j = 2; j < m.len; j++)
  224. if (m.data[j]) {
  225. on = true;
  226. break;
  227. }
  228. if (on)
  229. m.rid = 0;
  230. }
  231. if (m.rid == 0x80) {
  232. bool on = false;
  233. for (uint8_t j = 0; j < m.len; j++)
  234. if (m.data[j]) {
  235. on = true;
  236. break;
  237. }
  238. if (on)
  239. m.rid = 0;
  240. }
  241. }
  242. }
  243. __set_PRIMASK(pm);
  244. }
  245. void haptic82HostReport(const uint8_t *p, uint16_t n)
  246. {
  247. if (n < 3)
  248. return;
  249. g_haptic82Ms = millis();
  250. // any haptic activity arms a clear when it next goes idle (kills a latch from this use)
  251. g_hapClearArmed = true;
  252. // Track on/off only. Do NOT synthesize a stop burst: Steam's own stop is forwarded verbatim, and each extra
  253. // 0x82 is a discrete pad click -- the spurious end-of-movement "click"/buzz the real puck never produces.
  254. g_haptic82On = haptic82PayloadOn(p, n);
  255. }
  256. bool hapticSteamRumble(uint16_t lowFreq, uint16_t highFreq, uint8_t slot)
  257. {
  258. if (slot >= NSLOT)
  259. return false;
  260. // user rumble-strength scale (percent; 200 = double). Clamp to 16-bit.
  261. if (g_rumbleScale != 100) {
  262. uint32_t l = (uint32_t)lowFreq * g_rumbleScale / 100,
  263. h = (uint32_t)highFreq * g_rumbleScale / 100;
  264. lowFreq = (l > 0xFFFF) ? 0xFFFF : (uint16_t)l;
  265. highFreq = (h > 0xFFFF) ? 0xFFFF : (uint16_t)h;
  266. }
  267. bool on = lowFreq || highFreq;
  268. // Per-slot settle gate (the per-slot reconnect block + link-up check). 0x82 haptics in Steam mode use the
  269. // same gate; for XInput, the host only sends a stream while a controller is connected, so this also doubles
  270. // as "no controller here, no relay".
  271. if (on && haptic82Blocked(slot))
  272. return false;
  273. if (!on && !hapticLinkUp(slot))
  274. return false;
  275. // SDL's current Steam/Triton structs define output report 0x80 as:
  276. // type, uint16 intensity, {uint16 speed, int8 gain} left/right.
  277. // We map conventional gamepad low/high-frequency motors to left/right speeds and use max as intensity.
  278. uint16_t intensity = lowFreq > highFreq ? lowFreq : highFreq;
  279. uint8_t p[9];
  280. // haptic_type_t::HAPTIC_TYPE_RUMBLE; 0 is the off/zero report
  281. p[0] = on ? 0x04 : 0x00;
  282. p[1] = (uint8_t)(intensity & 0xFF);
  283. p[2] = (uint8_t)(intensity >> 8);
  284. p[3] = (uint8_t)(lowFreq & 0xFF);
  285. p[4] = (uint8_t)(lowFreq >> 8);
  286. p[5] = 0;
  287. p[6] = (uint8_t)(highFreq & 0xFF);
  288. p[7] = (uint8_t)(highFreq >> 8);
  289. p[8] = 0;
  290. if (!relayEnqueue(0x80, p, sizeof p, slot))
  291. return false;
  292. g_rumble80Ms[slot] = millis();
  293. g_rumble80On[slot] = on;
  294. return true;
  295. }
  296. // Queue a pending test-haptic / stop relay (runs inside the poll cadence -- never at raw loop rate). Test
  297. // haptics broadcast to all connected slots (slot 0xFF); the stop frame is broadcast too (a stuck latch can
  298. // affect any controller, and the haptic-engine clear-re-init is settings-only so it's harmless on healthy
  299. // ones).
  300. void rfConnQueueHapticRelay()
  301. {
  302. if (relayPending())
  303. return; // host relays first; injectables wait for an idle cycle
  304. static const uint8_t HAP_ON[3] = { 0x01, 0x01, 0xF7 };
  305. static const uint8_t HAP_OFF[3] = { 0x01, 0x01, 0x00 };
  306. if (g_testHaptic) {
  307. if (relayEnqueue(0x82, HAP_ON, 3, 0xFF))
  308. g_testHaptic--;
  309. } else if (g_hapticStop && !g_xbox) {
  310. if (relayEnqueue(0x82, HAP_OFF, 3, 0xFF))
  311. g_hapticStop--;
  312. }
  313. }
  314. // rfConnFlushRelay(ch, s1): drain one entry from the current slot's relay queue and TX it. Each slot's queue
  315. // is independent, so each controller only sees its own commands. With N connected slots the per-slot relay
  316. // rate is 1/N of the per-cycle rate; sustained buzz streams are still 1 packet/cycle/slot.
  317. void rfConnFlushRelay(uint8_t ch, uint8_t s1)
  318. {
  319. int cur = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  320. while (g_rqTail[cur] != g_rqHead[cur]) {
  321. RelayMsg &m = g_rq[cur][g_rqTail[cur]];
  322. // rid 0 = entry voided by hapticCancelPendingOn -> skip
  323. if (m.rid) {
  324. uint8_t rl = m.len;
  325. if (rl > RELAY_MAXP)
  326. rl = RELAY_MAXP;
  327. // On-air sub-TLV framing. CONFIRMED from real puck<->controller sniffs: a command LANDS on
  328. // the controller only with the type-01 + inner-len form E3 [2+rl][01][rid][innerlen][data];
  329. // the legacy form E3 [1+rl][05][rid][data] makes the controller DISCARD any 0x87+ command.
  330. //
  331. // Whitelist type-01 to only two commands: LED brightness (0x87 reg 0x2D) and power-off
  332. // (0x9F). Other 0x87 writes (e.g. reg 0x30 IMU enable, 0x34/0x35 haptic amplitude) must
  333. // stay on legacy form -- landing 0x30 freezes the gyro; landing 0x34/0x35 causes the buzz.
  334. bool land01 =
  335. (m.rid == 0x9F) ||
  336. (m.rid == 0x87 && rl >= 1 && m.data[0] == 0x2D);
  337. uint8_t p[5 + RELAY_MAXP], plen;
  338. if (land01) {
  339. p[0] = g_relayOp;
  340. p[1] = (uint8_t)(2 + rl);
  341. p[2] = 0x01;
  342. p[3] = m.rid;
  343. p[4] = rl;
  344. memcpy(p + 5, m.data, rl);
  345. plen = (uint8_t)(5 + rl);
  346. } else {
  347. p[0] = g_relayOp;
  348. p[1] = (uint8_t)(1 + rl);
  349. p[2] = 0x05;
  350. p[3] = m.rid;
  351. memcpy(p + 4, m.data, rl);
  352. plen = (uint8_t)(4 + rl);
  353. }
  354. hapLogAdd(0xFE, m.rid, m.data, rl);
  355. // release slot before TX
  356. g_rqTail[cur] = rqNext(g_rqTail[cur]);
  357. // s1 carries a PID distinct from the GET poll (caller cycles it) so the controller's ESB
  358. // dedup never treats the GET as a retransmit of this relay. 80us RX: relay is NO-ACK.
  359. rfConnTx(ch, s1, p, plen, 80);
  360. return; // one relay per poll cycle
  361. }
  362. g_rqTail[cur] = rqNext(g_rqTail[cur]);
  363. }
  364. }
  365. // Haptic-subsystem re-init: the captured sequence Steam sends when it (re)takes control (0x81 reset + 0x87
  366. // register writes). Brightness (reg 0x2D) is omitted to avoid stomping the LED. The 0x87 frames go out on
  367. // legacy framing so the controller discards them; the three 0x81 frames are the effective reset. slot=0xFF
  368. // broadcasts to all connected controllers (the re-init is settings-only and harmless on healthy controllers).
  369. // One-shot SET_SETTINGS (0x87) write of the controller's GLOBAL trackpad-haptics enable. The controller plays
  370. // touchpad haptic sequences autonomously (haptics-sequencer-touchpad) gated by settings/haptics/enabled; in the
  371. // emulated (non-Steam) modes the host never sends SC haptic reports, so the only way to silence the pad buzz is
  372. // to write this setting. Wire format [id][val u16 LE] -- confirmed from the controller's SET_SETTINGS handler
  373. // (decomp FUN_0001f61c; id 0x30 == settings/sensors/imu/mode is the cross-check anchor in the same id space).
  374. // The exact id for settings/haptics/enabled needs a one-time `scmd labels` HW read (candidates from the captured
  375. // reinit: 0x18 / 0x2e / 0x34 / 0x35). Until it is set, SETTING_HAPTICS_ENABLED stays 0xFF and this is inert.
  376. #define SETTING_HAPTICS_ENABLED 0xFF
  377. void hapticSetPadEnabled(uint8_t slot, bool on)
  378. {
  379. #if SETTING_HAPTICS_ENABLED != 0xFF
  380. uint8_t pl[3] = { SETTING_HAPTICS_ENABLED, (uint8_t)(on ? 1 : 0), 0 };
  381. relayEnqueue(0x87, pl, 3, slot);
  382. #else
  383. (void)slot;
  384. (void)on;
  385. #endif
  386. }
  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. // Re-apply the active emulated type's trackpad-haptics preference last (after the haptic-config writes
  411. // above, which would otherwise re-enable it). Default-on types send "enable"; Switch (padHaptics=0)
  412. // disables. Inert until the setting id is captured.
  413. hapticSetPadEnabled(slot, g_padHaptics != 0);
  414. }
  415. void hapticInit()
  416. {
  417. g_haptic82On = false;
  418. g_hapticStop = 0;
  419. for (int s = 0; s < NSLOT; s++) {
  420. g_rqHead[s] = g_rqTail[s] = 0;
  421. g_rumble80On[s] = false;
  422. g_rumble80Ms[s] = 0;
  423. // block stale Steam 0x82 until the link is stable after boot
  424. g_hapticBlockUntil[s] = millis() + HAPTIC_RECONNECT_BLOCK_MS;
  425. }
  426. }
  427. // Arm the post-(re)connect haptic block + schedule the clearing re-init. Called on the reliable first-reply
  428. // signal from rf_link and again from hapticTask's link-up edge detector. Per-slot: only the reconnected
  429. // slot is blocked; the broadcast re-init covers all slots.
  430. void hapticOnReconnect(int slot)
  431. {
  432. if (slot < 0 || slot >= NSLOT)
  433. return;
  434. g_hapticBlockUntil[slot] = millis() + HAPTIC_RECONNECT_BLOCK_MS;
  435. g_haptic82On = false;
  436. g_rumble80On[slot] = false;
  437. g_rumble80Ms[slot] = 0;
  438. hapticCancelPendingOn();
  439. // Re-init repeatedly across the settle window: the connect buzz engages early (during the block,
  440. // controller-internal), so a single late shot misses it.
  441. g_reinitAt = millis() + 200u;
  442. g_reinitLeft = HAPTIC_REINIT_SHOTS;
  443. uint8_t mk = 2;
  444. hapLogAdd(0xFD, 0xEE, &mk, 1);
  445. }
  446. void hapticTask()
  447. {
  448. // Per-slot link-edge detect (backup for hapticOnReconnect in rf_link).
  449. static bool wasHapticLinkUp[NSLOT] = { 0 };
  450. for (int s = 0; s < NSLOT; s++) {
  451. if (!g_slot[s].used)
  452. continue;
  453. bool up = hapticLinkUp(s);
  454. if (up && !wasHapticLinkUp[s]) {
  455. uint8_t mk = 1;
  456. hapLogAdd(0xFD, 0xEE, &mk, 1);
  457. hapticOnReconnect(s);
  458. }
  459. if (!up && wasHapticLinkUp[s]) {
  460. uint8_t mk = 0;
  461. hapLogAdd(0xFD, 0xEE, &mk, 1);
  462. }
  463. wasHapticLinkUp[s] = up;
  464. }
  465. if (g_reinitAt && anySlotLinkUp() &&
  466. (int32_t)(millis() - g_reinitAt) >= 0) {
  467. hapticReinit();
  468. g_reinitAt = (g_reinitLeft && --g_reinitLeft) ?
  469. (millis() + HAPTIC_REINIT_GAP_MS) :
  470. 0;
  471. }
  472. // Power-off on host sleep: only when VBUS is present (genuine sleep, not a cable unplug which also
  473. // trips the suspend edge briefly) AND the suspend has PERSISTED >= SUSPEND_OFF_MS. A brief USB
  474. // selective-suspend (host idle power-management) resumes in <1s; firing the power-off on its edge
  475. // powered the controllers off ourselves -> random drop/reconnect churn. Arm only on a genuine
  476. // resume->suspend edge (wasSusp=true at boot suppresses a false fire on boot-into-suspended).
  477. static bool wasSusp = true;
  478. static unsigned long suspSinceMs = 0;
  479. static bool suspArmed = false;
  480. bool susp = USBDevice.suspended();
  481. bool vbus = (NRF_POWER->USBREGSTATUS &
  482. POWER_USBREGSTATUS_VBUSDETECT_Msk) != 0;
  483. if (susp && !wasSusp) {
  484. suspSinceMs = millis();
  485. suspArmed = true;
  486. }
  487. if (!susp)
  488. suspArmed = false;
  489. if (suspArmed && vbus && (millis() - suspSinceMs) >= SUSPEND_OFF_MS) {
  490. hapticSendShutdown();
  491. suspArmed = false; // fire once per suspend
  492. }
  493. wasSusp = susp;
  494. // Steam-mode quiet timeout: mark 0x82 stream inactive. No synthesized stop -- Steam forwards its own.
  495. if (!g_xbox && g_haptic82On &&
  496. millis() - g_haptic82Ms > HAPTIC_QUIET_MS)
  497. g_haptic82On = false;
  498. // Per-slot stuck-rumble watchdog: force zero after 2.5s without a refresh.
  499. for (int s = 0; s < NSLOT; s++) {
  500. if (g_rumble80On[s] && millis() - g_rumble80Ms[s] > 2500u)
  501. hapticSteamRumble(0, 0, (uint8_t)s);
  502. }
  503. // Idle-clear: after haptic activity goes quiet, re-init once to clear any latch left behind.
  504. if (g_hapClearArmed &&
  505. (millis() - g_haptic82Ms) > HAPTIC_CLEAR_IDLE_MS) {
  506. g_hapClearArmed = false;
  507. hapticReinit();
  508. }
  509. }