usb_main.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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 "chibios_config.h"
  32. #include "debug.h"
  33. #include "suspend.h"
  34. #ifdef SLEEP_LED_ENABLE
  35. # include "sleep_led.h"
  36. # include "led.h"
  37. #endif
  38. #include "wait.h"
  39. #include "usb_device_state.h"
  40. #include "usb_descriptor.h"
  41. #include "usb_driver.h"
  42. #ifdef NKRO_ENABLE
  43. # include "keycode_config.h"
  44. extern keymap_config_t keymap_config;
  45. #endif
  46. /* ---------------------------------------------------------
  47. * Global interface variables and declarations
  48. * ---------------------------------------------------------
  49. */
  50. #ifndef usb_lld_connect_bus
  51. # define usb_lld_connect_bus(usbp)
  52. #endif
  53. #ifndef usb_lld_disconnect_bus
  54. # define usb_lld_disconnect_bus(usbp)
  55. #endif
  56. uint8_t keyboard_idle __attribute__((aligned(2))) = 0;
  57. uint8_t keyboard_protocol __attribute__((aligned(2))) = 1;
  58. uint8_t keyboard_led_state = 0;
  59. volatile uint16_t keyboard_idle_count = 0;
  60. static virtual_timer_t keyboard_idle_timer;
  61. #if CH_KERNEL_MAJOR >= 7
  62. static void keyboard_idle_timer_cb(struct ch_virtual_timer *, void *arg);
  63. #elif CH_KERNEL_MAJOR <= 6
  64. static void keyboard_idle_timer_cb(void *arg);
  65. #endif
  66. report_keyboard_t keyboard_report_sent = {{0}};
  67. #ifdef MOUSE_ENABLE
  68. report_mouse_t mouse_report_blank = {0};
  69. #endif /* MOUSE_ENABLE */
  70. #ifdef EXTRAKEY_ENABLE
  71. uint8_t extra_report_blank[3] = {0};
  72. #endif /* EXTRAKEY_ENABLE */
  73. /* ---------------------------------------------------------
  74. * Descriptors and USB driver objects
  75. * ---------------------------------------------------------
  76. */
  77. /* USB Low Level driver specific endpoint fields */
  78. #if !defined(usb_lld_endpoint_fields)
  79. # define usb_lld_endpoint_fields \
  80. 2, /* IN multiplier */ \
  81. NULL, /* SETUP buffer (not a SETUP endpoint) */
  82. #endif
  83. /* HID specific constants */
  84. #define HID_GET_REPORT 0x01
  85. #define HID_GET_IDLE 0x02
  86. #define HID_GET_PROTOCOL 0x03
  87. #define HID_SET_REPORT 0x09
  88. #define HID_SET_IDLE 0x0A
  89. #define HID_SET_PROTOCOL 0x0B
  90. /*
  91. * Handles the GET_DESCRIPTOR callback
  92. *
  93. * Returns the proper descriptor
  94. */
  95. static const USBDescriptor *usb_get_descriptor_cb(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t wIndex) {
  96. (void)usbp;
  97. static USBDescriptor desc;
  98. uint16_t wValue = ((uint16_t)dtype << 8) | dindex;
  99. desc.ud_string = NULL;
  100. desc.ud_size = get_usb_descriptor(wValue, wIndex, (const void **const) & desc.ud_string);
  101. if (desc.ud_string == NULL)
  102. return NULL;
  103. else
  104. return &desc;
  105. }
  106. #ifndef KEYBOARD_SHARED_EP
  107. /* keyboard endpoint state structure */
  108. static USBInEndpointState kbd_ep_state;
  109. /* keyboard endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  110. static const USBEndpointConfig kbd_ep_config = {
  111. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  112. NULL, /* SETUP packet notification callback */
  113. kbd_in_cb, /* IN notification callback */
  114. NULL, /* OUT notification callback */
  115. KEYBOARD_EPSIZE, /* IN maximum packet size */
  116. 0, /* OUT maximum packet size */
  117. &kbd_ep_state, /* IN Endpoint state */
  118. NULL, /* OUT endpoint state */
  119. usb_lld_endpoint_fields /* USB driver specific endpoint fields */
  120. };
  121. #endif
  122. #if defined(MOUSE_ENABLE) && !defined(MOUSE_SHARED_EP)
  123. /* mouse endpoint state structure */
  124. static USBInEndpointState mouse_ep_state;
  125. /* mouse endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  126. static const USBEndpointConfig mouse_ep_config = {
  127. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  128. NULL, /* SETUP packet notification callback */
  129. mouse_in_cb, /* IN notification callback */
  130. NULL, /* OUT notification callback */
  131. MOUSE_EPSIZE, /* IN maximum packet size */
  132. 0, /* OUT maximum packet size */
  133. &mouse_ep_state, /* IN Endpoint state */
  134. NULL, /* OUT endpoint state */
  135. usb_lld_endpoint_fields /* USB driver specific endpoint fields */
  136. };
  137. #endif
  138. #ifdef SHARED_EP_ENABLE
  139. /* shared endpoint state structure */
  140. static USBInEndpointState shared_ep_state;
  141. /* shared endpoint initialization structure (IN) - see USBEndpointConfig comment at top of file */
  142. static const USBEndpointConfig shared_ep_config = {
  143. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
  144. NULL, /* SETUP packet notification callback */
  145. shared_in_cb, /* IN notification callback */
  146. NULL, /* OUT notification callback */
  147. SHARED_EPSIZE, /* IN maximum packet size */
  148. 0, /* OUT maximum packet size */
  149. &shared_ep_state, /* IN Endpoint state */
  150. NULL, /* OUT endpoint state */
  151. usb_lld_endpoint_fields /* USB driver specific endpoint fields */
  152. };
  153. #endif
  154. #ifdef USB_ENDPOINTS_ARE_REORDERABLE
  155. typedef struct {
  156. size_t queue_capacity_in;
  157. size_t queue_capacity_out;
  158. USBInEndpointState in_ep_state;
  159. USBOutEndpointState out_ep_state;
  160. USBInEndpointState int_ep_state;
  161. USBEndpointConfig inout_ep_config;
  162. USBEndpointConfig int_ep_config;
  163. const QMKUSBConfig config;
  164. QMKUSBDriver driver;
  165. } usb_driver_config_t;
  166. #else
  167. typedef struct {
  168. size_t queue_capacity_in;
  169. size_t queue_capacity_out;
  170. USBInEndpointState in_ep_state;
  171. USBOutEndpointState out_ep_state;
  172. USBInEndpointState int_ep_state;
  173. USBEndpointConfig in_ep_config;
  174. USBEndpointConfig out_ep_config;
  175. USBEndpointConfig int_ep_config;
  176. const QMKUSBConfig config;
  177. QMKUSBDriver driver;
  178. } usb_driver_config_t;
  179. #endif
  180. #ifdef USB_ENDPOINTS_ARE_REORDERABLE
  181. /* Reusable initialization structure - see USBEndpointConfig comment at top of file */
  182. # define QMK_USB_DRIVER_CONFIG(stream, notification, fixedsize) \
  183. { \
  184. .queue_capacity_in = stream##_IN_CAPACITY, .queue_capacity_out = stream##_OUT_CAPACITY, \
  185. .inout_ep_config = \
  186. { \
  187. stream##_IN_MODE, /* Interrupt EP */ \
  188. NULL, /* SETUP packet notification callback */ \
  189. qmkusbDataTransmitted, /* IN notification callback */ \
  190. qmkusbDataReceived, /* OUT notification callback */ \
  191. stream##_EPSIZE, /* IN maximum packet size */ \
  192. stream##_EPSIZE, /* OUT maximum packet size */ \
  193. NULL, /* IN Endpoint state */ \
  194. NULL, /* OUT endpoint state */ \
  195. usb_lld_endpoint_fields /* USB driver specific endpoint fields */ \
  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. usb_lld_endpoint_fields /* USB driver specific endpoint fields */ \
  208. }, \
  209. .config = { \
  210. .usbp = &USB_DRIVER, \
  211. .bulk_in = stream##_IN_EPNUM, \
  212. .bulk_out = stream##_OUT_EPNUM, \
  213. .int_in = notification, \
  214. .in_buffers = stream##_IN_CAPACITY, \
  215. .out_buffers = stream##_OUT_CAPACITY, \
  216. .in_size = stream##_EPSIZE, \
  217. .out_size = stream##_EPSIZE, \
  218. .fixed_size = fixedsize, \
  219. .ib = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_IN_CAPACITY, stream##_EPSIZE)]){}, \
  220. .ob = (__attribute__((aligned(4))) uint8_t[BQ_BUFFER_SIZE(stream##_OUT_CAPACITY, stream##_EPSIZE)]){}, \
  221. } \
  222. }
  223. #else
  224. /* Reusable initialization structure - see USBEndpointConfig comment at top of file */
  225. # define QMK_USB_DRIVER_CONFIG(stream, notification, fixedsize) \
  226. { \
  227. .queue_capacity_in = stream##_IN_CAPACITY, .queue_capacity_out = stream##_OUT_CAPACITY, \
  228. .in_ep_config = \
  229. { \
  230. stream##_IN_MODE, /* Interrupt EP */ \
  231. NULL, /* SETUP packet notification callback */ \
  232. qmkusbDataTransmitted, /* IN notification callback */ \
  233. NULL, /* OUT notification callback */ \
  234. stream##_EPSIZE, /* IN maximum packet size */ \
  235. 0, /* OUT maximum packet size */ \
  236. NULL, /* IN Endpoint state */ \
  237. NULL, /* OUT endpoint state */ \
  238. usb_lld_endpoint_fields /* USB driver specific endpoint fields */ \
  239. }, \
  240. .out_ep_config = \
  241. { \
  242. stream##_OUT_MODE, /* Interrupt EP */ \
  243. NULL, /* SETUP packet notification callback */ \
  244. NULL, /* IN notification callback */ \
  245. qmkusbDataReceived, /* OUT notification callback */ \
  246. 0, /* IN maximum packet size */ \
  247. stream##_EPSIZE, /* OUT maximum packet size */ \
  248. NULL, /* IN Endpoint state */ \
  249. NULL, /* OUT endpoint state */ \
  250. usb_lld_endpoint_fields /* USB driver specific endpoint fields */ \
  251. }, \
  252. .int_ep_config = \
  253. { \
  254. USB_EP_MODE_TYPE_INTR, /* Interrupt EP */ \
  255. NULL, /* SETUP packet notification callback */ \
  256. qmkusbInterruptTransmitted, /* IN notification callback */ \
  257. NULL, /* OUT notification callback */ \
  258. CDC_NOTIFICATION_EPSIZE, /* IN maximum packet size */ \
  259. 0, /* OUT maximum packet size */ \
  260. NULL, /* IN Endpoint state */ \
  261. NULL, /* OUT endpoint state */ \
  262. usb_lld_endpoint_fields /* USB driver specific endpoint fields */ \
  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. # ifndef RAW_IN_CAPACITY
  314. # define RAW_IN_CAPACITY 4
  315. # endif
  316. # ifndef RAW_OUT_CAPACITY
  317. # define RAW_OUT_CAPACITY 4
  318. # endif
  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. #ifdef USB_ENDPOINTS_ARE_REORDERABLE
  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. #ifdef USB_ENDPOINTS_ARE_REORDERABLE
  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. usbStop(usbp);
  674. wait_ms(50);
  675. usbStart(usbp, &usbcfg);
  676. usbConnectBus(usbp);
  677. chVTObjectInit(&keyboard_idle_timer);
  678. }
  679. __attribute__((weak)) void restart_usb_driver(USBDriver *usbp) {
  680. usbDisconnectBus(usbp);
  681. usbStop(usbp);
  682. #if USB_SUSPEND_WAKEUP_DELAY > 0
  683. // Some hubs, kvm switches, and monitors do
  684. // weird things, with USB device state bouncing
  685. // around wildly on wakeup, yielding race
  686. // conditions that can corrupt the keyboard state.
  687. //
  688. // Pause for a while to let things settle...
  689. wait_ms(USB_SUSPEND_WAKEUP_DELAY);
  690. #endif
  691. usbStart(usbp, &usbcfg);
  692. usbConnectBus(usbp);
  693. }
  694. /* ---------------------------------------------------------
  695. * Keyboard functions
  696. * ---------------------------------------------------------
  697. */
  698. /* keyboard IN callback hander (a kbd report has made it IN) */
  699. #ifndef KEYBOARD_SHARED_EP
  700. void kbd_in_cb(USBDriver *usbp, usbep_t ep) {
  701. /* STUB */
  702. (void)usbp;
  703. (void)ep;
  704. }
  705. #endif
  706. /* start-of-frame handler
  707. * TODO: i guess it would be better to re-implement using timers,
  708. * so that this is not going to have to be checked every 1ms */
  709. void kbd_sof_cb(USBDriver *usbp) {
  710. (void)usbp;
  711. }
  712. /* Idle requests timer code
  713. * callback (called from ISR, unlocked state) */
  714. #if CH_KERNEL_MAJOR >= 7
  715. static void keyboard_idle_timer_cb(struct ch_virtual_timer *timer, void *arg) {
  716. (void)timer;
  717. #elif CH_KERNEL_MAJOR <= 6
  718. static void keyboard_idle_timer_cb(void *arg) {
  719. #endif
  720. USBDriver *usbp = (USBDriver *)arg;
  721. osalSysLockFromISR();
  722. /* check that the states of things are as they're supposed to */
  723. if (usbGetDriverStateI(usbp) != USB_ACTIVE) {
  724. /* do not rearm the timer, should be enabled on IDLE request */
  725. osalSysUnlockFromISR();
  726. return;
  727. }
  728. #ifdef NKRO_ENABLE
  729. if (!keymap_config.nkro && keyboard_idle && keyboard_protocol) {
  730. #else /* NKRO_ENABLE */
  731. if (keyboard_idle && keyboard_protocol) {
  732. #endif /* NKRO_ENABLE */
  733. /* TODO: are we sure we want the KBD_ENDPOINT? */
  734. if (!usbGetTransmitStatusI(usbp, KEYBOARD_IN_EPNUM)) {
  735. usbStartTransmitI(usbp, KEYBOARD_IN_EPNUM, (uint8_t *)&keyboard_report_sent, KEYBOARD_EPSIZE);
  736. }
  737. /* rearm the timer */
  738. chVTSetI(&keyboard_idle_timer, 4 * TIME_MS2I(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
  739. }
  740. /* do not rearm the timer if the condition above fails
  741. * it should be enabled again on either IDLE or SET_PROTOCOL requests */
  742. osalSysUnlockFromISR();
  743. }
  744. /* LED status */
  745. uint8_t keyboard_leds(void) {
  746. return keyboard_led_state;
  747. }
  748. /* prepare and start sending a report IN
  749. * not callable from ISR or locked state */
  750. void send_keyboard(report_keyboard_t *report) {
  751. osalSysLock();
  752. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  753. goto unlock;
  754. }
  755. #ifdef NKRO_ENABLE
  756. if (keymap_config.nkro && keyboard_protocol) { /* NKRO protocol */
  757. /* need to wait until the previous packet has made it through */
  758. /* can rewrite this using the synchronous API, then would wait
  759. * until *after* the packet has been transmitted. I think
  760. * this is more efficient */
  761. /* busy wait, should be short and not very common */
  762. if (usbGetTransmitStatusI(&USB_DRIVER, SHARED_IN_EPNUM)) {
  763. /* Need to either suspend, or loop and call unlock/lock during
  764. * every iteration - otherwise the system will remain locked,
  765. * no interrupts served, so USB not going through as well.
  766. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  767. osalThreadSuspendS(&(&USB_DRIVER)->epc[SHARED_IN_EPNUM]->in_state->thread);
  768. /* after osalThreadSuspendS returns USB status might have changed */
  769. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  770. goto unlock;
  771. }
  772. }
  773. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)report, sizeof(struct nkro_report));
  774. } else
  775. #endif /* NKRO_ENABLE */
  776. { /* regular protocol */
  777. /* need to wait until the previous packet has made it through */
  778. /* busy wait, should be short and not very common */
  779. if (usbGetTransmitStatusI(&USB_DRIVER, KEYBOARD_IN_EPNUM)) {
  780. /* Need to either suspend, or loop and call unlock/lock during
  781. * every iteration - otherwise the system will remain locked,
  782. * no interrupts served, so USB not going through as well.
  783. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  784. osalThreadSuspendS(&(&USB_DRIVER)->epc[KEYBOARD_IN_EPNUM]->in_state->thread);
  785. /* after osalThreadSuspendS returns USB status might have changed */
  786. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  787. goto unlock;
  788. }
  789. }
  790. uint8_t *data, size;
  791. if (keyboard_protocol) {
  792. data = (uint8_t *)report;
  793. size = KEYBOARD_REPORT_SIZE;
  794. } else { /* boot protocol */
  795. data = &report->mods;
  796. size = 8;
  797. }
  798. usbStartTransmitI(&USB_DRIVER, KEYBOARD_IN_EPNUM, data, size);
  799. }
  800. keyboard_report_sent = *report;
  801. unlock:
  802. osalSysUnlock();
  803. }
  804. /* ---------------------------------------------------------
  805. * Mouse functions
  806. * ---------------------------------------------------------
  807. */
  808. #ifdef MOUSE_ENABLE
  809. # ifndef MOUSE_SHARED_EP
  810. /* mouse IN callback hander (a mouse report has made it IN) */
  811. void mouse_in_cb(USBDriver *usbp, usbep_t ep) {
  812. (void)usbp;
  813. (void)ep;
  814. }
  815. # endif
  816. void send_mouse(report_mouse_t *report) {
  817. osalSysLock();
  818. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  819. osalSysUnlock();
  820. return;
  821. }
  822. if (usbGetTransmitStatusI(&USB_DRIVER, MOUSE_IN_EPNUM)) {
  823. /* Need to either suspend, or loop and call unlock/lock during
  824. * every iteration - otherwise the system will remain locked,
  825. * no interrupts served, so USB not going through as well.
  826. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  827. if (osalThreadSuspendTimeoutS(&(&USB_DRIVER)->epc[MOUSE_IN_EPNUM]->in_state->thread, TIME_MS2I(10)) == MSG_TIMEOUT) {
  828. osalSysUnlock();
  829. return;
  830. }
  831. }
  832. usbStartTransmitI(&USB_DRIVER, MOUSE_IN_EPNUM, (uint8_t *)report, sizeof(report_mouse_t));
  833. osalSysUnlock();
  834. }
  835. #else /* MOUSE_ENABLE */
  836. void send_mouse(report_mouse_t *report) {
  837. (void)report;
  838. }
  839. #endif /* MOUSE_ENABLE */
  840. /* ---------------------------------------------------------
  841. * Shared EP functions
  842. * ---------------------------------------------------------
  843. */
  844. #ifdef SHARED_EP_ENABLE
  845. /* shared IN callback hander */
  846. void shared_in_cb(USBDriver *usbp, usbep_t ep) {
  847. /* STUB */
  848. (void)usbp;
  849. (void)ep;
  850. }
  851. #endif
  852. /* ---------------------------------------------------------
  853. * Extrakey functions
  854. * ---------------------------------------------------------
  855. */
  856. void send_extra(uint8_t report_id, uint16_t data) {
  857. #ifdef EXTRAKEY_ENABLE
  858. osalSysLock();
  859. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  860. osalSysUnlock();
  861. return;
  862. }
  863. if (usbGetTransmitStatusI(&USB_DRIVER, SHARED_IN_EPNUM)) {
  864. /* Need to either suspend, or loop and call unlock/lock during
  865. * every iteration - otherwise the system will remain locked,
  866. * no interrupts served, so USB not going through as well.
  867. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  868. if (osalThreadSuspendTimeoutS(&(&USB_DRIVER)->epc[SHARED_IN_EPNUM]->in_state->thread, TIME_MS2I(10)) == MSG_TIMEOUT) {
  869. osalSysUnlock();
  870. return;
  871. }
  872. }
  873. static report_extra_t report;
  874. report = (report_extra_t){.report_id = report_id, .usage = data};
  875. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)&report, sizeof(report_extra_t));
  876. osalSysUnlock();
  877. #endif
  878. }
  879. void send_programmable_button(uint32_t data) {
  880. #ifdef PROGRAMMABLE_BUTTON_ENABLE
  881. osalSysLock();
  882. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  883. osalSysUnlock();
  884. return;
  885. }
  886. if (usbGetTransmitStatusI(&USB_DRIVER, SHARED_IN_EPNUM)) {
  887. /* Need to either suspend, or loop and call unlock/lock during
  888. * every iteration - otherwise the system will remain locked,
  889. * no interrupts served, so USB not going through as well.
  890. * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
  891. if (osalThreadSuspendTimeoutS(&(&USB_DRIVER)->epc[SHARED_IN_EPNUM]->in_state->thread, TIME_MS2I(10)) == MSG_TIMEOUT) {
  892. osalSysUnlock();
  893. return;
  894. }
  895. }
  896. static report_programmable_button_t report = {
  897. .report_id = REPORT_ID_PROGRAMMABLE_BUTTON,
  898. };
  899. report.usage = data;
  900. usbStartTransmitI(&USB_DRIVER, SHARED_IN_EPNUM, (uint8_t *)&report, sizeof(report));
  901. osalSysUnlock();
  902. #endif
  903. }
  904. void send_digitizer(report_digitizer_t *report) {
  905. #ifdef DIGITIZER_ENABLE
  906. # ifdef DIGITIZER_SHARED_EP
  907. osalSysLock();
  908. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  909. osalSysUnlock();
  910. return;
  911. }
  912. usbStartTransmitI(&USB_DRIVER, DIGITIZER_IN_EPNUM, (uint8_t *)report, sizeof(report_digitizer_t));
  913. osalSysUnlock();
  914. # else
  915. chnWrite(&drivers.digitizer_driver.driver, (uint8_t *)report, sizeof(report_digitizer_t));
  916. # endif
  917. #endif
  918. }
  919. /* ---------------------------------------------------------
  920. * Console functions
  921. * ---------------------------------------------------------
  922. */
  923. #ifdef CONSOLE_ENABLE
  924. int8_t sendchar(uint8_t c) {
  925. static bool timed_out = false;
  926. /* The `timed_out` state is an approximation of the ideal `is_listener_disconnected?` state.
  927. *
  928. * When a 5ms timeout write has timed out, hid_listen is most likely not running, or not
  929. * listening to this keyboard, so we go into the timed_out state. In this state we assume
  930. * that hid_listen is most likely not gonna be connected to us any time soon, so it would
  931. * be wasteful to write follow-up characters with a 5ms timeout, it would all add up and
  932. * unncecessarily slow down the firmware. However instead of just dropping the characters,
  933. * we write them with a TIME_IMMEDIATE timeout, which is a zero timeout,
  934. * and this will succeed only if hid_listen gets connected again. When a write with
  935. * TIME_IMMEDIATE timeout succeeds, we know that hid_listen is listening to us again, and
  936. * we can go back to the timed_out = false state, and following writes will be executed
  937. * with a 5ms timeout. The reason we don't just send all characters with the TIME_IMMEDIATE
  938. * timeout is that this could cause bytes to be lost even if hid_listen is running, if there
  939. * is a lot of data being sent over the console.
  940. *
  941. * This logic will work correctly as long as hid_listen is able to receive at least 200
  942. * bytes per second. On a heavily overloaded machine that's so overloaded that it's
  943. * unusable, and constantly swapping, hid_listen might have trouble receiving 200 bytes per
  944. * second, so some bytes might be lost on the console.
  945. */
  946. const sysinterval_t timeout = timed_out ? TIME_IMMEDIATE : TIME_MS2I(5);
  947. const size_t result = chnWriteTimeout(&drivers.console_driver.driver, &c, 1, timeout);
  948. timed_out = (result == 0);
  949. return result;
  950. }
  951. // Just a dummy function for now, this could be exposed as a weak function
  952. // Or connected to the actual QMK console
  953. static void console_receive(uint8_t *data, uint8_t length) {
  954. (void)data;
  955. (void)length;
  956. }
  957. void console_task(void) {
  958. uint8_t buffer[CONSOLE_EPSIZE];
  959. size_t size = 0;
  960. do {
  961. size = chnReadTimeout(&drivers.console_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  962. if (size > 0) {
  963. console_receive(buffer, size);
  964. }
  965. } while (size > 0);
  966. }
  967. #endif /* CONSOLE_ENABLE */
  968. #ifdef RAW_ENABLE
  969. void raw_hid_send(uint8_t *data, uint8_t length) {
  970. // TODO: implement variable size packet
  971. if (length != RAW_EPSIZE) {
  972. return;
  973. }
  974. chnWrite(&drivers.raw_driver.driver, data, length);
  975. }
  976. __attribute__((weak)) void raw_hid_receive(uint8_t *data, uint8_t length) {
  977. // Users should #include "raw_hid.h" in their own code
  978. // and implement this function there. Leave this as weak linkage
  979. // so users can opt to not handle data coming in.
  980. }
  981. void raw_hid_task(void) {
  982. uint8_t buffer[RAW_EPSIZE];
  983. size_t size = 0;
  984. do {
  985. size = chnReadTimeout(&drivers.raw_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  986. if (size > 0) {
  987. raw_hid_receive(buffer, size);
  988. }
  989. } while (size > 0);
  990. }
  991. #endif
  992. #ifdef MIDI_ENABLE
  993. void send_midi_packet(MIDI_EventPacket_t *event) {
  994. chnWrite(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t));
  995. }
  996. bool recv_midi_packet(MIDI_EventPacket_t *const event) {
  997. size_t size = chnReadTimeout(&drivers.midi_driver.driver, (uint8_t *)event, sizeof(MIDI_EventPacket_t), TIME_IMMEDIATE);
  998. return size == sizeof(MIDI_EventPacket_t);
  999. }
  1000. void midi_ep_task(void) {
  1001. uint8_t buffer[MIDI_STREAM_EPSIZE];
  1002. size_t size = 0;
  1003. do {
  1004. size = chnReadTimeout(&drivers.midi_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  1005. if (size > 0) {
  1006. MIDI_EventPacket_t event;
  1007. recv_midi_packet(&event);
  1008. }
  1009. } while (size > 0);
  1010. }
  1011. #endif
  1012. #ifdef VIRTSER_ENABLE
  1013. void virtser_init(void) {}
  1014. void virtser_send(const uint8_t byte) {
  1015. chnWrite(&drivers.serial_driver.driver, &byte, 1);
  1016. }
  1017. __attribute__((weak)) void virtser_recv(uint8_t c) {
  1018. // Ignore by default
  1019. }
  1020. void virtser_task(void) {
  1021. uint8_t numBytesReceived = 0;
  1022. uint8_t buffer[16];
  1023. do {
  1024. numBytesReceived = chnReadTimeout(&drivers.serial_driver.driver, buffer, sizeof(buffer), TIME_IMMEDIATE);
  1025. for (int i = 0; i < numBytesReceived; i++) {
  1026. virtser_recv(buffer[i]);
  1027. }
  1028. } while (numBytesReceived > 0);
  1029. }
  1030. #endif
  1031. void send_joystick(report_joystick_t *report) {
  1032. #ifdef JOYSTICK_ENABLE
  1033. osalSysLock();
  1034. if (usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
  1035. osalSysUnlock();
  1036. return;
  1037. }
  1038. usbStartTransmitI(&USB_DRIVER, JOYSTICK_IN_EPNUM, (uint8_t *)report, sizeof(report_joystick_t));
  1039. osalSysUnlock();
  1040. #endif
  1041. }