You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

526 satır
16KB

  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <Arduino.h>
  24. #include "USBHost_t36.h" // Read this header first for key info
  25. #include "keylayouts.h" // from Teensyduino core library
  26. typedef struct {
  27. KEYCODE_TYPE code;
  28. uint8_t ascii;
  29. } keycode_extra_t;
  30. typedef struct {
  31. KEYCODE_TYPE code;
  32. KEYCODE_TYPE codeNumlockOff;
  33. uint8_t charNumlockOn; // We will assume when num lock is on we have all characters...
  34. } keycode_numlock_t;
  35. typedef struct {
  36. uint16_t idVendor; // vendor id of keyboard
  37. uint16_t idProduct; // product id - 0 implies all of the ones from vendor;
  38. } keyboard_force_boot_protocol_t; // list of products to force into boot protocol
  39. #ifdef M
  40. #undef M
  41. #endif
  42. #define M(n) ((n) & KEYCODE_MASK)
  43. static const keycode_extra_t keycode_extras[] = {
  44. {M(KEY_ENTER), '\n'},
  45. {M(KEY_ESC), 0x1b},
  46. {M(KEY_TAB), 0x9 },
  47. {M(KEY_UP), KEYD_UP },
  48. {M(KEY_DOWN), KEYD_DOWN },
  49. {M(KEY_LEFT), KEYD_LEFT },
  50. {M(KEY_RIGHT), KEYD_RIGHT },
  51. {M(KEY_INSERT), KEYD_INSERT },
  52. {M(KEY_DELETE), KEYD_DELETE },
  53. {M(KEY_PAGE_UP), KEYD_PAGE_UP },
  54. {M(KEY_PAGE_DOWN), KEYD_PAGE_DOWN },
  55. {M(KEY_HOME), KEYD_HOME },
  56. {M(KEY_END), KEYD_END },
  57. {M(KEY_F1), KEYD_F1 },
  58. {M(KEY_F2), KEYD_F2 },
  59. {M(KEY_F3), KEYD_F3 },
  60. {M(KEY_F4), KEYD_F4 },
  61. {M(KEY_F5), KEYD_F5 },
  62. {M(KEY_F6), KEYD_F6 },
  63. {M(KEY_F7), KEYD_F7 },
  64. {M(KEY_F8), KEYD_F8 },
  65. {M(KEY_F9), KEYD_F9 },
  66. {M(KEY_F10), KEYD_F10 },
  67. {M(KEY_F11), KEYD_F11 },
  68. {M(KEY_F12), KEYD_F12 }
  69. };
  70. // Some of these mapped to key + shift.
  71. static const keycode_numlock_t keycode_numlock[] = {
  72. {M(KEYPAD_SLASH), '/', '/'},
  73. {M(KEYPAD_ASTERIX), '*', '*'},
  74. {M(KEYPAD_MINUS), '-', '-'},
  75. {M(KEYPAD_PLUS), '+', '+'},
  76. {M(KEYPAD_ENTER), '\n', '\n'},
  77. {M(KEYPAD_1), 0x80 | M(KEY_END), '1'},
  78. {M(KEYPAD_2), 0x80 | M(KEY_DOWN), '2'},
  79. {M(KEYPAD_3), 0x80 | M(KEY_PAGE_DOWN), '3'},
  80. {M(KEYPAD_4), 0x80 | M(KEY_LEFT), '4'},
  81. {M(KEYPAD_5), 0x00, '5'},
  82. {M(KEYPAD_6), 0x80 | M(KEY_RIGHT), '6'},
  83. {M(KEYPAD_7), 0x80 | M(KEY_HOME), '7'},
  84. {M(KEYPAD_8), 0x80 | M(KEY_UP), '8'},
  85. {M(KEYPAD_9), 0x80 | M(KEY_PAGE_UP), '9'},
  86. {M(KEYPAD_0), 0x80 | M(KEY_INSERT), '0'},
  87. {M(KEYPAD_PERIOD), 0x80 | M(KEY_DELETE), '.'}
  88. };
  89. static const keyboard_force_boot_protocol_t keyboard_forceBootMode[] = {
  90. {0x04D9, 0}
  91. };
  92. #define print USBHost::print_
  93. #define println USBHost::println_
  94. void KeyboardController::init()
  95. {
  96. contribute_Pipes(mypipes, sizeof(mypipes)/sizeof(Pipe_t));
  97. contribute_Transfers(mytransfers, sizeof(mytransfers)/sizeof(Transfer_t));
  98. contribute_String_Buffers(mystring_bufs, sizeof(mystring_bufs)/sizeof(strbuf_t));
  99. driver_ready_for_device(this);
  100. USBHIDParser::driver_ready_for_hid_collection(this);
  101. force_boot_protocol = false; // start off assuming not
  102. }
  103. bool KeyboardController::claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len)
  104. {
  105. println("KeyboardController claim this=", (uint32_t)this, HEX);
  106. // only claim at interface level
  107. if (type != 1) return false;
  108. if (len < 9+9+7) return false;
  109. print_hexbytes(descriptors, len);
  110. uint32_t numendpoint = descriptors[4];
  111. if (numendpoint < 1) return false;
  112. if (descriptors[5] != 3) return false; // bInterfaceClass, 3 = HID
  113. if (descriptors[6] != 1) return false; // bInterfaceSubClass, 1 = Boot Device
  114. if (descriptors[7] != 1) return false; // bInterfaceProtocol, 1 = Keyboard
  115. if (descriptors[9] != 9) return false;
  116. if (descriptors[10] != 33) return false; // HID descriptor (ignored, Boot Protocol)
  117. if (descriptors[18] != 7) return false;
  118. if (descriptors[19] != 5) return false; // endpoint descriptor
  119. uint32_t endpoint = descriptors[20];
  120. println("ep = ", endpoint, HEX);
  121. if ((endpoint & 0xF0) != 0x80) return false; // must be IN direction
  122. endpoint &= 0x0F;
  123. if (endpoint == 0) return false;
  124. if (descriptors[21] != 3) return false; // must be interrupt type
  125. uint32_t size = descriptors[22] | (descriptors[23] << 8);
  126. println("packet size = ", size);
  127. if ((size < 8) || (size > 64)) {
  128. return false; // Keyboard Boot Protocol is 8 bytes, but maybe others have longer...
  129. }
  130. #ifdef USBHS_KEYBOARD_INTERVAL
  131. uint32_t interval = USBHS_KEYBOARD_INTERVAL;
  132. #else
  133. uint32_t interval = descriptors[24];
  134. #endif
  135. println("polling interval = ", interval);
  136. datapipe = new_Pipe(dev, 3, endpoint, 1, 8, interval);
  137. datapipe->callback_function = callback;
  138. queue_Data_Transfer(datapipe, report, 8, this);
  139. // see if this device in list of devices that need to be set in
  140. // boot protocol mode
  141. bool in_forceBoot_mode_list = false;
  142. for (uint8_t i = 0; i < sizeof(keyboard_forceBootMode)/sizeof(keyboard_forceBootMode[0]); i++) {
  143. if (dev->idVendor == keyboard_forceBootMode[i].idVendor) {
  144. if ((dev->idProduct == keyboard_forceBootMode[i].idProduct) ||
  145. (keyboard_forceBootMode[i].idProduct == 0)) {
  146. in_forceBoot_mode_list = true;
  147. break;
  148. }
  149. }
  150. }
  151. if (in_forceBoot_mode_list) {
  152. println("SET_PROTOCOL Boot");
  153. mk_setup(setup, 0x21, 11, 0, 0, 0); // 11=SET_PROTOCOL BOOT
  154. } else {
  155. mk_setup(setup, 0x21, 10, 0, 0, 0); // 10=SET_IDLE
  156. }
  157. queue_Control_Transfer(dev, &setup, NULL, this);
  158. control_queued = true;
  159. return true;
  160. }
  161. void KeyboardController::control(const Transfer_t *transfer)
  162. {
  163. println("control callback (keyboard)");
  164. control_queued = false;
  165. print_hexbytes(transfer->buffer, transfer->length);
  166. // To decode hex dump to human readable HID report summary:
  167. // http://eleccelerator.com/usbdescreqparser/
  168. uint32_t mesg = transfer->setup.word1;
  169. println(" mesg = ", mesg, HEX);
  170. if (mesg == 0x00B21 && transfer->length == 0) { // SET_PROTOCOL
  171. mk_setup(setup, 0x21, 10, 0, 0, 0); // 10=SET_IDLE
  172. control_queued = true;
  173. queue_Control_Transfer(device, &setup, NULL, this);
  174. } else if (force_boot_protocol) {
  175. forceBootProtocol(); // lets setup to do the boot protocol
  176. force_boot_protocol = false; // turn back off
  177. }
  178. }
  179. void KeyboardController::callback(const Transfer_t *transfer)
  180. {
  181. //println("KeyboardController Callback (static)");
  182. if (transfer->driver) {
  183. ((KeyboardController *)(transfer->driver))->new_data(transfer);
  184. }
  185. }
  186. void KeyboardController::forceBootProtocol()
  187. {
  188. if (device && !control_queued) {
  189. mk_setup(setup, 0x21, 11, 0, 0, 0); // 11=SET_PROTOCOL BOOT
  190. control_queued = true;
  191. queue_Control_Transfer(device, &setup, NULL, this);
  192. } else {
  193. force_boot_protocol = true; // let system know we want to force this.
  194. }
  195. }
  196. void KeyboardController::disconnect()
  197. {
  198. // TODO: free resources
  199. }
  200. // Arduino defined this static weak symbol callback, and their
  201. // examples use it as the only way to detect new key presses,
  202. // so unfortunate as static weak callbacks are, it probably
  203. // needs to be supported for compatibility
  204. extern "C" {
  205. void __keyboardControllerEmptyCallback() { }
  206. }
  207. void keyPressed() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback")));
  208. void keyReleased() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback")));
  209. static bool contains(uint8_t b, const uint8_t *data)
  210. {
  211. if (data[2] == b || data[3] == b || data[4] == b) return true;
  212. if (data[5] == b || data[6] == b || data[7] == b) return true;
  213. return false;
  214. }
  215. void KeyboardController::new_data(const Transfer_t *transfer)
  216. {
  217. println("KeyboardController Callback (member)");
  218. print(" KB Data: ");
  219. print_hexbytes(transfer->buffer, 8);
  220. for (int i=2; i < 8; i++) {
  221. uint32_t key = prev_report[i];
  222. if (key >= 4 && !contains(key, report)) {
  223. key_release(prev_report[0], key);
  224. }
  225. }
  226. for (int i=2; i < 8; i++) {
  227. uint32_t key = report[i];
  228. if (key >= 4 && !contains(key, prev_report)) {
  229. key_press(report[0], key);
  230. }
  231. }
  232. memcpy(prev_report, report, 8);
  233. queue_Data_Transfer(datapipe, report, 8, this);
  234. }
  235. void KeyboardController::numLock(bool f) {
  236. if (leds_.numLock != f) {
  237. leds_.numLock = f;
  238. updateLEDS();
  239. }
  240. }
  241. void KeyboardController::capsLock(bool f) {
  242. if (leds_.capsLock != f) {
  243. leds_.capsLock = f;
  244. updateLEDS();
  245. }
  246. }
  247. void KeyboardController::scrollLock(bool f) {
  248. if (leds_.scrollLock != f) {
  249. leds_.scrollLock = f;
  250. updateLEDS();
  251. }
  252. }
  253. void KeyboardController::key_press(uint32_t mod, uint32_t key)
  254. {
  255. // TODO: queue events, perform callback from Task
  256. println(" press, key=", key);
  257. modifiers = mod;
  258. keyOEM = key;
  259. keyCode = convert_to_unicode(mod, key);
  260. println(" unicode = ", keyCode);
  261. if (keyPressedFunction) {
  262. keyPressedFunction(keyCode);
  263. } else {
  264. keyPressed();
  265. }
  266. }
  267. void KeyboardController::key_release(uint32_t mod, uint32_t key)
  268. {
  269. // TODO: queue events, perform callback from Task
  270. println(" release, key=", key);
  271. modifiers = mod;
  272. keyOEM = key;
  273. // Look for modifier keys
  274. if (key == M(KEY_NUM_LOCK)) {
  275. numLock(!leds_.numLock);
  276. // Lets toggle Numlock
  277. } else if (key == M(KEY_CAPS_LOCK)) {
  278. capsLock(!leds_.capsLock);
  279. } else if (key == M(KEY_SCROLL_LOCK)) {
  280. scrollLock(!leds_.scrollLock);
  281. } else {
  282. keyCode = convert_to_unicode(mod, key);
  283. if (keyReleasedFunction) {
  284. keyReleasedFunction(keyCode);
  285. } else {
  286. keyReleased();
  287. }
  288. }
  289. }
  290. uint16_t KeyboardController::convert_to_unicode(uint32_t mod, uint32_t key)
  291. {
  292. // WIP: special keys
  293. // TODO: dead key sequences
  294. if (key & SHIFT_MASK) {
  295. // Many of these keys will look like they are other keys with shift mask...
  296. // Check for any of our mapped extra keys
  297. for (uint8_t i = 0; i < (sizeof(keycode_numlock)/sizeof(keycode_numlock[0])); i++) {
  298. if (keycode_numlock[i].code == key) {
  299. // See if the user is using numlock or not...
  300. if (leds_.numLock) {
  301. return keycode_numlock[i].charNumlockOn;
  302. } else {
  303. key = keycode_numlock[i].codeNumlockOff;
  304. if (!(key & 0x80)) return key; // we have hard coded value
  305. key &= 0x7f; // mask off the extra and break out to process as other characters...
  306. break;
  307. }
  308. }
  309. }
  310. }
  311. // Check for any of our mapped extra keys - Done early as some of these keys are
  312. // above and some below the SHIFT_MASK value
  313. for (uint8_t i = 0; i < (sizeof(keycode_extras)/sizeof(keycode_extras[0])); i++) {
  314. if (keycode_extras[i].code == key) {
  315. return keycode_extras[i].ascii;
  316. }
  317. }
  318. // If we made it here without doing something then return 0;
  319. if (key & SHIFT_MASK) return 0;
  320. if ((mod & 0x02) || (mod & 0x20)) key |= SHIFT_MASK;
  321. if (leds_.capsLock) key ^= SHIFT_MASK; // Caps lock will switch the Shift;
  322. for (int i=0; i < 96; i++) {
  323. if (keycodes_ascii[i] == key) {
  324. if ((mod & 1) || (mod & 0x10)) return (i+32) & 0x1f; // Control key is down
  325. return i + 32;
  326. }
  327. }
  328. #ifdef ISO_8859_1_A0
  329. for (int i=0; i < 96; i++) {
  330. if (keycodes_iso_8859_1[i] == key) return i + 160;
  331. }
  332. #endif
  333. return 0;
  334. }
  335. void KeyboardController::LEDS(uint8_t leds) {
  336. println("Keyboard setLEDS ", leds, HEX);
  337. leds_.byte = leds;
  338. updateLEDS();
  339. }
  340. void KeyboardController::updateLEDS() {
  341. // Now lets tell keyboard new state.
  342. mk_setup(setup, 0x21, 9, 0x200, 0, sizeof(leds_.byte)); // hopefully this sets leds
  343. queue_Control_Transfer(device, &setup, &leds_.byte, this);
  344. }
  345. //=============================================================================
  346. // Keyboard Extras - Combined from other object
  347. //=============================================================================
  348. #define TOPUSAGE_SYS_CONTROL 0x10080
  349. #define TOPUSAGE_CONSUMER_CONTROL 0x0c0001
  350. hidclaim_t KeyboardController::claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage)
  351. {
  352. // Lets try to claim a few specific Keyboard related collection/reports
  353. //Serial.printf("KBH Claim %x\n", topusage);
  354. if ((topusage != TOPUSAGE_SYS_CONTROL)
  355. && (topusage != TOPUSAGE_CONSUMER_CONTROL)
  356. ) return CLAIM_NO;
  357. // only claim from one physical device
  358. //Serial.println("KeyboardController claim collection");
  359. // Lets only claim if this is the same device as claimed Keyboard...
  360. if (dev != device) return CLAIM_NO;
  361. if (mydevice != NULL && dev != mydevice) return CLAIM_NO;
  362. mydevice = dev;
  363. collections_claimed_++;
  364. return CLAIM_REPORT;
  365. }
  366. void KeyboardController::disconnect_collection(Device_t *dev)
  367. {
  368. if (--collections_claimed_ == 0) {
  369. mydevice = NULL;
  370. }
  371. }
  372. void KeyboardController::hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax)
  373. {
  374. //Serial.printf("KPC:hid_input_begin TUSE: %x TYPE: %x Range:%x %x\n", topusage, type, lgmin, lgmax);
  375. topusage_ = topusage; // remember which report we are processing.
  376. hid_input_begin_ = true;
  377. hid_input_data_ = false;
  378. }
  379. void KeyboardController::hid_input_data(uint32_t usage, int32_t value)
  380. {
  381. // Hack ignore 0xff00 high words as these are user values...
  382. if ((usage & 0xffff0000) == 0xff000000) return;
  383. //Serial.printf("KeyboardController: topusage= %x usage=%X, value=%d\n", topusage_, usage, value);
  384. // See if the value is in our keys_down list
  385. usage &= 0xffff; // only keep the actual key
  386. if (usage == 0) return; // lets not process 0, if only 0 happens, we will handle it on the end to remove existing pressed items.
  387. // Remember if we have received any logical key up events. Some keyboard appear to send them
  388. // others do no...
  389. hid_input_data_ = true;
  390. uint8_t key_index;
  391. for (key_index = 0; key_index < count_keys_down_; key_index++) {
  392. if (keys_down[key_index] == usage) {
  393. if (value) return; // still down
  394. if (extrasKeyReleasedFunction) {
  395. extrasKeyReleasedFunction(topusage_, usage);
  396. }
  397. // Remove from list
  398. count_keys_down_--;
  399. for (;key_index < count_keys_down_; key_index++) {
  400. keys_down[key_index] = keys_down[key_index+1];
  401. }
  402. return;
  403. }
  404. }
  405. // Was not in list
  406. if (!value) return; // still 0
  407. if (extrasKeyPressedFunction) {
  408. extrasKeyPressedFunction(topusage_, usage);
  409. }
  410. if (count_keys_down_ < MAX_KEYS_DOWN) {
  411. keys_down[count_keys_down_++] = usage;
  412. }
  413. }
  414. void KeyboardController::hid_input_end()
  415. {
  416. //Serial.println("KPC:hid_input_end");
  417. if (hid_input_begin_) {
  418. // See if we received any data from parser if not, assume all keys released...
  419. if (!hid_input_data_ ) {
  420. if (extrasKeyReleasedFunction) {
  421. while (count_keys_down_) {
  422. count_keys_down_--;
  423. extrasKeyReleasedFunction(topusage_, keys_down[count_keys_down_]);
  424. }
  425. }
  426. count_keys_down_ = 0;
  427. }
  428. hid_input_begin_ = false;
  429. }
  430. }
  431. //*****************************************************************************
  432. // Some simple query functions depend on which interface we are using...
  433. //*****************************************************************************
  434. uint16_t KeyboardController::idVendor()
  435. {
  436. if (device != nullptr) return device->idVendor;
  437. if (mydevice != nullptr) return mydevice->idVendor;
  438. return 0;
  439. }
  440. uint16_t KeyboardController::idProduct()
  441. {
  442. if (device != nullptr) return device->idProduct;
  443. if (mydevice != nullptr) return mydevice->idProduct;
  444. return 0;
  445. }
  446. const uint8_t *KeyboardController::manufacturer()
  447. {
  448. if ((device != nullptr) && (device->strbuf != nullptr)) return &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  449. if ((mydevice != nullptr) && (mydevice->strbuf != nullptr)) return &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  450. return nullptr;
  451. }
  452. const uint8_t *KeyboardController::product()
  453. {
  454. if ((device != nullptr) && (device->strbuf != nullptr)) return &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  455. if ((mydevice != nullptr) && (mydevice->strbuf != nullptr)) return &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  456. return nullptr;
  457. }
  458. const uint8_t *KeyboardController::serialNumber()
  459. {
  460. if ((device != nullptr) && (device->strbuf != nullptr)) return &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  461. if ((mydevice != nullptr) && (mydevice->strbuf != nullptr)) return &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  462. return nullptr;
  463. }