Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1306 linhas
46KB

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