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.

1383 lines
49KB

  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. * information about the BlueTooth HCI comes from logic analyzer captures
  24. * plus... http://affon.narod.ru/BT/bluetooth_app_c10.pdf
  25. */
  26. #include <Arduino.h>
  27. #include "USBHost_t36.h" // Read this header first for key info
  28. #define print USBHost::print_
  29. #define println USBHost::println_//#define DEBUG_BT
  30. #define DEBUG_BT
  31. #define DEBUG_BT_VERBOSE
  32. #ifndef DEBUG_BT
  33. #undef DEBUG_BT_VERBOSE
  34. void inline DBGPrintf(...) {};
  35. #else
  36. #define DBGPrintf USBHDBGSerial.printf
  37. #endif
  38. #ifndef DEBUG_BT_VERBOSE
  39. void inline VDBGPrintf(...) {};
  40. #else
  41. #define VDBGPrintf USBHDBGSerial.printf
  42. #endif
  43. /************************************************************/
  44. // Define HCI Commands OGF HIgh byte OCF is low byte...
  45. // Actually shifted values...
  46. /************************************************************/
  47. #define HCI_INQUIRY 0x0401
  48. #define HCI_INQUIRY_CANCEL 0x0402
  49. #define HCI_CREATE_CONNECTION 0x0405
  50. #define HCI_OP_ACCEPT_CONN_REQ 0x0409
  51. #define HCI_LINK_KEY_NEG_REPLY 0x040C
  52. #define HCI_PIN_CODE_REPLY 0x040D
  53. #define HCI_AUTH_REQUESTED 0x0411
  54. #define HCI_OP_REMOTE_NAME_REQ 0x0419
  55. #define HCI_OP_REMOTE_NAME_REQ_CANCEL 0x041a
  56. #define HCI_OP_READ_REMOTE_FEATURES 0x041b
  57. #define HCI_OP_READ_REMOTE_VERSION_INFORMATION 0x041D
  58. #define HCI_Write_Default_Link_Policy_Settings 0x080f
  59. #define HCI_Set_Event_Mask 0x0c01
  60. #define HCI_RESET 0x0c03
  61. #define HCI_Set_Event_Filter_Clear 0x0c05
  62. #define HCI_Read_Local_Name 0x0c14
  63. #define HCI_Read_Stored_Link_Key 0x0c0d
  64. #define HCI_DELETE_STORED_LINK_KEY 0x0c12
  65. #define HCI_WRITE_LOCAL_NAME 0x0c13
  66. #define Write_Connection_Accept_Timeout 0x0c16
  67. #define HCI_WRITE_SCAN_ENABLE 0x0c1a
  68. #define HCI_Read_Page_Scan_Activity 0x0c1b
  69. #define HCI_READ_CLASS_OF_DEVICE 0x0c23
  70. #define HCI_WRITE_CLASS_OF_DEV 0x0C24
  71. #define HCI_Read_Voice_Setting 0x0c25
  72. #define HCI_Read_Number_Of_Supported_IAC 0x0c38
  73. #define HCI_Read_Current_IAC_LAP 0x0c39
  74. #define HCI_WRITE_INQUIRY_MODE 0x0c45
  75. #define HCI_Read_Page_Scan_Type 0x0c46
  76. #define HCI_WRITE_EIR 0x0c52
  77. #define HCI_WRITE_SSP_MODE 0x0c56
  78. #define HCI_Read_Inquiry_Response_Transmit_Power_Level 0x0c58
  79. #define HCI_WRITE_LE_HOST_SUPPORTED 0x0c6d
  80. #define HCI_Read_Local_Supported_Features 0x1003
  81. #define HCI_Read_Local_Extended_Features 0x1004
  82. #define HCI_Read_Buffer_Size 0x1005
  83. #define HCI_Read_BD_ADDR 0x1009
  84. #define HCI_Read_Local_Version_Information 0x1001
  85. #define HCI_Read_Local_Supported_Commands 0x1002
  86. #define HCI_LE_SET_EVENT_MASK 0x2001
  87. #define HCI_LE_Read_Buffer_Size 0x2002
  88. #define HCI_LE_Read_Local_supported_Features 0x2003
  89. #define HCI_LE_READ_ADV_TX_POWER 0x2007
  90. #define HCI_LE_SET_ADV_DATA 0x2008
  91. #define HCI_LE_SET_SCAN_RSP_DATA 0x2009
  92. #define HCI_LE_READ_WHITE_LIST_SIZE 0x200f
  93. #define HCI_LE_CLEAR_WHITE_LIST 0x2010
  94. #define HCI_LE_Supported_States 0x201c
  95. /* Bluetooth L2CAP PSM - see http://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm */
  96. #define HID_CTRL_PSM 0x11 // HID_Control PSM Value
  97. #define HID_INTR_PSM 0x13 // HID_Interrupt PSM Value
  98. // Used For Connection Response
  99. #define PENDING 0x01
  100. #define SUCCESSFUL 0x00
  101. /* L2CAP signaling commands */
  102. #define L2CAP_CMD_COMMAND_REJECT 0x01
  103. #define L2CAP_CMD_CONNECTION_REQUEST 0x02
  104. #define L2CAP_CMD_CONNECTION_RESPONSE 0x03
  105. #define L2CAP_CMD_CONFIG_REQUEST 0x04
  106. #define L2CAP_CMD_CONFIG_RESPONSE 0x05
  107. #define L2CAP_CMD_DISCONNECT_REQUEST 0x06
  108. #define L2CAP_CMD_DISCONNECT_RESPONSE 0x07
  109. #define L2CAP_CMD_INFORMATION_REQUEST 0x0A
  110. #define L2CAP_CMD_INFORMATION_RESPONSE 0x0B
  111. #define HID_THDR_DATA_INPUT 0xa1
  112. // HID stuff
  113. #define HID_BOOT_PROTOCOL 0x00
  114. #define HID_RPT_PROTOCOL 0x01
  115. /* HCI Events */
  116. enum {EV_INQUIRY_COMPLETE= 0x01,EV_INQUIRY_RESULT= 0x02,EV_CONNECT_COMPLETE= 0x03,EV_INCOMING_CONNECT= 0x04,EV_DISCONNECT_COMPLETE= 0x05
  117. ,EV_AUTHENTICATION_COMPLETE= 0x06,EV_REMOTE_NAME_COMPLETE= 0x07,EV_ENCRYPTION_CHANGE= 0x08,EV_CHANGE_CONNECTION_LINK= 0x09,EV_ROLE_CHANGED= 0x12
  118. ,EV_NUM_COMPLETE_PKT= 0x13,EV_PIN_CODE_REQUEST= 0x16,EV_LINK_KEY_REQUEST= 0x17,EV_LINK_KEY_NOTIFICATION= 0x18,EV_DATA_BUFFER_OVERFLOW= 0x1A
  119. ,EV_MAX_SLOTS_CHANGE= 0x1B,EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE= 0x0C,EV_QOS_SETUP_COMPLETE= 0x0D,EV_COMMAND_COMPLETE= 0x0E,EV_COMMAND_STATUS= 0x0F
  120. ,EV_LOOPBACK_COMMAND= 0x19,EV_PAGE_SCAN_REP_MODE= 0x20 };
  121. // different modes
  122. enum {PC_RESET = 1, PC_WRITE_CLASS_DEVICE, PC_READ_BDADDR, PC_READ_LOCAL_VERSION,
  123. PC_SEND_INQUIRE, PC_INQUIRE_CANCEL=100, PC_AUTHENTICATION_REQUESTED=110, PC_LINK_KEY_NEGATIVE=120, PC_PIN_CODE_REPLY=130,
  124. PC_WRITE_SCAN_PAGE=200};
  125. //////////////
  126. //////////////
  127. // Setup some states for the TX pipe where we need to chain messages
  128. enum {STATE_TX_SEND_CONNECT_INT=200, STATE_TX_SEND_CONECT_RSP_SUCCESS, STATE_TX_SEND_CONFIG_REQ, STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS, STATE_TX_SEND_CONFIG_ISR_REQ};
  129. // This is a list of all the drivers inherited from the BTHIDInput class.
  130. // Unlike the list of USBDriver (managed in enumeration.cpp), drivers stay
  131. // on this list even when they have claimed a top level collection.
  132. BTHIDInput * BluetoothController::available_bthid_drivers_list = NULL;
  133. void BluetoothController::driver_ready_for_bluetooth(BTHIDInput *driver)
  134. {
  135. driver->next = NULL;
  136. if (available_bthid_drivers_list == NULL) {
  137. available_bthid_drivers_list = driver;
  138. } else {
  139. BTHIDInput *last = available_bthid_drivers_list;
  140. while (last->next) last = last->next;
  141. last->next = driver;
  142. }
  143. }
  144. // When a new top level collection is found, this function asks drivers
  145. // if they wish to claim it. The driver taking ownership of the
  146. // collection is returned, or NULL if no driver wants it.
  147. BTHIDInput * BluetoothController::find_driver(uint32_t device_type, uint8_t *remoteName)
  148. {
  149. USBHDBGSerial.printf("BluetoothController::find_driver");
  150. BTHIDInput *driver = available_bthid_drivers_list;
  151. while (driver) {
  152. USBHDBGSerial.printf(" driver %x\n", (uint32_t)driver);
  153. if (driver->claim_bluetooth(this, device_type, remoteName)) {
  154. USBHDBGSerial.printf(" *** Claimed ***\n");
  155. return driver;
  156. }
  157. driver = driver->next;
  158. }
  159. return NULL;
  160. }
  161. //12 01 00 02 FF 01 01 40 5C 0A E8 21 12 01 01 02 03 01
  162. //VendorID = 0A5C, ProductID = 21E8, Version = 0112
  163. //Class/Subclass/Protocol = 255 / 1 / 1
  164. BluetoothController::product_vendor_mapping_t BluetoothController::pid_vid_mapping[] = {
  165. { 0xA5C, 0x21E8 }};
  166. /************************************************************/
  167. // Initialization and claiming of devices & interfaces
  168. /************************************************************/
  169. void BluetoothController::init()
  170. {
  171. contribute_Pipes(mypipes, sizeof(mypipes)/sizeof(Pipe_t));
  172. contribute_Transfers(mytransfers, sizeof(mytransfers)/sizeof(Transfer_t));
  173. contribute_String_Buffers(mystring_bufs, sizeof(mystring_bufs)/sizeof(strbuf_t));
  174. driver_ready_for_device(this);
  175. }
  176. bool BluetoothController::claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len)
  177. {
  178. // only claim at device level
  179. println("BluetoothController claim this=", (uint32_t)this, HEX);
  180. if (type != 0) return false; // claim at the device level
  181. // Lets try to support the main USB Bluetooth class...
  182. // http://www.usb.org/developers/defined_class/#BaseClassE0h
  183. if (dev->bDeviceClass != 0xe0) {
  184. bool special_case_device = false;
  185. for (uint8_t i=0; i < (sizeof(pid_vid_mapping)/sizeof(pid_vid_mapping[0])); i++) {
  186. if ((pid_vid_mapping[i].idVendor == dev->idVendor) && (pid_vid_mapping[i].idProduct == dev->idProduct)) {
  187. special_case_device = true;
  188. break;
  189. }
  190. }
  191. if (!special_case_device) return false;
  192. }
  193. if ((dev->bDeviceSubClass != 1) || (dev->bDeviceProtocol != 1)) return false; // Bluetooth Programming Interface
  194. DBGPrintf("BluetoothController claim this=%x vid:pid=%x:%x\n ", (uint32_t)this, dev->idVendor, dev->idProduct);
  195. if (len > 512) {
  196. DBGPrintf(" Descriptor length %d only showing first 512\n ");
  197. len = 512;
  198. }
  199. for (uint16_t i=0; i < len; i++) {
  200. DBGPrintf("%x ", descriptors[i]);
  201. if ((i & 0x3f) == 0x3f) DBGPrintf("\n ");
  202. }
  203. DBGPrintf("\n ");
  204. // Lets try to process the first Interface and get the end points...
  205. // Some common stuff for both XBoxs
  206. uint32_t count_end_points = descriptors[4];
  207. if (count_end_points < 2) return false;
  208. uint32_t rxep = 0;
  209. uint32_t rx2ep = 0;
  210. uint32_t txep = 0;
  211. uint8_t rx_interval = 0;
  212. uint8_t rx2_interval = 0;
  213. uint8_t tx_interval = 0;
  214. rx_size_ = 0;
  215. rx2_size_ = 0;
  216. tx_size_ = 0;
  217. uint32_t descriptor_index = 9;
  218. while (count_end_points-- /*&& ((rxep == 0) || txep == 0) */) {
  219. if (descriptors[descriptor_index] != 7) return false; // length 7
  220. if (descriptors[descriptor_index+1] != 5) return false; // ep desc
  221. if ((descriptors[descriptor_index+4] <= 64)
  222. && (descriptors[descriptor_index+5] == 0)) {
  223. // have a bulk EP size
  224. if (descriptors[descriptor_index+2] & 0x80 ) {
  225. if (descriptors[descriptor_index+3] == 3) { // Interrupt
  226. rxep = descriptors[descriptor_index+2];
  227. rx_size_ = descriptors[descriptor_index+4];
  228. rx_interval = descriptors[descriptor_index+6];
  229. } else if (descriptors[descriptor_index+3] == 2) { // bulk
  230. rx2ep = descriptors[descriptor_index+2];
  231. rx2_size_ = descriptors[descriptor_index+4];
  232. rx2_interval = descriptors[descriptor_index+6];
  233. }
  234. } else {
  235. txep = descriptors[descriptor_index+2];
  236. tx_size_ = descriptors[descriptor_index+4];
  237. tx_interval = descriptors[descriptor_index+6];
  238. }
  239. }
  240. descriptor_index += 7; // setup to look at next one...
  241. }
  242. if ((rxep == 0) || (txep == 0)) {
  243. USBHDBGSerial.printf("Bluetooth end points not found: %d %d\n", rxep, txep);
  244. return false; // did not find two end points.
  245. }
  246. DBGPrintf(" rxep=%d(%d) txep=%d(%d) rx2ep=%d(%d)\n", rxep&15, rx_size_, txep, tx_size_,
  247. rx2ep&15, rx2_size_);
  248. print("BluetoothController, rxep=", rxep & 15);
  249. print("(", rx_size_);
  250. print("), txep=", txep);
  251. print("(", tx_size_);
  252. println(")");
  253. rxpipe_ = new_Pipe(dev, 3, rxep & 15, 1, rx_size_, rx_interval);
  254. if (!rxpipe_) return false;
  255. txpipe_ = new_Pipe(dev, 3, txep, 0, tx_size_, tx_interval);
  256. if (!txpipe_) {
  257. //free_Pipe(rxpipe_);
  258. return false;
  259. }
  260. rx2pipe_ = new_Pipe(dev, 2, rx2ep & 15, 1, rx2_size_, rx2_interval);
  261. if (!rx2pipe_) {
  262. // Free other pipes...
  263. return false;
  264. }
  265. rxpipe_->callback_function = rx_callback;
  266. queue_Data_Transfer(rxpipe_, rxbuf_, rx_size_, this);
  267. rx2pipe_->callback_function = rx2_callback;
  268. queue_Data_Transfer(rx2pipe_, rx2buf_, rx2_size_, this);
  269. txpipe_->callback_function = tx_callback;
  270. // Send out the reset
  271. device = dev; // yes this is normally done on return from this but should not hurt if we do it here.
  272. sendResetHCI();
  273. pending_control_ = PC_RESET;
  274. pending_control_tx_ = 0; //
  275. return true;
  276. }
  277. void BluetoothController::disconnect()
  278. {
  279. USBHDBGSerial.printf("Bluetooth Disconnect");
  280. if (device_driver_) {
  281. device_driver_->release_bluetooth();
  282. device_driver_ = nullptr;
  283. }
  284. connection_complete_ = false;
  285. }
  286. void BluetoothController::timer_event(USBDriverTimer *whichTimer)
  287. {
  288. }
  289. void BluetoothController::control(const Transfer_t *transfer)
  290. {
  291. println(" control callback (bluetooth) ", pending_control_, HEX);
  292. #ifdef DEBUG_BT_VERBOSE
  293. DBGPrintf(" Control callback (bluetooth): %d : ", pending_control_);
  294. uint8_t *buffer = (uint8_t*)transfer->buffer;
  295. for (uint8_t i=0; i < transfer->length; i++) DBGPrintf("%x ", buffer[i]);
  296. DBGPrintf("\n");
  297. #endif
  298. }
  299. /************************************************************/
  300. // Interrupt-based Data Movement
  301. /************************************************************/
  302. void BluetoothController::rx_callback(const Transfer_t *transfer)
  303. {
  304. if (!transfer->driver) return;
  305. ((BluetoothController *)(transfer->driver))->rx_data(transfer);
  306. }
  307. void BluetoothController::rx2_callback(const Transfer_t *transfer)
  308. {
  309. if (!transfer->driver) return;
  310. ((BluetoothController *)(transfer->driver))->rx2_data(transfer);
  311. }
  312. void BluetoothController::tx_callback(const Transfer_t *transfer)
  313. {
  314. if (!transfer->driver) return;
  315. ((BluetoothController *)(transfer->driver))->tx_data(transfer);
  316. }
  317. void BluetoothController::rx_data(const Transfer_t *transfer)
  318. {
  319. uint32_t len = transfer->length - ((transfer->qtd.token >> 16) & 0x7FFF);
  320. print_hexbytes((uint8_t*)transfer->buffer, len);
  321. DBGPrintf("BT rx_data(%d): ", len);
  322. uint8_t *buffer = (uint8_t*)transfer->buffer;
  323. for (uint8_t i=0; i < len; i++) DBGPrintf("%x ", buffer[i]);
  324. DBGPrintf("\n");
  325. // Note the logical packets returned from the device may be larger
  326. // than can fit in one of our packets, so we will detect this and
  327. // the next read will be continue in or rx_buf_ in the next logical
  328. // location. We will only go into process the next logical state
  329. // when we have the full response read in...
  330. if (rx_packet_data_remaining == 0) { // Previous command was fully handled
  331. rx_packet_data_remaining = rxbuf_[1] + 2; // length of data plus the two bytes at start...
  332. }
  333. // Now see if the data
  334. rx_packet_data_remaining -= len; // remove the length of this packet from length
  335. if (rx_packet_data_remaining == 0) { // read started at beginning of packet so get the total length of packet
  336. switch(rxbuf_[0]) { // Switch on event type
  337. case EV_COMMAND_COMPLETE: //0x0e
  338. handle_hci_command_complete();// Check if command succeeded
  339. break;
  340. case EV_COMMAND_STATUS: //0x0f
  341. handle_hci_command_status();
  342. break;
  343. case EV_INQUIRY_COMPLETE: // 0x01
  344. handle_hci_inquiry_complete();
  345. break;
  346. case EV_INQUIRY_RESULT: // 0x02
  347. handle_hci_inquiry_result();
  348. break;
  349. case EV_CONNECT_COMPLETE: // 0x03
  350. handle_hci_connection_complete();
  351. break;
  352. case EV_INCOMING_CONNECT: // 0x04
  353. handle_hci_incoming_connect();
  354. break;
  355. case EV_DISCONNECT_COMPLETE: // 0x05
  356. handle_hci_disconnect_complete();
  357. break;
  358. case EV_AUTHENTICATION_COMPLETE:// 0x06
  359. handle_hci_authentication_complete();
  360. break;
  361. case EV_REMOTE_NAME_COMPLETE: // 0x07
  362. handle_hci_remote_name_complete();
  363. break;
  364. case EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE:
  365. handle_hci_remote_version_information_complete();
  366. break;
  367. case EV_PIN_CODE_REQUEST: // 0x16
  368. handle_hci_pin_code_request();
  369. break;
  370. case EV_LINK_KEY_REQUEST: // 0x17
  371. handle_hci_link_key_request();
  372. break;
  373. case EV_LINK_KEY_NOTIFICATION: // 0x18
  374. handle_hci_link_key_notification();
  375. default:
  376. break;
  377. }
  378. // Start read at start of buffer.
  379. queue_Data_Transfer(rxpipe_, rxbuf_, rx_size_, this);
  380. } else {
  381. // Continue the read - Todo - maybe verify len == rx_size_
  382. queue_Data_Transfer(rxpipe_, buffer + rx_size_, rx_size_, this);
  383. return; // Don't process the message yet as we still have data to receive.
  384. }
  385. }
  386. //===================================================================
  387. // Called when an HCI command completes.
  388. void BluetoothController::handle_hci_command_complete()
  389. {
  390. uint16_t hci_command = rxbuf_[3] + (rxbuf_[4] << 8);
  391. uint8_t buffer_index;
  392. if(!rxbuf_[5]) {
  393. VDBGPrintf(" Command Completed! \n");
  394. } else {
  395. VDBGPrintf(" Command(%x) Completed - Error: %d! \n", hci_command, rxbuf_[5]);
  396. // BUGBUG:: probably need to queue something?
  397. }
  398. switch (hci_command) {
  399. case HCI_OP_REMOTE_NAME_REQ:
  400. break;
  401. case HCI_RESET: //0x0c03
  402. if (!rxbuf_[5]) pending_control_ = PC_WRITE_CLASS_DEVICE;
  403. // If it fails, will retry. maybe should have repeat max...
  404. break;
  405. case HCI_Set_Event_Filter_Clear: //0x0c05
  406. break;
  407. case HCI_Read_Local_Name: //0x0c14
  408. // received name back...
  409. {
  410. //BUGBUG:: probably want to grab string object and copy to
  411. USBHDBGSerial.printf(" Local name: %s\n", &rxbuf_[6]);
  412. /*
  413. uint8_t len = rxbuf_[1]+2; // Length field +2 for total bytes read
  414. for (uint8_t i=6; i < len; i++) {
  415. if (rxbuf_[i] == 0) {
  416. break;
  417. }
  418. USBHDBGSerial.printf("%c", rxbuf_[i]);
  419. }
  420. USBHDBGSerial.printf("\n"); */
  421. }
  422. break;
  423. case Write_Connection_Accept_Timeout: //0x0c16
  424. break;
  425. case HCI_READ_CLASS_OF_DEVICE: // 0x0c23
  426. break;
  427. case HCI_Read_Voice_Setting: //0x0c25
  428. break;
  429. case HCI_Read_Number_Of_Supported_IAC: //0x0c38
  430. break;
  431. case HCI_Read_Current_IAC_LAP: //0x0c39
  432. break;
  433. case HCI_WRITE_INQUIRY_MODE: //0x0c45
  434. break;
  435. case HCI_Read_Inquiry_Response_Transmit_Power_Level: //0x0c58
  436. break;
  437. case HCI_Read_Local_Supported_Features: //0x1003
  438. // Remember the features supported by local...
  439. for (buffer_index = 0; buffer_index < 8; buffer_index++) {
  440. features[buffer_index] = rxbuf_[buffer_index+6];
  441. }
  442. break;
  443. case HCI_Read_Buffer_Size: // 0x1005
  444. break;
  445. case HCI_Read_BD_ADDR: //0x1009
  446. {
  447. DBGPrintf(" BD Addr");
  448. for(uint8_t i = 0; i < 6; i++) {
  449. my_bdaddr_[i] = rxbuf_[6 + i];
  450. DBGPrintf(":%x", my_bdaddr_[i]);
  451. }
  452. DBGPrintf("\n");
  453. }
  454. break;
  455. case HCI_Read_Local_Version_Information: //0x1001
  456. hciVersion = rxbuf_[6]; // Should do error checking above...
  457. DBGPrintf(" Local Version: %x\n", hciVersion);
  458. pending_control_ = (do_pair_device_)? PC_SEND_INQUIRE : PC_WRITE_SCAN_PAGE;
  459. break;
  460. case HCI_Read_Local_Supported_Commands: //0x1002
  461. break;
  462. case HCI_LE_Read_Buffer_Size: //0x2002
  463. break;
  464. case HCI_LE_Read_Local_supported_Features: //0x2003
  465. break;
  466. case HCI_LE_Supported_States: //0x201c
  467. break;
  468. case HCI_Read_Local_Extended_Features: //0x1004
  469. break;
  470. case HCI_Set_Event_Mask: //0x0c01
  471. break;
  472. case HCI_Read_Stored_Link_Key: //0x0c0d
  473. break;
  474. case HCI_Write_Default_Link_Policy_Settings: //0x080f
  475. break;
  476. case HCI_Read_Page_Scan_Activity: //0x0c1b
  477. break;
  478. case HCI_Read_Page_Scan_Type: //0x0c46
  479. break;
  480. case HCI_LE_SET_EVENT_MASK: //0x2001
  481. break;
  482. case HCI_LE_READ_ADV_TX_POWER: //0x2007
  483. break;
  484. case HCI_LE_READ_WHITE_LIST_SIZE: //0x200f
  485. break;
  486. case HCI_LE_CLEAR_WHITE_LIST: //0x2010
  487. break;
  488. case HCI_DELETE_STORED_LINK_KEY: //0x0c12
  489. break;
  490. case HCI_WRITE_LOCAL_NAME: //0x0c13
  491. break;
  492. case HCI_WRITE_SCAN_ENABLE: //0x0c1a
  493. DBGPrintf("Write_Scan_enable Completed\n");
  494. if (device_driver_ && connection_complete_) { // We have a driver call their
  495. device_driver_->connectionComplete();
  496. connection_complete_ = false; // only call once
  497. }
  498. break;
  499. case HCI_WRITE_SSP_MODE: //0x0c56
  500. break;
  501. case HCI_WRITE_EIR: //0x0c52
  502. break;
  503. case HCI_WRITE_LE_HOST_SUPPORTED: //0x0c6d
  504. break;
  505. case HCI_LE_SET_SCAN_RSP_DATA: //0x2009
  506. break;
  507. }
  508. // And queue up the next command
  509. queue_next_hci_command();
  510. }
  511. void BluetoothController::queue_next_hci_command()
  512. {
  513. // Ok We completed a command now see if we need to queue another command
  514. // Still probably need to reorganize...
  515. switch (pending_control_) {
  516. // Initial setup states.
  517. case PC_RESET:
  518. sendResetHCI();
  519. break;
  520. case PC_WRITE_CLASS_DEVICE:
  521. sendHDCWriteClassOfDev();
  522. pending_control_++;
  523. break;
  524. case PC_READ_BDADDR:
  525. sendHCIReadBDAddr();
  526. pending_control_++;
  527. break;
  528. case PC_READ_LOCAL_VERSION:
  529. sendHCIReadLocalVersionInfo();
  530. //pending_control_++;
  531. break;
  532. // These are used when we are pairing.
  533. case PC_SEND_INQUIRE:
  534. sendHCI_INQUIRY();
  535. pending_control_++;
  536. break;
  537. case PC_INQUIRE_CANCEL:
  538. // lets try to create a connection...
  539. sendHCICreateConnection();
  540. pending_control_++;
  541. break;
  542. case PC_AUTHENTICATION_REQUESTED:
  543. break;
  544. case PC_LINK_KEY_NEGATIVE:
  545. break;
  546. case PC_PIN_CODE_REPLY:
  547. break;
  548. // None Pair mode
  549. case PC_WRITE_SCAN_PAGE:
  550. sendHCIWriteScanEnable(2);
  551. pending_control_ = 0; //
  552. break;
  553. default:
  554. break;
  555. }
  556. }
  557. void BluetoothController::handle_hci_command_status()
  558. {
  559. // <event type><param count><status><num packets allowed to be sent><CMD><CMD>
  560. #ifdef DEBUG_BT
  561. uint16_t hci_command = rxbuf_[4] + (rxbuf_[5] << 8);
  562. if (rxbuf_[2]) {
  563. DBGPrintf(" Command %x Status %x - ", hci_command, rxbuf_[2]);
  564. switch (rxbuf_[2]) {
  565. case 0x01: DBGPrintf("Unknown HCI Command\n"); break;
  566. case 0x02: DBGPrintf("Unknown Connection Identifier\n"); break;
  567. case 0x03: DBGPrintf("Hardware Failure\n"); break;
  568. case 0x04: DBGPrintf("Page Timeout\n"); break;
  569. case 0x05: DBGPrintf("Authentication Failure\n"); break;
  570. case 0x06: DBGPrintf("PIN or Key Missing\n"); break;
  571. case 0x07: DBGPrintf("Memory Capacity Exceeded\n"); break;
  572. case 0x08: DBGPrintf("Connection Timeout\n"); break;
  573. case 0x09: DBGPrintf("Connection Limit Exceeded\n"); break;
  574. case 0x0A: DBGPrintf("Synchronous Connection Limit To A Device Exceeded\n"); break;
  575. case 0x0B: DBGPrintf("Connection Already Exists\n"); break;
  576. case 0x0C: DBGPrintf("Command Disallowed\n"); break;
  577. case 0x0D: DBGPrintf("Connection Rejected due to Limited Resources\n"); break;
  578. case 0x0E: DBGPrintf("Connection Rejected Due To Security Reasons\n"); break;
  579. case 0x0F: DBGPrintf("Connection Rejected due to Unacceptable BD_ADDR\n"); break;
  580. default: DBGPrintf("???\n"); break;
  581. }
  582. } else {
  583. VDBGPrintf(" Command %x Status %x\n", hci_command, rxbuf_[2]);
  584. }
  585. #endif
  586. }
  587. void BluetoothController::handle_hci_inquiry_result()
  588. {
  589. // 2 f 1 79 22 23 a c5 cc 1 2 0 40 25 0 3b 2
  590. // Wondered if multiple items if all of the BDADDR are first then next field...
  591. // looks like it is that way...
  592. // Section 7.7.2
  593. DBGPrintf(" Inquiry Result - Count: %d\n", rxbuf_[2]);
  594. for (uint8_t i=0; i < rxbuf_[2]; i++) {
  595. uint8_t index_bd = 3 + (i*6);
  596. uint8_t index_ps = 3 + (6*rxbuf_[2]) + i;
  597. uint8_t index_class = 3 + (9*rxbuf_[2]) + i;
  598. uint8_t index_clock_offset = 3 + (12*rxbuf_[2]) + i;
  599. uint32_t bluetooth_class = rxbuf_[index_class] + ((uint32_t)rxbuf_[index_class+1] << 8) + ((uint32_t)rxbuf_[index_class+2] << 16);
  600. DBGPrintf(" BD:%x:%x:%x:%x:%x:%x, PS:%d, class: %x\n",
  601. rxbuf_[index_bd],rxbuf_[index_bd+1],rxbuf_[index_bd+2],rxbuf_[index_bd+3],rxbuf_[index_bd+4],rxbuf_[index_bd+5],
  602. rxbuf_[index_ps], bluetooth_class);
  603. // See if we know the class
  604. if ((bluetooth_class & 0xff00) == 0x2500) {
  605. DBGPrintf(" Peripheral device\n");
  606. if (bluetooth_class & 0x80) DBGPrintf(" Mouse\n");
  607. if (bluetooth_class & 0x40) DBGPrintf(" Keyboard\n");
  608. switch(bluetooth_class & 0x3c) {
  609. case 4: DBGPrintf(" Joystick\n"); break;
  610. case 8: DBGPrintf(" Gamepad\n"); break;
  611. case 0xc: DBGPrintf(" Remote Control\n"); break;
  612. }
  613. // BUGBUG, lets hard code to go to new state...
  614. for (uint8_t i = 0; i < 6; i++) device_bdaddr_[i] = rxbuf_[index_bd+i];
  615. device_class_ = bluetooth_class;
  616. device_driver_ = find_driver(device_class_);
  617. device_ps_repetion_mode_ = rxbuf_[index_ps]; // mode
  618. device_clock_offset_[0] = rxbuf_[index_clock_offset];
  619. device_clock_offset_[1] = rxbuf_[index_clock_offset+1];
  620. // Now we need to bail from inquiry and setup to try to connect...
  621. sendHCIInquiryCancel();
  622. pending_control_ = PC_INQUIRE_CANCEL;
  623. break;
  624. }
  625. }
  626. }
  627. void BluetoothController::handle_hci_inquiry_complete() {
  628. VDBGPrintf(" Inquiry Complete - status: %d\n", rxbuf_[2]);
  629. }
  630. void BluetoothController::handle_hci_connection_complete() {
  631. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  632. // ST CH CH BD BD BD BD BD BD LT EN
  633. // 03 0b 04 00 00 40 25 00 58 4b 00 01 00
  634. device_connection_handle_ = rxbuf_[3]+ (uint16_t)(rxbuf_[4]<<8);
  635. DBGPrintf(" Connection Complete - ST:%x LH:%x\n", rxbuf_[2], device_connection_handle_);
  636. if (do_pair_device_) {
  637. sendHCIAuthenticationRequested();
  638. pending_control_ = PC_AUTHENTICATION_REQUESTED;
  639. } else if (device_driver_ && (device_driver_->special_process_required & BTHIDInput::SP_NEED_CONNECT)) {
  640. DBGPrintf(" Needs connect to device(PS4?)\n");
  641. // The PS4 requires a connection request to it.
  642. delay(1);
  643. sendl2cap_ConnectionRequest(device_connection_handle_, connection_rxid_, control_dcid_, HID_CTRL_PSM);
  644. delay(1);
  645. uint8_t packet[2];
  646. memset(packet, 0, sizeof(packet));
  647. packet[0] = 0x43;
  648. packet[1] = 0x02; // Report ID
  649. USBHDBGSerial.printf("SixAxis Command Issued!\r\n");
  650. sendL2CapCommand(packet, sizeof(packet), 0x40);
  651. }
  652. }
  653. void BluetoothController::handle_hci_incoming_connect() {
  654. // BD BD BD BD BD BD CL CL CL LT
  655. // 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x40 0x05 0x00 0x01
  656. uint32_t class_of_device = rxbuf_[8] + (uint16_t)(rxbuf_[9]<<8) + (uint32_t)(rxbuf_[10]<<16);
  657. DBGPrintf(" Event: Incoming Connect - %x:%x:%x:%x:%x:%x CL:%x LT:%x\n",
  658. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7], class_of_device, rxbuf_[11]);
  659. if (((class_of_device & 0xff00) == 0x2500) || ((class_of_device & 0xff00) == 0x500)) {
  660. DBGPrintf(" Peripheral device\n");
  661. if (class_of_device & 0x80) DBGPrintf(" Mouse\n");
  662. if (class_of_device & 0x40) DBGPrintf(" Keyboard\n");
  663. switch(class_of_device & 0x3c) {
  664. case 4: DBGPrintf(" Joystick\n"); break;
  665. case 8: DBGPrintf(" Gamepad\n"); break;
  666. case 0xc: DBGPrintf(" Remote Control\n"); break;
  667. }
  668. device_driver_ = find_driver(class_of_device);
  669. // We need to save away the BDADDR and class link type?
  670. for(uint8_t i=0; i<6; i++) device_bdaddr_[i] = rxbuf_[i+2];
  671. device_class_ = class_of_device;
  672. sendHCIRemoteNameRequest();
  673. }
  674. // sendHCIAuthenticationRequested();
  675. // pending_control_ = PC_AUTHENTICATION_REQUESTED;
  676. }
  677. void BluetoothController::handle_hci_pin_code_request() {
  678. // 0x16 0x06 0x79 0x22 0x23 0x0A 0xC5 0xCC
  679. DBGPrintf(" Event: Pin Code Request %x:%x:%x:%x:%x:%x\n",
  680. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7]);
  681. sendHCIPinCodeReply();
  682. pending_control_ = PC_PIN_CODE_REPLY;
  683. }
  684. void BluetoothController::handle_hci_link_key_request() {
  685. // 17 6 79 22 23 a c5 cc
  686. DBGPrintf(" Event: Link Key Request %x:%x:%x:%x:%x:%x\n",
  687. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7]);
  688. // Now here is where we need to decide to say we have key or tell them to
  689. // cancel key... right now hard code to cancel...
  690. sendHCILinkKeyNegativeReply();
  691. pending_control_ = PC_LINK_KEY_NEGATIVE;
  692. }
  693. void BluetoothController::handle_hci_link_key_notification() {
  694. // 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 20 1 2 3 4
  695. // 18 17 79 22 23 a c5 cc 5e 98 d4 5e bb 15 66 da 67 fe 4f 87 2b 61 46 b4 0
  696. DBGPrintf(" Event: Link Key Notificaton %x:%x:%x:%x:%x:%x Type:%x\n key:",
  697. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7], rxbuf_[24]);
  698. for (uint8_t i = 8; i < 24; i++) DBGPrintf("%02x ", rxbuf_[i]);
  699. DBGPrintf("\n");
  700. // Now here is where we need to decide to say we have key or tell them to
  701. // cancel key... right now hard code to cancel...
  702. }
  703. void BluetoothController::handle_hci_disconnect_complete()
  704. {
  705. //5 4 0 48 0 13
  706. DBGPrintf(" Event: HCI Disconnect complete(%d): handle: %x, reason:%x\n", rxbuf_[2],
  707. rxbuf_[3]+(rxbuf_[4]<<8), rxbuf_[5]);
  708. if (device_driver_) {
  709. device_driver_->release_bluetooth();
  710. device_driver_ = nullptr;
  711. // Restore to normal...
  712. control_dcid_ = 0x70;
  713. interrupt_dcid_ = 0x71;
  714. }
  715. // Probably should clear out connection data.
  716. device_connection_handle_ = 0;
  717. device_class_ = 0;
  718. memset(device_bdaddr_, 0, sizeof(device_bdaddr_));
  719. //...
  720. }
  721. void BluetoothController::handle_hci_authentication_complete()
  722. {
  723. // 6 3 13 48 0
  724. DBGPrintf(" Event: HCI Authentication complete(%d): handle: %x\n", rxbuf_[2],
  725. rxbuf_[3]+(rxbuf_[4]<<8));
  726. // Start up lcap connection...
  727. connection_rxid_ = 0;
  728. sendl2cap_ConnectionRequest(device_connection_handle_, connection_rxid_, control_dcid_, HID_CTRL_PSM);
  729. }
  730. void BluetoothController::handle_hci_remote_name_complete() {
  731. // STAT bd bd bd bd bd bd
  732. // 0x07 0xFF 0x00 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x42 0x6C 0x75 0x65 0x74 0x6F 0x6F ...
  733. DBGPrintf(" Event: handle_hci_remote_name_complete(%d)\n", rxbuf_[2]);
  734. if (rxbuf_[2] == 0) {
  735. DBGPrintf(" Remote Name: ");
  736. for (uint8_t *psz = &rxbuf_[9]; *psz; psz++) DBGPrintf("%c", *psz);
  737. DBGPrintf("\n");
  738. }
  739. // Lets try to allocate a string buffer to store the name out...
  740. if (device_driver_) {
  741. if (!device_driver_->remoteNameComplete(&rxbuf_[9])) {
  742. device_driver_->release_bluetooth();
  743. device_driver_ = nullptr;
  744. }
  745. }
  746. if (!device_driver_) {
  747. device_driver_ = find_driver(device_class_, &rxbuf_[9]);
  748. // not sure I should call remote name again, but they already process...
  749. }
  750. if (device_driver_) {
  751. if (device_driver_->special_process_required & BTHIDInput::SP_PS3_IDS) {
  752. // Real hack see if PS3...
  753. control_dcid_ = 0x40;
  754. interrupt_dcid_ = 0x41;
  755. }
  756. }
  757. // Lets now try to accept the connection.
  758. sendHCIAcceptConnectionRequest();
  759. }
  760. void BluetoothController::handle_hci_remote_version_information_complete() {
  761. // STAT bd bd bd bd bd bd
  762. //c 8 0 48 0 5 45 0 0 0
  763. remote_ver_ = rxbuf_[6];
  764. remote_man_ = rxbuf_[7]+((uint16_t)rxbuf_[8]<< 8);
  765. remote_subv_ = rxbuf_[9];
  766. DBGPrintf(" Event: handle_hci_remote_version_information_complete(%d): ", rxbuf_[2]);
  767. DBGPrintf(" Handle: %x, Ver:%x, Man: %x, SV: %x\n",
  768. rxbuf_[3]+((uint16_t)rxbuf_[4]<< 8), remote_ver_, remote_man_, remote_subv_);
  769. // Lets now try to accept the connection.
  770. sendHCIAcceptConnectionRequest();
  771. }
  772. void BluetoothController::rx2_data(const Transfer_t *transfer)
  773. {
  774. uint32_t len = transfer->length - ((transfer->qtd.token >> 16) & 0x7FFF);
  775. DBGPrintf("\n=====================\nBT rx2_data(%d): ", len);
  776. uint8_t *buffer = (uint8_t*)transfer->buffer;
  777. for (uint8_t i=0; i < len; i++) DBGPrintf("%x ", buffer[i]);
  778. DBGPrintf("\n");
  779. // call backs. See if this is an L2CAP reply. example
  780. // HCI | l2cap
  781. //48 20 10 0 | c 0 1 0 | 3 0 8 0 44 0 70 0 0 0 0 0
  782. // BUGBUG need to do more verification, like the handle
  783. uint16_t hci_length = buffer[2] + ((uint16_t)buffer[3]<<8);
  784. uint16_t l2cap_length = buffer[4] + ((uint16_t)buffer[5]<<8);
  785. // uint16_t rsp_packet_length = buffer[10] + ((uint16_t)buffer[11]<<8);
  786. if ((hci_length == (l2cap_length + 4)) /*&& (hci_length == (rsp_packet_length+8))*/) {
  787. // All the lengths appear to be correct... need to do more...
  788. switch (buffer[8]) {
  789. case L2CAP_CMD_CONNECTION_REQUEST:
  790. process_l2cap_connection_request(&buffer[8]);
  791. break;
  792. case L2CAP_CMD_CONNECTION_RESPONSE:
  793. process_l2cap_connection_response(&buffer[8]);
  794. break;
  795. case L2CAP_CMD_CONFIG_REQUEST:
  796. process_l2cap_config_request(&buffer[8]);
  797. break;
  798. case L2CAP_CMD_CONFIG_RESPONSE:
  799. process_l2cap_config_response(&buffer[8]);
  800. break;
  801. case HID_THDR_DATA_INPUT:
  802. handleHIDTHDRData(buffer); // Pass the whole buffer...
  803. break;
  804. case L2CAP_CMD_COMMAND_REJECT:
  805. process_l2cap_command_reject(&buffer[8]);
  806. break;
  807. case L2CAP_CMD_DISCONNECT_REQUEST:
  808. process_l2cap_disconnect_request(&buffer[8]);
  809. break;
  810. }
  811. }
  812. // Queue up for next read...
  813. queue_Data_Transfer(rx2pipe_, rx2buf_, rx2_size_, this);
  814. }
  815. void BluetoothController::sendHCICommand(uint16_t hciCommand, uint16_t cParams, const uint8_t* data)
  816. {
  817. txbuf_[0] = hciCommand & 0xff;
  818. txbuf_[1] = (hciCommand >> 8) & 0xff;
  819. txbuf_[2] = cParams;
  820. if (cParams) {
  821. memcpy(&txbuf_[3], data, cParams); // copy in the commands parameters.
  822. }
  823. uint8_t nbytes = cParams+3;
  824. for (uint8_t i=0; i< nbytes; i++) DBGPrintf("%02x ", txbuf_[i]);
  825. DBGPrintf(")\n");
  826. mk_setup(setup, 0x20, 0x0, 0, 0, nbytes);
  827. queue_Control_Transfer(device, &setup, txbuf_, this);
  828. }
  829. //---------------------------------------------
  830. void BluetoothController::sendHCI_INQUIRY() {
  831. // Start unlimited inqury, set timeout to max and
  832. DBGPrintf("HCI_INQUIRY called (");
  833. static const uint8_t hci_inquiry_data[ ] = {
  834. 0x33, 0x8B, 0x9E, // Bluetooth assigned number LAP 0x9E8B33 General/unlimited inquiry Access mode
  835. 0x30, 0xa}; // Max inquiry time little over minute and up to 10 responses
  836. sendHCICommand(HCI_INQUIRY, sizeof(hci_inquiry_data), hci_inquiry_data);
  837. }
  838. //---------------------------------------------
  839. void BluetoothController::sendHCIInquiryCancel() {
  840. DBGPrintf("HCI_INQUIRY_CANCEL called (");
  841. sendHCICommand(HCI_INQUIRY_CANCEL, 0, nullptr);
  842. }
  843. //---------------------------------------------
  844. void BluetoothController::sendHCICreateConnection() {
  845. DBGPrintf("HCI_CREATE_CONNECTION called (");
  846. uint8_t connection_data[13];
  847. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  848. // BD BD BD BD BD BD PT PT PRS 0 CS CS ARS
  849. //0x79 0x22 0x23 0x0A 0xC5 0xCC 0x18 0xCC 0x01 0x00 0x00 0x00 0x00
  850. //0x05 0x04 0x0D 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x18 0xCC 0x01 0x00 0x00 0x00 0x00
  851. // 05 04 0d 40 25 00 c4 01 00 18 cc 01 00 00 00 00
  852. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  853. connection_data[6] = 0x18; //DM1/DH1
  854. connection_data[7] = 0xcc; //
  855. connection_data[8] = device_ps_repetion_mode_; // from device
  856. connection_data[9] = 0; //
  857. connection_data[10] = 0; // clock offset
  858. connection_data[11] = 0; // clock offset
  859. connection_data[12] = 0; // allow role swith no
  860. sendHCICommand(HCI_CREATE_CONNECTION, sizeof(connection_data), connection_data);
  861. }
  862. //---------------------------------------------
  863. void BluetoothController::sendHCIAcceptConnectionRequest() {
  864. DBGPrintf("HCI_OP_ACCEPT_CONN_REQ called (");
  865. uint8_t connection_data[7];
  866. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  867. // BD BD BD BD BD BD role
  868. //0x79 0x22 0x23 0x0A 0xC5 0xCC 0x00
  869. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  870. connection_data[6] = 0; // Role as master
  871. sendHCICommand(HCI_OP_ACCEPT_CONN_REQ, sizeof(connection_data), connection_data);
  872. }
  873. //---------------------------------------------
  874. void BluetoothController::sendHCIAuthenticationRequested() {
  875. DBGPrintf("HCI_AUTH_REQUESTED called (");
  876. uint8_t connection_data[2];
  877. connection_data[0] = device_connection_handle_ & 0xff;
  878. connection_data[1] = (device_connection_handle_>>8) & 0xff;
  879. sendHCICommand(HCI_AUTH_REQUESTED, sizeof(connection_data), connection_data);
  880. }
  881. //---------------------------------------------
  882. void BluetoothController::sendHCILinkKeyNegativeReply() {
  883. DBGPrintf("HCI_LINK_KEY_NEG_REPLY called (");
  884. uint8_t connection_data[6];
  885. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  886. sendHCICommand(HCI_LINK_KEY_NEG_REPLY, sizeof(connection_data), connection_data);
  887. }
  888. //---------------------------------------------
  889. // BUGBUG:: hard code string for this pass.
  890. void BluetoothController::sendHCIPinCodeReply() {
  891. // 0x0D 0x04 0x17 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x04 0x30 0x30 0x30 0x30 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
  892. DBGPrintf("HCI_PIN_CODE_REPLY called (");
  893. uint8_t connection_data[23];
  894. uint8_t i;
  895. for (i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  896. for (i=0; pair_pincode_[i] !=0; i++) connection_data[7+i] = pair_pincode_[i];
  897. connection_data[6] = i; // remember the length
  898. for (uint8_t i=7+connection_data[6]; i<23; i++) connection_data[i] = 0;
  899. sendHCICommand(HCI_PIN_CODE_REPLY, sizeof(connection_data), connection_data);
  900. }
  901. //---------------------------------------------
  902. void BluetoothController::sendResetHCI() {
  903. DBGPrintf("HCI_RESET called (");
  904. sendHCICommand(HCI_RESET, 0, nullptr);
  905. }
  906. void BluetoothController::sendHDCWriteClassOfDev() {
  907. // 0x24 0x0C 0x03 0x04 0x08 0x00
  908. const static uint8_t device_class_data[] = {BT_CLASS_DEVICE & 0xff, (BT_CLASS_DEVICE >> 8) & 0xff, (BT_CLASS_DEVICE >> 16) & 0xff};
  909. DBGPrintf("HCI_WRITE_CLASS_OF_DEV called (");
  910. sendHCICommand(HCI_WRITE_CLASS_OF_DEV, sizeof(device_class_data), device_class_data);
  911. }
  912. void BluetoothController::sendHCIReadBDAddr() {
  913. DBGPrintf("HCI_Read_BD_ADDR called (");
  914. sendHCICommand(HCI_Read_BD_ADDR, 0, nullptr);
  915. }
  916. void BluetoothController::sendHCIReadLocalVersionInfo() {
  917. DBGPrintf("HCI_Read_Local_Version_Information called (");
  918. sendHCICommand(HCI_Read_Local_Version_Information, 0, nullptr);
  919. }
  920. void BluetoothController::sendHCIWriteScanEnable(uint8_t scan_op) {// 0x0c1a
  921. // 0x1A 0x0C 0x01 0x02
  922. DBGPrintf("HCI_WRITE_SCAN_ENABLE called(");
  923. sendHCICommand(HCI_WRITE_SCAN_ENABLE, 1, &scan_op);
  924. }
  925. void BluetoothController::sendHCIRemoteNameRequest() { // 0x0419
  926. // BD BD BD BD BD BD PS 0 CLK CLK
  927. //0x19 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x01 0x00 0x00 0x00
  928. DBGPrintf("HCI_OP_REMOTE_NAME_REQ called (");
  929. uint8_t connection_data[10];
  930. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  931. connection_data[6] = 1; // page scan repeat mode...
  932. connection_data[7] = 0; // 0
  933. connection_data[8] = 0; // Clk offset
  934. connection_data[9] = 0;
  935. sendHCICommand(HCI_OP_REMOTE_NAME_REQ, sizeof(connection_data), connection_data);
  936. }
  937. void BluetoothController::sendHCIRemoteVersionInfoRequest() { // 0x041D
  938. // BD BD BD BD BD BD PS 0 CLK CLK
  939. //0x19 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x01 0x00 0x00 0x00
  940. DBGPrintf("HCI_OP_READ_REMOTE_VERSION_INFORMATION called (");
  941. uint8_t connection_data[2];
  942. connection_data[0] = device_connection_handle_ & 0xff;
  943. connection_data[1] = (device_connection_handle_>>8) & 0xff;
  944. sendHCICommand(HCI_OP_READ_REMOTE_VERSION_INFORMATION, sizeof(connection_data), connection_data);
  945. }
  946. // l2cap support functions.
  947. void BluetoothController::sendl2cap_ConnectionResponse(uint16_t handle, uint8_t rxid, uint16_t dcid, uint16_t scid, uint8_t result) {
  948. uint8_t l2capbuf[12];
  949. l2capbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
  950. l2capbuf[1] = rxid; // Identifier
  951. l2capbuf[2] = 0x08; // Length
  952. l2capbuf[3] = 0x00;
  953. l2capbuf[4] = dcid & 0xff; // Destination CID
  954. l2capbuf[5] = dcid >> 8;
  955. l2capbuf[6] = scid & 0xff; // Source CID
  956. l2capbuf[7] = scid >> 8;
  957. l2capbuf[8] = result; // Result: Pending or Success
  958. l2capbuf[9] = 0x00;
  959. l2capbuf[10] = 0x00; // No further information
  960. l2capbuf[11] = 0x00;
  961. DBGPrintf("L2CAP_CMD_CONNECTION_RESPONSE called(");
  962. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  963. }
  964. void BluetoothController::sendl2cap_ConnectionRequest(uint16_t handle, uint8_t rxid, uint16_t scid, uint16_t psm) {
  965. uint8_t l2capbuf[8];
  966. l2capbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
  967. l2capbuf[1] = rxid; // Identifier
  968. l2capbuf[2] = 0x04; // Length
  969. l2capbuf[3] = 0x00;
  970. l2capbuf[4] = (uint8_t)(psm & 0xff); // PSM
  971. l2capbuf[5] = (uint8_t)(psm >> 8);
  972. l2capbuf[6] = scid & 0xff; // Source CID
  973. l2capbuf[7] = (scid >> 8) & 0xff;
  974. DBGPrintf("ConnectionRequest called(");
  975. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  976. }
  977. void BluetoothController::sendl2cap_ConfigRequest(uint16_t handle, uint8_t rxid, uint16_t dcid) {
  978. uint8_t l2capbuf[12];
  979. l2capbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
  980. l2capbuf[1] = rxid; // Identifier
  981. l2capbuf[2] = 0x08; // Length
  982. l2capbuf[3] = 0x00;
  983. l2capbuf[4] = dcid & 0xff; // Destination CID
  984. l2capbuf[5] = (dcid >> 8) & 0xff;
  985. l2capbuf[6] = 0x00; // Flags
  986. l2capbuf[7] = 0x00;
  987. l2capbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
  988. l2capbuf[9] = 0x02; // Config Opt: length
  989. l2capbuf[10] = 0xFF; // MTU
  990. l2capbuf[11] = 0xFF;
  991. DBGPrintf("L2CAP_ConfigRequest called(");
  992. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  993. }
  994. void BluetoothController::sendl2cap_ConfigResponse(uint16_t handle, uint8_t rxid, uint16_t scid) {
  995. uint8_t l2capbuf[14];
  996. l2capbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
  997. l2capbuf[1] = rxid; // Identifier
  998. l2capbuf[2] = 0x0A; // Length
  999. l2capbuf[3] = 0x00;
  1000. l2capbuf[4] = scid & 0xff; // Source CID
  1001. l2capbuf[5] = (scid >> 8) & 0xff;
  1002. l2capbuf[6] = 0x00; // Flag
  1003. l2capbuf[7] = 0x00;
  1004. l2capbuf[8] = 0x00; // Result
  1005. l2capbuf[9] = 0x00;
  1006. l2capbuf[10] = 0x01; // Config
  1007. l2capbuf[11] = 0x02;
  1008. l2capbuf[12] = 0xA0;
  1009. l2capbuf[13] = 0x02;
  1010. DBGPrintf("L2CAP_ConfigResponse called(");
  1011. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  1012. }
  1013. //*******************************************************************
  1014. //*******************************************************************
  1015. void BluetoothController::tx_data(const Transfer_t *transfer)
  1016. {
  1017. println(" tx_data(bluetooth) ", pending_control_, HEX);
  1018. #ifdef DEBUG_BT_VERBOSE
  1019. DBGPrintf("tx_data callback (bluetooth): %d : ", pending_control_tx_);
  1020. uint8_t *buffer = (uint8_t*)transfer->buffer;
  1021. for (uint8_t i=0; i < transfer->length; i++) DBGPrintf("%x ", buffer[i]);
  1022. DBGPrintf("\n");
  1023. #endif
  1024. switch (pending_control_tx_) {
  1025. case STATE_TX_SEND_CONNECT_INT:
  1026. delay(1);
  1027. connection_rxid_++;
  1028. sendl2cap_ConnectionRequest(device_connection_handle_, connection_rxid_, interrupt_dcid_, HID_INTR_PSM);
  1029. pending_control_tx_ = 0;
  1030. break;
  1031. case STATE_TX_SEND_CONECT_RSP_SUCCESS:
  1032. delay(1);
  1033. // Tell the device we are ready
  1034. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_++, control_dcid_, control_scid_, SUCCESSFUL);
  1035. pending_control_tx_ = STATE_TX_SEND_CONFIG_REQ;
  1036. break;
  1037. case STATE_TX_SEND_CONFIG_REQ:
  1038. delay(1);
  1039. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, control_scid_);
  1040. pending_control_tx_ = 0;
  1041. break;
  1042. case STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS:
  1043. delay(1);
  1044. // Tell the device we are ready
  1045. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_++, interrupt_dcid_, interrupt_scid_, SUCCESSFUL);
  1046. pending_control_tx_ = STATE_TX_SEND_CONFIG_ISR_REQ;
  1047. break;
  1048. case STATE_TX_SEND_CONFIG_ISR_REQ:
  1049. delay(1);
  1050. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, interrupt_scid_);
  1051. pending_control_tx_ = 0;
  1052. break;
  1053. }
  1054. }
  1055. //*******************************************************************
  1056. //
  1057. // HCI ACL Packets
  1058. // HCI Handle Low, HCI_Handle_High (PB, BC), Total length low, TLH - HCI ACL Data packet
  1059. // length Low, length high, channel id low, channel id high - L2CAP header
  1060. // code, identifier, length, ... - Control-frame
  1061. /************************************************************/
  1062. /* L2CAP Commands */
  1063. // Public wrrapper function
  1064. void BluetoothController::sendL2CapCommand(uint8_t* data, uint8_t nbytes, int channel) {
  1065. uint16_t channel_out;
  1066. switch (channel) {
  1067. case CONTROL_SCID:
  1068. channel_out = control_scid_;
  1069. break;
  1070. default:
  1071. channel_out = (uint16_t)channel;
  1072. }
  1073. DBGPrintf("sendL2CapCommand: %x %d %x\n", (uint32_t)data, nbytes, channel, channel_out);
  1074. sendL2CapCommand (device_connection_handle_, data, nbytes, channel_out & 0xff, (channel_out >> 8) & 0xff);
  1075. }
  1076. void BluetoothController::sendL2CapCommand(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh)
  1077. {
  1078. txbuf_[0] = handle & 0xff; // HCI handle with PB,BC flag
  1079. txbuf_[1] = (((handle >> 8) & 0x0f) | 0x20);
  1080. txbuf_[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
  1081. txbuf_[3] = (uint8_t)((4 + nbytes) >> 8);
  1082. txbuf_[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
  1083. txbuf_[5] = (uint8_t)(nbytes >> 8);
  1084. txbuf_[6] = channelLow;
  1085. txbuf_[7] = channelHigh;
  1086. if (nbytes) {
  1087. memcpy(&txbuf_[8], data, nbytes); // copy in the commands parameters.
  1088. }
  1089. nbytes = nbytes+8;
  1090. for (uint8_t i=0; i< nbytes; i++) DBGPrintf("%02x ", txbuf_[i]);
  1091. DBGPrintf(")\n");
  1092. if (!queue_Data_Transfer(txpipe_, txbuf_, nbytes, this)) {
  1093. println("sendL2CapCommand failed");
  1094. }
  1095. }
  1096. void BluetoothController::process_l2cap_connection_request(uint8_t *data) {
  1097. // ID LEN LEN PSM PSM SCID SCID
  1098. // 0x02 0x02 0x04 0x00 0x11 0x00 0x43 0x00
  1099. uint16_t psm = data[4]+((uint16_t)data[5] << 8);
  1100. uint16_t scid = data[6]+((uint16_t)data[7] << 8);
  1101. connection_rxid_ = data[1];
  1102. DBGPrintf(" L2CAP Connection Request: ID: %d, PSM: %x, SCID: %x\n",connection_rxid_, psm, scid);
  1103. // Assuming not pair mode Send response like:
  1104. // RXID Len LEN DCID DCID SCID SCID RES 0 0 0
  1105. // 0x03 0x02 0x08 0x00 0x70 0x00 0x43 0x00 0x01 0x00 0x00 0x00
  1106. if (psm == HID_CTRL_PSM) {
  1107. control_scid_ = scid;
  1108. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_, control_dcid_, control_scid_, PENDING);
  1109. pending_control_tx_ = STATE_TX_SEND_CONECT_RSP_SUCCESS;
  1110. } else if (psm == HID_INTR_PSM) {
  1111. interrupt_scid_ = scid;
  1112. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_, interrupt_dcid_, interrupt_scid_, PENDING);
  1113. pending_control_tx_ = STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS;
  1114. }
  1115. }
  1116. // Process the l2cap_connection_response...
  1117. void BluetoothController::process_l2cap_connection_response(uint8_t *data) {
  1118. uint16_t scid = data[4]+((uint16_t)data[5] << 8);
  1119. uint16_t dcid = data[6]+((uint16_t)data[7] << 8);
  1120. DBGPrintf(" L2CAP Connection Response: ID: %d, Dest:%x, Source:%x, Result:%x, Status: %x\n",
  1121. data[1], scid, dcid,
  1122. data[8]+((uint16_t)data[9] << 8), data[10]+((uint16_t)data[11] << 8));
  1123. //48 20 10 0 | c 0 1 0 | 3 0 8 0 44 0 70 0 0 0 0 0
  1124. if (dcid == interrupt_dcid_) {
  1125. interrupt_scid_ = scid;
  1126. DBGPrintf(" Interrupt Response\n");
  1127. connection_rxid_++;
  1128. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, scid);
  1129. } else if (dcid == control_dcid_) {
  1130. control_scid_ = scid;
  1131. DBGPrintf(" Control Response\n");
  1132. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, scid);
  1133. }
  1134. }
  1135. void BluetoothController::process_l2cap_config_request(uint8_t *data) {
  1136. //48 20 10 0 c 0 1 0 *4 2 8 0 70 0 0 0 1 2 30 0
  1137. uint16_t dcid = data[4]+((uint16_t)data[5] << 8);
  1138. DBGPrintf(" L2CAP config Request: ID: %d, Dest:%x, Flags:%x, Options: %x %x %x %x\n",
  1139. data[1], dcid, data[6]+((uint16_t)data[7] << 8),
  1140. data[8], data[9], data[10], data[11]);
  1141. // Now see which dest was specified
  1142. if (dcid == control_dcid_) {
  1143. DBGPrintf(" Control Configuration request\n");
  1144. sendl2cap_ConfigResponse(device_connection_handle_, data[1], control_scid_);
  1145. } else if (dcid == interrupt_dcid_) {
  1146. DBGPrintf(" Interrupt Configuration request\n");
  1147. sendl2cap_ConfigResponse(device_connection_handle_, data[1], interrupt_scid_);
  1148. }
  1149. }
  1150. void BluetoothController::process_l2cap_config_response(uint8_t *data) {
  1151. // 48 20 12 0 e 0 1 0 5 0 a 0 70 0 0 0 0 0 1 2 30 0
  1152. uint16_t scid = data[4]+((uint16_t)data[5] << 8);
  1153. DBGPrintf(" L2CAP config Response: ID: %d, Source:%x, Flags:%x, Result:%x, Config: %x\n",
  1154. data[1], scid, data[6]+((uint16_t)data[7] << 8),
  1155. data[8]+((uint16_t)data[9] << 8), data[10]+((uint16_t)data[11] << 8));
  1156. if (scid == control_dcid_) {
  1157. // Set HID Boot mode
  1158. // Don't do if PS3...
  1159. if (!(device_driver_->special_process_required & BTHIDInput::SP_PS3_IDS)) {
  1160. setHIDProtocol(HID_BOOT_PROTOCOL); //
  1161. }
  1162. //setHIDProtocol(HID_RPT_PROTOCOL); //HID_RPT_PROTOCOL
  1163. if (do_pair_device_) {
  1164. pending_control_tx_ = STATE_TX_SEND_CONNECT_INT;
  1165. } else if (device_driver_ && (device_driver_->special_process_required & BTHIDInput::SP_NEED_CONNECT)) {
  1166. DBGPrintf(" Needs connect to device INT(PS4?)\n");
  1167. // The PS4 requires a connection request to it.
  1168. pending_control_tx_ = STATE_TX_SEND_CONNECT_INT;
  1169. } else {
  1170. pending_control_ = 0;
  1171. }
  1172. } else if (scid == interrupt_dcid_) {
  1173. // Enable SCan to page mode
  1174. connection_complete_ = true;
  1175. sendHCIWriteScanEnable(2);
  1176. }
  1177. }
  1178. void BluetoothController::process_l2cap_command_reject(uint8_t *data) {
  1179. // 48 20 b 0 7 0 70 0 *1 0 0 0 2 0 4
  1180. DBGPrintf(" L2CAP command reject: ID: %d, length:%x, Reason:%x, Data: %x %x \n",
  1181. data[1], data[2] + ((uint16_t)data[3] << 8), data[4], data[5], data[6]);
  1182. }
  1183. void BluetoothController::process_l2cap_disconnect_request(uint8_t *data) {
  1184. uint16_t dcid = data[4]+((uint16_t)data[5] << 8);
  1185. uint16_t scid = data[6]+((uint16_t)data[7] << 8);
  1186. DBGPrintf(" L2CAP disconnect request: ID: %d, Length:%x, Dest:%x, Source:%x\n",
  1187. data[1], data[2] + ((uint16_t)data[3] << 8), dcid, scid);
  1188. }
  1189. void BluetoothController::setHIDProtocol(uint8_t protocol) {
  1190. // Should verify protocol is boot or report
  1191. uint8_t l2capbuf[1];
  1192. l2capbuf[0] = 0x70 | protocol; // Set Protocol, see Bluetooth HID specs page 33
  1193. DBGPrintf("Set HID Protocol %d (", protocol);
  1194. sendL2CapCommand(device_connection_handle_, l2capbuf, sizeof(l2capbuf), control_scid_ & 0xff, control_scid_ >> 8);
  1195. }
  1196. void BluetoothController::handleHIDTHDRData(uint8_t *data) {
  1197. // Example
  1198. // T HID data
  1199. //48 20 d 0 9 0 71 0 a1 3 8a cc c5 a 23 22 79
  1200. uint16_t len = data[4] + ((uint16_t)data[5] << 8);
  1201. DBGPrintf("HID HDR Data: len: %d, Type: %d\n", len, data[9]);
  1202. // ??? How to parse??? Use HID object???
  1203. if (device_driver_) {
  1204. device_driver_->process_bluetooth_HID_data(&data[9], len-1); // We skip the first byte...
  1205. } else {
  1206. switch (data[9]) {
  1207. case 1:
  1208. DBGPrintf(" Keyboard report type\n");
  1209. break;
  1210. case 2:
  1211. DBGPrintf(" Mouse report type\n");
  1212. break;
  1213. case 3:
  1214. DBGPrintf(" Combo keyboard/pointing\n");
  1215. break;
  1216. default:
  1217. DBGPrintf(" Unknown report\n");
  1218. }
  1219. }
  1220. }