lufa.c 25 KB

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