You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bluetooth.cpp 47KB

7 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. *
  23. * information about the BlueTooth HCI comes from logic analyzer captures
  24. * plus... http://affon.narod.ru/BT/bluetooth_app_c10.pdf
  25. */
  26. #include <Arduino.h>
  27. #include "USBHost_t36.h" // Read this header first for key info
  28. #define print USBHost::print_
  29. #define println USBHost::println_//#define DEBUG_BT
  30. //#define DEBUG_BT
  31. #define DEBUG_BT_VERBOSE
  32. #ifndef DEBUG_BT
  33. #undef DEBUG_BT_VERBOSE
  34. void 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, STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS, STATE_TX_SEND_CONFIG_ISR_REQ};
  129. // This is a list of all the drivers inherited from the BTHIDInput class.
  130. // Unlike the list of USBDriver (managed in enumeration.cpp), drivers stay
  131. // on this list even when they have claimed a top level collection.
  132. BTHIDInput * BluetoothController::available_bthid_drivers_list = NULL;
  133. void BluetoothController::driver_ready_for_bluetooth(BTHIDInput *driver)
  134. {
  135. driver->next = NULL;
  136. if (available_bthid_drivers_list == NULL) {
  137. available_bthid_drivers_list = driver;
  138. } else {
  139. BTHIDInput *last = available_bthid_drivers_list;
  140. while (last->next) last = last->next;
  141. last->next = driver;
  142. }
  143. }
  144. // When a new top level collection is found, this function asks drivers
  145. // if they wish to claim it. The driver taking ownership of the
  146. // collection is returned, or NULL if no driver wants it.
  147. BTHIDInput * BluetoothController::find_driver(uint32_t device_type)
  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. pending_control_tx_ = 0; //
  275. return true;
  276. }
  277. void BluetoothController::disconnect()
  278. {
  279. USBHDBGSerial.printf("Bluetooth Disconnect");
  280. if (device_driver_) {
  281. device_driver_->release_bluetooth();
  282. device_driver_ = nullptr;
  283. }
  284. }
  285. void BluetoothController::control(const Transfer_t *transfer)
  286. {
  287. println(" control callback (bluetooth) ", pending_control_, HEX);
  288. #ifdef DEBUG_BT_VERBOSE
  289. DBGPrintf(" Control callback (bluetooth): %d : ", pending_control_);
  290. uint8_t *buffer = (uint8_t*)transfer->buffer;
  291. for (uint8_t i=0; i < transfer->length; i++) DBGPrintf("%x ", buffer[i]);
  292. DBGPrintf("\n");
  293. #endif
  294. }
  295. /************************************************************/
  296. // Interrupt-based Data Movement
  297. /************************************************************/
  298. void BluetoothController::rx_callback(const Transfer_t *transfer)
  299. {
  300. if (!transfer->driver) return;
  301. ((BluetoothController *)(transfer->driver))->rx_data(transfer);
  302. }
  303. void BluetoothController::rx2_callback(const Transfer_t *transfer)
  304. {
  305. if (!transfer->driver) return;
  306. ((BluetoothController *)(transfer->driver))->rx2_data(transfer);
  307. }
  308. void BluetoothController::tx_callback(const Transfer_t *transfer)
  309. {
  310. if (!transfer->driver) return;
  311. ((BluetoothController *)(transfer->driver))->tx_data(transfer);
  312. }
  313. void BluetoothController::rx_data(const Transfer_t *transfer)
  314. {
  315. uint32_t len = transfer->length - ((transfer->qtd.token >> 16) & 0x7FFF);
  316. print_hexbytes((uint8_t*)transfer->buffer, len);
  317. DBGPrintf("BT rx_data(%d): ", len);
  318. uint8_t *buffer = (uint8_t*)transfer->buffer;
  319. for (uint8_t i=0; i < len; i++) DBGPrintf("%x ", buffer[i]);
  320. DBGPrintf("\n");
  321. // Note the logical packets returned from the device may be larger
  322. // than can fit in one of our packets, so we will detect this and
  323. // the next read will be continue in or rx_buf_ in the next logical
  324. // location. We will only go into process the next logical state
  325. // when we have the full response read in...
  326. if (rx_packet_data_remaining == 0) { // Previous command was fully handled
  327. rx_packet_data_remaining = rxbuf_[1] + 2; // length of data plus the two bytes at start...
  328. }
  329. // Now see if the data
  330. rx_packet_data_remaining -= len; // remove the length of this packet from length
  331. if (rx_packet_data_remaining == 0) { // read started at beginning of packet so get the total length of packet
  332. switch(rxbuf_[0]) { // Switch on event type
  333. case EV_COMMAND_COMPLETE: //0x0e
  334. handle_hci_command_complete();// Check if command succeeded
  335. break;
  336. case EV_COMMAND_STATUS: //0x0f
  337. handle_hci_command_status();
  338. break;
  339. case EV_INQUIRY_COMPLETE: // 0x01
  340. handle_hci_inquiry_complete();
  341. break;
  342. case EV_INQUIRY_RESULT: // 0x02
  343. handle_hci_inquiry_result();
  344. break;
  345. case EV_CONNECT_COMPLETE: // 0x03
  346. handle_hci_connection_complete();
  347. break;
  348. case EV_INCOMING_CONNECT: // 0x04
  349. handle_hci_incoming_connect();
  350. break;
  351. case EV_DISCONNECT_COMPLETE: // 0x05
  352. handle_hci_disconnect_complete();
  353. break;
  354. case EV_AUTHENTICATION_COMPLETE:// 0x06
  355. handle_hci_authentication_complete();
  356. break;
  357. case EV_REMOTE_NAME_COMPLETE: // 0x07
  358. handle_hci_remote_name_complete();
  359. break;
  360. case EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE:
  361. handle_hci_remote_version_information_complete();
  362. break;
  363. case EV_PIN_CODE_REQUEST: // 0x16
  364. handle_hci_pin_code_request();
  365. break;
  366. case EV_LINK_KEY_REQUEST: // 0x17
  367. handle_hci_link_key_request();
  368. break;
  369. case EV_LINK_KEY_NOTIFICATION: // 0x18
  370. handle_hci_link_key_notification();
  371. default:
  372. break;
  373. }
  374. // Start read at start of buffer.
  375. queue_Data_Transfer(rxpipe_, rxbuf_, rx_size_, this);
  376. } else {
  377. // Continue the read - Todo - maybe verify len == rx_size_
  378. queue_Data_Transfer(rxpipe_, buffer + rx_size_, rx_size_, this);
  379. return; // Don't process the message yet as we still have data to receive.
  380. }
  381. }
  382. //===================================================================
  383. // Called when an HCI command completes.
  384. void BluetoothController::handle_hci_command_complete()
  385. {
  386. uint16_t hci_command = rxbuf_[3] + (rxbuf_[4] << 8);
  387. uint8_t buffer_index;
  388. if(!rxbuf_[5]) {
  389. VDBGPrintf(" Command Completed! \n");
  390. } else {
  391. VDBGPrintf(" Command(%x) Completed - Error: %d! \n", hci_command, rxbuf_[5]);
  392. // BUGBUG:: probably need to queue something?
  393. }
  394. switch (hci_command) {
  395. case HCI_OP_REMOTE_NAME_REQ:
  396. break;
  397. case HCI_RESET: //0x0c03
  398. if (!rxbuf_[5]) pending_control_ = PC_WRITE_CLASS_DEVICE;
  399. // If it fails, will retry. maybe should have repeat max...
  400. break;
  401. case HCI_Set_Event_Filter_Clear: //0x0c05
  402. break;
  403. case HCI_Read_Local_Name: //0x0c14
  404. // received name back...
  405. {
  406. //BUGBUG:: probably want to grab string object and copy to
  407. USBHDBGSerial.printf(" Local name: %s\n", &rxbuf_[6]);
  408. /*
  409. uint8_t len = rxbuf_[1]+2; // Length field +2 for total bytes read
  410. for (uint8_t i=6; i < len; i++) {
  411. if (rxbuf_[i] == 0) {
  412. break;
  413. }
  414. USBHDBGSerial.printf("%c", rxbuf_[i]);
  415. }
  416. USBHDBGSerial.printf("\n"); */
  417. }
  418. break;
  419. case Write_Connection_Accept_Timeout: //0x0c16
  420. break;
  421. case HCI_READ_CLASS_OF_DEVICE: // 0x0c23
  422. break;
  423. case HCI_Read_Voice_Setting: //0x0c25
  424. break;
  425. case HCI_Read_Number_Of_Supported_IAC: //0x0c38
  426. break;
  427. case HCI_Read_Current_IAC_LAP: //0x0c39
  428. break;
  429. case HCI_WRITE_INQUIRY_MODE: //0x0c45
  430. break;
  431. case HCI_Read_Inquiry_Response_Transmit_Power_Level: //0x0c58
  432. break;
  433. case HCI_Read_Local_Supported_Features: //0x1003
  434. // Remember the features supported by local...
  435. for (buffer_index = 0; buffer_index < 8; buffer_index++) {
  436. features[buffer_index] = rxbuf_[buffer_index+6];
  437. }
  438. break;
  439. case HCI_Read_Buffer_Size: // 0x1005
  440. break;
  441. case HCI_Read_BD_ADDR: //0x1009
  442. {
  443. DBGPrintf(" BD Addr");
  444. for(uint8_t i = 0; i < 6; i++) {
  445. my_bdaddr_[i] = rxbuf_[6 + i];
  446. DBGPrintf(":%x", my_bdaddr_[i]);
  447. }
  448. DBGPrintf("\n");
  449. }
  450. break;
  451. case HCI_Read_Local_Version_Information: //0x1001
  452. hciVersion = rxbuf_[6]; // Should do error checking above...
  453. DBGPrintf(" Local Version: %x\n", hciVersion);
  454. pending_control_ = (do_pair_device_)? PC_SEND_INQUIRE : PC_WRITE_SCAN_PAGE;
  455. break;
  456. case HCI_Read_Local_Supported_Commands: //0x1002
  457. break;
  458. case HCI_LE_Read_Buffer_Size: //0x2002
  459. break;
  460. case HCI_LE_Read_Local_supported_Features: //0x2003
  461. break;
  462. case HCI_LE_Supported_States: //0x201c
  463. break;
  464. case HCI_Read_Local_Extended_Features: //0x1004
  465. break;
  466. case HCI_Set_Event_Mask: //0x0c01
  467. break;
  468. case HCI_Read_Stored_Link_Key: //0x0c0d
  469. break;
  470. case HCI_Write_Default_Link_Policy_Settings: //0x080f
  471. break;
  472. case HCI_Read_Page_Scan_Activity: //0x0c1b
  473. break;
  474. case HCI_Read_Page_Scan_Type: //0x0c46
  475. break;
  476. case HCI_LE_SET_EVENT_MASK: //0x2001
  477. break;
  478. case HCI_LE_READ_ADV_TX_POWER: //0x2007
  479. break;
  480. case HCI_LE_READ_WHITE_LIST_SIZE: //0x200f
  481. break;
  482. case HCI_LE_CLEAR_WHITE_LIST: //0x2010
  483. break;
  484. case HCI_DELETE_STORED_LINK_KEY: //0x0c12
  485. break;
  486. case HCI_WRITE_LOCAL_NAME: //0x0c13
  487. break;
  488. case HCI_WRITE_SCAN_ENABLE: //0x0c1a
  489. DBGPrintf("Write_Scan_enable Completed\n");
  490. if (device_connection_handle_) {
  491. // Lets see if we can get the remote information
  492. //sendHCIRemoteVersionInfoRequest();
  493. }
  494. break;
  495. case HCI_WRITE_SSP_MODE: //0x0c56
  496. break;
  497. case HCI_WRITE_EIR: //0x0c52
  498. break;
  499. case HCI_WRITE_LE_HOST_SUPPORTED: //0x0c6d
  500. break;
  501. case HCI_LE_SET_SCAN_RSP_DATA: //0x2009
  502. break;
  503. }
  504. // And queue up the next command
  505. queue_next_hci_command();
  506. }
  507. void BluetoothController::queue_next_hci_command()
  508. {
  509. // Ok We completed a command now see if we need to queue another command
  510. // Still probably need to reorganize...
  511. switch (pending_control_) {
  512. // Initial setup states.
  513. case PC_RESET:
  514. sendResetHCI();
  515. break;
  516. case PC_WRITE_CLASS_DEVICE:
  517. sendHDCWriteClassOfDev();
  518. pending_control_++;
  519. break;
  520. case PC_READ_BDADDR:
  521. sendHCIReadBDAddr();
  522. pending_control_++;
  523. break;
  524. case PC_READ_LOCAL_VERSION:
  525. sendHCIReadLocalVersionInfo();
  526. //pending_control_++;
  527. break;
  528. // These are used when we are pairing.
  529. case PC_SEND_INQUIRE:
  530. sendHCI_INQUIRY();
  531. pending_control_++;
  532. break;
  533. case PC_INQUIRE_CANCEL:
  534. // lets try to create a connection...
  535. sendHCICreateConnection();
  536. pending_control_++;
  537. break;
  538. case PC_AUTHENTICATION_REQUESTED:
  539. break;
  540. case PC_LINK_KEY_NEGATIVE:
  541. break;
  542. case PC_PIN_CODE_REPLY:
  543. break;
  544. // None Pair mode
  545. case PC_WRITE_SCAN_PAGE:
  546. sendHCIWriteScanEnable(2);
  547. pending_control_ = 0; //
  548. break;
  549. default:
  550. break;
  551. }
  552. }
  553. void BluetoothController::handle_hci_command_status()
  554. {
  555. // <event type><param count><status><num packets allowed to be sent><CMD><CMD>
  556. #ifdef DEBUG_BT
  557. uint16_t hci_command = rxbuf_[4] + (rxbuf_[5] << 8);
  558. if (rxbuf_[2]) {
  559. DBGPrintf(" Command %x Status %x - ", hci_command, rxbuf_[2]);
  560. switch (rxbuf_[2]) {
  561. case 0x01: DBGPrintf("Unknown HCI Command\n"); break;
  562. case 0x02: DBGPrintf("Unknown Connection Identifier\n"); break;
  563. case 0x03: DBGPrintf("Hardware Failure\n"); break;
  564. case 0x04: DBGPrintf("Page Timeout\n"); break;
  565. case 0x05: DBGPrintf("Authentication Failure\n"); break;
  566. case 0x06: DBGPrintf("PIN or Key Missing\n"); break;
  567. case 0x07: DBGPrintf("Memory Capacity Exceeded\n"); break;
  568. case 0x08: DBGPrintf("Connection Timeout\n"); break;
  569. case 0x09: DBGPrintf("Connection Limit Exceeded\n"); break;
  570. case 0x0A: DBGPrintf("Synchronous Connection Limit To A Device Exceeded\n"); break;
  571. case 0x0B: DBGPrintf("Connection Already Exists\n"); break;
  572. case 0x0C: DBGPrintf("Command Disallowed\n"); break;
  573. case 0x0D: DBGPrintf("Connection Rejected due to Limited Resources\n"); break;
  574. case 0x0E: DBGPrintf("Connection Rejected Due To Security Reasons\n"); break;
  575. case 0x0F: DBGPrintf("Connection Rejected due to Unacceptable BD_ADDR\n"); break;
  576. default: DBGPrintf("???\n"); break;
  577. }
  578. } else {
  579. VDBGPrintf(" Command %x Status %x\n", hci_command, rxbuf_[2]);
  580. }
  581. #endif
  582. }
  583. void BluetoothController::handle_hci_inquiry_result()
  584. {
  585. // 2 f 1 79 22 23 a c5 cc 1 2 0 40 25 0 3b 2
  586. // Wondered if multiple items if all of the BDADDR are first then next field...
  587. // looks like it is that way...
  588. // Section 7.7.2
  589. DBGPrintf(" Inquiry Result - Count: %d\n", rxbuf_[2]);
  590. for (uint8_t i=0; i < rxbuf_[2]; i++) {
  591. uint8_t index_bd = 3 + (i*6);
  592. uint8_t index_ps = 3 + (6*rxbuf_[2]) + i;
  593. uint8_t index_class = 3 + (9*rxbuf_[2]) + i;
  594. uint8_t index_clock_offset = 3 + (12*rxbuf_[2]) + i;
  595. uint32_t bluetooth_class = rxbuf_[index_class] + ((uint32_t)rxbuf_[index_class+1] << 8) + ((uint32_t)rxbuf_[index_class+2] << 16);
  596. DBGPrintf(" BD:%x:%x:%x:%x:%x:%x, PS:%d, class: %x\n",
  597. rxbuf_[index_bd],rxbuf_[index_bd+1],rxbuf_[index_bd+2],rxbuf_[index_bd+3],rxbuf_[index_bd+4],rxbuf_[index_bd+5],
  598. rxbuf_[index_ps], bluetooth_class);
  599. // See if we know the class
  600. if ((bluetooth_class & 0xff00) == 0x2500) {
  601. DBGPrintf(" Peripheral device\n");
  602. if (bluetooth_class & 0x80) DBGPrintf(" Mouse\n");
  603. if (bluetooth_class & 0x40) DBGPrintf(" Keyboard\n");
  604. switch(bluetooth_class & 0x3c) {
  605. case 4: DBGPrintf(" Joystick\n"); break;
  606. case 8: DBGPrintf(" Gamepad\n"); break;
  607. case 0xc: DBGPrintf(" Remote Control\n"); break;
  608. }
  609. // BUGBUG, lets hard code to go to new state...
  610. for (uint8_t i = 0; i < 6; i++) device_bdaddr_[i] = rxbuf_[index_bd+i];
  611. device_class_ = bluetooth_class;
  612. device_driver_ = find_driver(device_class_);
  613. device_ps_repetion_mode_ = rxbuf_[index_ps]; // mode
  614. device_clock_offset_[0] = rxbuf_[index_clock_offset];
  615. device_clock_offset_[1] = rxbuf_[index_clock_offset+1];
  616. // Now we need to bail from inquiry and setup to try to connect...
  617. sendHCIInquiryCancel();
  618. pending_control_ = PC_INQUIRE_CANCEL;
  619. break;
  620. }
  621. }
  622. }
  623. void BluetoothController::handle_hci_inquiry_complete() {
  624. VDBGPrintf(" Inquiry Complete - status: %d\n", rxbuf_[2]);
  625. }
  626. void BluetoothController::handle_hci_connection_complete() {
  627. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  628. // ST CH CH BD BD BD BD BD BD LT EN
  629. // 03 0b 04 00 00 40 25 00 58 4b 00 01 00
  630. device_connection_handle_ = rxbuf_[3]+ (uint16_t)(rxbuf_[4]<<8);
  631. DBGPrintf(" Connection Complete - ST:%x LH:%x\n", rxbuf_[2], device_connection_handle_);
  632. if (do_pair_device_) {
  633. sendHCIAuthenticationRequested();
  634. pending_control_ = PC_AUTHENTICATION_REQUESTED;
  635. }
  636. }
  637. void BluetoothController::handle_hci_incoming_connect() {
  638. // BD BD BD BD BD BD CL CL CL LT
  639. // 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x40 0x05 0x00 0x01
  640. uint32_t class_of_device = rxbuf_[8] + (uint16_t)(rxbuf_[9]<<8) + (uint32_t)(rxbuf_[10]<<16);
  641. DBGPrintf(" Event: Incoming Connect - %x:%x:%x:%x:%x:%x CL:%x LT:%x\n",
  642. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7], class_of_device, rxbuf_[11]);
  643. if (((class_of_device & 0xff00) == 0x2500) || ((class_of_device & 0xff00) == 0x500)) {
  644. DBGPrintf(" Peripheral device\n");
  645. if (class_of_device & 0x80) DBGPrintf(" Mouse\n");
  646. if (class_of_device & 0x40) DBGPrintf(" Keyboard\n");
  647. switch(class_of_device & 0x3c) {
  648. case 4: DBGPrintf(" Joystick\n"); break;
  649. case 8: DBGPrintf(" Gamepad\n"); break;
  650. case 0xc: DBGPrintf(" Remote Control\n"); break;
  651. }
  652. device_driver_ = find_driver(class_of_device);
  653. // We need to save away the BDADDR and class link type?
  654. for(uint8_t i=0; i<6; i++) device_bdaddr_[i] = rxbuf_[i+2];
  655. device_class_ = class_of_device;
  656. sendHCIRemoteNameRequest();
  657. }
  658. // sendHCIAuthenticationRequested();
  659. // pending_control_ = PC_AUTHENTICATION_REQUESTED;
  660. }
  661. void BluetoothController::handle_hci_pin_code_request() {
  662. // 0x16 0x06 0x79 0x22 0x23 0x0A 0xC5 0xCC
  663. DBGPrintf(" Event: Pin Code Request %x:%x:%x:%x:%x:%x\n",
  664. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7]);
  665. sendHCIPinCodeReply();
  666. pending_control_ = PC_PIN_CODE_REPLY;
  667. }
  668. void BluetoothController::handle_hci_link_key_request() {
  669. // 17 6 79 22 23 a c5 cc
  670. DBGPrintf(" Event: Link Key Request %x:%x:%x:%x:%x:%x\n",
  671. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7]);
  672. // Now here is where we need to decide to say we have key or tell them to
  673. // cancel key... right now hard code to cancel...
  674. sendHCILinkKeyNegativeReply();
  675. pending_control_ = PC_LINK_KEY_NEGATIVE;
  676. }
  677. void BluetoothController::handle_hci_link_key_notification() {
  678. // 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
  679. // 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
  680. DBGPrintf(" Event: Link Key Notificaton %x:%x:%x:%x:%x:%x Type:%x\n key:",
  681. rxbuf_[2], rxbuf_[3], rxbuf_[4], rxbuf_[5], rxbuf_[6], rxbuf_[7], rxbuf_[24]);
  682. for (uint8_t i = 8; i < 24; i++) DBGPrintf("%02x ", rxbuf_[i]);
  683. DBGPrintf("\n");
  684. // Now here is where we need to decide to say we have key or tell them to
  685. // cancel key... right now hard code to cancel...
  686. }
  687. void BluetoothController::handle_hci_disconnect_complete()
  688. {
  689. //5 4 0 48 0 13
  690. DBGPrintf(" Event: HCI Disconnect complete(%d): handle: %x, reason:%x\n", rxbuf_[2],
  691. rxbuf_[3]+(rxbuf_[4]<<8), rxbuf_[5]);
  692. if (device_driver_) {
  693. device_driver_->release_bluetooth();
  694. device_driver_ = nullptr;
  695. }
  696. // Probably should clear out connection data.
  697. device_connection_handle_ = 0;
  698. device_class_ = 0;
  699. memset(device_bdaddr_, 0, sizeof(device_bdaddr_));
  700. //...
  701. }
  702. void BluetoothController::handle_hci_authentication_complete()
  703. {
  704. // 6 3 13 48 0
  705. DBGPrintf(" Event: HCI Authentication complete(%d): handle: %x\n", rxbuf_[2],
  706. rxbuf_[3]+(rxbuf_[4]<<8));
  707. // Start up lcap connection...
  708. connection_rxid_ = 0;
  709. sendl2cap_ConnectionRequest(device_connection_handle_, connection_rxid_, control_dcid_, HID_CTRL_PSM);
  710. }
  711. void BluetoothController::handle_hci_remote_name_complete() {
  712. // STAT bd bd bd bd bd bd
  713. // 0x07 0xFF 0x00 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x42 0x6C 0x75 0x65 0x74 0x6F 0x6F ...
  714. DBGPrintf(" Event: handle_hci_remote_name_complete(%d)\n", rxbuf_[2]);
  715. if (rxbuf_[2] == 0) {
  716. DBGPrintf(" Remote Name: ");
  717. for (uint8_t *psz = &rxbuf_[9]; *psz; psz++) DBGPrintf("%c", *psz);
  718. DBGPrintf("\n");
  719. }
  720. if (device_driver_) {
  721. /*
  722. if (!device_driver_->btstrbuf) {
  723. device_driver_->btstrbuf = USBHost::allocate_string_buffer();
  724. if (device_driver_->btstrbuf) {
  725. }
  726. }
  727. */
  728. device_driver_->remoteNameComplete(&rxbuf_[9]);
  729. }
  730. // Lets now try to accept the connection.
  731. sendHCIAcceptConnectionRequest();
  732. }
  733. void BluetoothController::handle_hci_remote_version_information_complete() {
  734. // STAT bd bd bd bd bd bd
  735. //c 8 0 48 0 5 45 0 0 0
  736. remote_ver_ = rxbuf_[6];
  737. remote_man_ = rxbuf_[7]+((uint16_t)rxbuf_[8]<< 8);
  738. remote_subv_ = rxbuf_[9];
  739. DBGPrintf(" Event: handle_hci_remote_version_information_complete(%d): ", rxbuf_[2]);
  740. DBGPrintf(" Handle: %x, Ver:%x, Man: %x, SV: %x\n",
  741. rxbuf_[3]+((uint16_t)rxbuf_[4]<< 8), remote_ver_, remote_man_, remote_subv_);
  742. // Lets now try to accept the connection.
  743. sendHCIAcceptConnectionRequest();
  744. }
  745. void BluetoothController::rx2_data(const Transfer_t *transfer)
  746. {
  747. uint32_t len = transfer->length - ((transfer->qtd.token >> 16) & 0x7FFF);
  748. DBGPrintf("\n=====================\nBT rx2_data(%d): ", len);
  749. uint8_t *buffer = (uint8_t*)transfer->buffer;
  750. for (uint8_t i=0; i < len; i++) DBGPrintf("%x ", buffer[i]);
  751. DBGPrintf("\n");
  752. // call backs. See if this is an L2CAP reply. example
  753. // HCI | l2cap
  754. //48 20 10 0 | c 0 1 0 | 3 0 8 0 44 0 70 0 0 0 0 0
  755. // BUGBUG need to do more verification, like the handle
  756. uint16_t hci_length = buffer[2] + ((uint16_t)buffer[3]<<8);
  757. uint16_t l2cap_length = buffer[4] + ((uint16_t)buffer[5]<<8);
  758. // uint16_t rsp_packet_length = buffer[10] + ((uint16_t)buffer[11]<<8);
  759. if ((hci_length == (l2cap_length + 4)) /*&& (hci_length == (rsp_packet_length+8))*/) {
  760. // All the lengths appear to be correct... need to do more...
  761. switch (buffer[8]) {
  762. case L2CAP_CMD_CONNECTION_REQUEST:
  763. process_l2cap_connection_request(&buffer[8]);
  764. break;
  765. case L2CAP_CMD_CONNECTION_RESPONSE:
  766. process_l2cap_connection_response(&buffer[8]);
  767. break;
  768. case L2CAP_CMD_CONFIG_REQUEST:
  769. process_l2cap_config_request(&buffer[8]);
  770. break;
  771. case L2CAP_CMD_CONFIG_RESPONSE:
  772. process_l2cap_config_response(&buffer[8]);
  773. break;
  774. case HID_THDR_DATA_INPUT:
  775. handleHIDTHDRData(buffer); // Pass the whole buffer...
  776. break;
  777. case L2CAP_CMD_COMMAND_REJECT:
  778. process_l2cap_command_reject(&buffer[8]);
  779. break;
  780. case L2CAP_CMD_DISCONNECT_REQUEST:
  781. process_l2cap_disconnect_request(&buffer[8]);
  782. break;
  783. }
  784. }
  785. // Queue up for next read...
  786. queue_Data_Transfer(rx2pipe_, rx2buf_, rx2_size_, this);
  787. }
  788. void BluetoothController::sendHCICommand(uint16_t hciCommand, uint16_t cParams, const uint8_t* data)
  789. {
  790. txbuf_[0] = hciCommand & 0xff;
  791. txbuf_[1] = (hciCommand >> 8) & 0xff;
  792. txbuf_[2] = cParams;
  793. if (cParams) {
  794. memcpy(&txbuf_[3], data, cParams); // copy in the commands parameters.
  795. }
  796. uint8_t nbytes = cParams+3;
  797. for (uint8_t i=0; i< nbytes; i++) DBGPrintf("%02x ", txbuf_[i]);
  798. DBGPrintf(")\n");
  799. mk_setup(setup, 0x20, 0x0, 0, 0, nbytes);
  800. queue_Control_Transfer(device, &setup, txbuf_, this);
  801. }
  802. //---------------------------------------------
  803. void BluetoothController::sendHCI_INQUIRY() {
  804. // Start unlimited inqury, set timeout to max and
  805. DBGPrintf("HCI_INQUIRY called (");
  806. static const uint8_t hci_inquiry_data[ ] = {
  807. 0x33, 0x8B, 0x9E, // Bluetooth assigned number LAP 0x9E8B33 General/unlimited inquiry Access mode
  808. 0x30, 0xa}; // Max inquiry time little over minute and up to 10 responses
  809. sendHCICommand(HCI_INQUIRY, sizeof(hci_inquiry_data), hci_inquiry_data);
  810. }
  811. //---------------------------------------------
  812. void BluetoothController::sendHCIInquiryCancel() {
  813. DBGPrintf("HCI_INQUIRY_CANCEL called (");
  814. sendHCICommand(HCI_INQUIRY_CANCEL, 0, nullptr);
  815. }
  816. //---------------------------------------------
  817. void BluetoothController::sendHCICreateConnection() {
  818. DBGPrintf("HCI_CREATE_CONNECTION called (");
  819. uint8_t connection_data[13];
  820. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  821. // BD BD BD BD BD BD PT PT PRS 0 CS CS ARS
  822. //0x79 0x22 0x23 0x0A 0xC5 0xCC 0x18 0xCC 0x01 0x00 0x00 0x00 0x00
  823. //0x05 0x04 0x0D 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x18 0xCC 0x01 0x00 0x00 0x00 0x00
  824. // 05 04 0d 40 25 00 c4 01 00 18 cc 01 00 00 00 00
  825. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  826. connection_data[6] = 0x18; //DM1/DH1
  827. connection_data[7] = 0xcc; //
  828. connection_data[8] = device_ps_repetion_mode_; // from device
  829. connection_data[9] = 0; //
  830. connection_data[10] = 0; // clock offset
  831. connection_data[11] = 0; // clock offset
  832. connection_data[12] = 0; // allow role swith no
  833. sendHCICommand(HCI_CREATE_CONNECTION, sizeof(connection_data), connection_data);
  834. }
  835. //---------------------------------------------
  836. void BluetoothController::sendHCIAcceptConnectionRequest() {
  837. DBGPrintf("HCI_OP_ACCEPT_CONN_REQ called (");
  838. uint8_t connection_data[7];
  839. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  840. // BD BD BD BD BD BD role
  841. //0x79 0x22 0x23 0x0A 0xC5 0xCC 0x00
  842. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  843. connection_data[6] = 0; // Role as master
  844. sendHCICommand(HCI_OP_ACCEPT_CONN_REQ, sizeof(connection_data), connection_data);
  845. }
  846. //---------------------------------------------
  847. void BluetoothController::sendHCIAuthenticationRequested() {
  848. DBGPrintf("HCI_AUTH_REQUESTED called (");
  849. uint8_t connection_data[2];
  850. connection_data[0] = device_connection_handle_ & 0xff;
  851. connection_data[1] = (device_connection_handle_>>8) & 0xff;
  852. sendHCICommand(HCI_AUTH_REQUESTED, sizeof(connection_data), connection_data);
  853. }
  854. //---------------------------------------------
  855. void BluetoothController::sendHCILinkKeyNegativeReply() {
  856. DBGPrintf("HCI_LINK_KEY_NEG_REPLY called (");
  857. uint8_t connection_data[6];
  858. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  859. sendHCICommand(HCI_LINK_KEY_NEG_REPLY, sizeof(connection_data), connection_data);
  860. }
  861. //---------------------------------------------
  862. // BUGBUG:: hard code string for this pass.
  863. void BluetoothController::sendHCIPinCodeReply() {
  864. // 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
  865. DBGPrintf("HCI_PIN_CODE_REPLY called (");
  866. uint8_t connection_data[23];
  867. uint8_t i;
  868. for (i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  869. for (i=0; pair_pincode_[i] !=0; i++) connection_data[7+i] = pair_pincode_[i];
  870. connection_data[6] = i; // remember the length
  871. for (uint8_t i=7+connection_data[6]; i<23; i++) connection_data[i] = 0;
  872. sendHCICommand(HCI_PIN_CODE_REPLY, sizeof(connection_data), connection_data);
  873. }
  874. //---------------------------------------------
  875. void BluetoothController::sendResetHCI() {
  876. DBGPrintf("HCI_RESET called (");
  877. sendHCICommand(HCI_RESET, 0, nullptr);
  878. }
  879. void BluetoothController::sendHDCWriteClassOfDev() {
  880. // 0x24 0x0C 0x03 0x04 0x08 0x00
  881. const static uint8_t device_class_data[] = {BT_CLASS_DEVICE & 0xff, (BT_CLASS_DEVICE >> 8) & 0xff, (BT_CLASS_DEVICE >> 16) & 0xff};
  882. DBGPrintf("HCI_WRITE_CLASS_OF_DEV called (");
  883. sendHCICommand(HCI_WRITE_CLASS_OF_DEV, sizeof(device_class_data), device_class_data);
  884. }
  885. void BluetoothController::sendHCIReadBDAddr() {
  886. DBGPrintf("HCI_Read_BD_ADDR called (");
  887. sendHCICommand(HCI_Read_BD_ADDR, 0, nullptr);
  888. }
  889. void BluetoothController::sendHCIReadLocalVersionInfo() {
  890. DBGPrintf("HCI_Read_Local_Version_Information called (");
  891. sendHCICommand(HCI_Read_Local_Version_Information, 0, nullptr);
  892. }
  893. void BluetoothController::sendHCIWriteScanEnable(uint8_t scan_op) {// 0x0c1a
  894. // 0x1A 0x0C 0x01 0x02
  895. DBGPrintf("HCI_WRITE_SCAN_ENABLE called(");
  896. sendHCICommand(HCI_WRITE_SCAN_ENABLE, 1, &scan_op);
  897. }
  898. void BluetoothController::sendHCIRemoteNameRequest() { // 0x0419
  899. // BD BD BD BD BD BD PS 0 CLK CLK
  900. //0x19 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x01 0x00 0x00 0x00
  901. DBGPrintf("HCI_OP_REMOTE_NAME_REQ called (");
  902. uint8_t connection_data[10];
  903. for (uint8_t i=0; i<6; i++) connection_data[i] = device_bdaddr_[i];
  904. connection_data[6] = 1; // page scan repeat mode...
  905. connection_data[7] = 0; // 0
  906. connection_data[8] = 0; // Clk offset
  907. connection_data[9] = 0;
  908. sendHCICommand(HCI_OP_REMOTE_NAME_REQ, sizeof(connection_data), connection_data);
  909. }
  910. void BluetoothController::sendHCIRemoteVersionInfoRequest() { // 0x041D
  911. // BD BD BD BD BD BD PS 0 CLK CLK
  912. //0x19 0x04 0x0A 0x79 0x22 0x23 0x0A 0xC5 0xCC 0x01 0x00 0x00 0x00
  913. DBGPrintf("HCI_OP_READ_REMOTE_VERSION_INFORMATION called (");
  914. uint8_t connection_data[2];
  915. connection_data[0] = device_connection_handle_ & 0xff;
  916. connection_data[1] = (device_connection_handle_>>8) & 0xff;
  917. sendHCICommand(HCI_OP_READ_REMOTE_VERSION_INFORMATION, sizeof(connection_data), connection_data);
  918. }
  919. // l2cap support functions.
  920. void BluetoothController::sendl2cap_ConnectionResponse(uint16_t handle, uint8_t rxid, uint16_t dcid, uint16_t scid, uint8_t result) {
  921. uint8_t l2capbuf[12];
  922. l2capbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
  923. l2capbuf[1] = rxid; // Identifier
  924. l2capbuf[2] = 0x08; // Length
  925. l2capbuf[3] = 0x00;
  926. l2capbuf[4] = dcid & 0xff; // Destination CID
  927. l2capbuf[5] = dcid >> 8;
  928. l2capbuf[6] = scid & 0xff; // Source CID
  929. l2capbuf[7] = scid >> 8;
  930. l2capbuf[8] = result; // Result: Pending or Success
  931. l2capbuf[9] = 0x00;
  932. l2capbuf[10] = 0x00; // No further information
  933. l2capbuf[11] = 0x00;
  934. DBGPrintf("L2CAP_CMD_CONNECTION_RESPONSE called(");
  935. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  936. }
  937. void BluetoothController::sendl2cap_ConnectionRequest(uint16_t handle, uint8_t rxid, uint16_t scid, uint16_t psm) {
  938. uint8_t l2capbuf[8];
  939. l2capbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
  940. l2capbuf[1] = rxid; // Identifier
  941. l2capbuf[2] = 0x04; // Length
  942. l2capbuf[3] = 0x00;
  943. l2capbuf[4] = (uint8_t)(psm & 0xff); // PSM
  944. l2capbuf[5] = (uint8_t)(psm >> 8);
  945. l2capbuf[6] = scid & 0xff; // Source CID
  946. l2capbuf[7] = (scid >> 8) & 0xff;
  947. DBGPrintf("`ConnectionRequest called(");
  948. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  949. }
  950. void BluetoothController::sendl2cap_ConfigRequest(uint16_t handle, uint8_t rxid, uint16_t dcid) {
  951. uint8_t l2capbuf[12];
  952. l2capbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
  953. l2capbuf[1] = rxid; // Identifier
  954. l2capbuf[2] = 0x08; // Length
  955. l2capbuf[3] = 0x00;
  956. l2capbuf[4] = dcid & 0xff; // Destination CID
  957. l2capbuf[5] = (dcid >> 8) & 0xff;
  958. l2capbuf[6] = 0x00; // Flags
  959. l2capbuf[7] = 0x00;
  960. l2capbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
  961. l2capbuf[9] = 0x02; // Config Opt: length
  962. l2capbuf[10] = 0xFF; // MTU
  963. l2capbuf[11] = 0xFF;
  964. DBGPrintf("L2CAP_ConfigRequest called(");
  965. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  966. }
  967. void BluetoothController::sendl2cap_ConfigResponse(uint16_t handle, uint8_t rxid, uint16_t scid) {
  968. uint8_t l2capbuf[14];
  969. l2capbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
  970. l2capbuf[1] = rxid; // Identifier
  971. l2capbuf[2] = 0x0A; // Length
  972. l2capbuf[3] = 0x00;
  973. l2capbuf[4] = scid & 0xff; // Source CID
  974. l2capbuf[5] = (scid >> 8) & 0xff;
  975. l2capbuf[6] = 0x00; // Flag
  976. l2capbuf[7] = 0x00;
  977. l2capbuf[8] = 0x00; // Result
  978. l2capbuf[9] = 0x00;
  979. l2capbuf[10] = 0x01; // Config
  980. l2capbuf[11] = 0x02;
  981. l2capbuf[12] = 0xA0;
  982. l2capbuf[13] = 0x02;
  983. DBGPrintf("L2CAP_ConfigResponse called(");
  984. sendL2CapCommand(handle, l2capbuf, sizeof(l2capbuf));
  985. }
  986. //*******************************************************************
  987. //*******************************************************************
  988. void BluetoothController::tx_data(const Transfer_t *transfer)
  989. {
  990. println(" tx_data(bluetooth) ", pending_control_, HEX);
  991. #ifdef DEBUG_BT_VERBOSE
  992. DBGPrintf("tx_data callback (bluetooth): %d : ", pending_control_tx_);
  993. uint8_t *buffer = (uint8_t*)transfer->buffer;
  994. for (uint8_t i=0; i < transfer->length; i++) DBGPrintf("%x ", buffer[i]);
  995. DBGPrintf("\n");
  996. #endif
  997. switch (pending_control_tx_) {
  998. case STATE_TX_SEND_CONNECT_INT:
  999. connection_rxid_++;
  1000. sendl2cap_ConnectionRequest(device_connection_handle_, connection_rxid_, interrupt_dcid_, HID_INTR_PSM);
  1001. pending_control_tx_ = 0;
  1002. break;
  1003. case STATE_TX_SEND_CONECT_RSP_SUCCESS:
  1004. delay(1);
  1005. // Tell the device we are ready
  1006. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_++, control_dcid_, control_scid_, SUCCESSFUL);
  1007. pending_control_tx_ = STATE_TX_SEND_CONFIG_REQ;
  1008. break;
  1009. case STATE_TX_SEND_CONFIG_REQ:
  1010. delay(1);
  1011. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, control_scid_);
  1012. pending_control_tx_ = 0;
  1013. break;
  1014. case STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS:
  1015. delay(1);
  1016. // Tell the device we are ready
  1017. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_++, interrupt_dcid_, interrupt_scid_, SUCCESSFUL);
  1018. pending_control_tx_ = STATE_TX_SEND_CONFIG_ISR_REQ;
  1019. break;
  1020. case STATE_TX_SEND_CONFIG_ISR_REQ:
  1021. delay(1);
  1022. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, interrupt_scid_);
  1023. pending_control_tx_ = 0;
  1024. break;
  1025. }
  1026. }
  1027. //*******************************************************************
  1028. //
  1029. // HCI ACL Packets
  1030. // HCI Handle Low, HCI_Handle_High (PB, BC), Total length low, TLH - HCI ACL Data packet
  1031. // length Low, length high, channel id low, channel id high - L2CAP header
  1032. // code, identifier, length, ... - Control-frame
  1033. /************************************************************/
  1034. /* L2CAP Commands */
  1035. void BluetoothController::sendL2CapCommand(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh)
  1036. {
  1037. txbuf_[0] = handle & 0xff; // HCI handle with PB,BC flag
  1038. txbuf_[1] = (((handle >> 8) & 0x0f) | 0x20);
  1039. txbuf_[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
  1040. txbuf_[3] = (uint8_t)((4 + nbytes) >> 8);
  1041. txbuf_[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
  1042. txbuf_[5] = (uint8_t)(nbytes >> 8);
  1043. txbuf_[6] = channelLow;
  1044. txbuf_[7] = channelHigh;
  1045. if (nbytes) {
  1046. memcpy(&txbuf_[8], data, nbytes); // copy in the commands parameters.
  1047. }
  1048. nbytes = nbytes+8;
  1049. for (uint8_t i=0; i< nbytes; i++) DBGPrintf("%02x ", txbuf_[i]);
  1050. DBGPrintf(")\n");
  1051. if (!queue_Data_Transfer(txpipe_, txbuf_, nbytes, this)) {
  1052. println("sendL2CapCommand failed");
  1053. }
  1054. }
  1055. void BluetoothController::process_l2cap_connection_request(uint8_t *data) {
  1056. // ID LEN LEN PSM PSM SCID SCID
  1057. // 0x02 0x02 0x04 0x00 0x11 0x00 0x43 0x00
  1058. uint16_t psm = data[4]+((uint16_t)data[5] << 8);
  1059. uint16_t scid = data[6]+((uint16_t)data[7] << 8);
  1060. connection_rxid_ = data[1];
  1061. DBGPrintf(" L2CAP Connection Request: ID: %d, PSM: %x, SCID: %x\n",connection_rxid_, psm, scid);
  1062. // Assuming not pair mode Send response like:
  1063. // RXID Len LEN DCID DCID SCID SCID RES 0 0 0
  1064. // 0x03 0x02 0x08 0x00 0x70 0x00 0x43 0x00 0x01 0x00 0x00 0x00
  1065. if (psm == HID_CTRL_PSM) {
  1066. control_scid_ = scid;
  1067. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_, control_dcid_, control_scid_, PENDING);
  1068. pending_control_tx_ = STATE_TX_SEND_CONECT_RSP_SUCCESS;
  1069. } else if (psm == HID_INTR_PSM) {
  1070. interrupt_scid_ = scid;
  1071. sendl2cap_ConnectionResponse(device_connection_handle_, connection_rxid_, interrupt_dcid_, interrupt_scid_, PENDING);
  1072. pending_control_tx_ = STATE_TX_SEND_CONECT_ISR_RSP_SUCCESS;
  1073. }
  1074. }
  1075. // Process the l2cap_connection_response...
  1076. void BluetoothController::process_l2cap_connection_response(uint8_t *data) {
  1077. uint16_t scid = data[4]+((uint16_t)data[5] << 8);
  1078. uint16_t dcid = data[6]+((uint16_t)data[7] << 8);
  1079. DBGPrintf(" L2CAP Connection Response: ID: %d, Dest:%x, Source:%x, Result:%x, Status: %x\n",
  1080. data[1], scid, dcid,
  1081. data[8]+((uint16_t)data[9] << 8), data[10]+((uint16_t)data[11] << 8));
  1082. //48 20 10 0 | c 0 1 0 | 3 0 8 0 44 0 70 0 0 0 0 0
  1083. if (dcid == interrupt_dcid_) {
  1084. interrupt_scid_ = scid;
  1085. DBGPrintf(" Interrupt Response\n");
  1086. connection_rxid_++;
  1087. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, scid);
  1088. } else if (dcid == control_dcid_) {
  1089. control_scid_ = scid;
  1090. DBGPrintf(" Control Response\n");
  1091. sendl2cap_ConfigRequest(device_connection_handle_, connection_rxid_, scid);
  1092. }
  1093. }
  1094. void BluetoothController::process_l2cap_config_request(uint8_t *data) {
  1095. //48 20 10 0 c 0 1 0 *4 2 8 0 70 0 0 0 1 2 30 0
  1096. uint16_t dcid = data[4]+((uint16_t)data[5] << 8);
  1097. DBGPrintf(" L2CAP config Request: ID: %d, Dest:%x, Flags:%x, Options: %x %x %x %x\n",
  1098. data[1], dcid, data[6]+((uint16_t)data[7] << 8),
  1099. data[8], data[9], data[10], data[11]);
  1100. // Now see which dest was specified
  1101. if (dcid == control_dcid_) {
  1102. DBGPrintf(" Control Configuration request\n");
  1103. sendl2cap_ConfigResponse(device_connection_handle_, data[1], control_scid_);
  1104. } else if (dcid == interrupt_dcid_) {
  1105. DBGPrintf(" Interrupt Configuration request\n");
  1106. sendl2cap_ConfigResponse(device_connection_handle_, data[1], interrupt_scid_);
  1107. }
  1108. }
  1109. void BluetoothController::process_l2cap_config_response(uint8_t *data) {
  1110. // 48 20 12 0 e 0 1 0 5 0 a 0 70 0 0 0 0 0 1 2 30 0
  1111. uint16_t scid = data[4]+((uint16_t)data[5] << 8);
  1112. DBGPrintf(" L2CAP config Response: ID: %d, Source:%x, Flags:%x, Result:%x, Config: %x\n",
  1113. data[1], scid, data[6]+((uint16_t)data[7] << 8),
  1114. data[8]+((uint16_t)data[9] << 8), data[10]+((uint16_t)data[11] << 8));
  1115. if (scid == control_dcid_) {
  1116. // Set HID Boot mode
  1117. setHIDProtocol(HID_BOOT_PROTOCOL); //
  1118. //setHIDProtocol(HID_RPT_PROTOCOL); //HID_RPT_PROTOCOL
  1119. if (do_pair_device_)
  1120. pending_control_tx_ = STATE_TX_SEND_CONNECT_INT;
  1121. else
  1122. pending_control_ = 0;
  1123. } else if (scid == interrupt_dcid_) {
  1124. // Enable SCan to page mode
  1125. sendHCIWriteScanEnable(2);
  1126. }
  1127. }
  1128. void BluetoothController::process_l2cap_command_reject(uint8_t *data) {
  1129. // 48 20 b 0 7 0 70 0 *1 0 0 0 2 0 4
  1130. DBGPrintf(" L2CAP command reject: ID: %d, length:%x, Reason:%x, Data: %x %x \n",
  1131. data[1], data[2] + ((uint16_t)data[3] << 8), data[4], data[5], data[6]);
  1132. }
  1133. void BluetoothController::process_l2cap_disconnect_request(uint8_t *data) {
  1134. uint16_t dcid = data[4]+((uint16_t)data[5] << 8);
  1135. uint16_t scid = data[6]+((uint16_t)data[7] << 8);
  1136. DBGPrintf(" L2CAP disconnect request: ID: %d, Length:%x, Dest:%x, Source:%x\n",
  1137. data[1], data[2] + ((uint16_t)data[3] << 8), dcid, scid);
  1138. }
  1139. void BluetoothController::setHIDProtocol(uint8_t protocol) {
  1140. // Should verify protocol is boot or report
  1141. uint8_t l2capbuf[1];
  1142. l2capbuf[0] = 0x70 | protocol; // Set Protocol, see Bluetooth HID specs page 33
  1143. DBGPrintf("Set HID Protocol %d (", protocol);
  1144. sendL2CapCommand(device_connection_handle_, l2capbuf, sizeof(l2capbuf), control_scid_ & 0xff, control_scid_ >> 8);
  1145. }
  1146. void BluetoothController::handleHIDTHDRData(uint8_t *data) {
  1147. // Example
  1148. // T HID data
  1149. //48 20 d 0 9 0 71 0 a1 3 8a cc c5 a 23 22 79
  1150. uint16_t len = data[4] + ((uint16_t)data[5] << 8);
  1151. DBGPrintf("HID HDR Data: len: %d, Type: %d\n", len, data[9]);
  1152. // ??? How to parse??? Use HID object???
  1153. if (device_driver_) {
  1154. device_driver_->process_bluetooth_HID_data(&data[9], len-1); // We skip the first byte...
  1155. } else {
  1156. switch (data[9]) {
  1157. case 1:
  1158. DBGPrintf(" Keyboard report type\n");
  1159. break;
  1160. case 2:
  1161. DBGPrintf(" Mouse report type\n");
  1162. break;
  1163. case 3:
  1164. DBGPrintf(" Combo keyboard/pointing\n");
  1165. break;
  1166. default:
  1167. DBGPrintf(" Unknown report\n");
  1168. }
  1169. }
  1170. }