lufa.c 25 KB

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