usb_main.c 53 KB

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