usb_main.c 35 KB

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