lufa.c 23 KB

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