lufa.c 30 KB

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