No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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