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.

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