usb_main.c 50 KB

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