usb_main.c 50 KB

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