lufa.c 33 KB

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