usb_main.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. usbStart(usbp, &usbcfg);
  649. usbConnectBus(usbp);
  650. }
  651. /* ---------------------------------------------------------
  652. * Keyboard functions
  653. * ---------------------------------------------------------
  654. */
  655. /* keyboard IN callback hander (a kbd report has made it IN) */
  656. #ifndef KEYBOARD_SHARED_EP
  657. void kbd_in_cb(USBDriver *usbp, usbep_t ep) {
  658. /* STUB */
  659. (void)usbp;
  660. (void)ep;
  661. }
  662. #endif
  663. /* start-of-frame handler
  664. * TODO: i guess it would be better to re-implement using timers,
  665. * so that this is not going to have to be checked every 1ms */
  666. void kbd_sof_cb(USBDriver *usbp) { (void)usbp; }
  667. /* Idle requests timer code
  668. * callback (called from ISR, unlocked state) */
  669. static void keyboard_idle_timer_cb(void *arg) {
  670. USBDriver *usbp = (USBDriver *)arg;
  671. osalSysLockFromISR();
  672. /* check that the states of things are as they're supposed to */
  673. if (usbGetDriverStateI(usbp) != USB_ACTIVE) {
  674. /* do not rearm the timer, should be enabled on IDLE request */
  675. osalSysUnlockFromISR();
  676. return;
  677. }
  678. #ifdef NKRO_ENABLE
  679. if (!keymap_config.nkro && keyboard_idle && keyboard_protocol) {
  680. #else /* NKRO_ENABLE */
  681. if (keyboard_idle && keyboard_protocol) {
  682. #endif /* NKRO_ENABLE */
  683. /* TODO: are we sure we want the KBD_ENDPOINT? */
  684. if (!usbGetTransmitStatusI(usbp, KEYBOARD_IN_EPNUM)) {
  685. usbStartTransmitI(usbp, KEYBOARD_IN_EPNUM, (uint8_t *)&keyboard_report_sent, KEYBOARD_EPSIZE);
  686. }
  687. /* rearm the timer */
  688. chVTSetI(&keyboard_idle_timer, 4 * TIME_MS2I(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
  689. }
  690. /* do not rearm the timer if the condition above fails
  691. * it should be enabled again on either IDLE or SET_PROTOCOL requests */
  692. osalSysUnlockFromISR();
  693. }
  694. /* LED status */
  695. uint8_t keyboard_leds(void) { return keyboard_led_state; }
  696. /* prepare and start sending a report IN
  697. * not callable from ISR or locked state */
  698. void send_keyboard(report_keyboard_t *report) {
  699. osalSysLock();
  700. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  701. goto unlock;
  702. }
  703. #ifdef NKRO_ENABLE
  704. if (keymap_config.nkro && keyboard_protocol) { /* NKRO protocol */
  705. /* need to wait until the previous packet has made it through */
  706. /* can rewrite this using the synchronous API, then would wait
  707. * until *after* the packet has been transmitted. I think
  708. * this is more efficient */
  709. /* busy wait, should be short and not very common */
  710. if (usbGetTransmitStatusI(&USB_DRIVER, SHARED_IN_EPNUM)) {
  711. /* Need to either suspend, or loop and call unlock/lock during
  712. * every iteration - otherwise the system will remain locked,
  713. * no interrupts served, so USB not going through as well.
  714. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  715. osalThreadSuspendS(&(&USB_DRIVER)->epc[SHARED_IN_EPNUM]->in_state->thread);
  716. /* after osalThreadSuspendS returns USB status might have changed */
  717. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  718. goto unlock;
  719. }
  720. }
  721. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)report, sizeof(struct nkro_report));
  722. } else
  723. #endif /* NKRO_ENABLE */
  724. { /* regular protocol */
  725. /* need to wait until the previous packet has made it through */
  726. /* busy wait, should be short and not very common */
  727. if (usbGetTransmitStatusI(&USB_DRIVER, KEYBOARD_IN_EPNUM)) {
  728. /* Need to either suspend, or loop and call unlock/lock during
  729. * every iteration - otherwise the system will remain locked,
  730. * no interrupts served, so USB not going through as well.
  731. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  732. osalThreadSuspendS(&(&USB_DRIVER)->epc[KEYBOARD_IN_EPNUM]->in_state->thread);
  733. /* after osalThreadSuspendS returns USB status might have changed */
  734. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  735. goto unlock;
  736. }
  737. }
  738. uint8_t *data, size;
  739. if (keyboard_protocol) {
  740. data = (uint8_t *)report;
  741. size = KEYBOARD_REPORT_SIZE;
  742. } else { /* boot protocol */
  743. data = &report->mods;
  744. size = 8;
  745. }
  746. usbStartTransmitI(&USB_DRIVER, KEYBOARD_IN_EPNUM, data, size);
  747. }
  748. keyboard_report_sent = *report;
  749. unlock:
  750. osalSysUnlock();
  751. }
  752. /* ---------------------------------------------------------
  753. * Mouse functions
  754. * ---------------------------------------------------------
  755. */
  756. #ifdef MOUSE_ENABLE
  757. # ifndef MOUSE_SHARED_EP
  758. /* mouse IN callback hander (a mouse report has made it IN) */
  759. void mouse_in_cb(USBDriver *usbp, usbep_t ep) {
  760. (void)usbp;
  761. (void)ep;
  762. }
  763. # endif
  764. void send_mouse(report_mouse_t *report) {
  765. osalSysLock();
  766. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  767. osalSysUnlock();
  768. return;
  769. }
  770. if (usbGetTransmitStatusI(&USB_DRIVER, MOUSE_IN_EPNUM)) {
  771. /* Need to either suspend, or loop and call unlock/lock during
  772. * every iteration - otherwise the system will remain locked,
  773. * no interrupts served, so USB not going through as well.
  774. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  775. if (osalThreadSuspendTimeoutS(&(&USB_DRIVER)->epc[MOUSE_IN_EPNUM]->in_state->thread, TIME_MS2I(10)) == MSG_TIMEOUT) {
  776. osalSysUnlock();
  777. return;
  778. }
  779. }
  780. usbStartTransmitI(&USB_DRIVER, MOUSE_IN_EPNUM, (uint8_t *)report, sizeof(report_mouse_t));
  781. osalSysUnlock();
  782. }
  783. #else /* MOUSE_ENABLE */
  784. void send_mouse(report_mouse_t *report) { (void)report; }
  785. #endif /* MOUSE_ENABLE */
  786. /* ---------------------------------------------------------
  787. * Shared EP functions
  788. * ---------------------------------------------------------
  789. */
  790. #ifdef SHARED_EP_ENABLE
  791. /* shared IN callback hander */
  792. void shared_in_cb(USBDriver *usbp, usbep_t ep) {
  793. /* STUB */
  794. (void)usbp;
  795. (void)ep;
  796. }
  797. #endif
  798. /* ---------------------------------------------------------
  799. * Extrakey functions
  800. * ---------------------------------------------------------
  801. */
  802. #ifdef EXTRAKEY_ENABLE
  803. static void send_extra(uint8_t report_id, uint16_t data) {
  804. osalSysLock();
  805. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  806. osalSysUnlock();
  807. return;
  808. }
  809. report_extra_t report = {.report_id = report_id, .usage = data};
  810. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)&report, sizeof(report_extra_t));
  811. osalSysUnlock();
  812. }
  813. #endif
  814. void send_system(uint16_t data) {
  815. #ifdef EXTRAKEY_ENABLE
  816. send_extra(REPORT_ID_SYSTEM, data);
  817. #endif
  818. }
  819. void send_consumer(uint16_t data) {
  820. #ifdef EXTRAKEY_ENABLE
  821. send_extra(REPORT_ID_CONSUMER, data);
  822. #endif
  823. }
  824. /* ---------------------------------------------------------
  825. * Console functions
  826. * ---------------------------------------------------------
  827. */
  828. #ifdef CONSOLE_ENABLE
  829. int8_t sendchar(uint8_t c) {
  830. // The previous implmentation had timeouts, but I think it's better to just slow down
  831. // and make sure that everything is transferred, rather than dropping stuff
  832. return chnWrite(&drivers.console_driver.driver, &c, 1);
  833. }
  834. // Just a dummy function for now, this could be exposed as a weak function
  835. // Or connected to the actual QMK console
  836. static void console_receive(uint8_t *data, uint8_t length) {
  837. (void)data;
  838. (void)length;
  839. }
  840. void console_task(void) {
  841. uint8_t buffer[CONSOLE_EPSIZE];
  842. size_t size = 0;
  843. do {
  844. size_t size = chnReadTimeout(&drivers.console_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  845. if (size > 0) {
  846. console_receive(buffer, size);
  847. }
  848. } while (size > 0);
  849. }
  850. #else /* CONSOLE_ENABLE */
  851. int8_t sendchar(uint8_t c) {
  852. (void)c;
  853. return 0;
  854. }
  855. #endif /* CONSOLE_ENABLE */
  856. void _putchar(char character) { sendchar(character); }
  857. #ifdef RAW_ENABLE
  858. void raw_hid_send(uint8_t *data, uint8_t length) {
  859. // TODO: implement variable size packet
  860. if (length != RAW_EPSIZE) {
  861. return;
  862. }
  863. chnWrite(&drivers.raw_driver.driver, data, length);
  864. }
  865. __attribute__((weak)) void raw_hid_receive(uint8_t *data, uint8_t length) {
  866. // Users should #include "raw_hid.h" in their own code
  867. // and implement this function there. Leave this as weak linkage
  868. // so users can opt to not handle data coming in.
  869. }
  870. void raw_hid_task(void) {
  871. uint8_t buffer[RAW_EPSIZE];
  872. size_t size = 0;
  873. do {
  874. size_t size = chnReadTimeout(&drivers.raw_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  875. if (size > 0) {
  876. raw_hid_receive(buffer, size);
  877. }
  878. } while (size > 0);
  879. }
  880. #endif
  881. #ifdef MIDI_ENABLE
  882. void send_midi_packet(MIDI_EventPacket_t *event) { chnWrite(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t)); }
  883. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  884. size_t size = chnReadTimeout(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t), TIME_IMMEDIATE);
  885. return size == sizeof(MIDI_EventPacket_t);
  886. }
  887. void midi_ep_task(void) {
  888. uint8_t buffer[MIDI_STREAM_EPSIZE];
  889. size_t size = 0;
  890. do {
  891. size_t size = chnReadTimeout(&drivers.midi_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  892. if (size > 0) {
  893. MIDI_EventPacket_t event;
  894. recv_midi_packet(&event);
  895. }
  896. } while (size > 0);
  897. }
  898. #endif
  899. #ifdef VIRTSER_ENABLE
  900. void virtser_send(const uint8_t byte) { chnWrite(&drivers.serial_driver.driver, &byte, 1); }
  901. __attribute__((weak)) void virtser_recv(uint8_t c) {
  902. // Ignore by default
  903. }
  904. void virtser_task(void) {
  905. uint8_t numBytesReceived = 0;
  906. uint8_t buffer[16];
  907. do {
  908. numBytesReceived = chnReadTimeout(&drivers.serial_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  909. for (int i = 0; i < numBytesReceived; i++) {
  910. virtser_recv(buffer[i]);
  911. }
  912. } while (numBytesReceived > 0);
  913. }
  914. #endif
  915. #ifdef JOYSTICK_ENABLE
  916. void send_joystick_packet(joystick_t *joystick) {
  917. joystick_report_t rep = {
  918. # if JOYSTICK_AXES_COUNT > 0
  919. .axes =
  920. {
  921. joystick->axes[0],
  922. # if JOYSTICK_AXES_COUNT >= 2
  923. joystick->axes[1],
  924. # endif
  925. # if JOYSTICK_AXES_COUNT >= 3
  926. joystick->axes[2],
  927. # endif
  928. # if JOYSTICK_AXES_COUNT >= 4
  929. joystick->axes[3],
  930. # endif
  931. # if JOYSTICK_AXES_COUNT >= 5
  932. joystick->axes[4],
  933. # endif
  934. # if JOYSTICK_AXES_COUNT >= 6
  935. joystick->axes[5],
  936. # endif
  937. },
  938. # endif // JOYSTICK_AXES_COUNT>0
  939. # if JOYSTICK_BUTTON_COUNT > 0
  940. .buttons =
  941. {
  942. joystick->buttons[0],
  943. # if JOYSTICK_BUTTON_COUNT > 8
  944. joystick->buttons[1],
  945. # endif
  946. # if JOYSTICK_BUTTON_COUNT > 16
  947. joystick->buttons[2],
  948. # endif
  949. # if JOYSTICK_BUTTON_COUNT > 24
  950. joystick->buttons[3],
  951. # endif
  952. }
  953. # endif // JOYSTICK_BUTTON_COUNT>0
  954. };
  955. // chnWrite(&drivers.joystick_driver.driver, (uint8_t *)&rep, sizeof(rep));
  956. osalSysLock();
  957. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  958. osalSysUnlock();
  959. return;
  960. }
  961. usbStartTransmitI(&USB_DRIVER, JOYSTICK_IN_EPNUM, (uint8_t *)&rep, sizeof(joystick_report_t));
  962. osalSysUnlock();
  963. }
  964. #endif