usb_main.c 42 KB

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