upload
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

lufa.c 27KB

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