usb_main.c 51 KB

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