usb_main.c 49 KB

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