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.

521 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, 10, 0, 0, 0); // 10=SET_IDLE
  162. queue_Control_Transfer(dev, &setup, NULL, this);
  163. return true;
  164. }
  165. void KeyboardController::control(const Transfer_t *transfer)
  166. {
  167. }
  168. void KeyboardController::callback(const Transfer_t *transfer)
  169. {
  170. //println("KeyboardController Callback (static)");
  171. if (transfer->driver) {
  172. ((KeyboardController *)(transfer->driver))->new_data(transfer);
  173. }
  174. }
  175. void KeyboardController::disconnect()
  176. {
  177. // TODO: free resources
  178. }
  179. // Arduino defined this static weak symbol callback, and their
  180. // examples use it as the only way to detect new key presses,
  181. // so unfortunate as static weak callbacks are, it probably
  182. // needs to be supported for compatibility
  183. extern "C" {
  184. void __keyboardControllerEmptyCallback() { }
  185. }
  186. void keyPressed() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback")));
  187. void keyReleased() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback")));
  188. static bool contains(uint8_t b, const uint8_t *data)
  189. {
  190. if (data[2] == b || data[3] == b || data[4] == b) return true;
  191. if (data[5] == b || data[6] == b || data[7] == b) return true;
  192. return false;
  193. }
  194. void KeyboardController::new_data(const Transfer_t *transfer)
  195. {
  196. println("KeyboardController Callback (member)");
  197. print(" KB Data: ");
  198. print_hexbytes(transfer->buffer, 8);
  199. for (int i=2; i < 8; i++) {
  200. uint32_t key = prev_report[i];
  201. if (key >= 4 && !contains(key, report)) {
  202. key_release(prev_report[0], key);
  203. }
  204. }
  205. for (int i=2; i < 8; i++) {
  206. uint32_t key = report[i];
  207. if (key >= 4 && !contains(key, prev_report)) {
  208. key_press(report[0], key);
  209. }
  210. }
  211. memcpy(prev_report, report, 8);
  212. queue_Data_Transfer(datapipe, report, 8, this);
  213. }
  214. void KeyboardController::numLock(bool f) {
  215. if (leds_.numLock != f) {
  216. leds_.numLock = f;
  217. updateLEDS();
  218. }
  219. }
  220. void KeyboardController::capsLock(bool f) {
  221. if (leds_.capsLock != f) {
  222. leds_.capsLock = f;
  223. updateLEDS();
  224. }
  225. }
  226. void KeyboardController::scrollLock(bool f) {
  227. if (leds_.scrollLock != f) {
  228. leds_.scrollLock = f;
  229. updateLEDS();
  230. }
  231. }
  232. void KeyboardController::key_press(uint32_t mod, uint32_t key)
  233. {
  234. // TODO: queue events, perform callback from Task
  235. println(" press, key=", key);
  236. modifiers = mod;
  237. keyOEM = key;
  238. keyCode = convert_to_unicode(mod, key);
  239. println(" unicode = ", keyCode);
  240. if (keyPressedFunction) {
  241. keyPressedFunction(keyCode);
  242. } else {
  243. keyPressed();
  244. }
  245. }
  246. void KeyboardController::key_release(uint32_t mod, uint32_t key)
  247. {
  248. // TODO: queue events, perform callback from Task
  249. println(" release, key=", key);
  250. modifiers = mod;
  251. keyOEM = key;
  252. // Look for modifier keys
  253. if (key == M(KEY_NUM_LOCK)) {
  254. numLock(!leds_.numLock);
  255. // Lets toggle Numlock
  256. } else if (key == M(KEY_CAPS_LOCK)) {
  257. capsLock(!leds_.capsLock);
  258. } else if (key == M(KEY_SCROLL_LOCK)) {
  259. scrollLock(!leds_.scrollLock);
  260. } else {
  261. keyCode = convert_to_unicode(mod, key);
  262. if (keyReleasedFunction) {
  263. keyReleasedFunction(keyCode);
  264. } else {
  265. keyReleased();
  266. }
  267. }
  268. }
  269. uint16_t KeyboardController::convert_to_unicode(uint32_t mod, uint32_t key)
  270. {
  271. // WIP: special keys
  272. // TODO: dead key sequences
  273. if (key & SHIFT_MASK) {
  274. // Many of these keys will look like they are other keys with shift mask...
  275. // Check for any of our mapped extra keys
  276. for (uint8_t i = 0; i < (sizeof(keycode_numlock)/sizeof(keycode_numlock[0])); i++) {
  277. if (keycode_numlock[i].code == key) {
  278. // See if the user is using numlock or not...
  279. if (leds_.numLock) {
  280. return keycode_numlock[i].charNumlockOn;
  281. } else {
  282. key = keycode_numlock[i].codeNumlockOff;
  283. if (!(key & 0x80)) return key; // we have hard coded value
  284. key &= 0x7f; // mask off the extra and break out to process as other characters...
  285. break;
  286. }
  287. }
  288. }
  289. }
  290. // Check for any of our mapped extra keys - Done early as some of these keys are
  291. // above and some below the SHIFT_MASK value
  292. for (uint8_t i = 0; i < (sizeof(keycode_extras)/sizeof(keycode_extras[0])); i++) {
  293. if (keycode_extras[i].code == key) {
  294. return keycode_extras[i].ascii;
  295. }
  296. }
  297. // If we made it here without doing something then return 0;
  298. if (key & SHIFT_MASK) return 0;
  299. if ((mod & 0x02) || (mod & 0x20)) key |= SHIFT_MASK;
  300. if (leds_.capsLock) key ^= SHIFT_MASK; // Caps lock will switch the Shift;
  301. for (int i=0; i < 96; i++) {
  302. if (keycodes_ascii[i] == key) {
  303. if ((mod & 1) || (mod & 0x10)) return (i+32) & 0x1f; // Control key is down
  304. return i + 32;
  305. }
  306. }
  307. #ifdef ISO_8859_1_A0
  308. for (int i=0; i < 96; i++) {
  309. if (keycodes_iso_8859_1[i] == key) return i + 160;
  310. }
  311. #endif
  312. return 0;
  313. }
  314. void KeyboardController::LEDS(uint8_t leds) {
  315. println("Keyboard setLEDS ", leds, HEX);
  316. leds_.byte = leds;
  317. updateLEDS();
  318. }
  319. void KeyboardController::updateLEDS() {
  320. // Now lets tell keyboard new state.
  321. if (device != nullptr) {
  322. // Only do it this way if we are a standard USB device
  323. mk_setup(setup, 0x21, 9, 0x200, 0, sizeof(leds_.byte)); // hopefully this sets leds
  324. queue_Control_Transfer(device, &setup, &leds_.byte, this);
  325. } else {
  326. // Bluetooth, need to setup back channel to Bluetooth controller.
  327. }
  328. }
  329. //=============================================================================
  330. // Keyboard Extras - Combined from other object
  331. //=============================================================================
  332. #define TOPUSAGE_SYS_CONTROL 0x10080
  333. #define TOPUSAGE_CONSUMER_CONTROL 0x0c0001
  334. hidclaim_t KeyboardController::claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage)
  335. {
  336. // Lets try to claim a few specific Keyboard related collection/reports
  337. //Serial.printf("KBH Claim %x\n", topusage);
  338. if ((topusage != TOPUSAGE_SYS_CONTROL)
  339. && (topusage != TOPUSAGE_CONSUMER_CONTROL)
  340. ) return CLAIM_NO;
  341. // only claim from one physical device
  342. //Serial.println("KeyboardController claim collection");
  343. // Lets only claim if this is the same device as claimed Keyboard...
  344. if (dev != device) return CLAIM_NO;
  345. if (mydevice != NULL && dev != mydevice) return CLAIM_NO;
  346. mydevice = dev;
  347. collections_claimed_++;
  348. return CLAIM_REPORT;
  349. }
  350. void KeyboardController::disconnect_collection(Device_t *dev)
  351. {
  352. if (--collections_claimed_ == 0) {
  353. mydevice = NULL;
  354. }
  355. }
  356. void KeyboardController::hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax)
  357. {
  358. //Serial.printf("KPC:hid_input_begin TUSE: %x TYPE: %x Range:%x %x\n", topusage, type, lgmin, lgmax);
  359. topusage_ = topusage; // remember which report we are processing.
  360. hid_input_begin_ = true;
  361. hid_input_data_ = false;
  362. }
  363. void KeyboardController::hid_input_data(uint32_t usage, int32_t value)
  364. {
  365. // Hack ignore 0xff00 high words as these are user values...
  366. if ((usage & 0xffff0000) == 0xff000000) return;
  367. //Serial.printf("KeyboardController: topusage= %x usage=%X, value=%d\n", topusage_, usage, value);
  368. // See if the value is in our keys_down list
  369. usage &= 0xffff; // only keep the actual key
  370. if (usage == 0) return; // lets not process 0, if only 0 happens, we will handle it on the end to remove existing pressed items.
  371. // Remember if we have received any logical key up events. Some keyboard appear to send them
  372. // others do no...
  373. hid_input_data_ = true;
  374. uint8_t key_index;
  375. for (key_index = 0; key_index < count_keys_down_; key_index++) {
  376. if (keys_down[key_index] == usage) {
  377. if (value) return; // still down
  378. if (extrasKeyReleasedFunction) {
  379. extrasKeyReleasedFunction(topusage_, usage);
  380. }
  381. // Remove from list
  382. count_keys_down_--;
  383. for (;key_index < count_keys_down_; key_index++) {
  384. keys_down[key_index] = keys_down[key_index+1];
  385. }
  386. return;
  387. }
  388. }
  389. // Was not in list
  390. if (!value) return; // still 0
  391. if (extrasKeyPressedFunction) {
  392. extrasKeyPressedFunction(topusage_, usage);
  393. }
  394. if (count_keys_down_ < MAX_KEYS_DOWN) {
  395. keys_down[count_keys_down_++] = usage;
  396. }
  397. }
  398. void KeyboardController::hid_input_end()
  399. {
  400. //Serial.println("KPC:hid_input_end");
  401. if (hid_input_begin_) {
  402. // See if we received any data from parser if not, assume all keys released...
  403. if (!hid_input_data_ ) {
  404. if (extrasKeyReleasedFunction) {
  405. while (count_keys_down_) {
  406. count_keys_down_--;
  407. extrasKeyReleasedFunction(topusage_, keys_down[count_keys_down_]);
  408. }
  409. }
  410. count_keys_down_ = 0;
  411. }
  412. hid_input_begin_ = false;
  413. }
  414. }
  415. bool KeyboardController::claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class)
  416. {
  417. Serial.printf("Keyboard Controller::claim_bluetooth - Class %x\n", bluetooth_class);
  418. if ((((bluetooth_class & 0xff00) == 0x2500) || (((bluetooth_class & 0xff00) == 0x500))) && (bluetooth_class & 0x40)) {
  419. Serial.printf("KeyboardController::claim_bluetooth TRUE\n");
  420. //btdevice = driver;
  421. return true;
  422. }
  423. return false;
  424. }
  425. bool KeyboardController::process_bluetooth_HID_data(const uint8_t *data, uint16_t length)
  426. {
  427. // Example DATA from bluetooth keyboard:
  428. // 0 1 2 3 4 5 6 7 8 910 1 2 3 4 5 6 7
  429. // LEN D
  430. //BT rx2_data(18): 48 20 e 0 a 0 70 0 a1 1 2 0 0 0 0 0 0 0
  431. //BT rx2_data(18): 48 20 e 0 a 0 70 0 a1 1 2 0 4 0 0 0 0 0
  432. //BT rx2_data(18): 48 20 e 0 a 0 70 0 a1 1 2 0 0 0 0 0 0 0
  433. // So Len=9 passed in data starting at report ID=1...
  434. Serial.printf("KeyboardController::process_bluetooth_HID_data\n");
  435. if (data[0] != 1) return false;
  436. print(" KB Data: ");
  437. print_hexbytes(data, length);
  438. for (int i=2; i < length; i++) {
  439. uint32_t key = prev_report[i];
  440. if (key >= 4 && !contains(key, report)) {
  441. key_release(prev_report[0], key);
  442. }
  443. }
  444. for (int i=2; i < 8; i++) {
  445. uint32_t key = data[i];
  446. if (key >= 4 && !contains(key, prev_report)) {
  447. key_press(data[1], key);
  448. }
  449. }
  450. // Save away the data.. But shift down one byte... Don't need the report number
  451. memcpy(prev_report, &data[1], 8);
  452. return true;
  453. }
  454. void KeyboardController::release_bluetooth()
  455. {
  456. //btdevice = nullptr;
  457. }