lufa.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. uint8_t keyboard_idle = 0;
  48. uint8_t keyboard_protocol = 1;
  49. static uint8_t keyboard_led_stats = 0;
  50. static report_keyboard_t keyboard_report_sent;
  51. /* Host driver */
  52. static uint8_t keyboard_leds(void);
  53. static void send_keyboard(report_keyboard_t *report);
  54. static void send_mouse(report_mouse_t *report);
  55. static void send_system(uint16_t data);
  56. static void send_consumer(uint16_t data);
  57. void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
  58. void usb_get_midi(MidiDevice * device);
  59. void midi_usb_init(MidiDevice * device);
  60. host_driver_t lufa_driver = {
  61. keyboard_leds,
  62. send_keyboard,
  63. send_mouse,
  64. send_system,
  65. send_consumer,
  66. usb_send_func,
  67. usb_get_midi,
  68. midi_usb_init
  69. };
  70. void SetupHardware(void);
  71. USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
  72. {
  73. .Config =
  74. {
  75. .StreamingInterfaceNumber = 1,
  76. .DataINEndpoint =
  77. {
  78. .Address = (ENDPOINT_DIR_IN | MIDI_STREAM_IN_EPNUM),
  79. .Size = MIDI_STREAM_EPSIZE,
  80. .Banks = 1,
  81. },
  82. .DataOUTEndpoint =
  83. {
  84. .Address = (ENDPOINT_DIR_OUT | MIDI_STREAM_OUT_EPNUM),
  85. .Size = MIDI_STREAM_EPSIZE,
  86. .Banks = 1,
  87. },
  88. },
  89. };
  90. #define SYSEX_START_OR_CONT 0x40
  91. #define SYSEX_ENDS_IN_1 0x50
  92. #define SYSEX_ENDS_IN_2 0x60
  93. #define SYSEX_ENDS_IN_3 0x70
  94. #define SYS_COMMON_1 0x50
  95. #define SYS_COMMON_2 0x20
  96. #define SYS_COMMON_3 0x30
  97. /*******************************************************************************
  98. * Console
  99. ******************************************************************************/
  100. #ifdef CONSOLE_ENABLE
  101. static void Console_Task(void)
  102. {
  103. /* Device must be connected and configured for the task to run */
  104. if (USB_DeviceState != DEVICE_STATE_Configured)
  105. return;
  106. uint8_t ep = Endpoint_GetCurrentEndpoint();
  107. #if 0
  108. // TODO: impl receivechar()/recvchar()
  109. Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
  110. /* Check to see if a packet has been sent from the host */
  111. if (Endpoint_IsOUTReceived())
  112. {
  113. /* Check to see if the packet contains data */
  114. if (Endpoint_IsReadWriteAllowed())
  115. {
  116. /* Create a temporary buffer to hold the read in report from the host */
  117. uint8_t ConsoleData[CONSOLE_EPSIZE];
  118. /* Read Console Report Data */
  119. Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
  120. /* Process Console Report Data */
  121. //ProcessConsoleHIDReport(ConsoleData);
  122. }
  123. /* Finalize the stream transfer to send the last packet */
  124. Endpoint_ClearOUT();
  125. }
  126. #endif
  127. /* IN packet */
  128. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  129. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  130. Endpoint_SelectEndpoint(ep);
  131. return;
  132. }
  133. // fill empty bank
  134. while (Endpoint_IsReadWriteAllowed())
  135. Endpoint_Write_8(0);
  136. // flash senchar packet
  137. if (Endpoint_IsINReady()) {
  138. Endpoint_ClearIN();
  139. }
  140. Endpoint_SelectEndpoint(ep);
  141. }
  142. #else
  143. static void Console_Task(void)
  144. {
  145. }
  146. #endif
  147. /*******************************************************************************
  148. * USB Events
  149. ******************************************************************************/
  150. /*
  151. * Event Order of Plug in:
  152. * 0) EVENT_USB_Device_Connect
  153. * 1) EVENT_USB_Device_Suspend
  154. * 2) EVENT_USB_Device_Reset
  155. * 3) EVENT_USB_Device_Wake
  156. */
  157. void EVENT_USB_Device_Connect(void)
  158. {
  159. print("[C]");
  160. /* For battery powered device */
  161. if (!USB_IsInitialized) {
  162. USB_Disable();
  163. USB_Init();
  164. USB_Device_EnableSOFEvents();
  165. }
  166. }
  167. void EVENT_USB_Device_Disconnect(void)
  168. {
  169. print("[D]");
  170. /* For battery powered device */
  171. USB_IsInitialized = false;
  172. /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
  173. if (USB_IsInitialized) {
  174. USB_Disable(); // Disable all interrupts
  175. USB_Controller_Enable();
  176. USB_INT_Enable(USB_INT_VBUSTI);
  177. }
  178. */
  179. }
  180. void EVENT_USB_Device_Reset(void)
  181. {
  182. print("[R]");
  183. }
  184. void EVENT_USB_Device_Suspend()
  185. {
  186. print("[S]");
  187. matrix_power_down();
  188. #ifdef SLEEP_LED_ENABLE
  189. sleep_led_enable();
  190. #endif
  191. }
  192. void EVENT_USB_Device_WakeUp()
  193. {
  194. print("[W]");
  195. suspend_wakeup_init();
  196. #ifdef SLEEP_LED_ENABLE
  197. sleep_led_disable();
  198. // NOTE: converters may not accept this
  199. led_set(host_keyboard_leds());
  200. #endif
  201. }
  202. void EVENT_USB_Device_StartOfFrame(void)
  203. {
  204. Console_Task();
  205. }
  206. /** Event handler for the USB_ConfigurationChanged event.
  207. * This is fired when the host sets the current configuration of the USB device after enumeration.
  208. */
  209. void EVENT_USB_Device_ConfigurationChanged(void)
  210. {
  211. bool ConfigSuccess = true;
  212. /* Setup Keyboard HID Report Endpoints */
  213. ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  214. KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
  215. #ifdef MOUSE_ENABLE
  216. /* Setup Mouse HID Report Endpoint */
  217. ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  218. MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
  219. #endif
  220. #ifdef EXTRAKEY_ENABLE
  221. /* Setup Extra HID Report Endpoint */
  222. ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  223. EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
  224. #endif
  225. #ifdef CONSOLE_ENABLE
  226. /* Setup Console HID Report Endpoints */
  227. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  228. CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
  229. #if 0
  230. ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
  231. CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
  232. #endif
  233. #endif
  234. #ifdef NKRO_ENABLE
  235. /* Setup NKRO HID Report Endpoints */
  236. ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
  237. NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
  238. #endif
  239. ConfigSuccess &= MIDI_Device_ConfigureEndpoints(&USB_MIDI_Interface);
  240. }
  241. /*
  242. Appendix G: HID Request Support Requirements
  243. The following table enumerates the requests that need to be supported by various types of HID class devices.
  244. Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
  245. ------------------------------------------------------------------------------------------
  246. Boot Mouse Required Optional Optional Optional Required Required
  247. Non-Boot Mouse Required Optional Optional Optional Optional Optional
  248. Boot Keyboard Required Optional Required Required Required Required
  249. Non-Boot Keybrd Required Optional Required Required Optional Optional
  250. Other Device Required Optional Optional Optional Optional Optional
  251. */
  252. /** Event handler for the USB_ControlRequest event.
  253. * This is fired before passing along unhandled control requests to the library for processing internally.
  254. */
  255. void EVENT_USB_Device_ControlRequest(void)
  256. {
  257. uint8_t* ReportData = NULL;
  258. uint8_t ReportSize = 0;
  259. MIDI_Device_ProcessControlRequest(&USB_MIDI_Interface);
  260. /* Handle HID Class specific requests */
  261. switch (USB_ControlRequest.bRequest)
  262. {
  263. case HID_REQ_GetReport:
  264. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  265. {
  266. Endpoint_ClearSETUP();
  267. // Interface
  268. switch (USB_ControlRequest.wIndex) {
  269. case KEYBOARD_INTERFACE:
  270. // TODO: test/check
  271. ReportData = (uint8_t*)&keyboard_report_sent;
  272. ReportSize = sizeof(keyboard_report_sent);
  273. break;
  274. }
  275. /* Write the report data to the control endpoint */
  276. Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
  277. Endpoint_ClearOUT();
  278. }
  279. break;
  280. case HID_REQ_SetReport:
  281. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  282. {
  283. // Interface
  284. switch (USB_ControlRequest.wIndex) {
  285. case KEYBOARD_INTERFACE:
  286. #ifdef NKRO_ENABLE
  287. case NKRO_INTERFACE:
  288. #endif
  289. Endpoint_ClearSETUP();
  290. while (!(Endpoint_IsOUTReceived())) {
  291. if (USB_DeviceState == DEVICE_STATE_Unattached)
  292. return;
  293. }
  294. keyboard_led_stats = Endpoint_Read_8();
  295. Endpoint_ClearOUT();
  296. Endpoint_ClearStatusStage();
  297. break;
  298. }
  299. }
  300. break;
  301. case HID_REQ_GetProtocol:
  302. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  303. {
  304. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  305. Endpoint_ClearSETUP();
  306. while (!(Endpoint_IsINReady()));
  307. Endpoint_Write_8(keyboard_protocol);
  308. Endpoint_ClearIN();
  309. Endpoint_ClearStatusStage();
  310. }
  311. }
  312. break;
  313. case HID_REQ_SetProtocol:
  314. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  315. {
  316. if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
  317. Endpoint_ClearSETUP();
  318. Endpoint_ClearStatusStage();
  319. keyboard_protocol = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
  320. #ifdef NKRO_ENABLE
  321. keyboard_nkro = !!keyboard_protocol;
  322. #endif
  323. clear_keyboard();
  324. }
  325. }
  326. break;
  327. case HID_REQ_SetIdle:
  328. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  329. {
  330. Endpoint_ClearSETUP();
  331. Endpoint_ClearStatusStage();
  332. keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
  333. }
  334. break;
  335. case HID_REQ_GetIdle:
  336. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  337. {
  338. Endpoint_ClearSETUP();
  339. while (!(Endpoint_IsINReady()));
  340. Endpoint_Write_8(keyboard_idle);
  341. Endpoint_ClearIN();
  342. Endpoint_ClearStatusStage();
  343. }
  344. break;
  345. }
  346. }
  347. /*******************************************************************************
  348. * Host driver
  349. ******************************************************************************/
  350. static uint8_t keyboard_leds(void)
  351. {
  352. return keyboard_led_stats;
  353. }
  354. static void send_keyboard(report_keyboard_t *report)
  355. {
  356. uint8_t timeout = 255;
  357. if (USB_DeviceState != DEVICE_STATE_Configured)
  358. return;
  359. /* Select the Keyboard Report Endpoint */
  360. #ifdef NKRO_ENABLE
  361. if (keyboard_nkro) {
  362. /* Report protocol - NKRO */
  363. Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
  364. /* Check if write ready for a polling interval around 1ms */
  365. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
  366. if (!Endpoint_IsReadWriteAllowed()) return;
  367. /* Write Keyboard Report Data */
  368. Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
  369. }
  370. else
  371. #endif
  372. {
  373. /* Boot protocol */
  374. Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
  375. /* Check if write ready for a polling interval around 10ms */
  376. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  377. if (!Endpoint_IsReadWriteAllowed()) return;
  378. /* Write Keyboard Report Data */
  379. Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
  380. }
  381. /* Finalize the stream transfer to send the last packet */
  382. Endpoint_ClearIN();
  383. keyboard_report_sent = *report;
  384. }
  385. static void send_mouse(report_mouse_t *report)
  386. {
  387. #ifdef MOUSE_ENABLE
  388. uint8_t timeout = 255;
  389. if (USB_DeviceState != DEVICE_STATE_Configured)
  390. return;
  391. /* Select the Mouse Report Endpoint */
  392. Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
  393. /* Check if write ready for a polling interval around 10ms */
  394. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  395. if (!Endpoint_IsReadWriteAllowed()) return;
  396. /* Write Mouse Report Data */
  397. Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
  398. /* Finalize the stream transfer to send the last packet */
  399. Endpoint_ClearIN();
  400. #endif
  401. }
  402. static void send_system(uint16_t data)
  403. {
  404. uint8_t timeout = 255;
  405. if (USB_DeviceState != DEVICE_STATE_Configured)
  406. return;
  407. report_extra_t r = {
  408. .report_id = REPORT_ID_SYSTEM,
  409. .usage = data
  410. };
  411. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  412. /* Check if write ready for a polling interval around 10ms */
  413. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  414. if (!Endpoint_IsReadWriteAllowed()) return;
  415. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  416. Endpoint_ClearIN();
  417. }
  418. static void send_consumer(uint16_t data)
  419. {
  420. uint8_t timeout = 255;
  421. if (USB_DeviceState != DEVICE_STATE_Configured)
  422. return;
  423. report_extra_t r = {
  424. .report_id = REPORT_ID_CONSUMER,
  425. .usage = data
  426. };
  427. Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
  428. /* Check if write ready for a polling interval around 10ms */
  429. while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
  430. if (!Endpoint_IsReadWriteAllowed()) return;
  431. Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
  432. Endpoint_ClearIN();
  433. }
  434. /*******************************************************************************
  435. * sendchar
  436. ******************************************************************************/
  437. #ifdef CONSOLE_ENABLE
  438. #define SEND_TIMEOUT 5
  439. int8_t sendchar(uint8_t c)
  440. {
  441. // Not wait once timeouted.
  442. // Because sendchar() is called so many times, waiting each call causes big lag.
  443. static bool timeouted = false;
  444. if (USB_DeviceState != DEVICE_STATE_Configured)
  445. return -1;
  446. uint8_t ep = Endpoint_GetCurrentEndpoint();
  447. Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
  448. if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
  449. goto ERROR_EXIT;
  450. }
  451. if (timeouted && !Endpoint_IsReadWriteAllowed()) {
  452. goto ERROR_EXIT;
  453. }
  454. timeouted = false;
  455. uint8_t timeout = SEND_TIMEOUT;
  456. while (!Endpoint_IsReadWriteAllowed()) {
  457. if (USB_DeviceState != DEVICE_STATE_Configured) {
  458. goto ERROR_EXIT;
  459. }
  460. if (Endpoint_IsStalled()) {
  461. goto ERROR_EXIT;
  462. }
  463. if (!(timeout--)) {
  464. timeouted = true;
  465. goto ERROR_EXIT;
  466. }
  467. _delay_ms(1);
  468. }
  469. Endpoint_Write_8(c);
  470. // send when bank is full
  471. if (!Endpoint_IsReadWriteAllowed())
  472. Endpoint_ClearIN();
  473. Endpoint_SelectEndpoint(ep);
  474. return 0;
  475. ERROR_EXIT:
  476. Endpoint_SelectEndpoint(ep);
  477. return -1;
  478. }
  479. #else
  480. int8_t sendchar(uint8_t c)
  481. {
  482. return 0;
  483. }
  484. #endif
  485. void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
  486. MIDI_EventPacket_t event;
  487. event.Data1 = byte0;
  488. event.Data2 = byte1;
  489. event.Data3 = byte2;
  490. //if the length is undefined we assume it is a SYSEX message
  491. if (midi_packet_length(byte0) == UNDEFINED) {
  492. switch(cnt) {
  493. case 3:
  494. if (byte2 == SYSEX_END)
  495. event.Event = MIDI_EVENT(0, SYSEX_ENDS_IN_3);
  496. else
  497. event.Event = MIDI_EVENT(0, SYSEX_START_OR_CONT);
  498. break;
  499. case 2:
  500. if (byte1 == SYSEX_END)
  501. event.Event = MIDI_EVENT(0, SYSEX_ENDS_IN_2);
  502. else
  503. event.Event = MIDI_EVENT(0, SYSEX_START_OR_CONT);
  504. break;
  505. case 1:
  506. if (byte0 == SYSEX_END)
  507. event.Event = MIDI_EVENT(0, SYSEX_ENDS_IN_1);
  508. else
  509. event.Event = MIDI_EVENT(0, SYSEX_START_OR_CONT);
  510. break;
  511. default:
  512. return; //invalid cnt
  513. }
  514. } else {
  515. //deal with 'system common' messages
  516. //TODO are there any more?
  517. switch(byte0 & 0xF0){
  518. case MIDI_SONGPOSITION:
  519. event.Event = MIDI_EVENT(0, SYS_COMMON_3);
  520. break;
  521. case MIDI_SONGSELECT:
  522. case MIDI_TC_QUARTERFRAME:
  523. event.Event = MIDI_EVENT(0, SYS_COMMON_2);
  524. break;
  525. default:
  526. event.Event = MIDI_EVENT(0, byte0);
  527. break;
  528. }
  529. }
  530. MIDI_Device_SendEventPacket(&USB_MIDI_Interface, &event);
  531. MIDI_Device_Flush(&USB_MIDI_Interface);
  532. MIDI_Device_USBTask(&USB_MIDI_Interface);
  533. USB_USBTask();
  534. }
  535. void usb_get_midi(MidiDevice * device) {
  536. MIDI_EventPacket_t event;
  537. while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
  538. midi_packet_length_t length = midi_packet_length(event.Data1);
  539. uint8_t input[3];
  540. input[0] = event.Data1;
  541. input[1] = event.Data2;
  542. input[2] = event.Data3;
  543. if (length == UNDEFINED) {
  544. //sysex
  545. if (event.Event == MIDI_EVENT(0, SYSEX_START_OR_CONT) || event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_3)) {
  546. length = 3;
  547. } else if (event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_2)) {
  548. length = 2;
  549. } else if(event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_1)) {
  550. length = 1;
  551. } else {
  552. //XXX what to do?
  553. }
  554. }
  555. //pass the data to the device input function
  556. if (length != UNDEFINED)
  557. midi_device_input(device, length, input);
  558. }
  559. MIDI_Device_USBTask(&USB_MIDI_Interface);
  560. USB_USBTask();
  561. }
  562. void midi_usb_init(MidiDevice * device){
  563. midi_device_init(device);
  564. midi_device_set_send_func(device, usb_send_func);
  565. midi_device_set_pre_input_process_func(device, usb_get_midi);
  566. SetupHardware();
  567. sei();
  568. }
  569. /*******************************************************************************
  570. * main
  571. ******************************************************************************/
  572. void SetupHardware(void)
  573. {
  574. /* Disable watchdog if enabled by bootloader/fuses */
  575. MCUSR &= ~(1 << WDRF);
  576. wdt_disable();
  577. /* Disable clock division */
  578. clock_prescale_set(clock_div_1);
  579. // Leonardo needs. Without this USB device is not recognized.
  580. USB_Disable();
  581. USB_Init();
  582. // for Console_Task
  583. USB_Device_EnableSOFEvents();
  584. print_set_sendchar(sendchar);
  585. }
  586. void fallthrough_callback(MidiDevice * device,
  587. uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
  588. void cc_callback(MidiDevice * device,
  589. uint8_t chan, uint8_t num, uint8_t val);
  590. void sysex_callback(MidiDevice * device,
  591. uint16_t start, uint8_t length, uint8_t * data);
  592. int main(void) __attribute__ ((weak));
  593. int main(void)
  594. {
  595. //setup the device
  596. midi_device_init(&midi_device);
  597. midi_device_set_send_func(&midi_device, usb_send_func);
  598. midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
  599. SetupHardware();
  600. sei();
  601. midi_register_fallthrough_callback(&midi_device, fallthrough_callback);
  602. midi_register_cc_callback(&midi_device, cc_callback);
  603. midi_register_sysex_callback(&midi_device, sysex_callback);
  604. midi_send_cc(&midi_device, 0, 1, 2);
  605. midi_send_cc(&midi_device, 15, 1, 0);
  606. midi_send_noteon(&midi_device, 0, 64, 127);
  607. midi_send_noteoff(&midi_device, 0, 64, 127);
  608. /* wait for USB startup & debug output */
  609. while (USB_DeviceState != DEVICE_STATE_Configured) {
  610. #if defined(INTERRUPT_CONTROL_ENDPOINT)
  611. ;
  612. #else
  613. USB_USBTask();
  614. #endif
  615. }
  616. print("USB configured.\n");
  617. /* init modules */
  618. keyboard_init();
  619. host_set_driver(&lufa_driver);
  620. #ifdef SLEEP_LED_ENABLE
  621. sleep_led_init();
  622. #endif
  623. print("Keyboard start.\n");
  624. while (1) {
  625. while (USB_DeviceState == DEVICE_STATE_Suspended) {
  626. print("[s]");
  627. suspend_power_down();
  628. if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
  629. USB_Device_SendRemoteWakeup();
  630. }
  631. }
  632. keyboard_task();
  633. midi_device_process(&midi_device);
  634. #if !defined(INTERRUPT_CONTROL_ENDPOINT)
  635. USB_USBTask();
  636. #endif
  637. }
  638. }
  639. //echo data back
  640. void fallthrough_callback(MidiDevice * device,
  641. uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2){
  642. //pass the data back to the device, using the general purpose send data
  643. //function, any bytes after cnt are ignored
  644. }
  645. void cc_callback(MidiDevice * device,
  646. uint8_t chan, uint8_t num, uint8_t val) {
  647. //sending it back on the next channel
  648. midi_send_cc(device, (chan + 1) % 16, num, val);
  649. }
  650. void sysex_callback(MidiDevice * device,
  651. uint16_t start, uint8_t length, uint8_t * data) {
  652. for (int i = 0; i < length; i++)
  653. midi_send_cc(device, 15, 0x7F & data[i], 0x7F & (start + i));
  654. }