usb_main.c 50 KB

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