usb_main.c 49 KB

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