usb_main.c 50 KB

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