usb_main.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. /*
  2. * (c) 2015 flabberast <s3+flabbergast@sdfeu.org>
  3. *
  4. * Based on the following work:
  5. * - Guillaume Duc's raw hid example (MIT License)
  6. * https://github.com/guiduc/usb-hid-chibios-example
  7. * - PJRC Teensy examples (MIT License)
  8. * https://www.pjrc.com/teensy/usb_keyboard.html
  9. * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD)
  10. * https://github.com/tmk/tmk_keyboard/
  11. * - ChibiOS demo code (Apache 2.0 License)
  12. * http://www.chibios.org
  13. *
  14. * Since some GPL'd code is used, this work is licensed under
  15. * GPL v2 or later.
  16. */
  17. /*
  18. * Implementation notes:
  19. *
  20. * USBEndpointConfig - Configured using explicit order instead of struct member name.
  21. * This is due to ChibiOS hal LLD differences, which is dependent on hardware,
  22. * "USBv1" devices have `ep_buffers` and "OTGv1" have `in_multiplier`.
  23. * Given `USBv1/hal_usb_lld.h` marks the field as "not currently used" this code file
  24. * makes the assumption this is safe to avoid littering with preprocessor directives.
  25. */
  26. #include <ch.h>
  27. #include <hal.h>
  28. #include <string.h>
  29. #include "usb_main.h"
  30. #include "host.h"
  31. #include "debug.h"
  32. #include "suspend.h"
  33. #ifdef SLEEP_LED_ENABLE
  34. # include "sleep_led.h"
  35. # include "led.h"
  36. #endif
  37. #include "wait.h"
  38. #include "usb_descriptor.h"
  39. #include "usb_driver.h"
  40. #ifdef NKRO_ENABLE
  41. # include "keycode_config.h"
  42. extern keymap_config_t keymap_config;
  43. #endif
  44. #ifdef JOYSTICK_ENABLE
  45. # include "joystick.h"
  46. #endif
  47. /* ---------------------------------------------------------
  48. * Global interface variables and declarations
  49. * ---------------------------------------------------------
  50. */
  51. #ifndef usb_lld_connect_bus
  52. # define usb_lld_connect_bus(usbp)
  53. #endif
  54. #ifndef usb_lld_disconnect_bus
  55. # define usb_lld_disconnect_bus(usbp)
  56. #endif
  57. uint8_t keyboard_idle __attribute__((aligned(2))) = 0;
  58. uint8_t keyboard_protocol __attribute__((aligned(2))) = 1;
  59. uint8_t keyboard_led_state = 0;
  60. volatile uint16_t keyboard_idle_count = 0;
  61. static virtual_timer_t keyboard_idle_timer;
  62. static void keyboard_idle_timer_cb(void *arg);
  63. report_keyboard_t keyboard_report_sent = {{0}};
  64. #ifdef MOUSE_ENABLE
  65. report_mouse_t mouse_report_blank = {0};
  66. #endif /* MOUSE_ENABLE */
  67. #ifdef EXTRAKEY_ENABLE
  68. uint8_t extra_report_blank[3] = {0};
  69. #endif /* EXTRAKEY_ENABLE */
  70. /* ---------------------------------------------------------
  71. * Descriptors and USB driver objects
  72. * ---------------------------------------------------------
  73. */
  74. /* HID specific constants */
  75. #define HID_GET_REPORT 0x01
  76. #define HID_GET_IDLE 0x02
  77. #define HID_GET_PROTOCOL 0x03
  78. #define HID_SET_REPORT 0x09
  79. #define HID_SET_IDLE 0x0A
  80. #define HID_SET_PROTOCOL 0x0B
  81. /*
  82. * Handles the GET_DESCRIPTOR callback
  83. *
  84. * Returns the proper descriptor
  85. */
  86. static const USBDescriptor *usb_get_descriptor_cb(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t wIndex) {
  87. (void)usbp;
  88. static USBDescriptor desc;
  89. uint16_t wValue = ((uint16_t)dtype << 8) | dindex;
  90. desc.ud_string = NULL;
  91. desc.ud_size = get_usb_descriptor(wValue, wIndex, (const void **const) & desc.ud_string);
  92. if (desc.ud_string == NULL)
  93. return NULL;
  94. else
  95. return &desc;
  96. }
  97. #ifndef KEYBOARD_SHARED_EP
  98. /* keyboard endpoint state structure */
  99. static USBInEndpointState kbd_ep_state;
  100. /* keyboard endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  101. static const USBEndpointConfig kbd_ep_config = {
  102. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  103. NULL, /* SETUP packet notification callback */
  104. kbd_in_cb, /* IN notification callback */
  105. NULL, /* OUT notification callback */
  106. KEYBOARD_EPSIZE, /* IN maximum packet size */
  107. 0, /* OUT maximum packet size */
  108. &kbd_ep_state, /* IN Endpoint state */
  109. NULL, /* OUT endpoint state */
  110. 2, /* IN multiplier */
  111. NULL /* SETUP buffer (not a SETUP endpoint) */
  112. };
  113. #endif
  114. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  115. /* mouse endpoint state structure */
  116. static USBInEndpointState mouse_ep_state;
  117. /* mouse endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  118. static const USBEndpointConfig mouse_ep_config = {
  119. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  120. NULL, /* SETUP packet notification callback */
  121. mouse_in_cb, /* IN notification callback */
  122. NULL, /* OUT notification callback */
  123. MOUSE_EPSIZE, /* IN maximum packet size */
  124. 0, /* OUT maximum packet size */
  125. &mouse_ep_state, /* IN Endpoint state */
  126. NULL, /* OUT endpoint state */
  127. 2, /* IN multiplier */
  128. NULL /* SETUP buffer (not a SETUP endpoint) */
  129. };
  130. #endif
  131. #ifdef SHARED_EP_ENABLE
  132. /* shared endpoint state structure */
  133. static USBInEndpointState shared_ep_state;
  134. /* shared endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  135. static const USBEndpointConfig shared_ep_config = {
  136. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  137. NULL, /* SETUP packet notification callback */
  138. shared_in_cb, /* IN notification callback */
  139. NULL, /* OUT notification callback */
  140. SHARED_EPSIZE, /* IN maximum packet size */
  141. 0, /* OUT maximum packet size */
  142. &shared_ep_state, /* IN Endpoint state */
  143. NULL, /* OUT endpoint state */
  144. 2, /* IN multiplier */
  145. NULL /* SETUP buffer (not a SETUP endpoint) */
  146. };
  147. #endif
  148. #if STM32_USB_USE_OTG1
  149. typedef struct {
  150. size_t queue_capacity_in;
  151. size_t queue_capacity_out;
  152. USBInEndpointState in_ep_state;
  153. USBOutEndpointState out_ep_state;
  154. USBInEndpointState int_ep_state;
  155. USBEndpointConfig inout_ep_config;
  156. USBEndpointConfig int_ep_config;
  157. const QMKUSBConfig config;
  158. QMKUSBDriver driver;
  159. } usb_driver_config_t;
  160. #else
  161. typedef struct {
  162. size_t queue_capacity_in;
  163. size_t queue_capacity_out;
  164. USBInEndpointState in_ep_state;
  165. USBOutEndpointState out_ep_state;
  166. USBInEndpointState int_ep_state;
  167. USBEndpointConfig in_ep_config;
  168. USBEndpointConfig out_ep_config;
  169. USBEndpointConfig int_ep_config;
  170. const QMKUSBConfig config;
  171. QMKUSBDriver driver;
  172. } usb_driver_config_t;
  173. #endif
  174. #if STM32_USB_USE_OTG1
  175. /* Reusable initialization structure - see USBEndpointConfig comment at top of file */
  176. # define QMK_USB_DRIVER_CONFIG(stream, notification, fixedsize) \
  177. { \
  178. .queue_capacity_in = stream##_IN_CAPACITY, .queue_capacity_out = stream##_OUT_CAPACITY, \
  179. .inout_ep_config = \
  180. { \
  181. stream##_IN_MODE, /* Interrupt EP */ \
  182. NULL, /* SETUP packet notification callback */ \
  183. qmkusbDataTransmitted, /* IN notification callback */ \
  184. qmkusbDataReceived, /* OUT notification callback */ \
  185. stream##_EPSIZE, /* IN maximum packet size */ \
  186. stream##_EPSIZE, /* OUT maximum packet size */ \
  187. NULL, /* IN Endpoint state */ \
  188. NULL, /* OUT endpoint state */ \
  189. 2, /* IN multiplier */ \
  190. NULL /* SETUP buffer (not a SETUP endpoint) */ \
  191. }, \
  192. .int_ep_config = \
  193. { \
  194. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ \
  195. NULL, /* SETUP packet notification callback */ \
  196. qmkusbInterruptTransmitted, /* IN notification callback */ \
  197. NULL, /* OUT notification callback */ \
  198. CDC_NOTIFICATION_EPSIZE, /* IN maximum packet size */ \
  199. 0, /* OUT maximum packet size */ \
  200. NULL, /* IN Endpoint state */ \
  201. NULL, /* OUT endpoint state */ \
  202. 2, /* IN multiplier */ \
  203. NULL, /* SETUP buffer (not a SETUP endpoint) */ \
  204. }, \
  205. .config = { \
  206. .usbp = &USB_DRIVER, \
  207. .bulk_in = stream##_IN_EPNUM, \
  208. .bulk_out = stream##_OUT_EPNUM, \
  209. .int_in = notification, \
  210. .in_buffers = stream##_IN_CAPACITY, \
  211. .out_buffers = stream##_OUT_CAPACITY, \
  212. .in_size = stream##_EPSIZE, \
  213. .out_size = stream##_EPSIZE, \
  214. .fixed_size = fixedsize, \
  215. .ib = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_IN_CAPACITY, stream##_EPSIZE)]){}, \
  216. .ob = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_OUT_CAPACITY, stream##_EPSIZE)]){}, \
  217. } \
  218. }
  219. #else
  220. /* Reusable initialization structure - see USBEndpointConfig comment at top of file */
  221. # define QMK_USB_DRIVER_CONFIG(stream, notification, fixedsize) \
  222. { \
  223. .queue_capacity_in = stream##_IN_CAPACITY, .queue_capacity_out = stream##_OUT_CAPACITY, \
  224. .in_ep_config = \
  225. { \
  226. stream##_IN_MODE, /* Interrupt EP */ \
  227. NULL, /* SETUP packet notification callback */ \
  228. qmkusbDataTransmitted, /* IN notification callback */ \
  229. NULL, /* OUT notification callback */ \
  230. stream##_EPSIZE, /* IN maximum packet size */ \
  231. 0, /* OUT maximum packet size */ \
  232. NULL, /* IN Endpoint state */ \
  233. NULL, /* OUT endpoint state */ \
  234. 2, /* IN multiplier */ \
  235. NULL /* SETUP buffer (not a SETUP endpoint) */ \
  236. }, \
  237. .out_ep_config = \
  238. { \
  239. stream##_OUT_MODE, /* Interrupt EP */ \
  240. NULL, /* SETUP packet notification callback */ \
  241. NULL, /* IN notification callback */ \
  242. qmkusbDataReceived, /* OUT notification callback */ \
  243. 0, /* IN maximum packet size */ \
  244. stream##_EPSIZE, /* OUT maximum packet size */ \
  245. NULL, /* IN Endpoint state */ \
  246. NULL, /* OUT endpoint state */ \
  247. 2, /* IN multiplier */ \
  248. NULL, /* SETUP buffer (not a SETUP endpoint) */ \
  249. }, \
  250. .int_ep_config = \
  251. { \
  252. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ \
  253. NULL, /* SETUP packet notification callback */ \
  254. qmkusbInterruptTransmitted, /* IN notification callback */ \
  255. NULL, /* OUT notification callback */ \
  256. CDC_NOTIFICATION_EPSIZE, /* IN maximum packet size */ \
  257. 0, /* OUT maximum packet size */ \
  258. NULL, /* IN Endpoint state */ \
  259. NULL, /* OUT endpoint state */ \
  260. 2, /* IN multiplier */ \
  261. NULL, /* SETUP buffer (not a SETUP endpoint) */ \
  262. }, \
  263. .config = { \
  264. .usbp = &USB_DRIVER, \
  265. .bulk_in = stream##_IN_EPNUM, \
  266. .bulk_out = stream##_OUT_EPNUM, \
  267. .int_in = notification, \
  268. .in_buffers = stream##_IN_CAPACITY, \
  269. .out_buffers = stream##_OUT_CAPACITY, \
  270. .in_size = stream##_EPSIZE, \
  271. .out_size = stream##_EPSIZE, \
  272. .fixed_size = fixedsize, \
  273. .ib = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_IN_CAPACITY, stream##_EPSIZE)]){}, \
  274. .ob = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_OUT_CAPACITY, stream##_EPSIZE)]){}, \
  275. } \
  276. }
  277. #endif
  278. typedef struct {
  279. union {
  280. struct {
  281. #ifdef CONSOLE_ENABLE
  282. usb_driver_config_t console_driver;
  283. #endif
  284. #ifdef RAW_ENABLE
  285. usb_driver_config_t raw_driver;
  286. #endif
  287. #ifdef MIDI_ENABLE
  288. usb_driver_config_t midi_driver;
  289. #endif
  290. #ifdef VIRTSER_ENABLE
  291. usb_driver_config_t serial_driver;
  292. #endif
  293. #ifdef JOYSTICK_ENABLE
  294. usb_driver_config_t joystick_driver;
  295. #endif
  296. };
  297. usb_driver_config_t array[0];
  298. };
  299. } usb_driver_configs_t;
  300. static usb_driver_configs_t drivers = {
  301. #ifdef CONSOLE_ENABLE
  302. # define CONSOLE_IN_CAPACITY 4
  303. # define CONSOLE_OUT_CAPACITY 4
  304. # define CONSOLE_IN_MODE USB_EP_MODE_TYPE_INTR
  305. # define CONSOLE_OUT_MODE USB_EP_MODE_TYPE_INTR
  306. .console_driver = QMK_USB_DRIVER_CONFIG(CONSOLE, 0, true),
  307. #endif
  308. #ifdef RAW_ENABLE
  309. # define RAW_IN_CAPACITY 4
  310. # define RAW_OUT_CAPACITY 4
  311. # define RAW_IN_MODE USB_EP_MODE_TYPE_INTR
  312. # define RAW_OUT_MODE USB_EP_MODE_TYPE_INTR
  313. .raw_driver = QMK_USB_DRIVER_CONFIG(RAW, 0, false),
  314. #endif
  315. #ifdef MIDI_ENABLE
  316. # define MIDI_STREAM_IN_CAPACITY 4
  317. # define MIDI_STREAM_OUT_CAPACITY 4
  318. # define MIDI_STREAM_IN_MODE USB_EP_MODE_TYPE_BULK
  319. # define MIDI_STREAM_OUT_MODE USB_EP_MODE_TYPE_BULK
  320. .midi_driver = QMK_USB_DRIVER_CONFIG(MIDI_STREAM, 0, false),
  321. #endif
  322. #ifdef VIRTSER_ENABLE
  323. # define CDC_IN_CAPACITY 4
  324. # define CDC_OUT_CAPACITY 4
  325. # define CDC_IN_MODE USB_EP_MODE_TYPE_BULK
  326. # define CDC_OUT_MODE USB_EP_MODE_TYPE_BULK
  327. .serial_driver = QMK_USB_DRIVER_CONFIG(CDC, CDC_NOTIFICATION_EPNUM, false),
  328. #endif
  329. #ifdef JOYSTICK_ENABLE
  330. # define JOYSTICK_IN_CAPACITY 4
  331. # define JOYSTICK_OUT_CAPACITY 4
  332. # define JOYSTICK_IN_MODE USB_EP_MODE_TYPE_BULK
  333. # define JOYSTICK_OUT_MODE USB_EP_MODE_TYPE_BULK
  334. .joystick_driver = QMK_USB_DRIVER_CONFIG(JOYSTICK, 0, false),
  335. #endif
  336. };
  337. #define NUM_USB_DRIVERS (sizeof(drivers) / sizeof(usb_driver_config_t))
  338. /* ---------------------------------------------------------
  339. * USB driver functions
  340. * ---------------------------------------------------------
  341. */
  342. #define USB_EVENT_QUEUE_SIZE 16
  343. usbevent_t event_queue[USB_EVENT_QUEUE_SIZE];
  344. uint8_t event_queue_head;
  345. uint8_t event_queue_tail;
  346. void usb_event_queue_init(void) {
  347. // Initialise the event queue
  348. memset(&event_queue, 0, sizeof(event_queue));
  349. event_queue_head = 0;
  350. event_queue_tail = 0;
  351. }
  352. static inline bool usb_event_queue_enqueue(usbevent_t event) {
  353. uint8_t next = (event_queue_head + 1) % USB_EVENT_QUEUE_SIZE;
  354. if (next == event_queue_tail) {
  355. return false;
  356. }
  357. event_queue[event_queue_head] = event;
  358. event_queue_head = next;
  359. return true;
  360. }
  361. static inline bool usb_event_queue_dequeue(usbevent_t *event) {
  362. if (event_queue_head == event_queue_tail) {
  363. return false;
  364. }
  365. *event = event_queue[event_queue_tail];
  366. event_queue_tail = (event_queue_tail + 1) % USB_EVENT_QUEUE_SIZE;
  367. return true;
  368. }
  369. static inline void usb_event_suspend_handler(void) {
  370. #ifdef SLEEP_LED_ENABLE
  371. sleep_led_enable();
  372. #endif /* SLEEP_LED_ENABLE */
  373. }
  374. static inline void usb_event_wakeup_handler(void) {
  375. suspend_wakeup_init();
  376. #ifdef SLEEP_LED_ENABLE
  377. sleep_led_disable();
  378. // NOTE: converters may not accept this
  379. led_set(host_keyboard_leds());
  380. #endif /* SLEEP_LED_ENABLE */
  381. }
  382. void usb_event_queue_task(void) {
  383. usbevent_t event;
  384. while (usb_event_queue_dequeue(&event)) {
  385. switch (event) {
  386. case USB_EVENT_SUSPEND:
  387. usb_event_suspend_handler();
  388. break;
  389. case USB_EVENT_WAKEUP:
  390. usb_event_wakeup_handler();
  391. break;
  392. default:
  393. // Nothing to do, we don't handle it.
  394. break;
  395. }
  396. }
  397. }
  398. /* Handles the USB driver global events
  399. * TODO: maybe disable some things when connection is lost? */
  400. static void usb_event_cb(USBDriver *usbp, usbevent_t event) {
  401. switch (event) {
  402. case USB_EVENT_ADDRESS:
  403. return;
  404. case USB_EVENT_CONFIGURED:
  405. osalSysLockFromISR();
  406. /* Enable the endpoints specified into the configuration. */
  407. #ifndef KEYBOARD_SHARED_EP
  408. usbInitEndpointI(usbp, KEYBOARD_IN_EPNUM, &kbd_ep_config);
  409. #endif
  410. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  411. usbInitEndpointI(usbp, MOUSE_IN_EPNUM, &mouse_ep_config);
  412. #endif
  413. #ifdef SHARED_EP_ENABLE
  414. usbInitEndpointI(usbp, SHARED_IN_EPNUM, &shared_ep_config);
  415. #endif
  416. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  417. #if STM32_USB_USE_OTG1
  418. usbInitEndpointI(usbp, drivers.array[i].config.bulk_in, &drivers.array[i].inout_ep_config);
  419. #else
  420. usbInitEndpointI(usbp, drivers.array[i].config.bulk_in, &drivers.array[i].in_ep_config);
  421. usbInitEndpointI(usbp, drivers.array[i].config.bulk_out, &drivers.array[i].out_ep_config);
  422. #endif
  423. if (drivers.array[i].config.int_in) {
  424. usbInitEndpointI(usbp, drivers.array[i].config.int_in, &drivers.array[i].int_ep_config);
  425. }
  426. qmkusbConfigureHookI(&drivers.array[i].driver);
  427. }
  428. osalSysUnlockFromISR();
  429. return;
  430. case USB_EVENT_SUSPEND:
  431. usb_event_queue_enqueue(USB_EVENT_SUSPEND);
  432. /* Falls into.*/
  433. case USB_EVENT_UNCONFIGURED:
  434. /* Falls into.*/
  435. case USB_EVENT_RESET:
  436. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  437. chSysLockFromISR();
  438. /* Disconnection event on suspend.*/
  439. qmkusbSuspendHookI(&drivers.array[i].driver);
  440. chSysUnlockFromISR();
  441. }
  442. return;
  443. case USB_EVENT_WAKEUP:
  444. // TODO: from ISR! print("[W]");
  445. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  446. chSysLockFromISR();
  447. /* Disconnection event on suspend.*/
  448. qmkusbWakeupHookI(&drivers.array[i].driver);
  449. chSysUnlockFromISR();
  450. }
  451. usb_event_queue_enqueue(USB_EVENT_WAKEUP);
  452. return;
  453. case USB_EVENT_STALLED:
  454. return;
  455. }
  456. }
  457. /* Function used locally in os/hal/src/usb.c for getting descriptors
  458. * need it here for HID descriptor */
  459. static uint16_t get_hword(uint8_t *p) {
  460. uint16_t hw;
  461. hw = (uint16_t)*p++;
  462. hw |= (uint16_t)*p << 8U;
  463. return hw;
  464. }
  465. /*
  466. * Appendix G: HID Request Support Requirements
  467. *
  468. * The following table enumerates the requests that need to be supported by various types of HID class devices.
  469. * Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  470. * ------------------------------------------------------------------------------------------
  471. * Boot Mouse Required Optional Optional Optional Required Required
  472. * Non-Boot Mouse Required Optional Optional Optional Optional Optional
  473. * Boot Keyboard Required Optional Required Required Required Required
  474. * Non-Boot Keybrd Required Optional Required Required Optional Optional
  475. * Other Device Required Optional Optional Optional Optional Optional
  476. */
  477. static uint8_t set_report_buf[2] __attribute__((aligned(2)));
  478. static void set_led_transfer_cb(USBDriver *usbp) {
  479. if (usbp->setup[6] == 2) { /* LSB(wLength) */
  480. uint8_t report_id = set_report_buf[0];
  481. if ((report_id == REPORT_ID_KEYBOARD) || (report_id == REPORT_ID_NKRO)) {
  482. keyboard_led_state = set_report_buf[1];
  483. }
  484. } else {
  485. keyboard_led_state = set_report_buf[0];
  486. }
  487. }
  488. /* Callback for SETUP request on the endpoint 0 (control) */
  489. static bool usb_request_hook_cb(USBDriver *usbp) {
  490. const USBDescriptor *dp;
  491. /* usbp->setup fields:
  492. * 0: bmRequestType (bitmask)
  493. * 1: bRequest
  494. * 2,3: (LSB,MSB) wValue
  495. * 4,5: (LSB,MSB) wIndex
  496. * 6,7: (LSB,MSB) wLength (number of bytes to transfer if there is a data phase) */
  497. /* Handle HID class specific requests */
  498. if (((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS) && ((usbp->setup[0] & USB_RTYPE_RECIPIENT_MASK) == USB_RTYPE_RECIPIENT_INTERFACE)) {
  499. switch (usbp->setup[0] & USB_RTYPE_DIR_MASK) {
  500. case USB_RTYPE_DIR_DEV2HOST:
  501. switch (usbp->setup[1]) { /* bRequest */
  502. case HID_GET_REPORT:
  503. switch (usbp->setup[4]) { /* LSB(wIndex) (check MSB==0?) */
  504. case KEYBOARD_INTERFACE:
  505. usbSetupTransfer(usbp, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent), NULL);
  506. return TRUE;
  507. break;
  508. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  509. case MOUSE_INTERFACE:
  510. usbSetupTransfer(usbp, (uint8_t *)&mouse_report_blank, sizeof(mouse_report_blank), NULL);
  511. return TRUE;
  512. break;
  513. #endif
  514. default:
  515. usbSetupTransfer(usbp, NULL, 0, NULL);
  516. return TRUE;
  517. break;
  518. }
  519. break;
  520. case HID_GET_PROTOCOL:
  521. if ((usbp->setup[4] == KEYBOARD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */
  522. usbSetupTransfer(usbp, &keyboard_protocol, 1, NULL);
  523. return TRUE;
  524. }
  525. break;
  526. case HID_GET_IDLE:
  527. usbSetupTransfer(usbp, &keyboard_idle, 1, NULL);
  528. return TRUE;
  529. break;
  530. }
  531. break;
  532. case USB_RTYPE_DIR_HOST2DEV:
  533. switch (usbp->setup[1]) { /* bRequest */
  534. case HID_SET_REPORT:
  535. switch (usbp->setup[4]) { /* LSB(wIndex) (check MSB==0?) */
  536. case KEYBOARD_INTERFACE:
  537. #if defined(SHARED_EP_ENABLE) && !defined(KEYBOARD_SHARED_EP)
  538. case SHARED_INTERFACE:
  539. #endif
  540. usbSetupTransfer(usbp, set_report_buf, sizeof(set_report_buf), set_led_transfer_cb);
  541. return TRUE;
  542. break;
  543. }
  544. break;
  545. case HID_SET_PROTOCOL:
  546. if ((usbp->setup[4] == KEYBOARD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */
  547. keyboard_protocol = ((usbp->setup[2]) != 0x00); /* LSB(wValue) */
  548. #ifdef NKRO_ENABLE
  549. keymap_config.nkro = !!keyboard_protocol;
  550. if (!keymap_config.nkro && keyboard_idle) {
  551. #else /* NKRO_ENABLE */
  552. if (keyboard_idle) {
  553. #endif /* NKRO_ENABLE */
  554. /* arm the idle timer if boot protocol & idle */
  555. osalSysLockFromISR();
  556. chVTSetI(&keyboard_idle_timer, 4 * TIME_MS2I(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
  557. osalSysUnlockFromISR();
  558. }
  559. }
  560. usbSetupTransfer(usbp, NULL, 0, NULL);
  561. return TRUE;
  562. break;
  563. case HID_SET_IDLE:
  564. keyboard_idle = usbp->setup[3]; /* MSB(wValue) */
  565. /* arm the timer */
  566. #ifdef NKRO_ENABLE
  567. if (!keymap_config.nkro && keyboard_idle) {
  568. #else /* NKRO_ENABLE */
  569. if (keyboard_idle) {
  570. #endif /* NKRO_ENABLE */
  571. osalSysLockFromISR();
  572. chVTSetI(&keyboard_idle_timer, 4 * TIME_MS2I(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
  573. osalSysUnlockFromISR();
  574. }
  575. usbSetupTransfer(usbp, NULL, 0, NULL);
  576. return TRUE;
  577. break;
  578. }
  579. break;
  580. }
  581. }
  582. /* Handle the Get_Descriptor Request for HID class (not handled by the default hook) */
  583. if ((usbp->setup[0] == 0x81) && (usbp->setup[1] == USB_REQ_GET_DESCRIPTOR)) {
  584. dp = usbp->config->get_descriptor_cb(usbp, usbp->setup[3], usbp->setup[2], get_hword(&usbp->setup[4]));
  585. if (dp == NULL) return FALSE;
  586. usbSetupTransfer(usbp, (uint8_t *)dp->ud_string, dp->ud_size, NULL);
  587. return TRUE;
  588. }
  589. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  590. if (drivers.array[i].config.int_in) {
  591. // NOTE: Assumes that we only have one serial driver
  592. return qmkusbRequestsHook(usbp);
  593. }
  594. }
  595. return FALSE;
  596. }
  597. /* Start-of-frame callback */
  598. static void usb_sof_cb(USBDriver *usbp) {
  599. kbd_sof_cb(usbp);
  600. osalSysLockFromISR();
  601. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  602. qmkusbSOFHookI(&drivers.array[i].driver);
  603. }
  604. osalSysUnlockFromISR();
  605. }
  606. /* USB driver configuration */
  607. static const USBConfig usbcfg = {
  608. usb_event_cb, /* USB events callback */
  609. usb_get_descriptor_cb, /* Device GET_DESCRIPTOR request callback */
  610. usb_request_hook_cb, /* Requests hook callback */
  611. usb_sof_cb /* Start Of Frame callback */
  612. };
  613. /*
  614. * Initialize the USB driver
  615. */
  616. void init_usb_driver(USBDriver *usbp) {
  617. for (int i = 0; i < NUM_USB_DRIVERS; i++) {
  618. #if STM32_USB_USE_OTG1
  619. QMKUSBDriver *driver = &drivers.array[i].driver;
  620. drivers.array[i].inout_ep_config.in_state = &drivers.array[i].in_ep_state;
  621. drivers.array[i].inout_ep_config.out_state = &drivers.array[i].out_ep_state;
  622. drivers.array[i].int_ep_config.in_state = &drivers.array[i].int_ep_state;
  623. qmkusbObjectInit(driver, &drivers.array[i].config);
  624. qmkusbStart(driver, &drivers.array[i].config);
  625. #else
  626. QMKUSBDriver *driver = &drivers.array[i].driver;
  627. drivers.array[i].in_ep_config.in_state = &drivers.array[i].in_ep_state;
  628. drivers.array[i].out_ep_config.out_state = &drivers.array[i].out_ep_state;
  629. drivers.array[i].int_ep_config.in_state = &drivers.array[i].int_ep_state;
  630. qmkusbObjectInit(driver, &drivers.array[i].config);
  631. qmkusbStart(driver, &drivers.array[i].config);
  632. #endif
  633. }
  634. /*
  635. * Activates the USB driver and then the USB bus pull-up on D+.
  636. * Note, a delay is inserted in order to not have to disconnect the cable
  637. * after a reset.
  638. */
  639. usbDisconnectBus(usbp);
  640. wait_ms(1500);
  641. usbStart(usbp, &usbcfg);
  642. usbConnectBus(usbp);
  643. chVTObjectInit(&keyboard_idle_timer);
  644. }
  645. void restart_usb_driver(USBDriver *usbp) {
  646. usbStop(usbp);
  647. usbDisconnectBus(usbp);
  648. #if USB_SUSPEND_WAKEUP_DELAY > 0
  649. // Some hubs, kvm switches, and monitors do
  650. // weird things, with USB device state bouncing
  651. // around wildly on wakeup, yielding race
  652. // conditions that can corrupt the keyboard state.
  653. //
  654. // Pause for a while to let things settle...
  655. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  656. #endif
  657. usbStart(usbp, &usbcfg);
  658. usbConnectBus(usbp);
  659. }
  660. /* ---------------------------------------------------------
  661. * Keyboard functions
  662. * ---------------------------------------------------------
  663. */
  664. /* keyboard IN callback hander (a kbd report has made it IN) */
  665. #ifndef KEYBOARD_SHARED_EP
  666. void kbd_in_cb(USBDriver *usbp, usbep_t ep) {
  667. /* STUB */
  668. (void)usbp;
  669. (void)ep;
  670. }
  671. #endif
  672. /* start-of-frame handler
  673. * TODO: i guess it would be better to re-implement using timers,
  674. * so that this is not going to have to be checked every 1ms */
  675. void kbd_sof_cb(USBDriver *usbp) { (void)usbp; }
  676. /* Idle requests timer code
  677. * callback (called from ISR, unlocked state) */
  678. static void keyboard_idle_timer_cb(void *arg) {
  679. USBDriver *usbp = (USBDriver *)arg;
  680. osalSysLockFromISR();
  681. /* check that the states of things are as they're supposed to */
  682. if (usbGetDriverStateI(usbp) != USB_ACTIVE) {
  683. /* do not rearm the timer, should be enabled on IDLE request */
  684. osalSysUnlockFromISR();
  685. return;
  686. }
  687. #ifdef NKRO_ENABLE
  688. if (!keymap_config.nkro && keyboard_idle && keyboard_protocol) {
  689. #else /* NKRO_ENABLE */
  690. if (keyboard_idle && keyboard_protocol) {
  691. #endif /* NKRO_ENABLE */
  692. /* TODO: are we sure we want the KBD_ENDPOINT? */
  693. if (!usbGetTransmitStatusI(usbp, KEYBOARD_IN_EPNUM)) {
  694. usbStartTransmitI(usbp, KEYBOARD_IN_EPNUM, (uint8_t *)&keyboard_report_sent, KEYBOARD_EPSIZE);
  695. }
  696. /* rearm the timer */
  697. chVTSetI(&keyboard_idle_timer, 4 * TIME_MS2I(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
  698. }
  699. /* do not rearm the timer if the condition above fails
  700. * it should be enabled again on either IDLE or SET_PROTOCOL requests */
  701. osalSysUnlockFromISR();
  702. }
  703. /* LED status */
  704. uint8_t keyboard_leds(void) { return keyboard_led_state; }
  705. /* prepare and start sending a report IN
  706. * not callable from ISR or locked state */
  707. void send_keyboard(report_keyboard_t *report) {
  708. osalSysLock();
  709. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  710. goto unlock;
  711. }
  712. #ifdef NKRO_ENABLE
  713. if (keymap_config.nkro && keyboard_protocol) { /* NKRO protocol */
  714. /* need to wait until the previous packet has made it through */
  715. /* can rewrite this using the synchronous API, then would wait
  716. * until *after* the packet has been transmitted. I think
  717. * this is more efficient */
  718. /* busy wait, should be short and not very common */
  719. if (usbGetTransmitStatusI(&USB_DRIVER, SHARED_IN_EPNUM)) {
  720. /* Need to either suspend, or loop and call unlock/lock during
  721. * every iteration - otherwise the system will remain locked,
  722. * no interrupts served, so USB not going through as well.
  723. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  724. osalThreadSuspendS(&(&USB_DRIVER)->epc[SHARED_IN_EPNUM]->in_state->thread);
  725. /* after osalThreadSuspendS returns USB status might have changed */
  726. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  727. goto unlock;
  728. }
  729. }
  730. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)report, sizeof(struct nkro_report));
  731. } else
  732. #endif /* NKRO_ENABLE */
  733. { /* regular protocol */
  734. /* need to wait until the previous packet has made it through */
  735. /* busy wait, should be short and not very common */
  736. if (usbGetTransmitStatusI(&USB_DRIVER, KEYBOARD_IN_EPNUM)) {
  737. /* Need to either suspend, or loop and call unlock/lock during
  738. * every iteration - otherwise the system will remain locked,
  739. * no interrupts served, so USB not going through as well.
  740. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  741. osalThreadSuspendS(&(&USB_DRIVER)->epc[KEYBOARD_IN_EPNUM]->in_state->thread);
  742. /* after osalThreadSuspendS returns USB status might have changed */
  743. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  744. goto unlock;
  745. }
  746. }
  747. uint8_t *data, size;
  748. if (keyboard_protocol) {
  749. data = (uint8_t *)report;
  750. size = KEYBOARD_REPORT_SIZE;
  751. } else { /* boot protocol */
  752. data = &report->mods;
  753. size = 8;
  754. }
  755. usbStartTransmitI(&USB_DRIVER, KEYBOARD_IN_EPNUM, data, size);
  756. }
  757. keyboard_report_sent = *report;
  758. unlock:
  759. osalSysUnlock();
  760. }
  761. /* ---------------------------------------------------------
  762. * Mouse functions
  763. * ---------------------------------------------------------
  764. */
  765. #ifdef MOUSE_ENABLE
  766. # ifndef MOUSE_SHARED_EP
  767. /* mouse IN callback hander (a mouse report has made it IN) */
  768. void mouse_in_cb(USBDriver *usbp, usbep_t ep) {
  769. (void)usbp;
  770. (void)ep;
  771. }
  772. # endif
  773. void send_mouse(report_mouse_t *report) {
  774. osalSysLock();
  775. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  776. osalSysUnlock();
  777. return;
  778. }
  779. if (usbGetTransmitStatusI(&USB_DRIVER, MOUSE_IN_EPNUM)) {
  780. /* Need to either suspend, or loop and call unlock/lock during
  781. * every iteration - otherwise the system will remain locked,
  782. * no interrupts served, so USB not going through as well.
  783. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  784. if (osalThreadSuspendTimeoutS(&(&USB_DRIVER)->epc[MOUSE_IN_EPNUM]->in_state->thread, TIME_MS2I(10)) == MSG_TIMEOUT) {
  785. osalSysUnlock();
  786. return;
  787. }
  788. }
  789. usbStartTransmitI(&USB_DRIVER, MOUSE_IN_EPNUM, (uint8_t *)report, sizeof(report_mouse_t));
  790. osalSysUnlock();
  791. }
  792. #else /* MOUSE_ENABLE */
  793. void send_mouse(report_mouse_t *report) { (void)report; }
  794. #endif /* MOUSE_ENABLE */
  795. /* ---------------------------------------------------------
  796. * Shared EP functions
  797. * ---------------------------------------------------------
  798. */
  799. #ifdef SHARED_EP_ENABLE
  800. /* shared IN callback hander */
  801. void shared_in_cb(USBDriver *usbp, usbep_t ep) {
  802. /* STUB */
  803. (void)usbp;
  804. (void)ep;
  805. }
  806. #endif
  807. /* ---------------------------------------------------------
  808. * Extrakey functions
  809. * ---------------------------------------------------------
  810. */
  811. #ifdef EXTRAKEY_ENABLE
  812. static void send_extra(uint8_t report_id, uint16_t data) {
  813. osalSysLock();
  814. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  815. osalSysUnlock();
  816. return;
  817. }
  818. report_extra_t report = {.report_id = report_id, .usage = data};
  819. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)&report, sizeof(report_extra_t));
  820. osalSysUnlock();
  821. }
  822. #endif
  823. void send_system(uint16_t data) {
  824. #ifdef EXTRAKEY_ENABLE
  825. send_extra(REPORT_ID_SYSTEM, data);
  826. #endif
  827. }
  828. void send_consumer(uint16_t data) {
  829. #ifdef EXTRAKEY_ENABLE
  830. send_extra(REPORT_ID_CONSUMER, data);
  831. #endif
  832. }
  833. /* ---------------------------------------------------------
  834. * Console functions
  835. * ---------------------------------------------------------
  836. */
  837. #ifdef CONSOLE_ENABLE
  838. int8_t sendchar(uint8_t c) {
  839. // The previous implmentation had timeouts, but I think it's better to just slow down
  840. // and make sure that everything is transferred, rather than dropping stuff
  841. return chnWrite(&drivers.console_driver.driver, &c, 1);
  842. }
  843. // Just a dummy function for now, this could be exposed as a weak function
  844. // Or connected to the actual QMK console
  845. static void console_receive(uint8_t *data, uint8_t length) {
  846. (void)data;
  847. (void)length;
  848. }
  849. void console_task(void) {
  850. uint8_t buffer[CONSOLE_EPSIZE];
  851. size_t size = 0;
  852. do {
  853. size_t size = chnReadTimeout(&drivers.console_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  854. if (size > 0) {
  855. console_receive(buffer, size);
  856. }
  857. } while (size > 0);
  858. }
  859. #endif /* CONSOLE_ENABLE */
  860. #ifdef RAW_ENABLE
  861. void raw_hid_send(uint8_t *data, uint8_t length) {
  862. // TODO: implement variable size packet
  863. if (length != RAW_EPSIZE) {
  864. return;
  865. }
  866. chnWrite(&drivers.raw_driver.driver, data, length);
  867. }
  868. __attribute__((weak)) void raw_hid_receive(uint8_t *data, uint8_t length) {
  869. // Users should #include "raw_hid.h" in their own code
  870. // and implement this function there. Leave this as weak linkage
  871. // so users can opt to not handle data coming in.
  872. }
  873. void raw_hid_task(void) {
  874. uint8_t buffer[RAW_EPSIZE];
  875. size_t size = 0;
  876. do {
  877. size_t size = chnReadTimeout(&drivers.raw_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  878. if (size > 0) {
  879. raw_hid_receive(buffer, size);
  880. }
  881. } while (size > 0);
  882. }
  883. #endif
  884. #ifdef MIDI_ENABLE
  885. void send_midi_packet(MIDI_EventPacket_t *event) { chnWrite(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t)); }
  886. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  887. size_t size = chnReadTimeout(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t), TIME_IMMEDIATE);
  888. return size == sizeof(MIDI_EventPacket_t);
  889. }
  890. void midi_ep_task(void) {
  891. uint8_t buffer[MIDI_STREAM_EPSIZE];
  892. size_t size = 0;
  893. do {
  894. size_t size = chnReadTimeout(&drivers.midi_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  895. if (size > 0) {
  896. MIDI_EventPacket_t event;
  897. recv_midi_packet(&event);
  898. }
  899. } while (size > 0);
  900. }
  901. #endif
  902. #ifdef VIRTSER_ENABLE
  903. void virtser_send(const uint8_t byte) { chnWrite(&drivers.serial_driver.driver, &byte, 1); }
  904. __attribute__((weak)) void virtser_recv(uint8_t c) {
  905. // Ignore by default
  906. }
  907. void virtser_task(void) {
  908. uint8_t numBytesReceived = 0;
  909. uint8_t buffer[16];
  910. do {
  911. numBytesReceived = chnReadTimeout(&drivers.serial_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  912. for (int i = 0; i < numBytesReceived; i++) {
  913. virtser_recv(buffer[i]);
  914. }
  915. } while (numBytesReceived > 0);
  916. }
  917. #endif
  918. #ifdef JOYSTICK_ENABLE
  919. void send_joystick_packet(joystick_t *joystick) {
  920. joystick_report_t rep = {
  921. # if JOYSTICK_AXES_COUNT > 0
  922. .axes =
  923. {
  924. joystick->axes[0],
  925. # if JOYSTICK_AXES_COUNT >= 2
  926. joystick->axes[1],
  927. # endif
  928. # if JOYSTICK_AXES_COUNT >= 3
  929. joystick->axes[2],
  930. # endif
  931. # if JOYSTICK_AXES_COUNT >= 4
  932. joystick->axes[3],
  933. # endif
  934. # if JOYSTICK_AXES_COUNT >= 5
  935. joystick->axes[4],
  936. # endif
  937. # if JOYSTICK_AXES_COUNT >= 6
  938. joystick->axes[5],
  939. # endif
  940. },
  941. # endif // JOYSTICK_AXES_COUNT>0
  942. # if JOYSTICK_BUTTON_COUNT > 0
  943. .buttons =
  944. {
  945. joystick->buttons[0],
  946. # if JOYSTICK_BUTTON_COUNT > 8
  947. joystick->buttons[1],
  948. # endif
  949. # if JOYSTICK_BUTTON_COUNT > 16
  950. joystick->buttons[2],
  951. # endif
  952. # if JOYSTICK_BUTTON_COUNT > 24
  953. joystick->buttons[3],
  954. # endif
  955. }
  956. # endif // JOYSTICK_BUTTON_COUNT>0
  957. };
  958. // chnWrite(&drivers.joystick_driver.driver, (uint8_t *)&rep, sizeof(rep));
  959. osalSysLock();
  960. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  961. osalSysUnlock();
  962. return;
  963. }
  964. usbStartTransmitI(&USB_DRIVER, JOYSTICK_IN_EPNUM, (uint8_t *)&rep, sizeof(joystick_report_t));
  965. osalSysUnlock();
  966. }
  967. #endif