lufa.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. /*
  2. * Copyright 2012 Jun Wako <wakojun@gmail.com>
  3. * This file is based on:
  4. * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
  5. * LUFA-120219/Demos/Device/Lowlevel/GenericHID
  6. */
  7. /*
  8. LUFA Library
  9. Copyright (C) Dean Camera, 2012.
  10. dean [at] fourwalledcubicle [dot] com
  11. www.lufa-lib.org
  12. */
  13. /*
  14. Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  15. Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
  16. Permission to use, copy, modify, distribute, and sell this
  17. software and its documentation for any purpose is hereby granted
  18. without fee, provided that the above copyright notice appear in
  19. all copies and that both that the copyright notice and this
  20. permission notice and warranty disclaimer appear in supporting
  21. documentation, and that the name of the author not be used in
  22. advertising or publicity pertaining to distribution of the
  23. software without specific, written prior permission.
  24. The author disclaim all warranties with regard to this
  25. software, including all implied warranties of merchantability
  26. and fitness. In no event shall the author be liable for any
  27. special, indirect or consequential damages or any damages
  28. whatsoever resulting from loss of use, data or profits, whether
  29. in an action of contract, negligence or other tortious action,
  30. arising out of or in connection with the use or performance of
  31. this software.
  32. */
  33. #include "report.h"
  34. #include "host.h"
  35. #include "host_driver.h"
  36. #include "keyboard.h"
  37. #include "action.h"
  38. #include "led.h"
  39. #include "sendchar.h"
  40. #include "debug.h"
  41. #ifdef SLEEP_LED_ENABLE
  42. #include "sleep_led.h"
  43. #endif
  44. #include "suspend.h"
  45. #include "descriptor.h"
  46. #include "lufa.h"
  47. #include "quantum.h"
  48. #include <util/atomic.h>
  49. #include "outputselect.h"
  50. #ifdef NKRO_ENABLE
  51. #include "keycode_config.h"
  52. extern keymap_config_t keymap_config;
  53. #endif
  54. #ifdef AUDIO_ENABLE
  55. #include <audio.h>
  56. #endif
  57. #ifdef BLUETOOTH_ENABLE
  58. #ifdef MODULE_ADAFRUIT_BLE
  59. #include "adafruit_ble.h"
  60. #else
  61. #include "bluetooth.h"
  62. #endif
  63. #endif
  64. #ifdef VIRTSER_ENABLE
  65. #include "virtser.h"
  66. #endif
  67. #if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
  68. #include "rgblight.h"
  69. #endif
  70. #ifdef MIDI_ENABLE
  71. #include "sysex_tools.h"
  72. #endif
  73. #ifdef RAW_ENABLE
  74. #include "raw_hid.h"
  75. #endif
  76. uint8_t keyboard_idle = 0;
  77. /* 0: Boot Protocol, 1: Report Protocol(default) */
  78. uint8_t keyboard_protocol = 1;
  79. static uint8_t keyboard_led_stats = 0;
  80. static report_keyboard_t keyboard_report_sent;
  81. #ifdef MIDI_ENABLE
  82. static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
  83. static void usb_get_midi(MidiDevice * device);
  84. static void midi_usb_init(MidiDevice * device);
  85. #endif
  86. /* Host driver */
  87. static uint8_t keyboard_leds(void);
  88. static void send_keyboard(report_keyboard_t *report);
  89. static void send_mouse(report_mouse_t *report);
  90. static void send_system(uint16_t data);
  91. static void send_consumer(uint16_t data);
  92. host_driver_t lufa_driver = {
  93. keyboard_leds,
  94. send_keyboard,
  95. send_mouse,
  96. send_system,
  97. send_consumer,
  98. #ifdef MIDI_ENABLE
  99. usb_send_func,
  100. usb_get_midi,
  101. midi_usb_init
  102. #endif
  103. };
  104. /*******************************************************************************
  105. * MIDI
  106. ******************************************************************************/
  107. #ifdef MIDI_ENABLE
  108. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
  109. {
  110. .Config =
  111. {
  112. .StreamingInterfaceNumber = AS_INTERFACE,
  113. .DataINEndpoint =
  114. {
  115. .Address = MIDI_STREAM_IN_EPADDR,
  116. .Size = MIDI_STREAM_EPSIZE,
  117. .Banks = 1,
  118. },
  119. .DataOUTEndpoint =
  120. {
  121. .Address = MIDI_STREAM_OUT_EPADDR,
  122. .Size = MIDI_STREAM_EPSIZE,
  123. .Banks = 1,
  124. },
  125. },
  126. };
  127. #define SYSEX_START_OR_CONT 0x40
  128. #define SYSEX_ENDS_IN_1 0x50
  129. #define SYSEX_ENDS_IN_2 0x60
  130. #define SYSEX_ENDS_IN_3 0x70
  131. #define SYS_COMMON_1 0x50
  132. #define SYS_COMMON_2 0x20
  133. #define SYS_COMMON_3 0x30
  134. #endif
  135. #ifdef VIRTSER_ENABLE
  136. USB_ClassInfo_CDC_Device_t cdc_device =
  137. {
  138. .Config =
  139. {
  140. .ControlInterfaceNumber = CCI_INTERFACE,
  141. .DataINEndpoint =
  142. {
  143. .Address = CDC_IN_EPADDR,
  144. .Size = CDC_EPSIZE,
  145. .Banks = 1,
  146. },
  147. .DataOUTEndpoint =
  148. {
  149. .Address = CDC_OUT_EPADDR,
  150. .Size = CDC_EPSIZE,
  151. .Banks = 1,
  152. },
  153. .NotificationEndpoint =
  154. {
  155. .Address = CDC_NOTIFICATION_EPADDR,
  156. .Size = CDC_NOTIFICATION_EPSIZE,
  157. .Banks = 1,
  158. },
  159. },
  160. };
  161. #endif
  162. #ifdef RAW_ENABLE
  163. void raw_hid_send( uint8_t *data, uint8_t length )
  164. {
  165. // TODO: implement variable size packet
  166. if ( length != RAW_EPSIZE )
  167. {
  168. return;
  169. }
  170. if (USB_DeviceState != DEVICE_STATE_Configured)
  171. {
  172. return;
  173. }
  174. // TODO: decide if we allow calls to raw_hid_send() in the middle
  175. // of other endpoint usage.
  176. uint8_t ep = Endpoint_GetCurrentEndpoint();
  177. Endpoint_SelectEndpoint(RAW_IN_EPNUM);
  178. // Check to see if the host is ready to accept another packet
  179. if (Endpoint_IsINReady())
  180. {
  181. // Write data
  182. Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
  183. // Finalize the stream transfer to send the last packet
  184. Endpoint_ClearIN();
  185. }
  186. Endpoint_SelectEndpoint(ep);
  187. }
  188. __attribute__ ((weak))
  189. void raw_hid_receive( uint8_t *data, uint8_t length )
  190. {
  191. // Users should #include "raw_hid.h" in their own code
  192. // and implement this function there. Leave this as weak linkage
  193. // so users can opt to not handle data coming in.
  194. }
  195. static void raw_hid_task(void)
  196. {
  197. // Create a temporary buffer to hold the read in data from the host
  198. uint8_t data[RAW_EPSIZE];
  199. bool data_read = false;
  200. // Device must be connected and configured for the task to run
  201. if (USB_DeviceState != DEVICE_STATE_Configured)
  202. return;
  203. Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
  204. // Check to see if a packet has been sent from the host
  205. if (Endpoint_IsOUTReceived())
  206. {
  207. // Check to see if the packet contains data
  208. if (Endpoint_IsReadWriteAllowed())
  209. {
  210. /* Read data */
  211. Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
  212. data_read = true;
  213. }
  214. // Finalize the stream transfer to receive the last packet
  215. Endpoint_ClearOUT();
  216. if ( data_read )
  217. {
  218. raw_hid_receive( data, sizeof(data) );
  219. }
  220. }
  221. }
  222. #endif
  223. /*******************************************************************************
  224. * Console
  225. ******************************************************************************/
  226. #ifdef CONSOLE_ENABLE
  227. static bool console_flush = false;
  228. #define CONSOLE_FLUSH_SET(b) do { \
  229. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
  230. console_flush = b; \
  231. } \
  232. } while (0)
  233. static void Console_Task(void)
  234. {
  235. /* Device must be connected and configured for the task to run */
  236. if (USB_DeviceState != DEVICE_STATE_Configured)
  237. return;
  238. /* Create a temporary buffer to hold the read in report from the host */
  239. uint8_t ConsoleData[CONSOLE_EPSIZE];
  240. bool data_read = false;
  241. uint8_t ep = Endpoint_GetCurrentEndpoint();
  242. // TODO: impl receivechar()/recvchar()
  243. Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
  244. /* Check to see if a packet has been sent from the host */
  245. if (Endpoint_IsOUTReceived())
  246. {
  247. /* Check to see if the packet contains data */
  248. if (Endpoint_IsReadWriteAllowed())
  249. {
  250. /* Read Console Report Data */
  251. Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
  252. data_read = true;
  253. }
  254. /* Finalize the stream transfer to send the last packet */
  255. Endpoint_ClearOUT();
  256. if (data_read) {
  257. /* Process Console Report Data */
  258. process_console_data_quantum(ConsoleData, sizeof(ConsoleData));
  259. }
  260. }
  261. if (console_flush) {
  262. /* IN packet */
  263. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  264. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  265. Endpoint_SelectEndpoint(ep);
  266. return;
  267. }
  268. // fill empty bank
  269. while (Endpoint_IsReadWriteAllowed())
  270. Endpoint_Write_8(0);
  271. // flash senchar packet
  272. if (Endpoint_IsINReady()) {
  273. Endpoint_ClearIN();
  274. }
  275. // CONSOLE_FLUSH_SET(false);
  276. }
  277. Endpoint_SelectEndpoint(ep);
  278. }
  279. #endif
  280. /*******************************************************************************
  281. * USB Events
  282. ******************************************************************************/
  283. /*
  284. * Event Order of Plug in:
  285. * 0) EVENT_USB_Device_Connect
  286. * 1) EVENT_USB_Device_Suspend
  287. * 2) EVENT_USB_Device_Reset
  288. * 3) EVENT_USB_Device_Wake
  289. */
  290. void EVENT_USB_Device_Connect(void)
  291. {
  292. print("[C]");
  293. /* For battery powered device */
  294. if (!USB_IsInitialized) {
  295. USB_Disable();
  296. USB_Init();
  297. USB_Device_EnableSOFEvents();
  298. }
  299. }
  300. void EVENT_USB_Device_Disconnect(void)
  301. {
  302. print("[D]");
  303. /* For battery powered device */
  304. USB_IsInitialized = false;
  305. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  306. if (USB_IsInitialized) {
  307. USB_Disable(); // Disable all interrupts
  308. USB_Controller_Enable();
  309. USB_INT_Enable(USB_INT_VBUSTI);
  310. }
  311. */
  312. }
  313. void EVENT_USB_Device_Reset(void)
  314. {
  315. print("[R]");
  316. }
  317. void EVENT_USB_Device_Suspend()
  318. {
  319. print("[S]");
  320. #ifdef SLEEP_LED_ENABLE
  321. sleep_led_enable();
  322. #endif
  323. }
  324. void EVENT_USB_Device_WakeUp()
  325. {
  326. print("[W]");
  327. suspend_wakeup_init();
  328. #ifdef SLEEP_LED_ENABLE
  329. sleep_led_disable();
  330. // NOTE: converters may not accept this
  331. led_set(host_keyboard_leds());
  332. #endif
  333. }
  334. #ifdef CONSOLE_ENABLE
  335. // called every 1ms
  336. void EVENT_USB_Device_StartOfFrame(void)
  337. {
  338. static uint8_t count;
  339. if (++count % 50) return;
  340. count = 0;
  341. //if (!console_flush) return;
  342. Console_Task();
  343. //console_flush = false;
  344. }
  345. #endif
  346. /** Event handler for the USB_ConfigurationChanged event.
  347. * This is fired when the host sets the current configuration of the USB device after enumeration.
  348. *
  349. * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
  350. * it is safe to use singl bank for all endpoints.
  351. */
  352. void EVENT_USB_Device_ConfigurationChanged(void)
  353. {
  354. bool ConfigSuccess = true;
  355. /* Setup Keyboard HID Report Endpoints */
  356. ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  357. KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
  358. #ifdef MOUSE_ENABLE
  359. /* Setup Mouse HID Report Endpoint */
  360. ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  361. MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
  362. #endif
  363. #ifdef EXTRAKEY_ENABLE
  364. /* Setup Extra HID Report Endpoint */
  365. ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  366. EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
  367. #endif
  368. #ifdef RAW_ENABLE
  369. /* Setup Raw HID Report Endpoints */
  370. ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  371. RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
  372. ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  373. RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
  374. #endif
  375. #ifdef CONSOLE_ENABLE
  376. /* Setup Console HID Report Endpoints */
  377. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  378. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  379. // #if 0
  380. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  381. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  382. // #endif
  383. #endif
  384. #ifdef NKRO_ENABLE
  385. /* Setup NKRO HID Report Endpoints */
  386. ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  387. NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
  388. #endif
  389. #ifdef MIDI_ENABLE
  390. ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
  391. ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
  392. #endif
  393. #ifdef VIRTSER_ENABLE
  394. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
  395. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
  396. ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
  397. #endif
  398. }
  399. /*
  400. Appendix G: HID Request Support Requirements
  401. The following table enumerates the requests that need to be supported by various types of HID class devices.
  402. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  403. ------------------------------------------------------------------------------------------
  404. Boot Mouse Required Optional Optional Optional Required Required
  405. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  406. Boot Keyboard Required Optional Required Required Required Required
  407. Non-Boot Keybrd Required Optional Required Required Optional Optional
  408. Other Device Required Optional Optional Optional Optional Optional
  409. */
  410. /** Event handler for the USB_ControlRequest event.
  411. * This is fired before passing along unhandled control requests to the library for processing internally.
  412. */
  413. void EVENT_USB_Device_ControlRequest(void)
  414. {
  415. uint8_t* ReportData = NULL;
  416. uint8_t ReportSize = 0;
  417. /* Handle HID Class specific requests */
  418. switch (USB_ControlRequest.bRequest)
  419. {
  420. case HID_REQ_GetReport:
  421. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  422. {
  423. Endpoint_ClearSETUP();
  424. // Interface
  425. switch (USB_ControlRequest.wIndex) {
  426. case KEYBOARD_INTERFACE:
  427. // TODO: test/check
  428. ReportData = (uint8_t*)&keyboard_report_sent;
  429. ReportSize = sizeof(keyboard_report_sent);
  430. break;
  431. }
  432. /* Write the report data to the control endpoint */
  433. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  434. Endpoint_ClearOUT();
  435. }
  436. break;
  437. case HID_REQ_SetReport:
  438. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  439. {
  440. // Interface
  441. switch (USB_ControlRequest.wIndex) {
  442. case KEYBOARD_INTERFACE:
  443. #ifdef NKRO_ENABLE
  444. case NKRO_INTERFACE:
  445. #endif
  446. Endpoint_ClearSETUP();
  447. while (!(Endpoint_IsOUTReceived())) {
  448. if (USB_DeviceState == DEVICE_STATE_Unattached)
  449. return;
  450. }
  451. keyboard_led_stats = Endpoint_Read_8();
  452. Endpoint_ClearOUT();
  453. Endpoint_ClearStatusStage();
  454. break;
  455. }
  456. }
  457. break;
  458. case HID_REQ_GetProtocol:
  459. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  460. {
  461. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  462. Endpoint_ClearSETUP();
  463. while (!(Endpoint_IsINReady()));
  464. Endpoint_Write_8(keyboard_protocol);
  465. Endpoint_ClearIN();
  466. Endpoint_ClearStatusStage();
  467. }
  468. }
  469. break;
  470. case HID_REQ_SetProtocol:
  471. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  472. {
  473. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  474. Endpoint_ClearSETUP();
  475. Endpoint_ClearStatusStage();
  476. keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
  477. clear_keyboard();
  478. }
  479. }
  480. break;
  481. case HID_REQ_SetIdle:
  482. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  483. {
  484. Endpoint_ClearSETUP();
  485. Endpoint_ClearStatusStage();
  486. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  487. }
  488. break;
  489. case HID_REQ_GetIdle:
  490. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  491. {
  492. Endpoint_ClearSETUP();
  493. while (!(Endpoint_IsINReady()));
  494. Endpoint_Write_8(keyboard_idle);
  495. Endpoint_ClearIN();
  496. Endpoint_ClearStatusStage();
  497. }
  498. break;
  499. }
  500. #ifdef VIRTSER_ENABLE
  501. CDC_Device_ProcessControlRequest(&cdc_device);
  502. #endif
  503. }
  504. /*******************************************************************************
  505. * Host driver
  506. ******************************************************************************/
  507. static uint8_t keyboard_leds(void)
  508. {
  509. return keyboard_led_stats;
  510. }
  511. static void send_keyboard(report_keyboard_t *report)
  512. {
  513. uint8_t timeout = 255;
  514. uint8_t where = where_to_send();
  515. #ifdef BLUETOOTH_ENABLE
  516. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  517. #ifdef MODULE_ADAFRUIT_BLE
  518. adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
  519. #elif MODULE_RN42
  520. bluefruit_serial_send(0xFD);
  521. bluefruit_serial_send(0x09);
  522. bluefruit_serial_send(0x01);
  523. for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
  524. bluefruit_serial_send(report->raw[i]);
  525. }
  526. #else
  527. bluefruit_serial_send(0xFD);
  528. for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
  529. bluefruit_serial_send(report->raw[i]);
  530. }
  531. #endif
  532. }
  533. #endif
  534. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  535. return;
  536. }
  537. /* Select the Keyboard Report Endpoint */
  538. #ifdef NKRO_ENABLE
  539. if (keyboard_protocol && keymap_config.nkro) {
  540. /* Report protocol - NKRO */
  541. Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
  542. /* Check if write ready for a polling interval around 1ms */
  543. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
  544. if (!Endpoint_IsReadWriteAllowed()) return;
  545. /* Write Keyboard Report Data */
  546. Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
  547. }
  548. else
  549. #endif
  550. {
  551. /* Boot protocol */
  552. Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
  553. /* Check if write ready for a polling interval around 10ms */
  554. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  555. if (!Endpoint_IsReadWriteAllowed()) return;
  556. /* Write Keyboard Report Data */
  557. Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
  558. }
  559. /* Finalize the stream transfer to send the last packet */
  560. Endpoint_ClearIN();
  561. keyboard_report_sent = *report;
  562. }
  563. static void send_mouse(report_mouse_t *report)
  564. {
  565. #ifdef MOUSE_ENABLE
  566. uint8_t timeout = 255;
  567. uint8_t where = where_to_send();
  568. #ifdef BLUETOOTH_ENABLE
  569. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  570. #ifdef MODULE_ADAFRUIT_BLE
  571. // FIXME: mouse buttons
  572. adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
  573. #else
  574. bluefruit_serial_send(0xFD);
  575. bluefruit_serial_send(0x00);
  576. bluefruit_serial_send(0x03);
  577. bluefruit_serial_send(report->buttons);
  578. bluefruit_serial_send(report->x);
  579. bluefruit_serial_send(report->y);
  580. bluefruit_serial_send(report->v); // should try sending the wheel v here
  581. bluefruit_serial_send(report->h); // should try sending the wheel h here
  582. bluefruit_serial_send(0x00);
  583. #endif
  584. }
  585. #endif
  586. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  587. return;
  588. }
  589. /* Select the Mouse Report Endpoint */
  590. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  591. /* Check if write ready for a polling interval around 10ms */
  592. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  593. if (!Endpoint_IsReadWriteAllowed()) return;
  594. /* Write Mouse Report Data */
  595. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  596. /* Finalize the stream transfer to send the last packet */
  597. Endpoint_ClearIN();
  598. #endif
  599. }
  600. static void send_system(uint16_t data)
  601. {
  602. uint8_t timeout = 255;
  603. if (USB_DeviceState != DEVICE_STATE_Configured)
  604. return;
  605. report_extra_t r = {
  606. .report_id = REPORT_ID_SYSTEM,
  607. .usage = data - SYSTEM_POWER_DOWN + 1
  608. };
  609. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  610. /* Check if write ready for a polling interval around 10ms */
  611. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  612. if (!Endpoint_IsReadWriteAllowed()) return;
  613. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  614. Endpoint_ClearIN();
  615. }
  616. static void send_consumer(uint16_t data)
  617. {
  618. uint8_t timeout = 255;
  619. uint8_t where = where_to_send();
  620. #ifdef BLUETOOTH_ENABLE
  621. if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
  622. #ifdef MODULE_ADAFRUIT_BLE
  623. adafruit_ble_send_consumer_key(data, 0);
  624. #elif MODULE_RN42
  625. static uint16_t last_data = 0;
  626. if (data == last_data) return;
  627. last_data = data;
  628. uint16_t bitmap = CONSUMER2RN42(data);
  629. bluefruit_serial_send(0xFD);
  630. bluefruit_serial_send(0x03);
  631. bluefruit_serial_send(0x03);
  632. bluefruit_serial_send(bitmap&0xFF);
  633. bluefruit_serial_send((bitmap>>8)&0xFF);
  634. #else
  635. static uint16_t last_data = 0;
  636. if (data == last_data) return;
  637. last_data = data;
  638. uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
  639. bluefruit_serial_send(0xFD);
  640. bluefruit_serial_send(0x00);
  641. bluefruit_serial_send(0x02);
  642. bluefruit_serial_send((bitmap>>8)&0xFF);
  643. bluefruit_serial_send(bitmap&0xFF);
  644. bluefruit_serial_send(0x00);
  645. bluefruit_serial_send(0x00);
  646. bluefruit_serial_send(0x00);
  647. bluefruit_serial_send(0x00);
  648. #endif
  649. }
  650. #endif
  651. if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
  652. return;
  653. }
  654. report_extra_t r = {
  655. .report_id = REPORT_ID_CONSUMER,
  656. .usage = data
  657. };
  658. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  659. /* Check if write ready for a polling interval around 10ms */
  660. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  661. if (!Endpoint_IsReadWriteAllowed()) return;
  662. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  663. Endpoint_ClearIN();
  664. }
  665. /*******************************************************************************
  666. * sendchar
  667. ******************************************************************************/
  668. #ifdef CONSOLE_ENABLE
  669. #define SEND_TIMEOUT 5
  670. int8_t sendchar(uint8_t c)
  671. {
  672. // Not wait once timeouted.
  673. // Because sendchar() is called so many times, waiting each call causes big lag.
  674. static bool timeouted = false;
  675. // prevents Console_Task() from running during sendchar() runs.
  676. // or char will be lost. These two function is mutually exclusive.
  677. CONSOLE_FLUSH_SET(false);
  678. if (USB_DeviceState != DEVICE_STATE_Configured)
  679. return -1;
  680. uint8_t ep = Endpoint_GetCurrentEndpoint();
  681. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  682. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  683. goto ERROR_EXIT;
  684. }
  685. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  686. goto ERROR_EXIT;
  687. }
  688. timeouted = false;
  689. uint8_t timeout = SEND_TIMEOUT;
  690. while (!Endpoint_IsReadWriteAllowed()) {
  691. if (USB_DeviceState != DEVICE_STATE_Configured) {
  692. goto ERROR_EXIT;
  693. }
  694. if (Endpoint_IsStalled()) {
  695. goto ERROR_EXIT;
  696. }
  697. if (!(timeout--)) {
  698. timeouted = true;
  699. goto ERROR_EXIT;
  700. }
  701. _delay_ms(1);
  702. }
  703. Endpoint_Write_8(c);
  704. // send when bank is full
  705. if (!Endpoint_IsReadWriteAllowed()) {
  706. while (!(Endpoint_IsINReady()));
  707. Endpoint_ClearIN();
  708. } else {
  709. CONSOLE_FLUSH_SET(true);
  710. }
  711. Endpoint_SelectEndpoint(ep);
  712. return 0;
  713. ERROR_EXIT:
  714. Endpoint_SelectEndpoint(ep);
  715. return -1;
  716. }
  717. #else
  718. int8_t sendchar(uint8_t c)
  719. {
  720. return 0;
  721. }
  722. #endif
  723. /*******************************************************************************
  724. * MIDI
  725. ******************************************************************************/
  726. #ifdef MIDI_ENABLE
  727. static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
  728. MIDI_EventPacket_t event;
  729. event.Data1 = byte0;
  730. event.Data2 = byte1;
  731. event.Data3 = byte2;
  732. uint8_t cable = 0;
  733. // Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPNUM);
  734. //if the length is undefined we assume it is a SYSEX message
  735. if (midi_packet_length(byte0) == UNDEFINED) {
  736. switch(cnt) {
  737. case 3:
  738. if (byte2 == SYSEX_END)
  739. event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_3);
  740. else
  741. event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
  742. break;
  743. case 2:
  744. if (byte1 == SYSEX_END)
  745. event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_2);
  746. else
  747. event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
  748. break;
  749. case 1:
  750. if (byte0 == SYSEX_END)
  751. event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_1);
  752. else
  753. event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
  754. break;
  755. default:
  756. return; //invalid cnt
  757. }
  758. } else {
  759. //deal with 'system common' messages
  760. //TODO are there any more?
  761. switch(byte0 & 0xF0){
  762. case MIDI_SONGPOSITION:
  763. event.Event = MIDI_EVENT(cable, SYS_COMMON_3);
  764. break;
  765. case MIDI_SONGSELECT:
  766. case MIDI_TC_QUARTERFRAME:
  767. event.Event = MIDI_EVENT(cable, SYS_COMMON_2);
  768. break;
  769. default:
  770. event.Event = MIDI_EVENT(cable, byte0);
  771. break;
  772. }
  773. }
  774. // Endpoint_Write_Stream_LE(&event, sizeof(event), NULL);
  775. // Endpoint_ClearIN();
  776. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, &event);
  777. MIDI_Device_Flush(&USB_MIDI_Interface);
  778. MIDI_Device_USBTask(&USB_MIDI_Interface);
  779. USB_USBTask();
  780. }
  781. static void usb_get_midi(MidiDevice * device) {
  782. MIDI_EventPacket_t event;
  783. while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
  784. midi_packet_length_t length = midi_packet_length(event.Data1);
  785. uint8_t input[3];
  786. input[0] = event.Data1;
  787. input[1] = event.Data2;
  788. input[2] = event.Data3;
  789. if (length == UNDEFINED) {
  790. //sysex
  791. if (event.Event == MIDI_EVENT(0, SYSEX_START_OR_CONT) || event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_3)) {
  792. length = 3;
  793. } else if (event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_2)) {
  794. length = 2;
  795. } else if(event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_1)) {
  796. length = 1;
  797. } else {
  798. //XXX what to do?
  799. }
  800. }
  801. //pass the data to the device input function
  802. if (length != UNDEFINED)
  803. midi_device_input(device, length, input);
  804. }
  805. MIDI_Device_USBTask(&USB_MIDI_Interface);
  806. USB_USBTask();
  807. }
  808. static void midi_usb_init(MidiDevice * device){
  809. midi_device_init(device);
  810. midi_device_set_send_func(device, usb_send_func);
  811. midi_device_set_pre_input_process_func(device, usb_get_midi);
  812. // SetupHardware();
  813. sei();
  814. }
  815. void MIDI_Task(void)
  816. {
  817. /* Device must be connected and configured for the task to run */
  818. dprint("in MIDI_TASK\n");
  819. if (USB_DeviceState != DEVICE_STATE_Configured)
  820. return;
  821. dprint("continuing in MIDI_TASK\n");
  822. Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPADDR);
  823. if (Endpoint_IsINReady())
  824. {
  825. dprint("Endpoint is ready\n");
  826. uint8_t MIDICommand = 0;
  827. uint8_t MIDIPitch;
  828. /* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
  829. uint8_t Channel = MIDI_CHANNEL(1);
  830. MIDICommand = MIDI_COMMAND_NOTE_ON;
  831. MIDIPitch = 0x3E;
  832. /* Check if a MIDI command is to be sent */
  833. if (MIDICommand)
  834. {
  835. dprint("Command exists\n");
  836. MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
  837. {
  838. .Event = MIDI_EVENT(0, MIDICommand),
  839. .Data1 = MIDICommand | Channel,
  840. .Data2 = MIDIPitch,
  841. .Data3 = MIDI_STANDARD_VELOCITY,
  842. };
  843. /* Write the MIDI event packet to the endpoint */
  844. Endpoint_Write_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
  845. /* Send the data in the endpoint to the host */
  846. Endpoint_ClearIN();
  847. }
  848. }
  849. /* Select the MIDI OUT stream */
  850. Endpoint_SelectEndpoint(MIDI_STREAM_OUT_EPADDR);
  851. /* Check if a MIDI command has been received */
  852. if (Endpoint_IsOUTReceived())
  853. {
  854. MIDI_EventPacket_t MIDIEvent;
  855. /* Read the MIDI event packet from the endpoint */
  856. Endpoint_Read_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
  857. /* If the endpoint is now empty, clear the bank */
  858. if (!(Endpoint_BytesInEndpoint()))
  859. {
  860. /* Clear the endpoint ready for new packet */
  861. Endpoint_ClearOUT();
  862. }
  863. }
  864. }
  865. #endif
  866. /*******************************************************************************
  867. * VIRTUAL SERIAL
  868. ******************************************************************************/
  869. #ifdef VIRTSER_ENABLE
  870. void virtser_init(void)
  871. {
  872. cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
  873. CDC_Device_SendControlLineStateChange(&cdc_device);
  874. }
  875. void virtser_recv(uint8_t c) __attribute__ ((weak));
  876. void virtser_recv(uint8_t c)
  877. {
  878. // Ignore by default
  879. }
  880. void virtser_task(void)
  881. {
  882. uint16_t count = CDC_Device_BytesReceived(&cdc_device);
  883. uint8_t ch;
  884. if (count)
  885. {
  886. ch = CDC_Device_ReceiveByte(&cdc_device);
  887. virtser_recv(ch);
  888. }
  889. }
  890. void virtser_send(const uint8_t byte)
  891. {
  892. uint8_t timeout = 255;
  893. uint8_t ep = Endpoint_GetCurrentEndpoint();
  894. if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
  895. {
  896. /* IN packet */
  897. Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
  898. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  899. Endpoint_SelectEndpoint(ep);
  900. return;
  901. }
  902. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  903. Endpoint_Write_8(byte);
  904. CDC_Device_Flush(&cdc_device);
  905. if (Endpoint_IsINReady()) {
  906. Endpoint_ClearIN();
  907. }
  908. Endpoint_SelectEndpoint(ep);
  909. }
  910. }
  911. #endif
  912. /*******************************************************************************
  913. * main
  914. ******************************************************************************/
  915. static void setup_mcu(void)
  916. {
  917. /* Disable watchdog if enabled by bootloader/fuses */
  918. MCUSR &= ~(1 << WDRF);
  919. wdt_disable();
  920. /* Disable clock division */
  921. // clock_prescale_set(clock_div_1);
  922. CLKPR = (1 << CLKPCE);
  923. CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
  924. }
  925. static void setup_usb(void)
  926. {
  927. // Leonardo needs. Without this USB device is not recognized.
  928. USB_Disable();
  929. USB_Init();
  930. // for Console_Task
  931. USB_Device_EnableSOFEvents();
  932. print_set_sendchar(sendchar);
  933. }
  934. #ifdef MIDI_ENABLE
  935. void fallthrough_callback(MidiDevice * device,
  936. uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
  937. void cc_callback(MidiDevice * device,
  938. uint8_t chan, uint8_t num, uint8_t val);
  939. void sysex_callback(MidiDevice * device,
  940. uint16_t start, uint8_t length, uint8_t * data);
  941. void setup_midi(void)
  942. {
  943. #ifdef MIDI_ADVANCED
  944. midi_init();
  945. #endif
  946. midi_device_init(&midi_device);
  947. midi_device_set_send_func(&midi_device, usb_send_func);
  948. midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
  949. }
  950. #endif
  951. int main(void) __attribute__ ((weak));
  952. int main(void)
  953. {
  954. #ifdef MIDI_ENABLE
  955. setup_midi();
  956. #endif
  957. setup_mcu();
  958. keyboard_setup();
  959. setup_usb();
  960. sei();
  961. #ifdef MIDI_ENABLE
  962. midi_register_fallthrough_callback(&midi_device, fallthrough_callback);
  963. midi_register_cc_callback(&midi_device, cc_callback);
  964. midi_register_sysex_callback(&midi_device, sysex_callback);
  965. // init_notes();
  966. // midi_send_cc(&midi_device, 0, 1, 2);
  967. // midi_send_cc(&midi_device, 15, 1, 0);
  968. // midi_send_noteon(&midi_device, 0, 64, 127);
  969. // midi_send_noteoff(&midi_device, 0, 64, 127);
  970. #endif
  971. #if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
  972. serial_init();
  973. #endif
  974. /* wait for USB startup & debug output */
  975. #ifdef WAIT_FOR_USB
  976. while (USB_DeviceState != DEVICE_STATE_Configured) {
  977. #if defined(INTERRUPT_CONTROL_ENDPOINT)
  978. ;
  979. #else
  980. USB_USBTask();
  981. #endif
  982. }
  983. print("USB configured.\n");
  984. #else
  985. USB_USBTask();
  986. #endif
  987. /* init modules */
  988. keyboard_init();
  989. host_set_driver(&lufa_driver);
  990. #ifdef SLEEP_LED_ENABLE
  991. sleep_led_init();
  992. #endif
  993. #ifdef VIRTSER_ENABLE
  994. virtser_init();
  995. #endif
  996. print("Keyboard start.\n");
  997. while (1) {
  998. #if !defined(NO_USB_STARTUP_CHECK)
  999. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  1000. print("[s]");
  1001. suspend_power_down();
  1002. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  1003. USB_Device_SendRemoteWakeup();
  1004. }
  1005. }
  1006. #endif
  1007. keyboard_task();
  1008. #ifdef MIDI_ENABLE
  1009. midi_device_process(&midi_device);
  1010. #ifdef MIDI_ADVANCED
  1011. midi_task();
  1012. #endif
  1013. #endif
  1014. #if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
  1015. rgblight_task();
  1016. #endif
  1017. #ifdef MODULE_ADAFRUIT_BLE
  1018. adafruit_ble_task();
  1019. #endif
  1020. #ifdef VIRTSER_ENABLE
  1021. virtser_task();
  1022. CDC_Device_USBTask(&cdc_device);
  1023. #endif
  1024. #ifdef RAW_ENABLE
  1025. raw_hid_task();
  1026. #endif
  1027. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  1028. USB_USBTask();
  1029. #endif
  1030. }
  1031. }
  1032. #ifdef MIDI_ENABLE
  1033. void fallthrough_callback(MidiDevice * device,
  1034. uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2){
  1035. #ifdef AUDIO_ENABLE
  1036. if (cnt == 3) {
  1037. switch (byte0 & 0xF0) {
  1038. case MIDI_NOTEON:
  1039. play_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0), (byte2 & 0x7F) / 8);
  1040. break;
  1041. case MIDI_NOTEOFF:
  1042. stop_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0));
  1043. break;
  1044. }
  1045. }
  1046. if (byte0 == MIDI_STOP) {
  1047. stop_all_notes();
  1048. }
  1049. #endif
  1050. }
  1051. void cc_callback(MidiDevice * device,
  1052. uint8_t chan, uint8_t num, uint8_t val) {
  1053. //sending it back on the next channel
  1054. // midi_send_cc(device, (chan + 1) % 16, num, val);
  1055. }
  1056. #ifdef API_SYSEX_ENABLE
  1057. uint8_t midi_buffer[MIDI_SYSEX_BUFFER] = {0};
  1058. #endif
  1059. void sysex_callback(MidiDevice * device, uint16_t start, uint8_t length, uint8_t * data) {
  1060. #ifdef API_SYSEX_ENABLE
  1061. // SEND_STRING("\n");
  1062. // send_word(start);
  1063. // SEND_STRING(": ");
  1064. // Don't store the header
  1065. int16_t pos = start - 4;
  1066. for (uint8_t place = 0; place < length; place++) {
  1067. // send_byte(*data);
  1068. if (pos >= 0) {
  1069. if (*data == 0xF7) {
  1070. // SEND_STRING("\nRD: ");
  1071. // for (uint8_t i = 0; i < start + place + 1; i++){
  1072. // send_byte(midi_buffer[i]);
  1073. // SEND_STRING(" ");
  1074. // }
  1075. const unsigned decoded_length = sysex_decoded_length(pos);
  1076. uint8_t decoded[API_SYSEX_MAX_SIZE];
  1077. sysex_decode(decoded, midi_buffer, pos);
  1078. process_api(decoded_length, decoded);
  1079. return;
  1080. }
  1081. else if (pos >= MIDI_SYSEX_BUFFER) {
  1082. return;
  1083. }
  1084. midi_buffer[pos] = *data;
  1085. }
  1086. // SEND_STRING(" ");
  1087. data++;
  1088. pos++;
  1089. }
  1090. #endif
  1091. }
  1092. #endif