usb_main.c 37 KB

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