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.

1279 lines
45KB

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