lufa.c 29 KB

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