lufa.c 27 KB

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