lufa.c 30 KB

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