usb_main.c 49 KB

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