lufa.c 31 KB

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