lufa.c 25 KB

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