lufa.c 27 KB

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