usb_main.c 27 KB

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