lufa.c 26 KB

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