1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN 24 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "hci.c" 39 40 /* 41 * hci.c 42 * 43 * Created by Matthias Ringwald on 4/29/09. 44 * 45 */ 46 47 #include "btstack_config.h" 48 49 50 #ifdef ENABLE_CLASSIC 51 #ifdef HAVE_EMBEDDED_TICK 52 #include "btstack_run_loop_embedded.h" 53 #endif 54 #endif 55 56 #ifdef ENABLE_BLE 57 #include "gap.h" 58 #include "ble/le_device_db.h" 59 #endif 60 61 #include <stdarg.h> 62 #include <string.h> 63 #include <inttypes.h> 64 65 #include "btstack_debug.h" 66 #include "btstack_event.h" 67 #include "btstack_linked_list.h" 68 #include "btstack_memory.h" 69 #include "bluetooth_company_id.h" 70 #include "bluetooth_data_types.h" 71 #include "gap.h" 72 #include "hci.h" 73 #include "hci_cmd.h" 74 #include "hci_dump.h" 75 #include "ad_parser.h" 76 77 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 78 #include <stdio.h> // sprintf 79 #endif 80 81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 82 #ifndef HCI_HOST_ACL_PACKET_NUM 83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM" 84 #endif 85 #ifndef HCI_HOST_ACL_PACKET_LEN 86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN" 87 #endif 88 #ifndef HCI_HOST_SCO_PACKET_NUM 89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM" 90 #endif 91 #ifndef HCI_HOST_SCO_PACKET_LEN 92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN" 93 #endif 94 #endif 95 96 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM) 97 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM." 98 #endif 99 100 #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT) 101 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT." 102 #endif 103 104 #define HCI_CONNECTION_TIMEOUT_MS 10000 105 106 #ifndef HCI_RESET_RESEND_TIMEOUT_MS 107 #define HCI_RESET_RESEND_TIMEOUT_MS 200 108 #endif 109 110 // Names are arbitrarily shortened to 32 bytes if not requested otherwise 111 #ifndef GAP_INQUIRY_MAX_NAME_LEN 112 #define GAP_INQUIRY_MAX_NAME_LEN 32 113 #endif 114 115 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested 116 #define GAP_INQUIRY_DURATION_MIN 0x01 117 #define GAP_INQUIRY_DURATION_MAX 0x30 118 #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02 119 #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03 120 #define GAP_INQUIRY_STATE_IDLE 0x00 121 #define GAP_INQUIRY_STATE_W4_ACTIVE 0x80 122 #define GAP_INQUIRY_STATE_ACTIVE 0x81 123 #define GAP_INQUIRY_STATE_W2_CANCEL 0x82 124 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83 125 #define GAP_INQUIRY_STATE_PERIODIC 0x84 126 #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85 127 128 // GAP Remote Name Request 129 #define GAP_REMOTE_NAME_STATE_IDLE 0 130 #define GAP_REMOTE_NAME_STATE_W2_SEND 1 131 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2 132 133 // GAP Pairing 134 #define GAP_PAIRING_STATE_IDLE 0 135 #define GAP_PAIRING_STATE_SEND_PIN 1 136 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE 2 137 #define GAP_PAIRING_STATE_SEND_PASSKEY 3 138 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE 4 139 #define GAP_PAIRING_STATE_SEND_CONFIRMATION 5 140 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6 141 #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE 7 142 143 // 144 // compact storage of relevant supported HCI Commands. 145 // X-Macro below provides enumeration and mapping table into the supported 146 // commands bitmap (64 bytes) from HCI Read Local Supported Commands 147 // 148 149 // format: command name, byte offset, bit nr in 64-byte supported commands 150 // currently stored in 32-bit variable 151 #define SUPPORTED_HCI_COMMANDS \ 152 X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES , 2, 5) \ 153 X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \ 154 X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE , 14, 7) \ 155 X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \ 156 X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE , 20, 4) \ 157 X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2 , 22, 2) \ 158 X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED , 24, 6) \ 159 X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \ 160 X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST , 32, 3) \ 161 X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND , 32, 6) \ 162 X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \ 163 X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE , 35, 1) \ 164 X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH , 35, 3) \ 165 X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY , 35, 5) \ 166 X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE , 36, 6) \ 167 X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2 , 41, 5) \ 168 X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE , 45, 7) \ 169 170 // enumerate supported commands 171 #define X(name, offset, bit) name, 172 enum { 173 SUPPORTED_HCI_COMMANDS 174 SUPPORTED_HCI_COMMANDS_COUNT 175 }; 176 #undef X 177 178 // prototypes 179 #ifdef ENABLE_CLASSIC 180 static void hci_update_scan_enable(void); 181 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable); 182 static int hci_local_ssp_activated(void); 183 static bool hci_remote_ssp_supported(hci_con_handle_t con_handle); 184 static bool hci_ssp_supported(hci_connection_t * connection); 185 static void hci_notify_if_sco_can_send_now(void); 186 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status); 187 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 188 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level); 189 static void hci_connection_timeout_handler(btstack_timer_source_t *timer); 190 static void hci_connection_timestamp(hci_connection_t *connection); 191 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn); 192 static void gap_inquiry_explode(uint8_t *packet, uint16_t size); 193 #endif 194 195 static int hci_power_control_on(void); 196 static void hci_power_control_off(void); 197 static void hci_state_reset(void); 198 static void hci_halting_timeout_handler(btstack_timer_source_t * ds); 199 static void hci_emit_transport_packet_sent(void); 200 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason); 201 static void hci_emit_nr_connections_changed(void); 202 static void hci_emit_hci_open_failed(void); 203 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status); 204 static void hci_emit_event(uint8_t * event, uint16_t size, int dump); 205 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size); 206 static void hci_run(void); 207 static int hci_is_le_connection(hci_connection_t * connection); 208 209 #ifdef ENABLE_CLASSIC 210 static int hci_have_usb_transport(void); 211 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection); 212 #endif 213 214 #ifdef ENABLE_BLE 215 static void hci_whitelist_free(void); 216 #ifdef ENABLE_LE_CENTRAL 217 // called from test/ble_client/advertising_data_parser.c 218 void le_handle_advertisement_report(uint8_t *packet, uint16_t size); 219 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address); 220 static hci_connection_t * gap_get_outgoing_connection(void); 221 static void hci_le_scan_stop(void); 222 static bool hci_run_general_gap_le(void); 223 #endif 224 #ifdef ENABLE_LE_PERIPHERAL 225 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 226 static void hci_periodic_advertiser_list_free(void); 227 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle); 228 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 229 #endif /* ENABLE_LE_PERIPHERAL */ 230 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 231 static uint8_t hci_iso_stream_create(hci_iso_type_t iso_type, hci_con_handle_t con_handle, uint8_t group_id, 232 hci_iso_stream_state_t state); 233 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream); 234 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id); 235 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle); 236 static void hci_iso_stream_requested_finalize(uint8_t big_handle); 237 static void hci_iso_stream_requested_confirm(uint8_t big_handle); 238 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size); 239 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle); 240 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id); 241 static void hci_iso_notify_can_send_now(void); 242 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status); 243 static void hci_emit_big_terminated(const le_audio_big_t * big); 244 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status); 245 static void hci_emit_big_sync_stopped(uint8_t big_handle); 246 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status); 247 static void 248 hci_emit_cis_created(uint8_t cig_id, hci_con_handle_t cis_con_handle, uint8_t status); 249 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle); 250 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 251 #endif /* ENABLE_BLE */ 252 253 // the STACK is here 254 #ifndef HAVE_MALLOC 255 static hci_stack_t hci_stack_static; 256 #endif 257 static hci_stack_t * hci_stack = NULL; 258 259 #ifdef ENABLE_CLASSIC 260 // default name 261 static const char * default_classic_name = "BTstack 00:00:00:00:00:00"; 262 263 // test helper 264 static uint8_t disable_l2cap_timeouts = 0; 265 #endif 266 267 // reset connection state on create and on reconnect 268 // don't overwrite addr, con handle, role 269 static void hci_connection_init(hci_connection_t * conn){ 270 conn->authentication_flags = AUTH_FLAG_NONE; 271 conn->bonding_flags = 0; 272 conn->requested_security_level = LEVEL_0; 273 #ifdef ENABLE_CLASSIC 274 conn->request_role = HCI_ROLE_INVALID; 275 conn->sniff_subrating_max_latency = 0xffff; 276 conn->qos_service_type = HCI_SERVICE_TYPE_INVALID; 277 conn->link_key_type = INVALID_LINK_KEY; 278 btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler); 279 btstack_run_loop_set_timer_context(&conn->timeout, conn); 280 hci_connection_timestamp(conn); 281 #endif 282 conn->acl_recombination_length = 0; 283 conn->acl_recombination_pos = 0; 284 conn->num_packets_sent = 0; 285 286 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 287 #ifdef ENABLE_BLE 288 conn->le_phy_update_all_phys = 0xff; 289 #endif 290 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 291 conn->le_max_tx_octets = 27; 292 #endif 293 #ifdef ENABLE_CLASSIC_PAIRING_OOB 294 conn->classic_oob_c_192 = NULL; 295 conn->classic_oob_r_192 = NULL; 296 conn->classic_oob_c_256 = NULL; 297 conn->classic_oob_r_256 = NULL; 298 #endif 299 } 300 301 /** 302 * create connection for given address 303 * 304 * @return connection OR NULL, if no memory left 305 */ 306 static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){ 307 log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type); 308 309 hci_connection_t * conn = btstack_memory_hci_connection_get(); 310 if (!conn) return NULL; 311 hci_connection_init(conn); 312 313 bd_addr_copy(conn->address, addr); 314 conn->address_type = addr_type; 315 conn->con_handle = HCI_CON_HANDLE_INVALID; 316 conn->role = HCI_ROLE_INVALID; 317 318 btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn); 319 320 return conn; 321 } 322 323 324 /** 325 * get le connection parameter range 326 * 327 * @return le connection parameter range struct 328 */ 329 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){ 330 *range = hci_stack->le_connection_parameter_range; 331 } 332 333 /** 334 * set le connection parameter range 335 * 336 */ 337 338 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){ 339 hci_stack->le_connection_parameter_range = *range; 340 } 341 342 /** 343 * @brief Test if connection parameters are inside in existing rage 344 * @param conn_interval_min (unit: 1.25ms) 345 * @param conn_interval_max (unit: 1.25ms) 346 * @param conn_latency 347 * @param supervision_timeout (unit: 10ms) 348 * @return 1 if included 349 */ 350 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){ 351 if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0; 352 if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0; 353 354 if (le_conn_latency < existing_range->le_conn_latency_min) return 0; 355 if (le_conn_latency > existing_range->le_conn_latency_max) return 0; 356 357 if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0; 358 if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0; 359 360 return 1; 361 } 362 363 /** 364 * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it) 365 * @note: default: 1 366 * @param max_peripheral_connections 367 */ 368 #ifdef ENABLE_LE_PERIPHERAL 369 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){ 370 hci_stack->le_max_number_peripheral_connections = max_peripheral_connections; 371 } 372 #endif 373 374 /** 375 * get hci connections iterator 376 * 377 * @return hci connections iterator 378 */ 379 380 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){ 381 btstack_linked_list_iterator_init(it, &hci_stack->connections); 382 } 383 384 /** 385 * get connection for a given handle 386 * 387 * @return connection OR NULL, if not found 388 */ 389 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 390 btstack_linked_list_iterator_t it; 391 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 392 while (btstack_linked_list_iterator_has_next(&it)){ 393 hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 394 if ( item->con_handle == con_handle ) { 395 return item; 396 } 397 } 398 return NULL; 399 } 400 401 /** 402 * get connection for given address 403 * 404 * @return connection OR NULL, if not found 405 */ 406 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){ 407 btstack_linked_list_iterator_t it; 408 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 409 while (btstack_linked_list_iterator_has_next(&it)){ 410 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 411 if (connection->address_type != addr_type) continue; 412 if (memcmp(addr, connection->address, 6) != 0) continue; 413 return connection; 414 } 415 return NULL; 416 } 417 418 #ifdef ENABLE_CLASSIC 419 420 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 421 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 422 } 423 424 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 425 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 426 } 427 428 #ifdef ENABLE_SCO_OVER_HCI 429 static int hci_number_sco_connections(void){ 430 int connections = 0; 431 btstack_linked_list_iterator_t it; 432 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 433 while (btstack_linked_list_iterator_has_next(&it)){ 434 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 435 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 436 connections++; 437 } 438 return connections; 439 } 440 #endif 441 442 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){ 443 hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer); 444 #ifdef HAVE_EMBEDDED_TICK 445 if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 446 // connections might be timed out 447 hci_emit_l2cap_check_timeout(connection); 448 } 449 #else 450 if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){ 451 // connections might be timed out 452 hci_emit_l2cap_check_timeout(connection); 453 } 454 #endif 455 } 456 457 static void hci_connection_timestamp(hci_connection_t *connection){ 458 #ifdef HAVE_EMBEDDED_TICK 459 connection->timestamp = btstack_run_loop_embedded_get_ticks(); 460 #else 461 connection->timestamp = btstack_run_loop_get_time_ms(); 462 #endif 463 } 464 465 /** 466 * add authentication flags and reset timer 467 * @note: assumes classic connection 468 * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets 469 */ 470 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 471 bd_addr_t addr; 472 reverse_bd_addr(bd_addr, addr); 473 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 474 if (conn) { 475 connectionSetAuthenticationFlags(conn, flags); 476 hci_connection_timestamp(conn); 477 } 478 } 479 480 static bool hci_pairing_active(hci_connection_t * hci_connection){ 481 return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0; 482 } 483 484 static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){ 485 if (hci_pairing_active(hci_connection)) return; 486 if (ssp){ 487 hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE; 488 } else { 489 hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE; 490 } 491 // if we are initiator, we have sent an HCI Authenticate Request 492 bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0; 493 494 // if we are responder, use minimal service security level as required level 495 if (!initiator){ 496 hci_connection->requested_security_level = (gap_security_level_t) btstack_max((uint32_t) hci_connection->requested_security_level, (uint32_t) hci_stack->gap_minimal_service_security_level); 497 } 498 499 log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level); 500 501 uint8_t event[12]; 502 event[0] = GAP_EVENT_PAIRING_STARTED; 503 event[1] = 10; 504 little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle); 505 reverse_bd_addr(hci_connection->address, &event[4]); 506 event[10] = (uint8_t) ssp; 507 event[11] = (uint8_t) initiator; 508 hci_emit_event(event, sizeof(event), 1); 509 } 510 511 static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){ 512 hci_connection->requested_security_level = LEVEL_0; 513 if (!hci_pairing_active(hci_connection)) return; 514 hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK; 515 #ifdef ENABLE_CLASSIC_PAIRING_OOB 516 hci_connection->classic_oob_c_192 = NULL; 517 hci_connection->classic_oob_r_192 = NULL; 518 hci_connection->classic_oob_c_256 = NULL; 519 hci_connection->classic_oob_r_256 = NULL; 520 #endif 521 log_info("pairing complete, status %02x", status); 522 523 uint8_t event[11]; 524 event[0] = GAP_EVENT_PAIRING_COMPLETE; 525 event[1] = 9; 526 little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle); 527 reverse_bd_addr(hci_connection->address, &event[4]); 528 event[10] = status; 529 hci_emit_event(event, sizeof(event), 1); 530 531 // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted 532 if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){ 533 hci_connection->bonding_flags &= ~BONDING_DEDICATED; 534 hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 535 hci_connection->bonding_status = status; 536 } 537 } 538 539 bool hci_authentication_active_for_handle(hci_con_handle_t handle){ 540 hci_connection_t * conn = hci_connection_for_handle(handle); 541 if (!conn) return false; 542 return hci_pairing_active(conn); 543 } 544 545 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){ 546 if (!hci_stack->link_key_db) return; 547 log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr)); 548 hci_stack->link_key_db->delete_link_key(addr); 549 } 550 551 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){ 552 if (!hci_stack->link_key_db) return; 553 log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type); 554 hci_stack->link_key_db->put_link_key(addr, link_key, type); 555 } 556 557 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){ 558 if (!hci_stack->link_key_db) return false; 559 int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0; 560 log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type); 561 return result; 562 } 563 564 void gap_delete_all_link_keys(void){ 565 bd_addr_t addr; 566 link_key_t link_key; 567 link_key_type_t type; 568 btstack_link_key_iterator_t it; 569 int ok = gap_link_key_iterator_init(&it); 570 if (!ok) { 571 log_error("could not initialize iterator"); 572 return; 573 } 574 while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){ 575 gap_drop_link_key_for_bd_addr(addr); 576 } 577 gap_link_key_iterator_done(&it); 578 } 579 580 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){ 581 if (!hci_stack->link_key_db) return 0; 582 if (!hci_stack->link_key_db->iterator_init) return 0; 583 return hci_stack->link_key_db->iterator_init(it); 584 } 585 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){ 586 if (!hci_stack->link_key_db) return 0; 587 return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type); 588 } 589 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){ 590 if (!hci_stack->link_key_db) return; 591 hci_stack->link_key_db->iterator_done(it); 592 } 593 #endif 594 595 static bool hci_is_le_connection_type(bd_addr_type_t address_type){ 596 switch (address_type){ 597 case BD_ADDR_TYPE_LE_PUBLIC: 598 case BD_ADDR_TYPE_LE_RANDOM: 599 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC: 600 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM: 601 return true; 602 default: 603 return false; 604 } 605 } 606 607 static int hci_is_le_connection(hci_connection_t * connection){ 608 return hci_is_le_connection_type(connection->address_type); 609 } 610 611 /** 612 * count connections 613 */ 614 static int nr_hci_connections(void){ 615 int count = 0; 616 btstack_linked_item_t *it; 617 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){ 618 count++; 619 } 620 return count; 621 } 622 623 uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){ 624 625 unsigned int num_packets_sent_classic = 0; 626 unsigned int num_packets_sent_le = 0; 627 628 btstack_linked_item_t *it; 629 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 630 hci_connection_t * connection = (hci_connection_t *) it; 631 if (hci_is_le_connection(connection)){ 632 num_packets_sent_le += connection->num_packets_sent; 633 } 634 if (connection->address_type == BD_ADDR_TYPE_ACL){ 635 num_packets_sent_classic += connection->num_packets_sent; 636 } 637 } 638 log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num); 639 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 640 int free_slots_le = 0; 641 642 if (free_slots_classic < 0){ 643 log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num); 644 return 0; 645 } 646 647 if (hci_stack->le_acl_packets_total_num){ 648 // if we have LE slots, they are used 649 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 650 if (free_slots_le < 0){ 651 log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num); 652 return 0; 653 } 654 } else { 655 // otherwise, classic slots are used for LE, too 656 free_slots_classic -= num_packets_sent_le; 657 if (free_slots_classic < 0){ 658 log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num); 659 return 0; 660 } 661 } 662 663 switch (address_type){ 664 case BD_ADDR_TYPE_UNKNOWN: 665 log_error("hci_number_free_acl_slots: unknown address type"); 666 return 0; 667 668 case BD_ADDR_TYPE_ACL: 669 return (uint16_t) free_slots_classic; 670 671 default: 672 if (hci_stack->le_acl_packets_total_num > 0){ 673 return (uint16_t) free_slots_le; 674 } 675 return (uint16_t) free_slots_classic; 676 } 677 } 678 679 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 680 // get connection type 681 hci_connection_t * connection = hci_connection_for_handle(con_handle); 682 if (!connection){ 683 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle); 684 return 0; 685 } 686 return hci_number_free_acl_slots_for_connection_type(connection->address_type); 687 } 688 689 #ifdef ENABLE_CLASSIC 690 static int hci_number_free_sco_slots(void){ 691 unsigned int num_sco_packets_sent = 0; 692 btstack_linked_item_t *it; 693 if (hci_stack->synchronous_flow_control_enabled){ 694 // explicit flow control 695 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 696 hci_connection_t * connection = (hci_connection_t *) it; 697 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 698 num_sco_packets_sent += connection->num_packets_sent; 699 } 700 if (num_sco_packets_sent > hci_stack->sco_packets_total_num){ 701 log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num); 702 return 0; 703 } 704 return hci_stack->sco_packets_total_num - num_sco_packets_sent; 705 } else { 706 // implicit flow control -- TODO 707 int num_ready = 0; 708 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 709 hci_connection_t * connection = (hci_connection_t *) it; 710 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 711 if (connection->sco_tx_ready == 0) continue; 712 num_ready++; 713 } 714 return num_ready; 715 } 716 } 717 #endif 718 719 // only used to send HCI Host Number Completed Packets 720 static int hci_can_send_comand_packet_transport(void){ 721 if (hci_stack->hci_packet_buffer_reserved) return 0; 722 723 // check for async hci transport implementations 724 if (hci_stack->hci_transport->can_send_packet_now){ 725 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 726 return 0; 727 } 728 } 729 return 1; 730 } 731 732 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 733 bool hci_can_send_command_packet_now(void){ 734 if (hci_can_send_comand_packet_transport() == 0) return false; 735 return hci_stack->num_cmd_packets > 0u; 736 } 737 738 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){ 739 // check for async hci transport implementations 740 if (!hci_stack->hci_transport->can_send_packet_now) return true; 741 return hci_stack->hci_transport->can_send_packet_now(packet_type); 742 } 743 744 static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){ 745 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false; 746 return hci_number_free_acl_slots_for_connection_type(address_type) > 0; 747 } 748 749 bool hci_can_send_acl_le_packet_now(void){ 750 if (hci_stack->hci_packet_buffer_reserved) return false; 751 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC); 752 } 753 754 bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 755 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false; 756 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 757 } 758 759 bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 760 if (hci_stack->hci_packet_buffer_reserved) return false; 761 return hci_can_send_prepared_acl_packet_now(con_handle); 762 } 763 764 #ifdef ENABLE_CLASSIC 765 bool hci_can_send_acl_classic_packet_now(void){ 766 if (hci_stack->hci_packet_buffer_reserved) return false; 767 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL); 768 } 769 770 bool hci_can_send_prepared_sco_packet_now(void){ 771 if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false; 772 if (hci_have_usb_transport()){ 773 return hci_stack->sco_can_send_now; 774 } else { 775 return hci_number_free_sco_slots() > 0; 776 } 777 } 778 779 bool hci_can_send_sco_packet_now(void){ 780 if (hci_stack->hci_packet_buffer_reserved) return false; 781 return hci_can_send_prepared_sco_packet_now(); 782 } 783 784 void hci_request_sco_can_send_now_event(void){ 785 hci_stack->sco_waiting_for_can_send_now = 1; 786 hci_notify_if_sco_can_send_now(); 787 } 788 #endif 789 790 // used for internal checks in l2cap.c 791 bool hci_is_packet_buffer_reserved(void){ 792 return hci_stack->hci_packet_buffer_reserved; 793 } 794 795 // reserves outgoing packet buffer. 796 // @return 1 if successful 797 bool hci_reserve_packet_buffer(void){ 798 if (hci_stack->hci_packet_buffer_reserved) { 799 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 800 return false; 801 } 802 hci_stack->hci_packet_buffer_reserved = true; 803 return true; 804 } 805 806 void hci_release_packet_buffer(void){ 807 hci_stack->hci_packet_buffer_reserved = false; 808 } 809 810 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 811 static int hci_transport_synchronous(void){ 812 return hci_stack->hci_transport->can_send_packet_now == NULL; 813 } 814 815 // used for debugging 816 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 817 static void hci_controller_dump_packets(void){ 818 // format: "{handle:04x}:{count:02d} " 819 char summaries[3][7 * 8 + 1]; 820 uint16_t totals[3]; 821 uint8_t index; 822 for (index = 0 ; index < 3 ; index++){ 823 summaries[index][0] = 0; 824 totals[index] = 0; 825 } 826 btstack_linked_item_t *it; 827 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 828 hci_connection_t * connection = (hci_connection_t *) it; 829 switch (connection->address_type){ 830 case BD_ADDR_TYPE_ACL: 831 index = 0; 832 break; 833 case BD_ADDR_TYPE_SCO: 834 index = 2; 835 break; 836 default: 837 index = 1; 838 break; 839 } 840 totals[index] += connection->num_packets_sent; 841 char item_text[10]; 842 sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent); 843 btstack_strcat(summaries[index], sizeof(summaries[0]), item_text); 844 } 845 for (index = 0 ; index < 3 ; index++){ 846 if (summaries[index][0] == 0){ 847 summaries[index][0] = '-'; 848 summaries[index][1] = 0; 849 } 850 } 851 log_info("Controller ACL BR/EDR: %s total %u / LE: %s total %u / SCO: %s total %u", summaries[0], totals[0], summaries[1], totals[1], summaries[2], totals[2]); 852 } 853 #endif 854 855 static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){ 856 857 // log_info("hci_send_acl_packet_fragments %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle); 858 859 // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers 860 uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length; 861 if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){ 862 max_acl_data_packet_length = hci_stack->le_data_packets_length; 863 } 864 865 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 866 if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){ 867 max_acl_data_packet_length = connection->le_max_tx_octets; 868 } 869 #endif 870 871 log_debug("hci_send_acl_packet_fragments entered"); 872 873 uint8_t status = ERROR_CODE_SUCCESS; 874 // multiple packets could be send on a synchronous HCI transport 875 while (true){ 876 877 log_debug("hci_send_acl_packet_fragments loop entered"); 878 879 // get current data 880 const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u; 881 int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos; 882 bool more_fragments = false; 883 884 // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 885 if (current_acl_data_packet_length > max_acl_data_packet_length){ 886 more_fragments = true; 887 current_acl_data_packet_length = max_acl_data_packet_length; 888 } 889 890 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 891 if (acl_header_pos > 0u){ 892 uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 893 handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u); 894 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags); 895 } 896 897 // update header len 898 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length); 899 900 // count packet 901 connection->num_packets_sent++; 902 log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments); 903 904 // update state for next fragment (if any) as "transport done" might be sent during send_packet already 905 if (more_fragments){ 906 // update start of next fragment to send 907 hci_stack->acl_fragmentation_pos += current_acl_data_packet_length; 908 } else { 909 // done 910 hci_stack->acl_fragmentation_pos = 0; 911 hci_stack->acl_fragmentation_total_size = 0; 912 } 913 914 // send packet 915 uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos]; 916 const int size = current_acl_data_packet_length + 4; 917 hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size); 918 hci_stack->acl_fragmentation_tx_active = 1; 919 int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 920 if (err != 0){ 921 // no error from HCI Transport expected 922 status = ERROR_CODE_HARDWARE_FAILURE; 923 } 924 925 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 926 hci_controller_dump_packets(); 927 #endif 928 929 log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments); 930 931 // done yet? 932 if (!more_fragments) break; 933 934 // can send more? 935 if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status; 936 } 937 938 log_debug("hci_send_acl_packet_fragments loop over"); 939 940 // release buffer now for synchronous transport 941 if (hci_transport_synchronous()){ 942 hci_stack->acl_fragmentation_tx_active = 0; 943 hci_release_packet_buffer(); 944 hci_emit_transport_packet_sent(); 945 } 946 947 return status; 948 } 949 950 // pre: caller has reserved the packet buffer 951 uint8_t hci_send_acl_packet_buffer(int size){ 952 btstack_assert(hci_stack->hci_packet_buffer_reserved); 953 954 uint8_t * packet = hci_stack->hci_packet_buffer; 955 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 956 957 // check for free places on Bluetooth module 958 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 959 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 960 hci_release_packet_buffer(); 961 hci_emit_transport_packet_sent(); 962 return BTSTACK_ACL_BUFFERS_FULL; 963 } 964 965 hci_connection_t *connection = hci_connection_for_handle( con_handle); 966 if (!connection) { 967 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 968 hci_release_packet_buffer(); 969 hci_emit_transport_packet_sent(); 970 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 971 } 972 973 #ifdef ENABLE_CLASSIC 974 hci_connection_timestamp(connection); 975 #endif 976 977 // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size); 978 979 // setup data 980 hci_stack->acl_fragmentation_total_size = size; 981 hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet 982 983 return hci_send_acl_packet_fragments(connection); 984 } 985 986 #ifdef ENABLE_CLASSIC 987 // pre: caller has reserved the packet buffer 988 uint8_t hci_send_sco_packet_buffer(int size){ 989 btstack_assert(hci_stack->hci_packet_buffer_reserved); 990 991 uint8_t * packet = hci_stack->hci_packet_buffer; 992 993 // skip checks in loopback mode 994 if (!hci_stack->loopback_mode){ 995 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); // same for ACL and SCO 996 997 // check for free places on Bluetooth module 998 if (!hci_can_send_prepared_sco_packet_now()) { 999 log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller"); 1000 hci_release_packet_buffer(); 1001 hci_emit_transport_packet_sent(); 1002 return BTSTACK_ACL_BUFFERS_FULL; 1003 } 1004 1005 // track send packet in connection struct 1006 hci_connection_t *connection = hci_connection_for_handle( con_handle); 1007 if (!connection) { 1008 log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle); 1009 hci_release_packet_buffer(); 1010 hci_emit_transport_packet_sent(); 1011 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 1012 } 1013 1014 if (hci_have_usb_transport()){ 1015 // token used 1016 hci_stack->sco_can_send_now = false; 1017 } else { 1018 if (hci_stack->synchronous_flow_control_enabled){ 1019 connection->num_packets_sent++; 1020 } else { 1021 connection->sco_tx_ready--; 1022 } 1023 } 1024 } 1025 1026 hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size); 1027 1028 #ifdef HAVE_SCO_TRANSPORT 1029 hci_stack->sco_transport->send_packet(packet, size); 1030 hci_release_packet_buffer(); 1031 hci_emit_transport_packet_sent(); 1032 1033 return 0; 1034 #else 1035 int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size); 1036 if (hci_transport_synchronous()){ 1037 hci_release_packet_buffer(); 1038 hci_emit_transport_packet_sent(); 1039 } 1040 1041 if (err != 0){ 1042 return ERROR_CODE_HARDWARE_FAILURE; 1043 } 1044 return ERROR_CODE_SUCCESS; 1045 #endif 1046 } 1047 #endif 1048 1049 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 1050 static uint8_t hci_send_iso_packet_fragments(void){ 1051 1052 uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length; 1053 uint8_t status = ERROR_CODE_SUCCESS; 1054 // multiple packets could be send on a synchronous HCI transport 1055 while (true){ 1056 1057 // get current data 1058 const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u; 1059 int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos; 1060 bool more_fragments = false; 1061 1062 // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 1063 if (current_iso_data_packet_length > max_iso_data_packet_length){ 1064 more_fragments = true; 1065 current_iso_data_packet_length = max_iso_data_packet_length; 1066 } 1067 1068 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 1069 uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1070 uint8_t pb_flags; 1071 if (iso_header_pos == 0u){ 1072 // first fragment, keep TS field 1073 pb_flags = more_fragments ? 0x00 : 0x02; 1074 handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u); 1075 } else { 1076 // later fragment, drop TS field 1077 pb_flags = more_fragments ? 0x01 : 0x03; 1078 handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u); 1079 } 1080 little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags); 1081 1082 // update header len 1083 little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length); 1084 1085 // update state for next fragment (if any) as "transport done" might be sent during send_packet already 1086 if (more_fragments){ 1087 // update start of next fragment to send 1088 hci_stack->iso_fragmentation_pos += current_iso_data_packet_length; 1089 } else { 1090 // done 1091 hci_stack->iso_fragmentation_pos = 0; 1092 hci_stack->iso_fragmentation_total_size = 0; 1093 } 1094 1095 // send packet 1096 uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos]; 1097 const int size = current_iso_data_packet_length + 4; 1098 hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size); 1099 hci_stack->iso_fragmentation_tx_active = true; 1100 int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size); 1101 if (err != 0){ 1102 // no error from HCI Transport expected 1103 status = ERROR_CODE_HARDWARE_FAILURE; 1104 } 1105 1106 // done yet? 1107 if (!more_fragments) break; 1108 1109 // can send more? 1110 if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false; 1111 } 1112 1113 // release buffer now for synchronous transport 1114 if (hci_transport_synchronous()){ 1115 hci_stack->iso_fragmentation_tx_active = false; 1116 hci_release_packet_buffer(); 1117 hci_emit_transport_packet_sent(); 1118 } 1119 1120 return status; 1121 } 1122 1123 uint8_t hci_send_iso_packet_buffer(uint16_t size){ 1124 btstack_assert(hci_stack->hci_packet_buffer_reserved); 1125 1126 hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff; 1127 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle); 1128 if (iso_stream == NULL){ 1129 hci_release_packet_buffer(); 1130 hci_iso_notify_can_send_now(); 1131 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 1132 } 1133 1134 // TODO: check for space on controller 1135 1136 // skip iso packets if needed 1137 if (iso_stream->num_packets_to_skip > 0){ 1138 iso_stream->num_packets_to_skip--; 1139 // pretend it was processed and trigger next one 1140 hci_release_packet_buffer(); 1141 hci_iso_notify_can_send_now(); 1142 return ERROR_CODE_SUCCESS; 1143 } 1144 1145 // track outgoing packet sent 1146 log_info("Outgoing ISO packet for con handle 0x%04x", con_handle); 1147 iso_stream->num_packets_sent++; 1148 1149 // setup data 1150 hci_stack->iso_fragmentation_total_size = size; 1151 hci_stack->iso_fragmentation_pos = 4; // start of L2CAP packet 1152 1153 return hci_send_iso_packet_fragments(); 1154 } 1155 #endif 1156 1157 static void acl_handler(uint8_t *packet, uint16_t size){ 1158 1159 // get info 1160 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 1161 hci_connection_t *conn = hci_connection_for_handle(con_handle); 1162 uint8_t acl_flags = READ_ACL_FLAGS(packet); 1163 uint16_t acl_length = READ_ACL_LENGTH(packet); 1164 1165 // ignore non-registered handle 1166 if (!conn){ 1167 log_error("acl_handler called with non-registered handle %u!" , con_handle); 1168 return; 1169 } 1170 1171 // assert packet is complete 1172 if ((acl_length + 4u) != size){ 1173 log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4); 1174 return; 1175 } 1176 1177 #ifdef ENABLE_CLASSIC 1178 // update idle timestamp 1179 hci_connection_timestamp(conn); 1180 #endif 1181 1182 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 1183 hci_stack->host_completed_packets = 1; 1184 conn->num_packets_completed++; 1185 #endif 1186 1187 // handle different packet types 1188 switch (acl_flags & 0x03u) { 1189 1190 case 0x01: // continuation fragment 1191 1192 // sanity checks 1193 if (conn->acl_recombination_pos == 0u) { 1194 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle); 1195 return; 1196 } 1197 if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){ 1198 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x", 1199 conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 1200 conn->acl_recombination_pos = 0; 1201 return; 1202 } 1203 1204 // append fragment payload (header already stored) 1205 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], 1206 &packet[4], acl_length); 1207 conn->acl_recombination_pos += acl_length; 1208 1209 // forward complete L2CAP packet if complete. 1210 if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header 1211 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos); 1212 // reset recombination buffer 1213 conn->acl_recombination_length = 0; 1214 conn->acl_recombination_pos = 0; 1215 } 1216 break; 1217 1218 case 0x02: { // first fragment 1219 1220 // sanity check 1221 if (conn->acl_recombination_pos) { 1222 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet 1223 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){ 1224 log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle); 1225 } 1226 conn->acl_recombination_pos = 0; 1227 } 1228 1229 // peek into L2CAP packet! 1230 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 1231 1232 // compare fragment size to L2CAP packet size 1233 if (acl_length >= (l2cap_length + 4u)){ 1234 // forward fragment as L2CAP packet 1235 hci_emit_acl_packet(packet, acl_length + 4u); 1236 } else { 1237 1238 if (acl_length > HCI_ACL_BUFFER_SIZE){ 1239 log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x", 1240 4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 1241 return; 1242 } 1243 1244 // store first fragment and tweak acl length for complete package 1245 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], 1246 packet, acl_length + 4u); 1247 conn->acl_recombination_pos = acl_length + 4u; 1248 conn->acl_recombination_length = l2cap_length; 1249 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u); 1250 } 1251 break; 1252 1253 } 1254 default: 1255 log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03); 1256 return; 1257 } 1258 1259 // execute main loop 1260 hci_run(); 1261 } 1262 1263 static void hci_connection_stop_timer(hci_connection_t * conn){ 1264 btstack_run_loop_remove_timer(&conn->timeout); 1265 #ifdef ENABLE_CLASSIC 1266 btstack_run_loop_remove_timer(&conn->timeout_sco); 1267 #endif 1268 } 1269 1270 static void hci_shutdown_connection(hci_connection_t *conn){ 1271 log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1272 1273 #ifdef ENABLE_CLASSIC 1274 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT) 1275 bd_addr_type_t addr_type = conn->address_type; 1276 #endif 1277 #ifdef HAVE_SCO_TRANSPORT 1278 hci_con_handle_t con_handle = conn->con_handle; 1279 #endif 1280 #endif 1281 1282 hci_connection_stop_timer(conn); 1283 1284 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 1285 btstack_memory_hci_connection_free( conn ); 1286 1287 // now it's gone 1288 hci_emit_nr_connections_changed(); 1289 1290 #ifdef ENABLE_CLASSIC 1291 #ifdef ENABLE_SCO_OVER_HCI 1292 // update SCO 1293 if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){ 1294 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 1295 } 1296 #endif 1297 #ifdef HAVE_SCO_TRANSPORT 1298 if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){ 1299 hci_stack->sco_transport->close(con_handle); 1300 } 1301 #endif 1302 #endif 1303 } 1304 1305 #ifdef ENABLE_CLASSIC 1306 1307 static const uint16_t packet_type_sizes[] = { 1308 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 1309 HCI_ACL_DH1_SIZE, 0, 0, 0, 1310 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 1311 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 1312 }; 1313 static const uint8_t packet_type_feature_requirement_bit[] = { 1314 0, // 3 slot packets 1315 1, // 5 slot packets 1316 25, // EDR 2 mpbs 1317 26, // EDR 3 mbps 1318 39, // 3 slot EDR packts 1319 40, // 5 slot EDR packet 1320 }; 1321 static const uint16_t packet_type_feature_packet_mask[] = { 1322 0x0f00, // 3 slot packets 1323 0xf000, // 5 slot packets 1324 0x1102, // EDR 2 mpbs 1325 0x2204, // EDR 3 mbps 1326 0x0300, // 3 slot EDR packts 1327 0x3000, // 5 slot EDR packet 1328 }; 1329 1330 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 1331 // enable packet types based on size 1332 uint16_t packet_types = 0; 1333 unsigned int i; 1334 for (i=0;i<16;i++){ 1335 if (packet_type_sizes[i] == 0) continue; 1336 if (packet_type_sizes[i] <= buffer_size){ 1337 packet_types |= 1 << i; 1338 } 1339 } 1340 // disable packet types due to missing local supported features 1341 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 1342 unsigned int bit_idx = packet_type_feature_requirement_bit[i]; 1343 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 1344 if (feature_set) continue; 1345 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 1346 packet_types &= ~packet_type_feature_packet_mask[i]; 1347 } 1348 // flip bits for "may not be used" 1349 packet_types ^= 0x3306; 1350 return packet_types; 1351 } 1352 1353 uint16_t hci_usable_acl_packet_types(void){ 1354 return hci_stack->packet_types; 1355 } 1356 #endif 1357 1358 uint8_t* hci_get_outgoing_packet_buffer(void){ 1359 // hci packet buffer is >= acl data packet length 1360 return hci_stack->hci_packet_buffer; 1361 } 1362 1363 uint16_t hci_max_acl_data_packet_length(void){ 1364 return hci_stack->acl_data_packet_length; 1365 } 1366 1367 #ifdef ENABLE_CLASSIC 1368 bool hci_extended_sco_link_supported(void){ 1369 // No. 31, byte 3, bit 7 1370 return (hci_stack->local_supported_features[3] & (1 << 7)) != 0; 1371 } 1372 #endif 1373 1374 bool hci_non_flushable_packet_boundary_flag_supported(void){ 1375 // No. 54, byte 6, bit 6 1376 return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u; 1377 } 1378 1379 #ifdef ENABLE_CLASSIC 1380 static int gap_ssp_supported(void){ 1381 // No. 51, byte 6, bit 3 1382 return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u; 1383 } 1384 #endif 1385 1386 static int hci_classic_supported(void){ 1387 #ifdef ENABLE_CLASSIC 1388 // No. 37, byte 4, bit 5, = No BR/EDR Support 1389 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 1390 #else 1391 return 0; 1392 #endif 1393 } 1394 1395 static int hci_le_supported(void){ 1396 #ifdef ENABLE_BLE 1397 // No. 37, byte 4, bit 6 = LE Supported (Controller) 1398 return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u; 1399 #else 1400 return 0; 1401 #endif 1402 } 1403 1404 static bool hci_command_supported(uint8_t command_index){ 1405 return (hci_stack->local_supported_commands & (1LU << command_index)) != 0; 1406 } 1407 1408 #ifdef ENABLE_BLE 1409 1410 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 1411 static bool hci_extended_advertising_supported(void){ 1412 return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE); 1413 } 1414 #endif 1415 1416 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){ 1417 if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){ 1418 (void)memcpy(own_addr, hci_stack->local_bd_addr, 6); 1419 } else { 1420 (void)memcpy(own_addr, hci_stack->le_random_address, 6); 1421 } 1422 } 1423 1424 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){ 1425 *addr_type = hci_stack->le_own_addr_type; 1426 hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr); 1427 } 1428 1429 #ifdef ENABLE_LE_PERIPHERAL 1430 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){ 1431 *addr_type = hci_stack->le_advertisements_own_addr_type; 1432 hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr); 1433 }; 1434 #endif 1435 1436 #ifdef ENABLE_LE_CENTRAL 1437 1438 /** 1439 * @brief Get own addr type and address used for LE connections (Central) 1440 */ 1441 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){ 1442 *addr_type = hci_stack->le_connection_own_addr_type; 1443 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr); 1444 } 1445 1446 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){ 1447 1448 uint16_t offset = 3; 1449 uint8_t num_reports = packet[offset]; 1450 offset += 1; 1451 1452 uint16_t i; 1453 uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var 1454 for (i=0; (i<num_reports) && (offset < size);i++){ 1455 // sanity checks on data_length: 1456 uint8_t data_length = packet[offset + 8]; 1457 if (data_length > LE_ADVERTISING_DATA_SIZE) return; 1458 if ((offset + 9u + data_length + 1u) > size) return; 1459 // setup event 1460 uint8_t event_size = 10u + data_length; 1461 uint16_t pos = 0; 1462 event[pos++] = GAP_EVENT_ADVERTISING_REPORT; 1463 event[pos++] = event_size; 1464 (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address 1465 offset += 8; 1466 pos += 8; 1467 event[pos++] = packet[offset + 1 + data_length]; // rssi 1468 event[pos++] = data_length; 1469 offset++; 1470 (void)memcpy(&event[pos], &packet[offset], data_length); 1471 pos += data_length; 1472 offset += data_length + 1u; // rssi 1473 hci_emit_event(event, pos, 1); 1474 } 1475 } 1476 1477 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 1478 void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) { 1479 uint16_t offset = 3; 1480 uint8_t num_reports = packet[offset++]; 1481 uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var 1482 uint8_t i; 1483 for (i=0; (i<num_reports) && (offset < size);i++){ 1484 // sanity checks on data_length: 1485 uint16_t data_length = packet[offset + 23]; 1486 if (data_length > LE_ADVERTISING_DATA_SIZE) return; 1487 if ((offset + 24u + data_length) > size) return; 1488 uint16_t event_type = little_endian_read_16(packet, offset); 1489 offset += 2; 1490 if ((event_type & 0x10) != 0) { 1491 // setup legacy event 1492 uint8_t legacy_event_type; 1493 switch (event_type){ 1494 case 0b0010011: 1495 // ADV_IND 1496 legacy_event_type = 0; 1497 break; 1498 case 0b0010101: 1499 // ADV_DIRECT_IND 1500 legacy_event_type = 1; 1501 break; 1502 case 0b0010010: 1503 // ADV_SCAN_IND 1504 legacy_event_type = 2; 1505 break; 1506 case 0b0010000: 1507 // ADV_NONCONN_IND 1508 legacy_event_type = 3; 1509 break; 1510 case 0b0011011: 1511 case 0b0011010: 1512 // SCAN_RSP 1513 legacy_event_type = 4; 1514 break; 1515 default: 1516 legacy_event_type = 0; 1517 break; 1518 } 1519 uint16_t pos = 0; 1520 event[pos++] = GAP_EVENT_ADVERTISING_REPORT; 1521 event[pos++] = 10u + data_length; 1522 event[pos++] = legacy_event_type; 1523 // copy address type + address 1524 (void) memcpy(&event[pos], &packet[offset], 1 + 6); 1525 offset += 7; 1526 pos += 7; 1527 // skip primary_phy, secondary_phy, advertising_sid, tx_power 1528 offset += 4; 1529 // copy rssi 1530 event[pos++] = packet[offset++]; 1531 // skip periodic advertising interval and direct address 1532 offset += 9; 1533 // copy data len + data; 1534 (void) memcpy(&event[pos], &packet[offset], 1 + data_length); 1535 pos += 1 +data_length; 1536 offset += 1+ data_length; 1537 hci_emit_event(event, pos, 1); 1538 } else { 1539 event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT; 1540 uint8_t report_len = 24 + data_length; 1541 event[1] = report_len; 1542 little_endian_store_16(event, 2, event_type); 1543 memcpy(&event[4], &packet[offset], report_len); 1544 offset += report_len; 1545 hci_emit_event(event, 2 + report_len, 1); 1546 } 1547 } 1548 } 1549 #endif 1550 1551 #endif 1552 #endif 1553 1554 #ifdef ENABLE_BLE 1555 #ifdef ENABLE_LE_PERIPHERAL 1556 static void hci_update_advertisements_enabled_for_current_roles(void){ 1557 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){ 1558 // get number of active le slave connections 1559 int num_slave_connections = 0; 1560 btstack_linked_list_iterator_t it; 1561 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 1562 while (btstack_linked_list_iterator_has_next(&it)){ 1563 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 1564 log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con)); 1565 if (con->state != OPEN) continue; 1566 if (con->role != HCI_ROLE_SLAVE) continue; 1567 if (!hci_is_le_connection(con)) continue; 1568 num_slave_connections++; 1569 } 1570 log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections); 1571 hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections; 1572 } else { 1573 hci_stack->le_advertisements_enabled_for_current_roles = false; 1574 } 1575 } 1576 #endif 1577 #endif 1578 1579 #ifdef ENABLE_CLASSIC 1580 static void gap_run_set_local_name(void){ 1581 hci_reserve_packet_buffer(); 1582 uint8_t * packet = hci_stack->hci_packet_buffer; 1583 // construct HCI Command and send 1584 uint16_t opcode = hci_write_local_name.opcode; 1585 hci_stack->last_cmd_opcode = opcode; 1586 packet[0] = opcode & 0xff; 1587 packet[1] = opcode >> 8; 1588 packet[2] = DEVICE_NAME_LEN; 1589 memset(&packet[3], 0, DEVICE_NAME_LEN); 1590 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name); 1591 uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN); 1592 // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call 1593 (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy); 1594 // expand '00:00:00:00:00:00' in name with bd_addr 1595 btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr); 1596 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN); 1597 } 1598 1599 static void gap_run_set_eir_data(void){ 1600 hci_reserve_packet_buffer(); 1601 uint8_t * packet = hci_stack->hci_packet_buffer; 1602 // construct HCI Command in-place and send 1603 uint16_t opcode = hci_write_extended_inquiry_response.opcode; 1604 hci_stack->last_cmd_opcode = opcode; 1605 uint16_t offset = 0; 1606 packet[offset++] = opcode & 0xff; 1607 packet[offset++] = opcode >> 8; 1608 packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN; 1609 packet[offset++] = 0; // FEC not required 1610 memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN); 1611 if (hci_stack->eir_data){ 1612 // copy items and expand '00:00:00:00:00:00' in name with bd_addr 1613 ad_context_t context; 1614 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) { 1615 uint8_t data_type = ad_iterator_get_data_type(&context); 1616 uint8_t size = ad_iterator_get_data_len(&context); 1617 const uint8_t *data = ad_iterator_get_data(&context); 1618 // copy item 1619 packet[offset++] = size + 1; 1620 packet[offset++] = data_type; 1621 memcpy(&packet[offset], data, size); 1622 // update name item 1623 if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){ 1624 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr); 1625 } 1626 offset += size; 1627 } 1628 } else { 1629 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name); 1630 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2); 1631 packet[offset++] = bytes_to_copy + 1; 1632 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME; 1633 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy); 1634 // expand '00:00:00:00:00:00' in name with bd_addr 1635 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr); 1636 } 1637 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN); 1638 } 1639 1640 static void hci_run_gap_tasks_classic(void){ 1641 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) { 1642 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE; 1643 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 1644 return; 1645 } 1646 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) { 1647 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME; 1648 gap_run_set_local_name(); 1649 return; 1650 } 1651 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) { 1652 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA; 1653 gap_run_set_eir_data(); 1654 return; 1655 } 1656 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) { 1657 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY; 1658 hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings); 1659 return; 1660 } 1661 // write page scan activity 1662 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) { 1663 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY; 1664 hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window); 1665 return; 1666 } 1667 // write page scan type 1668 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) { 1669 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE; 1670 hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type); 1671 return; 1672 } 1673 // write page timeout 1674 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) { 1675 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT; 1676 hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout); 1677 return; 1678 } 1679 // send scan enable 1680 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) { 1681 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE; 1682 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 1683 return; 1684 } 1685 // send write scan activity 1686 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) { 1687 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY; 1688 hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window); 1689 return; 1690 } 1691 } 1692 #endif 1693 1694 #ifndef HAVE_HOST_CONTROLLER_API 1695 1696 static uint32_t hci_transport_uart_get_main_baud_rate(void){ 1697 if (!hci_stack->config) return 0; 1698 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1699 // Limit baud rate for Broadcom chipsets to 3 mbps 1700 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){ 1701 baud_rate = 3000000; 1702 } 1703 return baud_rate; 1704 } 1705 1706 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){ 1707 UNUSED(ds); 1708 1709 switch (hci_stack->substate){ 1710 case HCI_INIT_W4_SEND_RESET: 1711 log_info("Resend HCI Reset"); 1712 hci_stack->substate = HCI_INIT_SEND_RESET; 1713 hci_stack->num_cmd_packets = 1; 1714 hci_run(); 1715 break; 1716 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET: 1717 log_info("Resend HCI Reset - CSR Warm Boot with Link Reset"); 1718 if (hci_stack->hci_transport->reset_link){ 1719 hci_stack->hci_transport->reset_link(); 1720 } 1721 1722 /* fall through */ 1723 1724 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 1725 log_info("Resend HCI Reset - CSR Warm Boot"); 1726 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1727 hci_stack->num_cmd_packets = 1; 1728 hci_run(); 1729 break; 1730 case HCI_INIT_W4_SEND_BAUD_CHANGE: 1731 if (hci_stack->hci_transport->set_baudrate){ 1732 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1733 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate); 1734 hci_stack->hci_transport->set_baudrate(baud_rate); 1735 } 1736 // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP 1737 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 1738 if (hci_stack->hci_transport->reset_link){ 1739 log_info("Link Reset"); 1740 hci_stack->hci_transport->reset_link(); 1741 } 1742 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1743 hci_run(); 1744 } 1745 break; 1746 case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY: 1747 // otherwise continue 1748 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1749 hci_send_cmd(&hci_read_local_supported_commands); 1750 break; 1751 default: 1752 break; 1753 } 1754 } 1755 #endif 1756 1757 static void hci_initializing_next_state(void){ 1758 hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1); 1759 } 1760 1761 static void hci_init_done(void){ 1762 // done. tell the app 1763 log_info("hci_init_done -> HCI_STATE_WORKING"); 1764 hci_stack->state = HCI_STATE_WORKING; 1765 hci_emit_state(); 1766 } 1767 1768 // assumption: hci_can_send_command_packet_now() == true 1769 static void hci_initializing_run(void){ 1770 log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now()); 1771 1772 if (!hci_can_send_command_packet_now()) return; 1773 1774 #ifndef HAVE_HOST_CONTROLLER_API 1775 bool need_baud_change = hci_stack->config 1776 && hci_stack->chipset 1777 && hci_stack->chipset->set_baudrate_command 1778 && hci_stack->hci_transport->set_baudrate 1779 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1780 #endif 1781 1782 switch (hci_stack->substate){ 1783 case HCI_INIT_SEND_RESET: 1784 hci_state_reset(); 1785 1786 #ifndef HAVE_HOST_CONTROLLER_API 1787 // prepare reset if command complete not received in 100ms 1788 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1789 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1790 btstack_run_loop_add_timer(&hci_stack->timeout); 1791 #endif 1792 // send command 1793 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 1794 hci_send_cmd(&hci_reset); 1795 break; 1796 case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION: 1797 hci_send_cmd(&hci_read_local_version_information); 1798 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION; 1799 break; 1800 1801 #ifndef HAVE_HOST_CONTROLLER_API 1802 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 1803 hci_state_reset(); 1804 // prepare reset if command complete not received in 100ms 1805 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1806 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1807 btstack_run_loop_add_timer(&hci_stack->timeout); 1808 // send command 1809 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 1810 hci_send_cmd(&hci_reset); 1811 break; 1812 case HCI_INIT_SEND_RESET_ST_WARM_BOOT: 1813 hci_state_reset(); 1814 hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT; 1815 hci_send_cmd(&hci_reset); 1816 break; 1817 case HCI_INIT_SEND_BAUD_CHANGE_BCM: { 1818 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1819 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1820 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1821 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM; 1822 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1823 break; 1824 } 1825 case HCI_INIT_SET_BD_ADDR: 1826 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr)); 1827 hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer); 1828 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1829 hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR; 1830 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1831 break; 1832 case HCI_INIT_SEND_READ_LOCAL_NAME: 1833 #ifdef ENABLE_CLASSIC 1834 hci_send_cmd(&hci_read_local_name); 1835 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME; 1836 break; 1837 #endif 1838 /* fall through */ 1839 1840 case HCI_INIT_SEND_BAUD_CHANGE: 1841 if (need_baud_change) { 1842 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1843 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1844 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1845 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1846 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1847 // STLC25000D: baudrate change happens within 0.5 s after command was send, 1848 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial) 1849 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){ 1850 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1851 btstack_run_loop_add_timer(&hci_stack->timeout); 1852 } 1853 break; 1854 } 1855 1856 /* fall through */ 1857 1858 case HCI_INIT_CUSTOM_INIT: 1859 // Custom initialization 1860 if (hci_stack->chipset && hci_stack->chipset->next_command){ 1861 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer); 1862 bool send_cmd = false; 1863 switch (hci_stack->chipset_result){ 1864 case BTSTACK_CHIPSET_VALID_COMMAND: 1865 send_cmd = true; 1866 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT; 1867 break; 1868 case BTSTACK_CHIPSET_WARMSTART_REQUIRED: 1869 send_cmd = true; 1870 // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete 1871 log_info("CSR Warm Boot"); 1872 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1873 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1874 btstack_run_loop_add_timer(&hci_stack->timeout); 1875 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO) 1876 && hci_stack->config 1877 && hci_stack->chipset 1878 // && hci_stack->chipset->set_baudrate_command -- there's no such command 1879 && hci_stack->hci_transport->set_baudrate 1880 && hci_transport_uart_get_main_baud_rate()){ 1881 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1882 } else { 1883 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET; 1884 } 1885 break; 1886 default: 1887 break; 1888 } 1889 1890 if (send_cmd){ 1891 int size = 3u + hci_stack->hci_packet_buffer[2u]; 1892 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1893 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size); 1894 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 1895 break; 1896 } 1897 log_info("Init script done"); 1898 1899 // Init script download on Broadcom chipsets causes: 1900 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) && 1901 ( (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) 1902 || (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){ 1903 1904 // - baud rate to reset, restore UART baud rate if needed 1905 if (need_baud_change) { 1906 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init; 1907 log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate); 1908 hci_stack->hci_transport->set_baudrate(baud_rate); 1909 } 1910 1911 uint16_t bcm_delay_ms = 300; 1912 // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time 1913 // -> Work around: wait here. 1914 log_info("BCM delay (%u ms) after init script", bcm_delay_ms); 1915 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY; 1916 btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms); 1917 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1918 btstack_run_loop_add_timer(&hci_stack->timeout); 1919 break; 1920 } 1921 } 1922 #endif 1923 /* fall through */ 1924 1925 case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS: 1926 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1927 hci_send_cmd(&hci_read_local_supported_commands); 1928 break; 1929 case HCI_INIT_READ_BD_ADDR: 1930 hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR; 1931 hci_send_cmd(&hci_read_bd_addr); 1932 break; 1933 case HCI_INIT_READ_BUFFER_SIZE: 1934 // only read buffer size if supported 1935 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){ 1936 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE; 1937 hci_send_cmd(&hci_read_buffer_size); 1938 break; 1939 } 1940 1941 /* fall through */ 1942 1943 case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES: 1944 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES; 1945 hci_send_cmd(&hci_read_local_supported_features); 1946 break; 1947 1948 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 1949 case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL: 1950 hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL; 1951 hci_send_cmd(&hci_set_controller_to_host_flow_control, 3); // ACL + SCO Flow Control 1952 break; 1953 case HCI_INIT_HOST_BUFFER_SIZE: 1954 hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE; 1955 hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN, 1956 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM); 1957 break; 1958 #endif 1959 1960 case HCI_INIT_SET_EVENT_MASK: 1961 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK; 1962 if (hci_le_supported()){ 1963 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU); 1964 } else { 1965 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1966 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU); 1967 } 1968 break; 1969 1970 case HCI_INIT_SET_EVENT_MASK_2: 1971 // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244, 1972 // setting Event Mask 2 causes Controller to drop Encryption Change events. 1973 if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2) 1974 && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){ 1975 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2; 1976 // Encryption Change Event v2 - bit 25 1977 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0); 1978 break; 1979 } 1980 1981 #ifdef ENABLE_CLASSIC 1982 /* fall through */ 1983 1984 case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE: 1985 if (hci_classic_supported() && gap_ssp_supported()){ 1986 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE; 1987 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 1988 break; 1989 } 1990 1991 /* fall through */ 1992 1993 case HCI_INIT_WRITE_INQUIRY_MODE: 1994 if (hci_classic_supported()){ 1995 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE; 1996 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode); 1997 break; 1998 } 1999 2000 /* fall through */ 2001 2002 case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE: 2003 // skip write secure connections host support if not supported or disabled 2004 if (hci_classic_supported() && hci_stack->secure_connections_enable 2005 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) { 2006 hci_stack->secure_connections_active = true; 2007 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE; 2008 hci_send_cmd(&hci_write_secure_connections_host_support, 1); 2009 break; 2010 } 2011 2012 /* fall through */ 2013 2014 case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE: 2015 // skip set min encryption key size 2016 if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) { 2017 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE; 2018 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size); 2019 break; 2020 } 2021 2022 #ifdef ENABLE_SCO_OVER_HCI 2023 /* fall through */ 2024 2025 // only sent if ENABLE_SCO_OVER_HCI is defined 2026 case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 2027 // skip write synchronous flow control if not supported 2028 if (hci_classic_supported() 2029 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) { 2030 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE; 2031 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled 2032 break; 2033 } 2034 /* fall through */ 2035 2036 case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING: 2037 // skip write default erroneous data reporting if not supported 2038 if (hci_classic_supported() 2039 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) { 2040 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING; 2041 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1); 2042 break; 2043 } 2044 #endif 2045 2046 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM) 2047 /* fall through */ 2048 2049 // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined 2050 case HCI_INIT_BCM_WRITE_SCO_PCM_INT: 2051 if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){ 2052 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT; 2053 #ifdef ENABLE_SCO_OVER_HCI 2054 log_info("BCM: Route SCO data via HCI transport"); 2055 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0); 2056 #endif 2057 #ifdef ENABLE_SCO_OVER_PCM 2058 log_info("BCM: Route SCO data via PCM interface"); 2059 #ifdef ENABLE_BCM_PCM_WBS 2060 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz 2061 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1); 2062 #else 2063 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz 2064 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1); 2065 #endif 2066 #endif 2067 break; 2068 } 2069 #endif 2070 2071 #ifdef ENABLE_SCO_OVER_PCM 2072 /* fall through */ 2073 2074 case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM: 2075 if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){ 2076 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM; 2077 log_info("BCM: Config PCM interface for I2S"); 2078 #ifdef ENABLE_BCM_PCM_WBS 2079 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz 2080 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2); 2081 #else 2082 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz 2083 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1); 2084 #endif 2085 break; 2086 } 2087 #endif 2088 #endif 2089 2090 #ifdef ENABLE_BLE 2091 /* fall through */ 2092 2093 // LE INIT 2094 case HCI_INIT_LE_READ_BUFFER_SIZE: 2095 if (hci_le_supported()){ 2096 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE; 2097 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){ 2098 hci_send_cmd(&hci_le_read_buffer_size_v2); 2099 } else { 2100 hci_send_cmd(&hci_le_read_buffer_size); 2101 } 2102 break; 2103 } 2104 2105 /* fall through */ 2106 2107 case HCI_INIT_WRITE_LE_HOST_SUPPORTED: 2108 // skip write le host if not supported (e.g. on LE only EM9301) 2109 if (hci_le_supported() 2110 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) { 2111 // LE Supported Host = 1, Simultaneous Host = 0 2112 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED; 2113 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 2114 break; 2115 } 2116 2117 /* fall through */ 2118 2119 case HCI_INIT_LE_SET_EVENT_MASK: 2120 if (hci_le_supported()){ 2121 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK; 2122 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x07); // all events from core v5.3 without LE Enhanced Connection Complete 2123 break; 2124 } 2125 #endif 2126 2127 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 2128 /* fall through */ 2129 2130 case HCI_INIT_LE_READ_MAX_DATA_LENGTH: 2131 if (hci_le_supported() 2132 && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) { 2133 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH; 2134 hci_send_cmd(&hci_le_read_maximum_data_length); 2135 break; 2136 } 2137 2138 /* fall through */ 2139 2140 case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH: 2141 if (hci_le_supported() 2142 && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) { 2143 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH; 2144 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 2145 break; 2146 } 2147 #endif 2148 2149 #ifdef ENABLE_LE_CENTRAL 2150 /* fall through */ 2151 2152 case HCI_INIT_READ_WHITE_LIST_SIZE: 2153 if (hci_le_supported()){ 2154 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE; 2155 hci_send_cmd(&hci_le_read_white_list_size); 2156 break; 2157 } 2158 2159 #endif 2160 2161 #ifdef ENABLE_LE_PERIPHERAL 2162 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 2163 /* fall through */ 2164 2165 case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN: 2166 if (hci_extended_advertising_supported()){ 2167 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN; 2168 hci_send_cmd(&hci_le_read_maximum_advertising_data_length); 2169 break; 2170 } 2171 #endif 2172 #endif 2173 /* fall through */ 2174 2175 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2176 case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS: 2177 if (hci_le_supported()) { 2178 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS; 2179 hci_send_cmd(&hci_le_set_host_feature, 32, 1); 2180 break; 2181 } 2182 #endif 2183 2184 /* fall through */ 2185 2186 case HCI_INIT_DONE: 2187 hci_stack->substate = HCI_INIT_DONE; 2188 // main init sequence complete 2189 #ifdef ENABLE_CLASSIC 2190 // check if initial Classic GAP Tasks are completed 2191 if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) { 2192 hci_run_gap_tasks_classic(); 2193 break; 2194 } 2195 #endif 2196 #ifdef ENABLE_BLE 2197 #ifdef ENABLE_LE_CENTRAL 2198 // check if initial LE GAP Tasks are completed 2199 if (hci_le_supported() && hci_stack->le_scanning_param_update) { 2200 hci_run_general_gap_le(); 2201 break; 2202 } 2203 #endif 2204 #endif 2205 hci_init_done(); 2206 break; 2207 2208 default: 2209 return; 2210 } 2211 } 2212 2213 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){ 2214 bool command_completed = false; 2215 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){ 2216 uint16_t opcode = little_endian_read_16(packet,3); 2217 if (opcode == hci_stack->last_cmd_opcode){ 2218 command_completed = true; 2219 log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate); 2220 } else { 2221 log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate); 2222 } 2223 } 2224 2225 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){ 2226 uint8_t status = packet[2]; 2227 uint16_t opcode = little_endian_read_16(packet,4); 2228 if (opcode == hci_stack->last_cmd_opcode){ 2229 if (status){ 2230 command_completed = true; 2231 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate); 2232 } else { 2233 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 2234 } 2235 } else { 2236 log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 2237 } 2238 } 2239 #ifndef HAVE_HOST_CONTROLLER_API 2240 // Vendor == CSR 2241 if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){ 2242 // TODO: track actual command 2243 command_completed = true; 2244 } 2245 2246 // Vendor == Toshiba 2247 if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){ 2248 // TODO: track actual command 2249 command_completed = true; 2250 // Fix: no HCI Command Complete received, so num_cmd_packets not reset 2251 hci_stack->num_cmd_packets = 1; 2252 } 2253 #endif 2254 2255 return command_completed; 2256 } 2257 2258 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){ 2259 2260 UNUSED(size); // ok: less than 6 bytes are read from our buffer 2261 2262 bool command_completed = hci_initializing_event_handler_command_completed(packet); 2263 2264 #ifndef HAVE_HOST_CONTROLLER_API 2265 2266 // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661: 2267 // Command complete for HCI Reset arrives after we've resent the HCI Reset command 2268 // 2269 // HCI Reset 2270 // Timeout 100 ms 2271 // HCI Reset 2272 // Command Complete Reset 2273 // HCI Read Local Version Information 2274 // Command Complete Reset - but we expected Command Complete Read Local Version Information 2275 // hang... 2276 // 2277 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 2278 if (!command_completed 2279 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2280 && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){ 2281 2282 uint16_t opcode = little_endian_read_16(packet,3); 2283 if (opcode == hci_reset.opcode){ 2284 hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION; 2285 return; 2286 } 2287 } 2288 2289 // CSR & H5 2290 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 2291 if (!command_completed 2292 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2293 && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){ 2294 2295 uint16_t opcode = little_endian_read_16(packet,3); 2296 if (opcode == hci_reset.opcode){ 2297 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS; 2298 return; 2299 } 2300 } 2301 2302 // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT 2303 // fix: Correct substate and behave as command below 2304 if (command_completed){ 2305 switch (hci_stack->substate){ 2306 case HCI_INIT_SEND_RESET: 2307 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 2308 break; 2309 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 2310 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 2311 break; 2312 default: 2313 break; 2314 } 2315 } 2316 2317 #endif 2318 2319 if (!command_completed) return; 2320 2321 bool need_baud_change = false; 2322 bool need_addr_change = false; 2323 2324 #ifndef HAVE_HOST_CONTROLLER_API 2325 need_baud_change = hci_stack->config 2326 && hci_stack->chipset 2327 && hci_stack->chipset->set_baudrate_command 2328 && hci_stack->hci_transport->set_baudrate 2329 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 2330 2331 need_addr_change = hci_stack->custom_bd_addr_set 2332 && hci_stack->chipset 2333 && hci_stack->chipset->set_bd_addr_command; 2334 #endif 2335 2336 switch(hci_stack->substate){ 2337 2338 #ifndef HAVE_HOST_CONTROLLER_API 2339 case HCI_INIT_SEND_RESET: 2340 // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET 2341 // fix: just correct substate and behave as command below 2342 2343 /* fall through */ 2344 #endif 2345 2346 case HCI_INIT_W4_SEND_RESET: 2347 btstack_run_loop_remove_timer(&hci_stack->timeout); 2348 hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION; 2349 return; 2350 2351 #ifndef HAVE_HOST_CONTROLLER_API 2352 case HCI_INIT_W4_SEND_BAUD_CHANGE: 2353 // for STLC2500D, baud rate change already happened. 2354 // for others, baud rate gets changed now 2355 if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){ 2356 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 2357 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate); 2358 hci_stack->hci_transport->set_baudrate(baud_rate); 2359 } 2360 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2361 return; 2362 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 2363 btstack_run_loop_remove_timer(&hci_stack->timeout); 2364 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2365 return; 2366 case HCI_INIT_W4_CUSTOM_INIT: 2367 // repeat custom init 2368 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2369 return; 2370 #endif 2371 2372 case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS: 2373 if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) && 2374 ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) || 2375 (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) { 2376 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM; 2377 return; 2378 } 2379 if (need_addr_change){ 2380 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 2381 return; 2382 } 2383 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2384 return; 2385 #ifndef HAVE_HOST_CONTROLLER_API 2386 case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: 2387 if (need_baud_change){ 2388 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 2389 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate); 2390 hci_stack->hci_transport->set_baudrate(baud_rate); 2391 } 2392 if (need_addr_change){ 2393 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 2394 return; 2395 } 2396 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2397 return; 2398 case HCI_INIT_W4_SET_BD_ADDR: 2399 // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command 2400 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) 2401 || (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){ 2402 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT; 2403 return; 2404 } 2405 // skipping st warm boot 2406 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2407 return; 2408 case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT: 2409 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2410 return; 2411 #endif 2412 2413 case HCI_INIT_DONE: 2414 // set state if we came here by fall through 2415 hci_stack->substate = HCI_INIT_DONE; 2416 return; 2417 2418 default: 2419 break; 2420 } 2421 hci_initializing_next_state(); 2422 } 2423 2424 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){ 2425 // CC2564C might emit Connection Complete for rejected incoming SCO connection 2426 // To prevent accidentally free'ing the HCI connection for the ACL connection, 2427 // check if we have been aware of the HCI connection 2428 switch (conn->state){ 2429 case SENT_CREATE_CONNECTION: 2430 case RECEIVED_CONNECTION_REQUEST: 2431 break; 2432 default: 2433 return; 2434 } 2435 2436 log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address)); 2437 bd_addr_t bd_address; 2438 (void)memcpy(&bd_address, conn->address, 6); 2439 2440 #ifdef ENABLE_CLASSIC 2441 // cache needed data 2442 int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED; 2443 #endif 2444 2445 // connection failed, remove entry 2446 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 2447 btstack_memory_hci_connection_free( conn ); 2448 2449 #ifdef ENABLE_CLASSIC 2450 // notify client if dedicated bonding 2451 if (notify_dedicated_bonding_failed){ 2452 log_info("hci notify_dedicated_bonding_failed"); 2453 hci_emit_dedicated_bonding_result(bd_address, status); 2454 } 2455 2456 // if authentication error, also delete link key 2457 if (status == ERROR_CODE_AUTHENTICATION_FAILURE) { 2458 gap_drop_link_key_for_bd_addr(bd_address); 2459 } 2460 #else 2461 UNUSED(status); 2462 #endif 2463 } 2464 2465 #ifdef ENABLE_CLASSIC 2466 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){ 2467 // SSP Controller 2468 if (features[6] & (1 << 3)){ 2469 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER; 2470 } 2471 // eSCO 2472 if (features[3] & (1<<7)){ 2473 conn->remote_supported_features[0] |= 1; 2474 } 2475 // Extended features 2476 if (features[7] & (1<<7)){ 2477 conn->remote_supported_features[0] |= 2; 2478 } 2479 } 2480 2481 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){ 2482 // SSP Host 2483 if (features[0] & (1 << 0)){ 2484 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST; 2485 } 2486 // SC Host 2487 if (features[0] & (1 << 3)){ 2488 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST; 2489 } 2490 } 2491 2492 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){ 2493 // SC Controller 2494 if (features[1] & (1 << 0)){ 2495 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 2496 } 2497 } 2498 2499 static void hci_handle_remote_features_received(hci_connection_t * conn){ 2500 conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE; 2501 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 2502 log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags); 2503 if (conn->bonding_flags & BONDING_DEDICATED){ 2504 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2505 } 2506 } 2507 static bool hci_remote_sc_enabled(hci_connection_t * connection){ 2508 const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 2509 return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask; 2510 } 2511 2512 #endif 2513 2514 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) { 2515 // handle BT initialization 2516 if (hci_stack->state == HCI_STATE_INITIALIZING) { 2517 hci_initializing_event_handler(packet, size); 2518 } 2519 2520 // help with BT sleep 2521 if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP) 2522 && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE) 2523 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2524 && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){ 2525 hci_initializing_next_state(); 2526 } 2527 } 2528 2529 #ifdef ENABLE_CLASSIC 2530 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) { 2531 conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED; 2532 conn->encryption_key_size = encryption_key_size; 2533 gap_security_level_t security_level = gap_security_level_for_connection(conn); 2534 2535 // trigger disconnect for dedicated bonding, skip emit security level as disconnect is pending 2536 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 2537 conn->bonding_flags &= ~BONDING_DEDICATED; 2538 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 2539 conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS; 2540 return; 2541 } 2542 2543 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) { 2544 conn->requested_security_level = LEVEL_0; 2545 hci_emit_security_level(conn->con_handle, security_level); 2546 return; 2547 } 2548 2549 // Request remote features if not already done 2550 hci_trigger_remote_features_for_connection(conn); 2551 2552 // Request Authentication if not already done 2553 if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return; 2554 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2555 } 2556 #endif 2557 2558 static void hci_store_local_supported_commands(const uint8_t * packet){ 2559 // create mapping table 2560 #define X(name, offset, bit) { offset, bit }, 2561 static struct { 2562 uint8_t byte_offset; 2563 uint8_t bit_position; 2564 } supported_hci_commands_map [] = { 2565 SUPPORTED_HCI_COMMANDS 2566 }; 2567 #undef X 2568 2569 // create names for debug purposes 2570 #ifdef ENABLE_LOG_DEBUG 2571 #define X(name, offset, bit) #name, 2572 static const char * command_names[] = { 2573 SUPPORTED_HCI_COMMANDS 2574 }; 2575 #undef X 2576 #endif 2577 2578 hci_stack->local_supported_commands = 0; 2579 const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1]; 2580 uint16_t i; 2581 for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){ 2582 if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){ 2583 #ifdef ENABLE_LOG_DEBUG 2584 log_info("Command %s (%u) supported %u/%u", command_names[i], i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position); 2585 #else 2586 log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position); 2587 #endif 2588 hci_stack->local_supported_commands |= (1LU << i); 2589 } 2590 } 2591 log_info("Local supported commands summary %04x", hci_stack->local_supported_commands); 2592 } 2593 2594 static void handle_command_complete_event(uint8_t * packet, uint16_t size){ 2595 UNUSED(size); 2596 2597 uint16_t manufacturer; 2598 #ifdef ENABLE_CLASSIC 2599 hci_con_handle_t handle; 2600 hci_connection_t * conn; 2601 #endif 2602 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS)) 2603 uint8_t status; 2604 #endif 2605 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2606 le_audio_cig_t * cig; 2607 #endif 2608 2609 // get num cmd packets - limit to 1 to reduce complexity 2610 hci_stack->num_cmd_packets = packet[2] ? 1 : 0; 2611 2612 uint16_t opcode = hci_event_command_complete_get_command_opcode(packet); 2613 switch (opcode){ 2614 case HCI_OPCODE_HCI_READ_LOCAL_NAME: 2615 if (packet[5]) break; 2616 // terminate, name 248 chars 2617 packet[6+248] = 0; 2618 log_info("local name: %s", &packet[6]); 2619 break; 2620 case HCI_OPCODE_HCI_READ_BUFFER_SIZE: 2621 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 2622 if (hci_stack->state == HCI_STATE_INITIALIZING) { 2623 uint16_t acl_len = little_endian_read_16(packet, 6); 2624 uint16_t sco_len = packet[8]; 2625 2626 // determine usable ACL/SCO payload size 2627 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE); 2628 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE); 2629 2630 hci_stack->acl_packets_total_num = (uint8_t) little_endian_read_16(packet, 9); 2631 hci_stack->sco_packets_total_num = (uint8_t) little_endian_read_16(packet, 11); 2632 2633 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u", 2634 acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num, 2635 hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num); 2636 } 2637 break; 2638 case HCI_OPCODE_HCI_READ_RSSI: 2639 if (packet[5] == ERROR_CODE_SUCCESS){ 2640 uint8_t event[5]; 2641 event[0] = GAP_EVENT_RSSI_MEASUREMENT; 2642 event[1] = 3; 2643 (void)memcpy(&event[2], &packet[6], 3); 2644 hci_emit_event(event, sizeof(event), 1); 2645 } 2646 break; 2647 #ifdef ENABLE_BLE 2648 case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2: 2649 hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9); 2650 hci_stack->le_iso_packets_total_num = packet[11]; 2651 log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u", 2652 hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num); 2653 2654 /* fall through */ 2655 2656 case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE: 2657 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6); 2658 hci_stack->le_acl_packets_total_num = packet[8]; 2659 // determine usable ACL payload size 2660 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){ 2661 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE; 2662 } 2663 log_info("hci_le_read_buffer_size: acl size %u, acl count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num); 2664 break; 2665 #endif 2666 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 2667 case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH: 2668 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6); 2669 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8); 2670 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 2671 break; 2672 #endif 2673 #ifdef ENABLE_LE_CENTRAL 2674 case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE: 2675 hci_stack->le_whitelist_capacity = packet[6]; 2676 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity); 2677 break; 2678 #endif 2679 #ifdef ENABLE_LE_PERIPHERAL 2680 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 2681 case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH: 2682 hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6); 2683 break; 2684 case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS: 2685 if (hci_stack->le_advertising_set_in_current_command != 0) { 2686 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command); 2687 hci_stack->le_advertising_set_in_current_command = 0; 2688 if (advertising_set == NULL) break; 2689 uint8_t adv_status = packet[6]; 2690 uint8_t tx_power = packet[7]; 2691 uint8_t event[] = { HCI_EVENT_META_GAP, 4, GAP_SUBEVENT_ADVERTISING_SET_INSTALLED, hci_stack->le_advertising_set_in_current_command, adv_status, tx_power }; 2692 if (adv_status == 0){ 2693 advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET; 2694 } 2695 hci_emit_event(event, sizeof(event), 1); 2696 } 2697 break; 2698 case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET: 2699 if (hci_stack->le_advertising_set_in_current_command != 0) { 2700 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command); 2701 hci_stack->le_advertising_set_in_current_command = 0; 2702 if (advertising_set == NULL) break; 2703 uint8_t adv_status = packet[5]; 2704 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status }; 2705 if (adv_status == 0){ 2706 btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set); 2707 } 2708 hci_emit_event(event, sizeof(event), 1); 2709 } 2710 break; 2711 #endif 2712 #endif 2713 case HCI_OPCODE_HCI_READ_BD_ADDR: 2714 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr); 2715 log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 2716 #ifdef ENABLE_CLASSIC 2717 if (hci_stack->link_key_db){ 2718 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr); 2719 } 2720 #endif 2721 break; 2722 #ifdef ENABLE_CLASSIC 2723 case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE: 2724 hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable); 2725 break; 2726 case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE: 2727 status = hci_event_command_complete_get_return_parameters(packet)[0]; 2728 if (status == ERROR_CODE_SUCCESS) { 2729 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC; 2730 } else { 2731 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2732 } 2733 break; 2734 case HCI_OPCODE_HCI_INQUIRY_CANCEL: 2735 case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE: 2736 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){ 2737 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2738 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 2739 hci_emit_event(event, sizeof(event), 1); 2740 } 2741 break; 2742 #endif 2743 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES: 2744 (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8); 2745 2746 #ifdef ENABLE_CLASSIC 2747 // determine usable ACL packet types based on host buffer size and supported features 2748 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]); 2749 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported()); 2750 #endif 2751 // Classic/LE 2752 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 2753 break; 2754 case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION: 2755 manufacturer = little_endian_read_16(packet, 10); 2756 // map Cypress to Broadcom 2757 if (manufacturer == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){ 2758 log_info("Treat Cypress as Broadcom"); 2759 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION; 2760 little_endian_store_16(packet, 10, manufacturer); 2761 } 2762 hci_stack->manufacturer = manufacturer; 2763 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer); 2764 break; 2765 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS: 2766 hci_store_local_supported_commands(packet); 2767 break; 2768 #ifdef ENABLE_CLASSIC 2769 case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 2770 if (packet[5]) return; 2771 hci_stack->synchronous_flow_control_enabled = 1; 2772 break; 2773 case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE: 2774 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2775 handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1); 2776 conn = hci_connection_for_handle(handle); 2777 if (conn != NULL) { 2778 uint8_t key_size = 0; 2779 if (status == 0){ 2780 key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3]; 2781 log_info("Handle %04x key Size: %u", handle, key_size); 2782 } else { 2783 key_size = 1; 2784 log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status); 2785 } 2786 hci_handle_read_encryption_key_size_complete(conn, key_size); 2787 } 2788 break; 2789 // assert pairing complete event is emitted. 2790 // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust 2791 case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY: 2792 case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY: 2793 case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY: 2794 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 2795 // lookup connection by gap pairing addr 2796 conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL); 2797 if (conn == NULL) break; 2798 hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE); 2799 break; 2800 2801 #ifdef ENABLE_CLASSIC_PAIRING_OOB 2802 case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA: 2803 case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{ 2804 uint8_t event[67]; 2805 event[0] = GAP_EVENT_LOCAL_OOB_DATA; 2806 event[1] = 65; 2807 (void)memset(&event[2], 0, 65); 2808 if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){ 2809 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32); 2810 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){ 2811 event[2] = 3; 2812 (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32); 2813 } else { 2814 event[2] = 1; 2815 } 2816 } 2817 hci_emit_event(event, sizeof(event), 0); 2818 break; 2819 } 2820 2821 // note: only needed if user does not provide OOB data 2822 case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY: 2823 conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle); 2824 hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID; 2825 if (conn == NULL) break; 2826 hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE); 2827 break; 2828 #endif 2829 #endif 2830 #ifdef ENABLE_BLE 2831 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2832 case HCI_OPCODE_HCI_LE_SET_CIG_PARAMETERS: 2833 // lookup CIG 2834 cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id); 2835 if (cig != NULL){ 2836 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2837 uint8_t i = 0; 2838 if (status == ERROR_CODE_SUCCESS){ 2839 // assign CIS handles to pre-allocated CIS 2840 btstack_linked_list_iterator_t it; 2841 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 2842 while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) { 2843 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 2844 if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) && 2845 (iso_stream->iso_type == HCI_ISO_TYPE_CIS)){ 2846 hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i)); 2847 iso_stream->con_handle = cis_handle; 2848 cig->cis_con_handles[i] = cis_handle; 2849 i++; 2850 } 2851 } 2852 cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST; 2853 hci_emit_cig_created(cig, status); 2854 } else { 2855 hci_emit_cig_created(cig, status); 2856 btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig); 2857 } 2858 } 2859 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 2860 break; 2861 case HCI_OPCODE_HCI_LE_CREATE_CIS: 2862 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2863 if (status != ERROR_CODE_SUCCESS){ 2864 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID); 2865 } 2866 break; 2867 case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST: 2868 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2869 if (status != ERROR_CODE_SUCCESS){ 2870 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID); 2871 } 2872 break; 2873 case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: { 2874 // lookup BIG by state 2875 btstack_linked_list_iterator_t it; 2876 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 2877 while (btstack_linked_list_iterator_has_next(&it)) { 2878 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 2879 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){ 2880 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2881 if (status == ERROR_CODE_SUCCESS){ 2882 big->state_vars.next_bis++; 2883 if (big->state_vars.next_bis == big->num_bis){ 2884 big->state = LE_AUDIO_BIG_STATE_ACTIVE; 2885 hci_emit_big_created(big, ERROR_CODE_SUCCESS); 2886 } else { 2887 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 2888 } 2889 } else { 2890 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED; 2891 big->state_vars.status = status; 2892 } 2893 return; 2894 } 2895 } 2896 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 2897 while (btstack_linked_list_iterator_has_next(&it)) { 2898 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 2899 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){ 2900 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2901 if (status == ERROR_CODE_SUCCESS){ 2902 big_sync->state_vars.next_bis++; 2903 if (big_sync->state_vars.next_bis == big_sync->num_bis){ 2904 big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE; 2905 hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS); 2906 } else { 2907 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 2908 } 2909 } else { 2910 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED; 2911 big_sync->state_vars.status = status; 2912 } 2913 return; 2914 } 2915 } 2916 // Lookup CIS via active group operation 2917 if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){ 2918 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){ 2919 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 2920 2921 // lookup CIS by state 2922 btstack_linked_list_iterator_t it; 2923 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 2924 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2925 while (btstack_linked_list_iterator_has_next(&it)){ 2926 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 2927 handle = iso_stream->con_handle; 2928 switch (iso_stream->state){ 2929 case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT: 2930 if (status != ERROR_CODE_SUCCESS){ 2931 hci_iso_stream_finalize(iso_stream); 2932 hci_emit_cis_created(HCI_ISO_GROUP_ID_SINGLE_CIS, handle, status); 2933 break; 2934 } 2935 if (iso_stream->max_sdu_c_to_p > 0){ 2936 iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT; 2937 } else { 2938 hci_emit_cis_created(HCI_ISO_GROUP_ID_SINGLE_CIS, handle, ERROR_CODE_SUCCESS); 2939 } 2940 break; 2941 case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT: 2942 if (status != ERROR_CODE_SUCCESS){ 2943 hci_iso_stream_finalize(iso_stream); 2944 hci_emit_cis_created(HCI_ISO_GROUP_ID_SINGLE_CIS, handle, status); 2945 break; 2946 } 2947 hci_emit_cis_created(HCI_ISO_GROUP_ID_SINGLE_CIS, handle, ERROR_CODE_SUCCESS); 2948 break; 2949 default: 2950 break; 2951 } 2952 } 2953 } else { 2954 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 2955 cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id); 2956 if (cig != NULL) { 2957 // emit cis created if all ISO Paths have been created 2958 // assume we are central 2959 uint8_t cis_index = cig->state_vars.next_cis >> 1; 2960 uint8_t cis_direction = cig->state_vars.next_cis & 1; 2961 bool outgoing_needed = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0; 2962 // if outgoing has been setup, or incoming was setup but outgoing not required 2963 if ((cis_direction == 1) || (outgoing_needed == false)){ 2964 hci_emit_cis_created(cig->cig_id, cig->cis_con_handles[cis_index], status); 2965 } 2966 // next state 2967 cig->state_vars.next_cis++; 2968 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH; 2969 } 2970 } 2971 } 2972 break; 2973 } 2974 case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: { 2975 // lookup BIG by state 2976 btstack_linked_list_iterator_t it; 2977 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 2978 while (btstack_linked_list_iterator_has_next(&it)) { 2979 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 2980 uint8_t big_handle = big_sync->big_handle; 2981 switch (big_sync->state){ 2982 case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED: 2983 btstack_linked_list_iterator_remove(&it); 2984 hci_emit_big_sync_created(big_sync, big_sync->state_vars.status); 2985 return; 2986 default: 2987 btstack_linked_list_iterator_remove(&it); 2988 hci_emit_big_sync_stopped(big_handle); 2989 return; 2990 } 2991 } 2992 break; 2993 } 2994 #endif 2995 #endif 2996 default: 2997 break; 2998 } 2999 } 3000 3001 static void handle_command_status_event(uint8_t * packet, uint16_t size) { 3002 UNUSED(size); 3003 3004 // get num cmd packets - limit to 1 to reduce complexity 3005 hci_stack->num_cmd_packets = packet[3] ? 1 : 0; 3006 3007 // get opcode and command status 3008 uint16_t opcode = hci_event_command_status_get_command_opcode(packet); 3009 3010 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS) 3011 uint8_t status = hci_event_command_status_get_status(packet); 3012 #endif 3013 3014 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) 3015 bd_addr_type_t addr_type; 3016 #endif 3017 3018 switch (opcode){ 3019 #ifdef ENABLE_CLASSIC 3020 case HCI_OPCODE_HCI_CREATE_CONNECTION: 3021 case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION: 3022 #endif 3023 #ifdef ENABLE_LE_CENTRAL 3024 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION: 3025 #endif 3026 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) 3027 addr_type = hci_stack->outgoing_addr_type; 3028 3029 // reset outgoing address info 3030 memset(hci_stack->outgoing_addr, 0, 6); 3031 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN; 3032 3033 // on error 3034 if (status != ERROR_CODE_SUCCESS){ 3035 #ifdef ENABLE_LE_CENTRAL 3036 if (hci_is_le_connection_type(addr_type)){ 3037 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 3038 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 3039 } 3040 #endif 3041 // error => outgoing connection failed 3042 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type); 3043 if (conn != NULL){ 3044 hci_handle_connection_failed(conn, status); 3045 } 3046 } 3047 break; 3048 #endif 3049 #ifdef ENABLE_CLASSIC 3050 case HCI_OPCODE_HCI_INQUIRY: 3051 if (status == ERROR_CODE_SUCCESS) { 3052 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE; 3053 } else { 3054 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 3055 } 3056 break; 3057 #endif 3058 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3059 case HCI_OPCODE_HCI_LE_CREATE_CIS: 3060 case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST: 3061 if (status == ERROR_CODE_SUCCESS){ 3062 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID); 3063 } else { 3064 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID); 3065 } 3066 break; 3067 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 3068 default: 3069 break; 3070 } 3071 } 3072 3073 #ifdef ENABLE_BLE 3074 static void event_handle_le_connection_complete(const uint8_t * packet){ 3075 bd_addr_t addr; 3076 bd_addr_type_t addr_type; 3077 hci_connection_t * conn; 3078 3079 // Connection management 3080 reverse_bd_addr(&packet[8], addr); 3081 addr_type = (bd_addr_type_t)packet[7]; 3082 log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr)); 3083 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3084 3085 #ifdef ENABLE_LE_CENTRAL 3086 // handle error: error is reported only to the initiator -> outgoing connection 3087 if (packet[3]){ 3088 3089 // handle cancelled outgoing connection 3090 // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command, 3091 // either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated. 3092 // In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)." 3093 if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){ 3094 // reset state 3095 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 3096 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 3097 // get outgoing connection conn struct for direct connect 3098 conn = gap_get_outgoing_connection(); 3099 } 3100 3101 // outgoing le connection establishment is done 3102 if (conn){ 3103 // remove entry 3104 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 3105 btstack_memory_hci_connection_free( conn ); 3106 } 3107 return; 3108 } 3109 #endif 3110 3111 // on success, both hosts receive connection complete event 3112 if (packet[6] == HCI_ROLE_MASTER){ 3113 #ifdef ENABLE_LE_CENTRAL 3114 // if we're master on an le connection, it was an outgoing connection and we're done with it 3115 // note: no hci_connection_t object exists yet for connect with whitelist 3116 if (hci_is_le_connection_type(addr_type)){ 3117 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 3118 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 3119 } 3120 #endif 3121 } else { 3122 #ifdef ENABLE_LE_PERIPHERAL 3123 // if we're slave, it was an incoming connection, advertisements have stopped 3124 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 3125 #endif 3126 } 3127 3128 // LE connections are auto-accepted, so just create a connection if there isn't one already 3129 if (!conn){ 3130 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 3131 } 3132 3133 // no memory, sorry. 3134 if (!conn){ 3135 return; 3136 } 3137 3138 conn->state = OPEN; 3139 conn->role = packet[6]; 3140 conn->con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet); 3141 conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet); 3142 3143 #ifdef ENABLE_LE_PERIPHERAL 3144 if (packet[6] == HCI_ROLE_SLAVE){ 3145 hci_update_advertisements_enabled_for_current_roles(); 3146 } 3147 #endif 3148 3149 // init unenhanced att bearer mtu 3150 conn->att_connection.mtu = ATT_DEFAULT_MTU; 3151 conn->att_connection.mtu_exchanged = false; 3152 3153 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 3154 3155 // restart timer 3156 // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 3157 // btstack_run_loop_add_timer(&conn->timeout); 3158 3159 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 3160 3161 hci_emit_nr_connections_changed(); 3162 } 3163 #endif 3164 3165 #ifdef ENABLE_CLASSIC 3166 static bool hci_ssp_security_level_possible_for_io_cap(gap_security_level_t level, uint8_t io_cap_local, uint8_t io_cap_remote){ 3167 if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false; 3168 // LEVEL_4 is tested by l2cap 3169 // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible 3170 // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7 3171 if (level >= LEVEL_3){ 3172 // MITM not possible without keyboard or display 3173 if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false; 3174 if (io_cap_local >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false; 3175 3176 // MITM possible if one side has keyboard and the other has keyboard or display 3177 if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY) return true; 3178 if (io_cap_local == SSP_IO_CAPABILITY_KEYBOARD_ONLY) return true; 3179 3180 // MITM not possible if one side has only display and other side has no keyboard 3181 if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY) return false; 3182 if (io_cap_local == SSP_IO_CAPABILITY_DISPLAY_ONLY) return false; 3183 } 3184 // LEVEL 2 requires SSP, which is a given 3185 return true; 3186 } 3187 3188 static bool btstack_is_null(uint8_t * data, uint16_t size){ 3189 uint16_t i; 3190 for (i=0; i < size ; i++){ 3191 if (data[i] != 0) { 3192 return false; 3193 } 3194 } 3195 return true; 3196 } 3197 3198 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){ 3199 // get requested security level 3200 gap_security_level_t requested_security_level = conn->requested_security_level; 3201 if (hci_stack->gap_secure_connections_only_mode){ 3202 requested_security_level = LEVEL_4; 3203 } 3204 3205 // assess security: LEVEL 4 requires SC 3206 // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller 3207 if ((requested_security_level == LEVEL_4) && 3208 ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) && 3209 !hci_remote_sc_enabled(conn)){ 3210 log_info("Level 4 required, but SC not supported -> abort"); 3211 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3212 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3213 return; 3214 } 3215 3216 // assess security based on io capabilities 3217 if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){ 3218 // responder: fully validate io caps of both sides as well as OOB data 3219 bool security_possible = false; 3220 security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io); 3221 3222 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3223 // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256, 3224 // so we merge the OOB data availability 3225 uint8_t have_oob_data = conn->io_cap_response_oob_data; 3226 if (conn->classic_oob_c_192 != NULL){ 3227 have_oob_data |= 1; 3228 } 3229 if (conn->classic_oob_c_256 != NULL){ 3230 have_oob_data |= 2; 3231 } 3232 // for up to Level 3, either P-192 as well as P-256 will do 3233 // if we don't support SC, then a) conn->classic_oob_c_256 will be NULL and b) remote should not report P-256 available 3234 // if remote does not SC, we should not receive P-256 data either 3235 if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){ 3236 security_possible = true; 3237 } 3238 // for Level 4, P-256 is needed 3239 if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){ 3240 security_possible = true; 3241 } 3242 #endif 3243 3244 if (security_possible == false){ 3245 log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level); 3246 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3247 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3248 return; 3249 } 3250 } else { 3251 // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported 3252 #ifndef ENABLE_CLASSIC_PAIRING_OOB 3253 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 3254 if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){ 3255 log_info("Level 3+ required, but no input/output -> abort"); 3256 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3257 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3258 return; 3259 } 3260 #endif 3261 #endif 3262 } 3263 3264 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 3265 if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){ 3266 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 3267 } else { 3268 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3269 } 3270 #endif 3271 } 3272 3273 #endif 3274 3275 static void event_handler(uint8_t *packet, uint16_t size){ 3276 3277 uint16_t event_length = packet[1]; 3278 3279 // assert packet is complete 3280 if (size != (event_length + 2u)){ 3281 log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2); 3282 return; 3283 } 3284 3285 hci_con_handle_t handle; 3286 hci_connection_t * conn; 3287 int i; 3288 3289 #ifdef ENABLE_CLASSIC 3290 hci_link_type_t link_type; 3291 bd_addr_t addr; 3292 bd_addr_type_t addr_type; 3293 #endif 3294 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3295 hci_iso_stream_t * iso_stream; 3296 le_audio_big_t * big; 3297 le_audio_big_sync_t * big_sync; 3298 #endif 3299 3300 // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet)); 3301 3302 switch (hci_event_packet_get_type(packet)) { 3303 3304 case HCI_EVENT_COMMAND_COMPLETE: 3305 handle_command_complete_event(packet, size); 3306 break; 3307 3308 case HCI_EVENT_COMMAND_STATUS: 3309 handle_command_status_event(packet, size); 3310 break; 3311 3312 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 3313 if (size < 3) return; 3314 uint16_t num_handles = packet[2]; 3315 if (size != (3u + num_handles * 4u)) return; 3316 #ifdef ENABLE_CLASSIC 3317 bool notify_sco = false; 3318 #endif 3319 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3320 bool notify_iso = false; 3321 #endif 3322 uint16_t offset = 3; 3323 for (i=0; i<num_handles;i++){ 3324 handle = little_endian_read_16(packet, offset) & 0x0fffu; 3325 offset += 2u; 3326 uint16_t num_packets = little_endian_read_16(packet, offset); 3327 offset += 2u; 3328 3329 conn = hci_connection_for_handle(handle); 3330 if (conn != NULL) { 3331 3332 if (conn->num_packets_sent >= num_packets) { 3333 conn->num_packets_sent -= num_packets; 3334 } else { 3335 log_error("hci_number_completed_packets, more packet slots freed then sent."); 3336 conn->num_packets_sent = 0; 3337 } 3338 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent); 3339 #ifdef ENABLE_CLASSIC 3340 if (conn->address_type == BD_ADDR_TYPE_SCO){ 3341 notify_sco = true; 3342 } 3343 #endif 3344 } 3345 3346 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 3347 hci_controller_dump_packets(); 3348 #endif 3349 3350 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3351 if (conn == NULL){ 3352 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle); 3353 if (iso_stream != NULL){ 3354 if (iso_stream->num_packets_sent >= num_packets) { 3355 iso_stream->num_packets_sent -= num_packets; 3356 } else { 3357 log_error("hci_number_completed_packets, more packet slots freed then sent."); 3358 iso_stream->num_packets_sent = 0; 3359 } 3360 if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){ 3361 le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id); 3362 if (big != NULL){ 3363 big->num_completed_timestamp_current_valid = true; 3364 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms(); 3365 } 3366 } 3367 log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", 3368 num_packets, handle, iso_stream->num_packets_sent); 3369 notify_iso = true; 3370 } 3371 } 3372 #endif 3373 } 3374 3375 #ifdef ENABLE_CLASSIC 3376 if (notify_sco){ 3377 hci_notify_if_sco_can_send_now(); 3378 } 3379 #endif 3380 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3381 if (notify_iso){ 3382 hci_iso_notify_can_send_now(); 3383 } 3384 #endif 3385 break; 3386 } 3387 3388 #ifdef ENABLE_CLASSIC 3389 case HCI_EVENT_FLUSH_OCCURRED: 3390 // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog() 3391 handle = hci_event_flush_occurred_get_handle(packet); 3392 conn = hci_connection_for_handle(handle); 3393 if (conn) { 3394 log_info("Flush occurred, disconnect 0x%04x", handle); 3395 conn->state = SEND_DISCONNECT; 3396 } 3397 break; 3398 3399 case HCI_EVENT_INQUIRY_COMPLETE: 3400 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){ 3401 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 3402 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 3403 hci_emit_event(event, sizeof(event), 1); 3404 } 3405 break; 3406 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 3407 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){ 3408 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE; 3409 } 3410 break; 3411 case HCI_EVENT_CONNECTION_REQUEST: 3412 reverse_bd_addr(&packet[2], addr); 3413 link_type = (hci_link_type_t) packet[11]; 3414 3415 // CVE-2020-26555: reject incoming connection from device with same BD ADDR 3416 if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){ 3417 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR; 3418 bd_addr_copy(hci_stack->decline_addr, addr); 3419 break; 3420 } 3421 3422 if (hci_stack->gap_classic_accept_callback != NULL){ 3423 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){ 3424 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS; 3425 bd_addr_copy(hci_stack->decline_addr, addr); 3426 break; 3427 } 3428 } 3429 3430 // TODO: eval COD 8-10 3431 log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type); 3432 addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO; 3433 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3434 if (!conn) { 3435 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 3436 } 3437 if (!conn) { 3438 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 3439 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES; 3440 bd_addr_copy(hci_stack->decline_addr, addr); 3441 hci_run(); 3442 // avoid event to higher layer 3443 return; 3444 } 3445 conn->role = HCI_ROLE_SLAVE; 3446 conn->state = RECEIVED_CONNECTION_REQUEST; 3447 // store info about eSCO 3448 if (link_type == HCI_LINK_TYPE_ESCO){ 3449 conn->remote_supported_features[0] |= 1; 3450 } 3451 hci_run(); 3452 break; 3453 3454 case HCI_EVENT_CONNECTION_COMPLETE: 3455 // Connection management 3456 reverse_bd_addr(&packet[5], addr); 3457 log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 3458 addr_type = BD_ADDR_TYPE_ACL; 3459 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3460 if (conn) { 3461 if (!packet[2]){ 3462 conn->state = OPEN; 3463 conn->con_handle = little_endian_read_16(packet, 3); 3464 3465 // trigger write supervision timeout if we're master 3466 if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){ 3467 conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT; 3468 } 3469 3470 // trigger write automatic flush timeout 3471 if (hci_stack->automatic_flush_timeout != 0){ 3472 conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT; 3473 } 3474 3475 // restart timer 3476 btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 3477 btstack_run_loop_add_timer(&conn->timeout); 3478 3479 // trigger remote features for dedicated bonding 3480 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 3481 hci_trigger_remote_features_for_connection(conn); 3482 } 3483 3484 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 3485 3486 hci_emit_nr_connections_changed(); 3487 } else { 3488 // connection failed 3489 hci_handle_connection_failed(conn, packet[2]); 3490 } 3491 } 3492 break; 3493 3494 case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE: 3495 reverse_bd_addr(&packet[5], addr); 3496 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 3497 log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr)); 3498 if (packet[2]){ 3499 // connection failed 3500 if (conn){ 3501 hci_handle_connection_failed(conn, packet[2]); 3502 } 3503 break; 3504 } 3505 if (!conn) { 3506 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 3507 } 3508 if (!conn) { 3509 break; 3510 } 3511 conn->state = OPEN; 3512 conn->con_handle = little_endian_read_16(packet, 3); 3513 3514 #ifdef ENABLE_SCO_OVER_HCI 3515 // update SCO 3516 if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){ 3517 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 3518 } 3519 // trigger can send now 3520 if (hci_have_usb_transport()){ 3521 hci_stack->sco_can_send_now = true; 3522 } 3523 #endif 3524 #ifdef HAVE_SCO_TRANSPORT 3525 // configure sco transport 3526 if (hci_stack->sco_transport != NULL){ 3527 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT; 3528 hci_stack->sco_transport->open(conn->con_handle, sco_format); 3529 } 3530 #endif 3531 break; 3532 3533 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 3534 handle = little_endian_read_16(packet, 3); 3535 conn = hci_connection_for_handle(handle); 3536 if (!conn) break; 3537 if (!packet[2]){ 3538 const uint8_t * features = &packet[5]; 3539 hci_handle_remote_features_page_0(conn, features); 3540 3541 // read extended features if possible 3542 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES) 3543 && ((conn->remote_supported_features[0] & 2) != 0)) { 3544 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1; 3545 break; 3546 } 3547 } 3548 hci_handle_remote_features_received(conn); 3549 break; 3550 3551 case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE: 3552 handle = little_endian_read_16(packet, 3); 3553 conn = hci_connection_for_handle(handle); 3554 if (!conn) break; 3555 // status = ok, page = 1 3556 if (!packet[2]) { 3557 uint8_t page_number = packet[5]; 3558 uint8_t maximum_page_number = packet[6]; 3559 const uint8_t * features = &packet[7]; 3560 bool done = false; 3561 switch (page_number){ 3562 case 1: 3563 hci_handle_remote_features_page_1(conn, features); 3564 if (maximum_page_number >= 2){ 3565 // get Secure Connections (Controller) from Page 2 if available 3566 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2; 3567 } else { 3568 // otherwise, assume SC (Controller) == SC (Host) 3569 if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){ 3570 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 3571 } 3572 done = true; 3573 } 3574 break; 3575 case 2: 3576 hci_handle_remote_features_page_2(conn, features); 3577 done = true; 3578 break; 3579 default: 3580 break; 3581 } 3582 if (!done) break; 3583 } 3584 hci_handle_remote_features_received(conn); 3585 break; 3586 3587 case HCI_EVENT_LINK_KEY_REQUEST: 3588 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY 3589 hci_event_link_key_request_get_bd_addr(packet, addr); 3590 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3591 if (!conn) break; 3592 3593 // lookup link key in db if not cached 3594 if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){ 3595 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type); 3596 } 3597 3598 // response sent by hci_run() 3599 conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST; 3600 #endif 3601 break; 3602 3603 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 3604 hci_event_link_key_request_get_bd_addr(packet, addr); 3605 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3606 if (!conn) break; 3607 3608 hci_pairing_complete(conn, ERROR_CODE_SUCCESS); 3609 3610 // CVE-2020-26555: ignore NULL link key 3611 // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption 3612 if (btstack_is_null(&packet[8], 16)) break; 3613 3614 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 3615 // Change Connection Encryption keeps link key type 3616 if (link_key_type != CHANGED_COMBINATION_KEY){ 3617 conn->link_key_type = link_key_type; 3618 } 3619 3620 // cache link key. link keys stored in little-endian format for legacy reasons 3621 memcpy(&conn->link_key, &packet[8], 16); 3622 3623 // only store link key: 3624 // - if bondable enabled 3625 if (hci_stack->bondable == false) break; 3626 // - if security level sufficient 3627 if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break; 3628 // - for SSP, also check if remote side requested bonding as well 3629 if (conn->link_key_type != COMBINATION_KEY){ 3630 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 3631 if (!remote_bonding){ 3632 break; 3633 } 3634 } 3635 gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type); 3636 break; 3637 } 3638 3639 case HCI_EVENT_PIN_CODE_REQUEST: 3640 hci_event_pin_code_request_get_bd_addr(packet, addr); 3641 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3642 if (!conn) break; 3643 3644 hci_pairing_started(conn, false); 3645 // abort pairing if: non-bondable mode (pin code request is not forwarded to app) 3646 if (!hci_stack->bondable ){ 3647 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST; 3648 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED); 3649 hci_run(); 3650 return; 3651 } 3652 // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app) 3653 if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){ 3654 log_info("Level 4 required, but SC not supported -> abort"); 3655 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST; 3656 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3657 hci_run(); 3658 return; 3659 } 3660 break; 3661 3662 case HCI_EVENT_IO_CAPABILITY_RESPONSE: 3663 hci_event_io_capability_response_get_bd_addr(packet, addr); 3664 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3665 if (!conn) break; 3666 3667 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE); 3668 hci_pairing_started(conn, true); 3669 conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet); 3670 conn->io_cap_response_io = hci_event_io_capability_response_get_io_capability(packet); 3671 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3672 conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet); 3673 #endif 3674 break; 3675 3676 case HCI_EVENT_IO_CAPABILITY_REQUEST: 3677 hci_event_io_capability_response_get_bd_addr(packet, addr); 3678 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3679 if (!conn) break; 3680 3681 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST); 3682 hci_connection_timestamp(conn); 3683 hci_pairing_started(conn, true); 3684 break; 3685 3686 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3687 case HCI_EVENT_REMOTE_OOB_DATA_REQUEST: 3688 hci_event_remote_oob_data_request_get_bd_addr(packet, addr); 3689 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3690 if (!conn) break; 3691 3692 hci_connection_timestamp(conn); 3693 3694 hci_pairing_started(conn, true); 3695 3696 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY); 3697 break; 3698 #endif 3699 3700 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 3701 hci_event_user_confirmation_request_get_bd_addr(packet, addr); 3702 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3703 if (!conn) break; 3704 if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) { 3705 if (hci_stack->ssp_auto_accept){ 3706 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY); 3707 }; 3708 } else { 3709 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3710 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY); 3711 // don't forward event to app 3712 hci_run(); 3713 return; 3714 } 3715 break; 3716 3717 case HCI_EVENT_USER_PASSKEY_REQUEST: 3718 // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request 3719 if (hci_stack->ssp_auto_accept){ 3720 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY); 3721 }; 3722 break; 3723 3724 case HCI_EVENT_MODE_CHANGE: 3725 handle = hci_event_mode_change_get_handle(packet); 3726 conn = hci_connection_for_handle(handle); 3727 if (!conn) break; 3728 conn->connection_mode = hci_event_mode_change_get_mode(packet); 3729 log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode); 3730 break; 3731 #endif 3732 3733 case HCI_EVENT_ENCRYPTION_CHANGE: 3734 case HCI_EVENT_ENCRYPTION_CHANGE_V2: 3735 handle = hci_event_encryption_change_get_connection_handle(packet); 3736 conn = hci_connection_for_handle(handle); 3737 if (!conn) break; 3738 if (hci_event_encryption_change_get_status(packet) == 0u) { 3739 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet); 3740 if (encryption_enabled){ 3741 if (hci_is_le_connection(conn)){ 3742 // For LE, we accept connection as encrypted 3743 conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED; 3744 } 3745 #ifdef ENABLE_CLASSIC 3746 else { 3747 3748 // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS) 3749 bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type); 3750 bool connected_uses_aes_ccm = encryption_enabled == 2; 3751 if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){ 3752 log_info("SC during pairing, but only E0 now -> abort"); 3753 conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 3754 break; 3755 } 3756 3757 // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication 3758 if (connected_uses_aes_ccm){ 3759 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3760 } 3761 3762 #ifdef ENABLE_TESTING_SUPPORT 3763 // work around for issue with PTS dongle 3764 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3765 #endif 3766 // validate encryption key size 3767 if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) { 3768 uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet); 3769 // already got encryption key size 3770 hci_handle_read_encryption_key_size_complete(conn, encryption_key_size); 3771 } else { 3772 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) { 3773 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller) 3774 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 3775 } else { 3776 // if not, pretend everything is perfect 3777 hci_handle_read_encryption_key_size_complete(conn, 16); 3778 } 3779 } 3780 } 3781 #endif 3782 } else { 3783 conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED; 3784 } 3785 } else { 3786 uint8_t status = hci_event_encryption_change_get_status(packet); 3787 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 3788 conn->bonding_flags &= ~BONDING_DEDICATED; 3789 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 3790 conn->bonding_status = status; 3791 } 3792 } 3793 3794 break; 3795 3796 #ifdef ENABLE_CLASSIC 3797 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 3798 handle = hci_event_authentication_complete_get_connection_handle(packet); 3799 conn = hci_connection_for_handle(handle); 3800 if (!conn) break; 3801 3802 // clear authentication active flag 3803 conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST; 3804 hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet)); 3805 3806 // authenticated only if auth status == 0 3807 if (hci_event_authentication_complete_get_status(packet) == 0){ 3808 // authenticated 3809 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3810 3811 // If not already encrypted, start encryption 3812 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){ 3813 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 3814 break; 3815 } 3816 } 3817 3818 // emit updated security level 3819 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 3820 break; 3821 3822 case HCI_EVENT_SIMPLE_PAIRING_COMPLETE: 3823 hci_event_simple_pairing_complete_get_bd_addr(packet, addr); 3824 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3825 if (!conn) break; 3826 3827 // treat successfully paired connection as authenticated 3828 if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){ 3829 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3830 } 3831 3832 hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet)); 3833 break; 3834 #endif 3835 3836 // HCI_EVENT_DISCONNECTION_COMPLETE 3837 // has been split, to first notify stack before shutting connection down 3838 // see end of function, too. 3839 case HCI_EVENT_DISCONNECTION_COMPLETE: 3840 if (packet[2]) break; // status != 0 3841 handle = little_endian_read_16(packet, 3); 3842 // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active 3843 if (hci_stack->acl_fragmentation_total_size > 0u) { 3844 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){ 3845 int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u; 3846 log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer); 3847 hci_stack->acl_fragmentation_total_size = 0; 3848 hci_stack->acl_fragmentation_pos = 0; 3849 if (release_buffer){ 3850 hci_release_packet_buffer(); 3851 } 3852 } 3853 } 3854 3855 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3856 // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active 3857 if (hci_stack->iso_fragmentation_total_size > 0u) { 3858 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){ 3859 int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u; 3860 log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer); 3861 hci_stack->iso_fragmentation_total_size = 0; 3862 hci_stack->iso_fragmentation_pos = 0; 3863 if (release_buffer){ 3864 hci_release_packet_buffer(); 3865 } 3866 } 3867 } 3868 3869 // finalize iso stream if handle matches 3870 iso_stream = hci_iso_stream_for_con_handle(handle); 3871 if (iso_stream != NULL){ 3872 hci_iso_stream_finalize(iso_stream); 3873 break; 3874 } 3875 #endif 3876 3877 conn = hci_connection_for_handle(handle); 3878 if (!conn) break; 3879 #ifdef ENABLE_CLASSIC 3880 // pairing failed if it was ongoing 3881 hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 3882 #endif 3883 3884 // emit dedicatd bonding event 3885 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){ 3886 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status); 3887 } 3888 3889 // mark connection for shutdown, stop timers, reset state 3890 conn->state = RECEIVED_DISCONNECTION_COMPLETE; 3891 hci_connection_stop_timer(conn); 3892 hci_connection_init(conn); 3893 3894 #ifdef ENABLE_BLE 3895 #ifdef ENABLE_LE_PERIPHERAL 3896 // re-enable advertisements for le connections if active 3897 if (hci_is_le_connection(conn)){ 3898 hci_update_advertisements_enabled_for_current_roles(); 3899 } 3900 #endif 3901 #endif 3902 break; 3903 3904 case HCI_EVENT_HARDWARE_ERROR: 3905 log_error("Hardware Error: 0x%02x", packet[2]); 3906 if (hci_stack->hardware_error_callback){ 3907 (*hci_stack->hardware_error_callback)(packet[2]); 3908 } else { 3909 // if no special requests, just reboot stack 3910 hci_power_control_off(); 3911 hci_power_control_on(); 3912 } 3913 break; 3914 3915 #ifdef ENABLE_CLASSIC 3916 case HCI_EVENT_ROLE_CHANGE: 3917 if (packet[2]) break; // status != 0 3918 reverse_bd_addr(&packet[3], addr); 3919 addr_type = BD_ADDR_TYPE_ACL; 3920 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3921 if (!conn) break; 3922 conn->role = packet[9]; 3923 break; 3924 #endif 3925 3926 case HCI_EVENT_TRANSPORT_PACKET_SENT: 3927 // release packet buffer only for asynchronous transport and if there are not further fragments 3928 if (hci_transport_synchronous()) { 3929 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT"); 3930 return; // instead of break: to avoid re-entering hci_run() 3931 } 3932 hci_stack->acl_fragmentation_tx_active = 0; 3933 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3934 hci_stack->iso_fragmentation_tx_active = 0; 3935 if (hci_stack->iso_fragmentation_total_size) break; 3936 #endif 3937 if (hci_stack->acl_fragmentation_total_size) break; 3938 hci_release_packet_buffer(); 3939 3940 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3941 hci_iso_notify_can_send_now(); 3942 #endif 3943 // L2CAP receives this event via the hci_emit_event below 3944 3945 #ifdef ENABLE_CLASSIC 3946 // For SCO, we do the can_send_now_check here 3947 hci_notify_if_sco_can_send_now(); 3948 #endif 3949 break; 3950 3951 #ifdef ENABLE_CLASSIC 3952 case HCI_EVENT_SCO_CAN_SEND_NOW: 3953 // For SCO, we do the can_send_now_check here 3954 hci_stack->sco_can_send_now = true; 3955 hci_notify_if_sco_can_send_now(); 3956 return; 3957 3958 // explode inquriy results for easier consumption 3959 case HCI_EVENT_INQUIRY_RESULT: 3960 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 3961 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 3962 gap_inquiry_explode(packet, size); 3963 break; 3964 #endif 3965 3966 #ifdef ENABLE_BLE 3967 case HCI_EVENT_LE_META: 3968 switch (packet[2]){ 3969 #ifdef ENABLE_LE_CENTRAL 3970 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 3971 if (!hci_stack->le_scanning_enabled) break; 3972 le_handle_advertisement_report(packet, size); 3973 break; 3974 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 3975 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT: 3976 if (!hci_stack->le_scanning_enabled) break; 3977 le_handle_extended_advertisement_report(packet, size); 3978 break; 3979 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT: 3980 hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE; 3981 hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE; 3982 break; 3983 #endif 3984 #endif 3985 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 3986 event_handle_le_connection_complete(packet); 3987 break; 3988 3989 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]); 3990 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE: 3991 handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet); 3992 conn = hci_connection_for_handle(handle); 3993 if (!conn) break; 3994 conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet); 3995 break; 3996 3997 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST: 3998 // connection 3999 handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet); 4000 conn = hci_connection_for_handle(handle); 4001 if (conn) { 4002 // read arguments 4003 uint16_t le_conn_interval_min = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet); 4004 uint16_t le_conn_interval_max = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet); 4005 uint16_t le_conn_latency = hci_subevent_le_remote_connection_parameter_request_get_latency(packet); 4006 uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet); 4007 4008 // validate against current connection parameter range 4009 le_connection_parameter_range_t existing_range; 4010 gap_get_connection_parameter_range(&existing_range); 4011 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout); 4012 if (update_parameter){ 4013 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY; 4014 conn->le_conn_interval_min = le_conn_interval_min; 4015 conn->le_conn_interval_max = le_conn_interval_max; 4016 conn->le_conn_latency = le_conn_latency; 4017 conn->le_supervision_timeout = le_supervision_timeout; 4018 } else { 4019 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY; 4020 } 4021 } 4022 break; 4023 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 4024 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE: 4025 handle = hci_subevent_le_data_length_change_get_connection_handle(packet); 4026 conn = hci_connection_for_handle(handle); 4027 if (conn) { 4028 conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet); 4029 } 4030 break; 4031 #endif 4032 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4033 case HCI_SUBEVENT_LE_CIS_ESTABLISHED: 4034 if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){ 4035 handle = hci_subevent_le_cis_established_get_connection_handle(packet); 4036 uint8_t status = hci_subevent_le_cis_established_get_status(packet); 4037 iso_stream = hci_iso_stream_for_con_handle(handle); 4038 btstack_assert(iso_stream != NULL); 4039 // track SDU 4040 iso_stream->max_sdu_c_to_p = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet); 4041 iso_stream->max_sdu_p_to_c = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet); 4042 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){ 4043 // CIS Accept by Peripheral 4044 if (status == ERROR_CODE_SUCCESS){ 4045 if (iso_stream->max_sdu_p_to_c > 0){ 4046 // we're peripheral and we will send data 4047 iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT; 4048 } else { 4049 // we're peripheral and we will only receive data 4050 iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT; 4051 } 4052 } else { 4053 hci_iso_stream_finalize(iso_stream); 4054 hci_emit_cis_created(HCI_ISO_GROUP_ID_INVALID, handle, status); 4055 } 4056 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 4057 } else { 4058 // CIG Setup by Central 4059 le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id); 4060 btstack_assert(cig != NULL); 4061 // update iso stream state 4062 if (status == ERROR_CODE_SUCCESS){ 4063 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED; 4064 } else { 4065 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE; 4066 } 4067 // update cig state 4068 uint8_t i; 4069 for (i=0;i<cig->num_cis;i++){ 4070 if (cig->cis_con_handles[i] == handle){ 4071 cig->cis_setup_active[i] = false; 4072 if (status == ERROR_CODE_SUCCESS){ 4073 cig->cis_setup_active[i] = false; 4074 cig->cis_established[i] = true; 4075 } else { 4076 hci_emit_cis_created(cig->cig_id, handle, status); 4077 } 4078 } 4079 } 4080 4081 // trigger iso path setup if complete 4082 bool setup_active = false; 4083 for (i=0;i<cig->num_cis;i++){ 4084 setup_active |= cig->cis_setup_active[i]; 4085 } 4086 if (setup_active == false){ 4087 cig->state_vars.next_cis = 0; 4088 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH; 4089 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 4090 } 4091 } 4092 } 4093 break; 4094 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE: 4095 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 4096 big = hci_big_for_handle(packet[4]); 4097 if (big != NULL){ 4098 uint8_t status = packet[3]; 4099 if (status == ERROR_CODE_SUCCESS){ 4100 // store bis_con_handles and trigger iso path setup 4101 uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]); 4102 uint8_t i; 4103 for (i=0;i<num_bis;i++){ 4104 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i)); 4105 big->bis_con_handles[i] = bis_handle; 4106 // assign bis handle 4107 btstack_linked_list_iterator_t it; 4108 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 4109 while (btstack_linked_list_iterator_has_next(&it)){ 4110 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 4111 if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) && 4112 (iso_stream->group_id == big->big_handle)){ 4113 iso_stream->con_handle = bis_handle; 4114 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED; 4115 break; 4116 } 4117 } 4118 } 4119 if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 4120 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 4121 big->state_vars.next_bis = 0; 4122 } 4123 } else { 4124 // create BIG failed or has been stopped by us 4125 hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle); 4126 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 4127 if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){ 4128 hci_emit_big_created(big, status); 4129 } else { 4130 hci_emit_big_terminated(big); 4131 } 4132 } 4133 } 4134 break; 4135 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE: 4136 big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet)); 4137 if (big != NULL){ 4138 // finalize associated ISO streams 4139 btstack_linked_list_iterator_t it; 4140 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 4141 while (btstack_linked_list_iterator_has_next(&it)){ 4142 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 4143 if (iso_stream->group_id == big->big_handle){ 4144 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->con_handle); 4145 btstack_linked_list_iterator_remove(&it); 4146 btstack_memory_hci_iso_stream_free(iso_stream); 4147 } 4148 } 4149 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 4150 switch (big->state){ 4151 case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED: 4152 hci_emit_big_created(big, big->state_vars.status); 4153 break; 4154 default: 4155 hci_emit_big_terminated(big); 4156 break; 4157 } 4158 } 4159 break; 4160 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED: 4161 big_sync = hci_big_sync_for_handle(packet[4]); 4162 if (big_sync != NULL){ 4163 uint8_t status = packet[3]; 4164 uint8_t big_handle = packet[4]; 4165 if (status == ERROR_CODE_SUCCESS){ 4166 // store bis_con_handles and trigger iso path setup 4167 uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]); 4168 uint8_t i; 4169 for (i=0;i<num_bis;i++){ 4170 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i)); 4171 } 4172 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 4173 // trigger iso path setup 4174 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 4175 big_sync->state_vars.next_bis = 0; 4176 } 4177 } else { 4178 // create BIG Sync failed or has been stopped by us 4179 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 4180 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 4181 hci_emit_big_sync_created(big_sync, status); 4182 } else { 4183 hci_emit_big_sync_stopped(big_handle); 4184 } 4185 } 4186 } 4187 break; 4188 case HCI_SUBEVENT_LE_BIG_SYNC_LOST: 4189 big_sync = hci_big_sync_for_handle(packet[4]); 4190 if (big_sync != NULL){ 4191 uint8_t big_handle = packet[4]; 4192 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 4193 hci_emit_big_sync_stopped(big_handle); 4194 } 4195 break; 4196 #endif 4197 default: 4198 break; 4199 } 4200 break; 4201 #endif 4202 case HCI_EVENT_VENDOR_SPECIFIC: 4203 // Vendor specific commands often create vendor specific event instead of num completed packets 4204 // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour 4205 switch (hci_stack->manufacturer){ 4206 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO: 4207 hci_stack->num_cmd_packets = 1; 4208 break; 4209 default: 4210 break; 4211 } 4212 break; 4213 default: 4214 break; 4215 } 4216 4217 handle_event_for_current_stack_state(packet, size); 4218 4219 // notify upper stack 4220 hci_emit_event(packet, size, 0); // don't dump, already happened in packet handler 4221 4222 // moved here to give upper stack a chance to close down everything with hci_connection_t intact 4223 if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){ 4224 handle = little_endian_read_16(packet, 3); 4225 hci_connection_t * aConn = hci_connection_for_handle(handle); 4226 // discard connection if app did not trigger a reconnect in the event handler 4227 if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){ 4228 hci_shutdown_connection(aConn); 4229 } 4230 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 4231 hci_controller_dump_packets(); 4232 #endif 4233 } 4234 4235 // execute main loop 4236 hci_run(); 4237 } 4238 4239 #ifdef ENABLE_CLASSIC 4240 4241 #ifdef ENABLE_SCO_OVER_HCI 4242 static void sco_tx_timeout_handler(btstack_timer_source_t * ts); 4243 static void sco_schedule_tx(hci_connection_t * conn); 4244 4245 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){ 4246 log_debug("SCO TX Timeout"); 4247 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts); 4248 hci_connection_t * conn = hci_connection_for_handle(con_handle); 4249 if (!conn) return; 4250 4251 // trigger send 4252 conn->sco_tx_ready = 1; 4253 // extra packet if CVSD but SCO buffer is too short 4254 if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){ 4255 conn->sco_tx_ready++; 4256 } 4257 hci_notify_if_sco_can_send_now(); 4258 } 4259 4260 4261 #define SCO_TX_AFTER_RX_MS (6) 4262 4263 static void sco_schedule_tx(hci_connection_t * conn){ 4264 4265 uint32_t now = btstack_run_loop_get_time_ms(); 4266 uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS; 4267 int time_delta_ms = sco_tx_ms - now; 4268 4269 btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco; 4270 4271 // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms); 4272 btstack_run_loop_remove_timer(timer); 4273 btstack_run_loop_set_timer(timer, time_delta_ms); 4274 btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle); 4275 btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler); 4276 btstack_run_loop_add_timer(timer); 4277 } 4278 #endif 4279 4280 static void sco_handler(uint8_t * packet, uint16_t size){ 4281 // lookup connection struct 4282 hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet); 4283 hci_connection_t * conn = hci_connection_for_handle(con_handle); 4284 if (!conn) return; 4285 4286 #ifdef ENABLE_SCO_OVER_HCI 4287 // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes 4288 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 4289 if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){ 4290 packet[2] = 0x3c; 4291 memmove(&packet[3], &packet[23], 63); 4292 size = 63; 4293 } 4294 } 4295 4296 if (hci_have_usb_transport()){ 4297 // Nothing to do 4298 } else { 4299 // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent); 4300 if (hci_stack->synchronous_flow_control_enabled == 0){ 4301 uint32_t now = btstack_run_loop_get_time_ms(); 4302 4303 if (!conn->sco_rx_valid){ 4304 // ignore first 10 packets 4305 conn->sco_rx_count++; 4306 // log_debug("sco rx count %u", conn->sco_rx_count); 4307 if (conn->sco_rx_count == 10) { 4308 // use first timestamp as is and pretent it just started 4309 conn->sco_rx_ms = now; 4310 conn->sco_rx_valid = 1; 4311 conn->sco_rx_count = 0; 4312 sco_schedule_tx(conn); 4313 } 4314 } else { 4315 // track expected arrival timme 4316 conn->sco_rx_count++; 4317 conn->sco_rx_ms += 7; 4318 int delta = (int32_t) (now - conn->sco_rx_ms); 4319 if (delta > 0){ 4320 conn->sco_rx_ms++; 4321 } 4322 // log_debug("sco rx %u", conn->sco_rx_ms); 4323 sco_schedule_tx(conn); 4324 } 4325 } 4326 } 4327 #endif 4328 4329 // deliver to app 4330 if (hci_stack->sco_packet_handler) { 4331 hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size); 4332 } 4333 4334 #ifdef HAVE_SCO_TRANSPORT 4335 // We can send one packet for each received packet 4336 conn->sco_tx_ready++; 4337 hci_notify_if_sco_can_send_now(); 4338 #endif 4339 4340 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 4341 conn->num_packets_completed++; 4342 hci_stack->host_completed_packets = 1; 4343 hci_run(); 4344 #endif 4345 } 4346 #endif 4347 4348 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 4349 hci_dump_packet(packet_type, 1, packet, size); 4350 switch (packet_type) { 4351 case HCI_EVENT_PACKET: 4352 event_handler(packet, size); 4353 break; 4354 case HCI_ACL_DATA_PACKET: 4355 acl_handler(packet, size); 4356 break; 4357 #ifdef ENABLE_CLASSIC 4358 case HCI_SCO_DATA_PACKET: 4359 sco_handler(packet, size); 4360 break; 4361 #endif 4362 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4363 case HCI_ISO_DATA_PACKET: 4364 hci_iso_packet_handler(packet, size); 4365 break; 4366 #endif 4367 default: 4368 break; 4369 } 4370 } 4371 4372 /** 4373 * @brief Add event packet handler. 4374 */ 4375 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4376 btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler); 4377 } 4378 4379 /** 4380 * @brief Remove event packet handler. 4381 */ 4382 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4383 btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler); 4384 } 4385 4386 /** Register HCI packet handlers */ 4387 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){ 4388 hci_stack->acl_packet_handler = handler; 4389 } 4390 4391 #ifdef ENABLE_CLASSIC 4392 /** 4393 * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles. 4394 */ 4395 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){ 4396 hci_stack->sco_packet_handler = handler; 4397 } 4398 #endif 4399 4400 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4401 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){ 4402 hci_stack->iso_packet_handler = handler; 4403 } 4404 #endif 4405 4406 static void hci_state_reset(void){ 4407 // no connections yet 4408 hci_stack->connections = NULL; 4409 4410 // keep discoverable/connectable as this has been requested by the client(s) 4411 // hci_stack->discoverable = 0; 4412 // hci_stack->connectable = 0; 4413 // hci_stack->bondable = 1; 4414 // hci_stack->own_addr_type = 0; 4415 4416 // buffer is free 4417 hci_stack->hci_packet_buffer_reserved = false; 4418 4419 // no pending cmds 4420 hci_stack->decline_reason = 0; 4421 4422 hci_stack->secure_connections_active = false; 4423 4424 #ifdef ENABLE_CLASSIC 4425 hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY; 4426 hci_stack->page_timeout = 0x6000; // ca. 15 sec 4427 4428 hci_stack->gap_tasks_classic = 4429 GAP_TASK_SET_DEFAULT_LINK_POLICY | 4430 GAP_TASK_SET_CLASS_OF_DEVICE | 4431 GAP_TASK_SET_LOCAL_NAME | 4432 GAP_TASK_SET_EIR_DATA | 4433 GAP_TASK_WRITE_SCAN_ENABLE | 4434 GAP_TASK_WRITE_PAGE_TIMEOUT; 4435 #endif 4436 4437 #ifdef ENABLE_CLASSIC_PAIRING_OOB 4438 hci_stack->classic_read_local_oob_data = false; 4439 hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID; 4440 #endif 4441 4442 // LE 4443 #ifdef ENABLE_BLE 4444 memset(hci_stack->le_random_address, 0, 6); 4445 hci_stack->le_random_address_set = 0; 4446 #endif 4447 #ifdef ENABLE_LE_CENTRAL 4448 hci_stack->le_scanning_active = false; 4449 hci_stack->le_scanning_param_update = true; 4450 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 4451 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 4452 hci_stack->le_whitelist_capacity = 0; 4453 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 4454 hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID; 4455 #endif 4456 #endif 4457 #ifdef ENABLE_LE_PERIPHERAL 4458 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 4459 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){ 4460 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 4461 } 4462 if (hci_stack->le_advertisements_data != NULL){ 4463 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 4464 } 4465 #endif 4466 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4467 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID; 4468 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID; 4469 #endif 4470 } 4471 4472 #ifdef ENABLE_CLASSIC 4473 /** 4474 * @brief Configure Bluetooth hardware control. Has to be called before power on. 4475 */ 4476 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){ 4477 // store and open remote device db 4478 hci_stack->link_key_db = link_key_db; 4479 if (hci_stack->link_key_db) { 4480 hci_stack->link_key_db->open(); 4481 } 4482 } 4483 #endif 4484 4485 void hci_init(const hci_transport_t *transport, const void *config){ 4486 4487 #ifdef HAVE_MALLOC 4488 if (!hci_stack) { 4489 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 4490 } 4491 #else 4492 hci_stack = &hci_stack_static; 4493 #endif 4494 memset(hci_stack, 0, sizeof(hci_stack_t)); 4495 4496 // reference to use transport layer implementation 4497 hci_stack->hci_transport = transport; 4498 4499 // reference to used config 4500 hci_stack->config = config; 4501 4502 // setup pointer for outgoing packet buffer 4503 hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE]; 4504 4505 // max acl payload size defined in config.h 4506 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 4507 4508 // register packet handlers with transport 4509 transport->register_packet_handler(&packet_handler); 4510 4511 hci_stack->state = HCI_STATE_OFF; 4512 4513 // class of device 4514 hci_stack->class_of_device = 0x007a020c; // Smartphone 4515 4516 // bondable by default 4517 hci_stack->bondable = 1; 4518 4519 #ifdef ENABLE_CLASSIC 4520 // classic name 4521 hci_stack->local_name = default_classic_name; 4522 4523 // Master slave policy 4524 hci_stack->master_slave_policy = 1; 4525 4526 // Allow Role Switch 4527 hci_stack->allow_role_switch = 1; 4528 4529 // Default / minimum security level = 2 4530 hci_stack->gap_security_level = LEVEL_2; 4531 4532 // Default Security Mode 4 4533 hci_stack->gap_security_mode = GAP_SECURITY_MODE_4; 4534 4535 // Errata-11838 mandates 7 bytes for GAP Security Level 1-3 4536 hci_stack->gap_required_encyrption_key_size = 7; 4537 4538 // Link Supervision Timeout 4539 hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT; 4540 4541 #endif 4542 4543 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 4544 hci_stack->ssp_enable = 1; 4545 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 4546 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 4547 hci_stack->ssp_auto_accept = 1; 4548 4549 // Secure Connections: enable (requires support from Controller) 4550 hci_stack->secure_connections_enable = true; 4551 4552 // voice setting - signed 16 bit pcm data with CVSD over the air 4553 hci_stack->sco_voice_setting = 0x60; 4554 4555 #ifdef ENABLE_LE_CENTRAL 4556 // connection parameter to use for outgoing connections 4557 hci_stack->le_connection_scan_interval = 0x0060; // 60ms 4558 hci_stack->le_connection_scan_window = 0x0030; // 30ms 4559 hci_stack->le_connection_interval_min = 0x0008; // 10 ms 4560 hci_stack->le_connection_interval_max = 0x0018; // 30 ms 4561 hci_stack->le_connection_latency = 4; // 4 4562 hci_stack->le_supervision_timeout = 0x0048; // 720 ms 4563 hci_stack->le_minimum_ce_length = 2; // 1.25 ms 4564 hci_stack->le_maximum_ce_length = 0x0030; // 30 ms 4565 4566 // default LE Scanning 4567 hci_stack->le_scan_type = 0x1; // active 4568 hci_stack->le_scan_interval = 0x1e0; // 300 ms 4569 hci_stack->le_scan_window = 0x30; // 30 ms 4570 #endif 4571 4572 #ifdef ENABLE_LE_PERIPHERAL 4573 hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral 4574 #endif 4575 4576 // connection parameter range used to answer connection parameter update requests in l2cap 4577 hci_stack->le_connection_parameter_range.le_conn_interval_min = 6; 4578 hci_stack->le_connection_parameter_range.le_conn_interval_max = 3200; 4579 hci_stack->le_connection_parameter_range.le_conn_latency_min = 0; 4580 hci_stack->le_connection_parameter_range.le_conn_latency_max = 500; 4581 hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 10; 4582 hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200; 4583 4584 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4585 hci_stack->iso_packets_to_queue = 1; 4586 #endif 4587 4588 hci_state_reset(); 4589 } 4590 4591 void hci_deinit(void){ 4592 btstack_run_loop_remove_timer(&hci_stack->timeout); 4593 #ifdef HAVE_MALLOC 4594 if (hci_stack) { 4595 free(hci_stack); 4596 } 4597 #endif 4598 hci_stack = NULL; 4599 4600 #ifdef ENABLE_CLASSIC 4601 disable_l2cap_timeouts = 0; 4602 #endif 4603 } 4604 4605 /** 4606 * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information 4607 */ 4608 void hci_set_chipset(const btstack_chipset_t *chipset_driver){ 4609 hci_stack->chipset = chipset_driver; 4610 4611 // reset chipset driver - init is also called on power_up 4612 if (hci_stack->chipset && hci_stack->chipset->init){ 4613 hci_stack->chipset->init(hci_stack->config); 4614 } 4615 } 4616 4617 /** 4618 * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on. 4619 */ 4620 void hci_set_control(const btstack_control_t *hardware_control){ 4621 // references to used control implementation 4622 hci_stack->control = hardware_control; 4623 // init with transport config 4624 hardware_control->init(hci_stack->config); 4625 } 4626 4627 static void hci_discard_connections(void){ 4628 btstack_linked_list_iterator_t it; 4629 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 4630 while (btstack_linked_list_iterator_has_next(&it)){ 4631 // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection 4632 hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 4633 hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host 4634 hci_shutdown_connection(connection); 4635 } 4636 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4637 while (hci_stack->iso_streams != NULL){ 4638 hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams); 4639 } 4640 #endif 4641 } 4642 4643 void hci_close(void){ 4644 4645 #ifdef ENABLE_CLASSIC 4646 // close remote device db 4647 if (hci_stack->link_key_db) { 4648 hci_stack->link_key_db->close(); 4649 } 4650 #endif 4651 4652 hci_discard_connections(); 4653 4654 hci_power_control(HCI_POWER_OFF); 4655 4656 #ifdef HAVE_MALLOC 4657 free(hci_stack); 4658 #endif 4659 hci_stack = NULL; 4660 } 4661 4662 #ifdef HAVE_SCO_TRANSPORT 4663 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){ 4664 hci_stack->sco_transport = sco_transport; 4665 sco_transport->register_packet_handler(&packet_handler); 4666 } 4667 #endif 4668 4669 #ifdef ENABLE_CLASSIC 4670 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){ 4671 // validate ranage and set 4672 if (encryption_key_size < 7) return; 4673 if (encryption_key_size > 16) return; 4674 hci_stack->gap_required_encyrption_key_size = encryption_key_size; 4675 } 4676 4677 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){ 4678 if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){ 4679 hci_stack->gap_security_mode = security_mode; 4680 return ERROR_CODE_SUCCESS; 4681 } else { 4682 return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 4683 } 4684 } 4685 4686 gap_security_mode_t gap_get_security_mode(void){ 4687 return hci_stack->gap_security_mode; 4688 } 4689 4690 void gap_set_security_level(gap_security_level_t security_level){ 4691 hci_stack->gap_security_level = security_level; 4692 } 4693 4694 gap_security_level_t gap_get_security_level(void){ 4695 if (hci_stack->gap_secure_connections_only_mode){ 4696 return LEVEL_4; 4697 } 4698 return hci_stack->gap_security_level; 4699 } 4700 4701 void gap_set_minimal_service_security_level(gap_security_level_t security_level){ 4702 hci_stack->gap_minimal_service_security_level = security_level; 4703 } 4704 4705 void gap_set_secure_connections_only_mode(bool enable){ 4706 hci_stack->gap_secure_connections_only_mode = enable; 4707 } 4708 4709 bool gap_get_secure_connections_only_mode(void){ 4710 return hci_stack->gap_secure_connections_only_mode; 4711 } 4712 #endif 4713 4714 #ifdef ENABLE_CLASSIC 4715 void gap_set_class_of_device(uint32_t class_of_device){ 4716 hci_stack->class_of_device = class_of_device; 4717 hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE; 4718 hci_run(); 4719 } 4720 4721 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){ 4722 hci_stack->default_link_policy_settings = default_link_policy_settings; 4723 hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY; 4724 hci_run(); 4725 } 4726 4727 void gap_set_allow_role_switch(bool allow_role_switch){ 4728 hci_stack->allow_role_switch = allow_role_switch ? 1 : 0; 4729 } 4730 4731 uint8_t hci_get_allow_role_switch(void){ 4732 return hci_stack->allow_role_switch; 4733 } 4734 4735 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){ 4736 hci_stack->link_supervision_timeout = link_supervision_timeout; 4737 } 4738 4739 void gap_enable_link_watchdog(uint16_t timeout_ms){ 4740 hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625 4741 } 4742 4743 uint16_t hci_automatic_flush_timeout(void){ 4744 return hci_stack->automatic_flush_timeout; 4745 } 4746 4747 void hci_disable_l2cap_timeout_check(void){ 4748 disable_l2cap_timeouts = 1; 4749 } 4750 #endif 4751 4752 #ifndef HAVE_HOST_CONTROLLER_API 4753 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h 4754 void hci_set_bd_addr(bd_addr_t addr){ 4755 (void)memcpy(hci_stack->custom_bd_addr, addr, 6); 4756 hci_stack->custom_bd_addr_set = 1; 4757 } 4758 #endif 4759 4760 // State-Module-Driver overview 4761 // state module low-level 4762 // HCI_STATE_OFF off close 4763 // HCI_STATE_INITIALIZING, on open 4764 // HCI_STATE_WORKING, on open 4765 // HCI_STATE_HALTING, on open 4766 // HCI_STATE_SLEEPING, off/sleep close 4767 // HCI_STATE_FALLING_ASLEEP on open 4768 4769 static int hci_power_control_on(void){ 4770 4771 // power on 4772 int err = 0; 4773 if (hci_stack->control && hci_stack->control->on){ 4774 err = (*hci_stack->control->on)(); 4775 } 4776 if (err){ 4777 log_error( "POWER_ON failed"); 4778 hci_emit_hci_open_failed(); 4779 return err; 4780 } 4781 4782 // int chipset driver 4783 if (hci_stack->chipset && hci_stack->chipset->init){ 4784 hci_stack->chipset->init(hci_stack->config); 4785 } 4786 4787 // init transport 4788 if (hci_stack->hci_transport->init){ 4789 hci_stack->hci_transport->init(hci_stack->config); 4790 } 4791 4792 // open transport 4793 err = hci_stack->hci_transport->open(); 4794 if (err){ 4795 log_error( "HCI_INIT failed, turning Bluetooth off again"); 4796 if (hci_stack->control && hci_stack->control->off){ 4797 (*hci_stack->control->off)(); 4798 } 4799 hci_emit_hci_open_failed(); 4800 return err; 4801 } 4802 return 0; 4803 } 4804 4805 static void hci_power_control_off(void){ 4806 4807 log_info("hci_power_control_off"); 4808 4809 // close low-level device 4810 hci_stack->hci_transport->close(); 4811 4812 log_info("hci_power_control_off - hci_transport closed"); 4813 4814 // power off 4815 if (hci_stack->control && hci_stack->control->off){ 4816 (*hci_stack->control->off)(); 4817 } 4818 4819 log_info("hci_power_control_off - control closed"); 4820 4821 hci_stack->state = HCI_STATE_OFF; 4822 } 4823 4824 static void hci_power_control_sleep(void){ 4825 4826 log_info("hci_power_control_sleep"); 4827 4828 #if 0 4829 // don't close serial port during sleep 4830 4831 // close low-level device 4832 hci_stack->hci_transport->close(hci_stack->config); 4833 #endif 4834 4835 // sleep mode 4836 if (hci_stack->control && hci_stack->control->sleep){ 4837 (*hci_stack->control->sleep)(); 4838 } 4839 4840 hci_stack->state = HCI_STATE_SLEEPING; 4841 } 4842 4843 static int hci_power_control_wake(void){ 4844 4845 log_info("hci_power_control_wake"); 4846 4847 // wake on 4848 if (hci_stack->control && hci_stack->control->wake){ 4849 (*hci_stack->control->wake)(); 4850 } 4851 4852 #if 0 4853 // open low-level device 4854 int err = hci_stack->hci_transport->open(hci_stack->config); 4855 if (err){ 4856 log_error( "HCI_INIT failed, turning Bluetooth off again"); 4857 if (hci_stack->control && hci_stack->control->off){ 4858 (*hci_stack->control->off)(); 4859 } 4860 hci_emit_hci_open_failed(); 4861 return err; 4862 } 4863 #endif 4864 4865 return 0; 4866 } 4867 4868 static void hci_power_enter_initializing_state(void){ 4869 // set up state machine 4870 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 4871 hci_stack->hci_packet_buffer_reserved = false; 4872 hci_stack->state = HCI_STATE_INITIALIZING; 4873 hci_stack->substate = HCI_INIT_SEND_RESET; 4874 } 4875 4876 static void hci_power_enter_halting_state(void){ 4877 #ifdef ENABLE_BLE 4878 hci_whitelist_free(); 4879 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 4880 hci_periodic_advertiser_list_free(); 4881 #endif 4882 #endif 4883 // see hci_run 4884 hci_stack->state = HCI_STATE_HALTING; 4885 hci_stack->substate = HCI_HALTING_CLASSIC_STOP; 4886 // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore 4887 btstack_run_loop_set_timer(&hci_stack->timeout, 1000); 4888 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 4889 btstack_run_loop_add_timer(&hci_stack->timeout); 4890 } 4891 4892 // returns error 4893 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){ 4894 int err; 4895 switch (power_mode){ 4896 case HCI_POWER_ON: 4897 err = hci_power_control_on(); 4898 if (err != 0) { 4899 log_error("hci_power_control_on() error %d", err); 4900 return err; 4901 } 4902 hci_power_enter_initializing_state(); 4903 break; 4904 case HCI_POWER_OFF: 4905 // do nothing 4906 break; 4907 case HCI_POWER_SLEEP: 4908 // do nothing (with SLEEP == OFF) 4909 break; 4910 default: 4911 btstack_assert(false); 4912 break; 4913 } 4914 return ERROR_CODE_SUCCESS; 4915 } 4916 4917 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){ 4918 switch (power_mode){ 4919 case HCI_POWER_ON: 4920 // do nothing 4921 break; 4922 case HCI_POWER_OFF: 4923 // no connections yet, just turn it off 4924 hci_power_control_off(); 4925 break; 4926 case HCI_POWER_SLEEP: 4927 // no connections yet, just turn it off 4928 hci_power_control_sleep(); 4929 break; 4930 default: 4931 btstack_assert(false); 4932 break; 4933 } 4934 return ERROR_CODE_SUCCESS; 4935 } 4936 4937 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) { 4938 switch (power_mode){ 4939 case HCI_POWER_ON: 4940 // do nothing 4941 break; 4942 case HCI_POWER_OFF: 4943 hci_power_enter_halting_state(); 4944 break; 4945 case HCI_POWER_SLEEP: 4946 // see hci_run 4947 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 4948 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 4949 break; 4950 default: 4951 btstack_assert(false); 4952 break; 4953 } 4954 return ERROR_CODE_SUCCESS; 4955 } 4956 4957 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) { 4958 switch (power_mode){ 4959 case HCI_POWER_ON: 4960 hci_power_enter_initializing_state(); 4961 break; 4962 case HCI_POWER_OFF: 4963 // do nothing 4964 break; 4965 case HCI_POWER_SLEEP: 4966 // see hci_run 4967 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 4968 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 4969 break; 4970 default: 4971 btstack_assert(false); 4972 break; 4973 } 4974 return ERROR_CODE_SUCCESS; 4975 } 4976 4977 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) { 4978 switch (power_mode){ 4979 case HCI_POWER_ON: 4980 hci_power_enter_initializing_state(); 4981 break; 4982 case HCI_POWER_OFF: 4983 hci_power_enter_halting_state(); 4984 break; 4985 case HCI_POWER_SLEEP: 4986 // do nothing 4987 break; 4988 default: 4989 btstack_assert(false); 4990 break; 4991 } 4992 return ERROR_CODE_SUCCESS; 4993 } 4994 4995 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) { 4996 int err; 4997 switch (power_mode){ 4998 case HCI_POWER_ON: 4999 err = hci_power_control_wake(); 5000 if (err) return err; 5001 hci_power_enter_initializing_state(); 5002 break; 5003 case HCI_POWER_OFF: 5004 hci_power_enter_halting_state(); 5005 break; 5006 case HCI_POWER_SLEEP: 5007 // do nothing 5008 break; 5009 default: 5010 btstack_assert(false); 5011 break; 5012 } 5013 return ERROR_CODE_SUCCESS; 5014 } 5015 5016 int hci_power_control(HCI_POWER_MODE power_mode){ 5017 log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state); 5018 int err = 0; 5019 switch (hci_stack->state){ 5020 case HCI_STATE_OFF: 5021 err = hci_power_control_state_off(power_mode); 5022 break; 5023 case HCI_STATE_INITIALIZING: 5024 err = hci_power_control_state_initializing(power_mode); 5025 break; 5026 case HCI_STATE_WORKING: 5027 err = hci_power_control_state_working(power_mode); 5028 break; 5029 case HCI_STATE_HALTING: 5030 err = hci_power_control_state_halting(power_mode); 5031 break; 5032 case HCI_STATE_FALLING_ASLEEP: 5033 err = hci_power_control_state_falling_asleep(power_mode); 5034 break; 5035 case HCI_STATE_SLEEPING: 5036 err = hci_power_control_state_sleeping(power_mode); 5037 break; 5038 default: 5039 btstack_assert(false); 5040 break; 5041 } 5042 if (err != 0){ 5043 return err; 5044 } 5045 5046 // create internal event 5047 hci_emit_state(); 5048 5049 // trigger next/first action 5050 hci_run(); 5051 5052 return 0; 5053 } 5054 5055 5056 static void hci_halting_run(void) { 5057 5058 log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate); 5059 5060 hci_connection_t *connection; 5061 #ifdef ENABLE_BLE 5062 #ifdef ENABLE_LE_PERIPHERAL 5063 bool stop_advertismenets; 5064 #endif 5065 #endif 5066 5067 switch (hci_stack->substate) { 5068 case HCI_HALTING_CLASSIC_STOP: 5069 #ifdef ENABLE_CLASSIC 5070 if (!hci_can_send_command_packet_now()) return; 5071 5072 if (hci_stack->connectable || hci_stack->discoverable){ 5073 hci_stack->substate = HCI_HALTING_LE_ADV_STOP; 5074 hci_send_cmd(&hci_write_scan_enable, 0); 5075 return; 5076 } 5077 #endif 5078 /* fall through */ 5079 5080 case HCI_HALTING_LE_ADV_STOP: 5081 hci_stack->substate = HCI_HALTING_LE_ADV_STOP; 5082 5083 #ifdef ENABLE_BLE 5084 #ifdef ENABLE_LE_PERIPHERAL 5085 if (!hci_can_send_command_packet_now()) return; 5086 5087 stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0; 5088 5089 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5090 if (hci_extended_advertising_supported()){ 5091 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5092 btstack_linked_list_iterator_t it; 5093 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 5094 // stop all periodic advertisements and check if an extended set is active 5095 while (btstack_linked_list_iterator_has_next(&it)){ 5096 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 5097 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) { 5098 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 5099 hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle); 5100 return; 5101 } 5102 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) { 5103 stop_advertismenets = true; 5104 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5105 } 5106 } 5107 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5108 if (stop_advertismenets){ 5109 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5110 hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL); 5111 return; 5112 } 5113 } 5114 else 5115 #else /* ENABLE_LE_PERIPHERAL */ 5116 { 5117 if (stop_advertismenets) { 5118 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5119 hci_send_cmd(&hci_le_set_advertise_enable, 0); 5120 return; 5121 } 5122 } 5123 #endif /* ENABLE_LE_EXTENDED_ADVERTISING*/ 5124 #endif /* ENABLE_LE_PERIPHERAL */ 5125 #endif /* ENABLE_BLE */ 5126 5127 /* fall through */ 5128 5129 case HCI_HALTING_LE_SCAN_STOP: 5130 hci_stack->substate = HCI_HALTING_LE_SCAN_STOP; 5131 if (!hci_can_send_command_packet_now()) return; 5132 5133 #ifdef ENABLE_BLE 5134 #ifdef ENABLE_LE_CENTRAL 5135 if (hci_stack->le_scanning_active){ 5136 hci_le_scan_stop(); 5137 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL; 5138 return; 5139 } 5140 #endif 5141 #endif 5142 5143 /* fall through */ 5144 5145 case HCI_HALTING_DISCONNECT_ALL: 5146 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL; 5147 if (!hci_can_send_command_packet_now()) return; 5148 5149 // close all open connections 5150 connection = (hci_connection_t *) hci_stack->connections; 5151 if (connection) { 5152 hci_con_handle_t con_handle = (uint16_t) connection->con_handle; 5153 5154 // check state 5155 if (connection->state == SENT_DISCONNECT) return; 5156 connection->state = SENT_DISCONNECT; 5157 5158 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle); 5159 5160 // finally, send the disconnect command 5161 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 5162 return; 5163 } 5164 5165 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 5166 // stop BIGs and BIG Syncs 5167 if (hci_stack->le_audio_bigs != NULL){ 5168 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs; 5169 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return; 5170 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 5171 hci_send_cmd(&hci_le_terminate_big, big->big_handle); 5172 return; 5173 } 5174 if (hci_stack->le_audio_big_syncs != NULL){ 5175 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs; 5176 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return; 5177 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 5178 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 5179 return; 5180 } 5181 #endif 5182 5183 btstack_run_loop_remove_timer(&hci_stack->timeout); 5184 5185 // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event 5186 log_info("HCI_STATE_HALTING: wait 50 ms"); 5187 hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER; 5188 btstack_run_loop_set_timer(&hci_stack->timeout, 50); 5189 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 5190 btstack_run_loop_add_timer(&hci_stack->timeout); 5191 break; 5192 5193 case HCI_HALTING_CLOSE: 5194 // close left over connections (that had not been properly closed before) 5195 hci_discard_connections(); 5196 5197 log_info("HCI_STATE_HALTING, calling off"); 5198 5199 // switch mode 5200 hci_power_control_off(); 5201 5202 log_info("HCI_STATE_HALTING, emitting state"); 5203 hci_emit_state(); 5204 log_info("HCI_STATE_HALTING, done"); 5205 break; 5206 5207 case HCI_HALTING_W4_CLOSE_TIMER: 5208 // keep waiting 5209 5210 break; 5211 default: 5212 break; 5213 } 5214 }; 5215 5216 static void hci_falling_asleep_run(void){ 5217 hci_connection_t * connection; 5218 switch(hci_stack->substate) { 5219 case HCI_FALLING_ASLEEP_DISCONNECT: 5220 log_info("HCI_STATE_FALLING_ASLEEP"); 5221 // close all open connections 5222 connection = (hci_connection_t *) hci_stack->connections; 5223 if (connection){ 5224 5225 // send disconnect 5226 if (!hci_can_send_command_packet_now()) return; 5227 5228 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 5229 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 5230 5231 // send disconnected event right away - causes higher layer connections to get closed, too. 5232 hci_shutdown_connection(connection); 5233 return; 5234 } 5235 5236 if (hci_classic_supported()){ 5237 // disable page and inquiry scan 5238 if (!hci_can_send_command_packet_now()) return; 5239 5240 log_info("HCI_STATE_HALTING, disabling inq scans"); 5241 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 5242 5243 // continue in next sub state 5244 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE; 5245 break; 5246 } 5247 5248 /* fall through */ 5249 5250 case HCI_FALLING_ASLEEP_COMPLETE: 5251 log_info("HCI_STATE_HALTING, calling sleep"); 5252 // switch mode 5253 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 5254 hci_emit_state(); 5255 break; 5256 5257 default: 5258 break; 5259 } 5260 } 5261 5262 #ifdef ENABLE_CLASSIC 5263 5264 static void hci_update_scan_enable(void){ 5265 // 2 = page scan, 1 = inq scan 5266 hci_stack->new_scan_enable_value = (hci_stack->connectable << 1) | hci_stack->discoverable; 5267 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE; 5268 hci_run(); 5269 } 5270 5271 void gap_discoverable_control(uint8_t enable){ 5272 if (enable) enable = 1; // normalize argument 5273 5274 if (hci_stack->discoverable == enable){ 5275 hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable); 5276 return; 5277 } 5278 5279 hci_stack->discoverable = enable; 5280 hci_update_scan_enable(); 5281 } 5282 5283 void gap_connectable_control(uint8_t enable){ 5284 if (enable) enable = 1; // normalize argument 5285 5286 // don't emit event 5287 if (hci_stack->connectable == enable) return; 5288 5289 hci_stack->connectable = enable; 5290 hci_update_scan_enable(); 5291 } 5292 #endif 5293 5294 void gap_local_bd_addr(bd_addr_t address_buffer){ 5295 (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6); 5296 } 5297 5298 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 5299 static void hci_host_num_completed_packets(void){ 5300 5301 // create packet manually as arrays are not supported and num_commands should not get reduced 5302 hci_reserve_packet_buffer(); 5303 uint8_t * packet = hci_get_outgoing_packet_buffer(); 5304 5305 uint16_t size = 0; 5306 uint16_t num_handles = 0; 5307 packet[size++] = 0x35; 5308 packet[size++] = 0x0c; 5309 size++; // skip param len 5310 size++; // skip num handles 5311 5312 // add { handle, packets } entries 5313 btstack_linked_item_t * it; 5314 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 5315 hci_connection_t * connection = (hci_connection_t *) it; 5316 if (connection->num_packets_completed){ 5317 little_endian_store_16(packet, size, connection->con_handle); 5318 size += 2; 5319 little_endian_store_16(packet, size, connection->num_packets_completed); 5320 size += 2; 5321 // 5322 num_handles++; 5323 connection->num_packets_completed = 0; 5324 } 5325 } 5326 5327 packet[2] = size - 3; 5328 packet[3] = num_handles; 5329 5330 hci_stack->host_completed_packets = 0; 5331 5332 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 5333 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 5334 5335 // release packet buffer for synchronous transport implementations 5336 if (hci_transport_synchronous()){ 5337 hci_release_packet_buffer(); 5338 hci_emit_transport_packet_sent(); 5339 } 5340 } 5341 #endif 5342 5343 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){ 5344 UNUSED(ds); 5345 hci_stack->substate = HCI_HALTING_CLOSE; 5346 // allow packet handlers to defer final shutdown 5347 hci_emit_state(); 5348 hci_run(); 5349 } 5350 5351 static bool hci_run_acl_fragments(void){ 5352 if (hci_stack->acl_fragmentation_total_size > 0u) { 5353 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 5354 hci_connection_t *connection = hci_connection_for_handle(con_handle); 5355 if (connection) { 5356 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 5357 hci_send_acl_packet_fragments(connection); 5358 return true; 5359 } 5360 } else { 5361 // connection gone -> discard further fragments 5362 log_info("hci_run: fragmented ACL packet no connection -> discard fragment"); 5363 hci_stack->acl_fragmentation_total_size = 0; 5364 hci_stack->acl_fragmentation_pos = 0; 5365 } 5366 } 5367 return false; 5368 } 5369 5370 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 5371 static bool hci_run_iso_fragments(void){ 5372 if (hci_stack->iso_fragmentation_total_size > 0u) { 5373 // TODO: flow control 5374 if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){ 5375 hci_send_iso_packet_fragments(); 5376 return true; 5377 } 5378 } 5379 return false; 5380 } 5381 #endif 5382 5383 #ifdef ENABLE_CLASSIC 5384 5385 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5386 static bool hci_classic_operation_active(void) { 5387 if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){ 5388 return true; 5389 } 5390 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){ 5391 return true; 5392 } 5393 btstack_linked_item_t * it; 5394 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) { 5395 hci_connection_t *connection = (hci_connection_t *) it; 5396 switch (connection->state) { 5397 case SENT_CREATE_CONNECTION: 5398 case SENT_CANCEL_CONNECTION: 5399 case SENT_DISCONNECT: 5400 return true; 5401 default: 5402 break; 5403 } 5404 } 5405 return false; 5406 } 5407 #endif 5408 5409 static bool hci_run_general_gap_classic(void){ 5410 5411 // assert stack is working and classic is active 5412 if (hci_classic_supported() == false) return false; 5413 if (hci_stack->state != HCI_STATE_WORKING) return false; 5414 5415 // decline incoming connections 5416 if (hci_stack->decline_reason){ 5417 uint8_t reason = hci_stack->decline_reason; 5418 hci_stack->decline_reason = 0; 5419 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 5420 return true; 5421 } 5422 5423 if (hci_stack->gap_tasks_classic != 0){ 5424 hci_run_gap_tasks_classic(); 5425 return true; 5426 } 5427 5428 // start/stop inquiry 5429 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){ 5430 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5431 if (hci_classic_operation_active() == false) 5432 #endif 5433 { 5434 uint8_t duration = hci_stack->inquiry_state; 5435 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE; 5436 if (hci_stack->inquiry_max_period_length != 0){ 5437 hci_send_cmd(&hci_periodic_inquiry_mode, hci_stack->inquiry_max_period_length, hci_stack->inquiry_min_period_length, hci_stack->inquiry_lap, duration, 0); 5438 } else { 5439 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0); 5440 } 5441 return true; 5442 } 5443 } 5444 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){ 5445 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 5446 hci_send_cmd(&hci_inquiry_cancel); 5447 return true; 5448 } 5449 5450 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){ 5451 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 5452 hci_send_cmd(&hci_exit_periodic_inquiry_mode); 5453 return true; 5454 } 5455 5456 // remote name request 5457 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){ 5458 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5459 if (hci_classic_operation_active() == false) 5460 #endif 5461 { 5462 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE; 5463 hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr, 5464 hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset); 5465 return true; 5466 } 5467 } 5468 #ifdef ENABLE_CLASSIC_PAIRING_OOB 5469 // Local OOB data 5470 if (hci_stack->classic_read_local_oob_data){ 5471 hci_stack->classic_read_local_oob_data = false; 5472 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){ 5473 hci_send_cmd(&hci_read_local_extended_oob_data); 5474 } else { 5475 hci_send_cmd(&hci_read_local_oob_data); 5476 } 5477 } 5478 #endif 5479 // pairing 5480 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){ 5481 uint8_t state = hci_stack->gap_pairing_state; 5482 uint8_t pin_code[16]; 5483 switch (state){ 5484 case GAP_PAIRING_STATE_SEND_PIN: 5485 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5486 memset(pin_code, 0, 16); 5487 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len); 5488 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code); 5489 break; 5490 case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE: 5491 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5492 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr); 5493 break; 5494 case GAP_PAIRING_STATE_SEND_PASSKEY: 5495 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5496 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey); 5497 break; 5498 case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE: 5499 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5500 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr); 5501 break; 5502 case GAP_PAIRING_STATE_SEND_CONFIRMATION: 5503 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5504 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr); 5505 break; 5506 case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE: 5507 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5508 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr); 5509 break; 5510 default: 5511 break; 5512 } 5513 return true; 5514 } 5515 return false; 5516 } 5517 #endif 5518 5519 #ifdef ENABLE_BLE 5520 5521 #ifdef ENABLE_LE_CENTRAL 5522 static void hci_le_scan_stop(void){ 5523 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5524 if (hci_extended_advertising_supported()) { 5525 hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0); 5526 } else 5527 #endif 5528 { 5529 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 5530 } 5531 } 5532 #endif 5533 5534 #ifdef ENABLE_LE_PERIPHERAL 5535 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5536 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){ 5537 uint8_t operation = 0; 5538 if (pos == 0){ 5539 // first fragment or complete data 5540 operation |= 1; 5541 } 5542 if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){ 5543 // last fragment or complete data 5544 operation |= 2; 5545 } 5546 return operation; 5547 } 5548 #endif 5549 #endif 5550 5551 static bool hci_run_general_gap_le(void){ 5552 5553 btstack_linked_list_iterator_t lit; 5554 5555 // Phase 1: collect what to stop 5556 5557 #ifdef ENABLE_LE_CENTRAL 5558 bool scanning_stop = false; 5559 bool connecting_stop = false; 5560 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5561 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5562 bool periodic_sync_stop = false; 5563 #endif 5564 #endif 5565 #endif 5566 5567 #ifdef ENABLE_LE_PERIPHERAL 5568 bool advertising_stop = false; 5569 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5570 le_advertising_set_t * advertising_stop_set = NULL; 5571 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5572 bool periodic_advertising_stop = false; 5573 #endif 5574 #endif 5575 #endif 5576 5577 // check if own address changes 5578 bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0; 5579 5580 // check if whitelist needs modification 5581 bool whitelist_modification_pending = false; 5582 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 5583 while (btstack_linked_list_iterator_has_next(&lit)){ 5584 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 5585 if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){ 5586 whitelist_modification_pending = true; 5587 break; 5588 } 5589 } 5590 5591 // check if resolving list needs modification 5592 bool resolving_list_modification_pending = false; 5593 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 5594 bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE); 5595 if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){ 5596 resolving_list_modification_pending = true; 5597 } 5598 #endif 5599 5600 #ifdef ENABLE_LE_CENTRAL 5601 5602 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5603 // check if periodic advertiser list needs modification 5604 bool periodic_list_modification_pending = false; 5605 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 5606 while (btstack_linked_list_iterator_has_next(&lit)){ 5607 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 5608 if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){ 5609 periodic_list_modification_pending = true; 5610 break; 5611 } 5612 } 5613 #endif 5614 5615 // scanning control 5616 if (hci_stack->le_scanning_active) { 5617 // stop if: 5618 // - parameter change required 5619 // - it's disabled 5620 // - whitelist change required but used for scanning 5621 // - resolving list modified 5622 // - own address changes 5623 bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1; 5624 if ((hci_stack->le_scanning_param_update) || 5625 !hci_stack->le_scanning_enabled || 5626 (scanning_uses_whitelist && whitelist_modification_pending) || 5627 resolving_list_modification_pending || 5628 random_address_change){ 5629 5630 scanning_stop = true; 5631 } 5632 } 5633 5634 // connecting control 5635 bool connecting_with_whitelist; 5636 switch (hci_stack->le_connecting_state){ 5637 case LE_CONNECTING_DIRECT: 5638 case LE_CONNECTING_WHITELIST: 5639 // stop connecting if: 5640 // - connecting uses white and whitelist modification pending 5641 // - if it got disabled 5642 // - resolving list modified 5643 // - own address changes 5644 connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST; 5645 if ((connecting_with_whitelist && whitelist_modification_pending) || 5646 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) || 5647 resolving_list_modification_pending || 5648 random_address_change) { 5649 5650 connecting_stop = true; 5651 } 5652 break; 5653 default: 5654 break; 5655 } 5656 5657 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5658 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5659 // periodic sync control 5660 bool sync_with_advertiser_list; 5661 switch(hci_stack->le_periodic_sync_state){ 5662 case LE_CONNECTING_DIRECT: 5663 case LE_CONNECTING_WHITELIST: 5664 // stop sync if: 5665 // - sync with advertiser list and advertiser list modification pending 5666 // - if it got disabled 5667 sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST; 5668 if ((sync_with_advertiser_list && periodic_list_modification_pending) || 5669 (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){ 5670 periodic_sync_stop = true; 5671 } 5672 break; 5673 default: 5674 break; 5675 } 5676 #endif 5677 #endif 5678 5679 #endif /* ENABLE_LE_CENTRAL */ 5680 5681 #ifdef ENABLE_LE_PERIPHERAL 5682 // le advertisement control 5683 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){ 5684 // stop if: 5685 // - parameter change required 5686 // - random address used in advertising and changes 5687 // - it's disabled 5688 // - whitelist change required but used for advertisement filter policy 5689 // - resolving list modified 5690 // - own address changes 5691 bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0; 5692 bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC; 5693 bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0; 5694 if (advertising_change || 5695 (advertising_uses_random_address && random_address_change) || 5696 (hci_stack->le_advertisements_enabled_for_current_roles == 0) || 5697 (advertising_uses_whitelist && whitelist_modification_pending) || 5698 resolving_list_modification_pending || 5699 random_address_change) { 5700 5701 advertising_stop = true; 5702 } 5703 } 5704 5705 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5706 if (hci_extended_advertising_supported() && (advertising_stop == false)){ 5707 btstack_linked_list_iterator_t it; 5708 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 5709 while (btstack_linked_list_iterator_has_next(&it)){ 5710 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 5711 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) { 5712 // stop if: 5713 // - parameter change required 5714 // - random address used in connectable advertising and changes 5715 // - it's disabled 5716 // - whitelist change required but used for advertisement filter policy 5717 // - resolving list modified 5718 // - own address changes 5719 // - advertisement set will be removed 5720 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0; 5721 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0; 5722 bool advertising_uses_random_address = 5723 (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) && 5724 advertising_connectable; 5725 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0; 5726 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0; 5727 bool advertising_set_random_address_change = 5728 (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0; 5729 bool advertising_set_will_be_removed = 5730 (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0; 5731 if (advertising_parameter_change || 5732 (advertising_uses_random_address && advertising_set_random_address_change) || 5733 (advertising_enabled == false) || 5734 (advertising_uses_whitelist && whitelist_modification_pending) || 5735 resolving_list_modification_pending || 5736 advertising_set_will_be_removed) { 5737 5738 advertising_stop = true; 5739 advertising_stop_set = advertising_set; 5740 break; 5741 } 5742 } 5743 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5744 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) { 5745 // stop if: 5746 // - it's disabled 5747 // - parameter change required 5748 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0; 5749 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0; 5750 if ((periodic_enabled == false) || periodic_parameter_change){ 5751 periodic_advertising_stop = true; 5752 advertising_stop_set = advertising_set; 5753 } 5754 } 5755 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5756 } 5757 } 5758 #endif 5759 5760 #endif 5761 5762 5763 // Phase 2: stop everything that should be off during modifications 5764 5765 5766 // 2.1 Outgoing connection 5767 #ifdef ENABLE_LE_CENTRAL 5768 if (connecting_stop){ 5769 hci_send_cmd(&hci_le_create_connection_cancel); 5770 return true; 5771 } 5772 #endif 5773 5774 // 2.2 Scanning 5775 #ifdef ENABLE_LE_CENTRAL 5776 if (scanning_stop){ 5777 hci_stack->le_scanning_active = false; 5778 hci_le_scan_stop(); 5779 return true; 5780 } 5781 5782 // 2.3 Periodic Sync 5783 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5784 if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){ 5785 uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle; 5786 hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID; 5787 hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle); 5788 return true; 5789 } 5790 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5791 if (periodic_sync_stop){ 5792 hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL; 5793 hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel); 5794 return true; 5795 } 5796 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5797 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 5798 #endif /* ENABLE_LE_CENTRAL */ 5799 5800 // 2.4 Advertising: legacy, extended, periodic 5801 #ifdef ENABLE_LE_PERIPHERAL 5802 if (advertising_stop){ 5803 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5804 if (hci_extended_advertising_supported()) { 5805 uint8_t advertising_stop_handle; 5806 if (advertising_stop_set != NULL){ 5807 advertising_stop_handle = advertising_stop_set->advertising_handle; 5808 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5809 } else { 5810 advertising_stop_handle = 0; 5811 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5812 } 5813 const uint8_t advertising_handles[] = { advertising_stop_handle }; 5814 const uint16_t durations[] = { 0 }; 5815 const uint16_t max_events[] = { 0 }; 5816 hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events); 5817 } else 5818 #endif 5819 { 5820 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5821 hci_send_cmd(&hci_le_set_advertise_enable, 0); 5822 } 5823 return true; 5824 } 5825 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5826 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5827 if (periodic_advertising_stop){ 5828 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 5829 hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle); 5830 return true; 5831 } 5832 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5833 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 5834 #endif /* ENABLE_LE_PERIPHERAL */ 5835 5836 5837 // Phase 3: modify 5838 5839 if (random_address_change){ 5840 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 5841 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5842 if (hci_extended_advertising_supported()) { 5843 hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address); 5844 } 5845 #endif 5846 { 5847 hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address); 5848 } 5849 return true; 5850 } 5851 5852 #ifdef ENABLE_LE_CENTRAL 5853 if (hci_stack->le_scanning_param_update){ 5854 hci_stack->le_scanning_param_update = false; 5855 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5856 if (hci_extended_advertising_supported()){ 5857 // prepare arrays for all PHYs 5858 uint8_t scan_types[1] = { hci_stack->le_scan_type }; 5859 uint16_t scan_intervals[1] = { hci_stack->le_scan_interval }; 5860 uint16_t scan_windows[1] = { hci_stack->le_scan_window }; 5861 uint8_t scanning_phys = 1; // LE 1M PHY 5862 hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type, 5863 hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows); 5864 } else 5865 #endif 5866 { 5867 hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, 5868 hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy); 5869 } 5870 return true; 5871 } 5872 #endif 5873 5874 #ifdef ENABLE_LE_PERIPHERAL 5875 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){ 5876 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 5877 hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type; 5878 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5879 if (hci_extended_advertising_supported()){ 5880 // map advertisment type to advertising event properties 5881 uint16_t adv_event_properties = 0; 5882 const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000}; 5883 if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){ 5884 adv_event_properties = mapping[hci_stack->le_advertisements_type]; 5885 } 5886 hci_stack->le_advertising_set_in_current_command = 0; 5887 hci_send_cmd(&hci_le_set_extended_advertising_parameters, 5888 0, 5889 adv_event_properties, 5890 hci_stack->le_advertisements_interval_min, 5891 hci_stack->le_advertisements_interval_max, 5892 hci_stack->le_advertisements_channel_map, 5893 hci_stack->le_advertisements_own_addr_type, 5894 hci_stack->le_advertisements_direct_address_type, 5895 hci_stack->le_advertisements_direct_address, 5896 hci_stack->le_advertisements_filter_policy, 5897 0x7f, // tx power: no preference 5898 0x01, // primary adv phy: LE 1M 5899 0, // secondary adv max skip 5900 0, // secondary adv phy 5901 0, // adv sid 5902 0 // scan request notification 5903 ); 5904 } 5905 #endif 5906 { 5907 hci_send_cmd(&hci_le_set_advertising_parameters, 5908 hci_stack->le_advertisements_interval_min, 5909 hci_stack->le_advertisements_interval_max, 5910 hci_stack->le_advertisements_type, 5911 hci_stack->le_advertisements_own_addr_type, 5912 hci_stack->le_advertisements_direct_address_type, 5913 hci_stack->le_advertisements_direct_address, 5914 hci_stack->le_advertisements_channel_map, 5915 hci_stack->le_advertisements_filter_policy); 5916 } 5917 return true; 5918 } 5919 5920 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){ 5921 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 5922 uint8_t adv_data_clean[31]; 5923 memset(adv_data_clean, 0, sizeof(adv_data_clean)); 5924 (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data, 5925 hci_stack->le_advertisements_data_len); 5926 btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr); 5927 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5928 if (hci_extended_advertising_supported()){ 5929 hci_stack->le_advertising_set_in_current_command = 0; 5930 hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean); 5931 } else 5932 #endif 5933 { 5934 hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean); 5935 } 5936 return true; 5937 } 5938 5939 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){ 5940 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 5941 uint8_t scan_data_clean[31]; 5942 memset(scan_data_clean, 0, sizeof(scan_data_clean)); 5943 (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data, 5944 hci_stack->le_scan_response_data_len); 5945 btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr); 5946 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5947 if (hci_extended_advertising_supported()){ 5948 hci_stack->le_advertising_set_in_current_command = 0; 5949 hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean); 5950 } else 5951 #endif 5952 { 5953 hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean); 5954 } 5955 return true; 5956 } 5957 5958 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5959 if (hci_extended_advertising_supported()) { 5960 btstack_linked_list_iterator_t it; 5961 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 5962 while (btstack_linked_list_iterator_has_next(&it)){ 5963 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 5964 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) { 5965 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET; 5966 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5967 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle); 5968 return true; 5969 } 5970 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){ 5971 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 5972 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address); 5973 return true; 5974 } 5975 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){ 5976 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 5977 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5978 hci_send_cmd(&hci_le_set_extended_advertising_parameters, 5979 advertising_set->advertising_handle, 5980 advertising_set->extended_params.advertising_event_properties, 5981 advertising_set->extended_params.primary_advertising_interval_min, 5982 advertising_set->extended_params.primary_advertising_interval_max, 5983 advertising_set->extended_params.primary_advertising_channel_map, 5984 advertising_set->extended_params.own_address_type, 5985 advertising_set->extended_params.peer_address_type, 5986 advertising_set->extended_params.peer_address, 5987 advertising_set->extended_params.advertising_filter_policy, 5988 advertising_set->extended_params.advertising_tx_power, 5989 advertising_set->extended_params.primary_advertising_phy, 5990 advertising_set->extended_params.secondary_advertising_max_skip, 5991 advertising_set->extended_params.secondary_advertising_phy, 5992 advertising_set->extended_params.advertising_sid, 5993 advertising_set->extended_params.scan_request_notification_enable 5994 ); 5995 return true; 5996 } 5997 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) { 5998 uint16_t pos = advertising_set->adv_data_pos; 5999 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len); 6000 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 6001 if ((operation & 0x02) != 0){ 6002 // last fragment or complete data 6003 operation |= 2; 6004 advertising_set->adv_data_pos = 0; 6005 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 6006 } else { 6007 advertising_set->adv_data_pos += data_to_upload; 6008 } 6009 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 6010 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]); 6011 return true; 6012 } 6013 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) { 6014 uint16_t pos = advertising_set->scan_data_pos; 6015 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len); 6016 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 6017 if ((operation & 0x02) != 0){ 6018 advertising_set->scan_data_pos = 0; 6019 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 6020 } else { 6021 advertising_set->scan_data_pos += data_to_upload; 6022 } 6023 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 6024 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]); 6025 return true; 6026 } 6027 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 6028 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){ 6029 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS; 6030 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 6031 hci_send_cmd(&hci_le_set_periodic_advertising_parameters, 6032 advertising_set->advertising_handle, 6033 advertising_set->periodic_params.periodic_advertising_interval_min, 6034 advertising_set->periodic_params.periodic_advertising_interval_max, 6035 advertising_set->periodic_params.periodic_advertising_properties); 6036 return true; 6037 } 6038 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) { 6039 uint16_t pos = advertising_set->periodic_data_pos; 6040 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len); 6041 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 6042 if ((operation & 0x02) != 0){ 6043 // last fragment or complete data 6044 operation |= 2; 6045 advertising_set->periodic_data_pos = 0; 6046 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA; 6047 } else { 6048 advertising_set->periodic_data_pos += data_to_upload; 6049 } 6050 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 6051 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]); 6052 return true; 6053 } 6054 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 6055 } 6056 } 6057 #endif 6058 6059 #endif 6060 6061 #ifdef ENABLE_LE_CENTRAL 6062 // if connect with whitelist was active and is not cancelled yet, wait until next time 6063 if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false; 6064 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6065 // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time 6066 if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false; 6067 #endif 6068 #endif 6069 6070 // LE Whitelist Management 6071 if (whitelist_modification_pending){ 6072 // add/remove entries 6073 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 6074 while (btstack_linked_list_iterator_has_next(&lit)){ 6075 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 6076 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){ 6077 entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER; 6078 hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address); 6079 return true; 6080 } 6081 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){ 6082 entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER; 6083 entry->state |= LE_WHITELIST_ON_CONTROLLER; 6084 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address); 6085 return true; 6086 } 6087 if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){ 6088 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 6089 btstack_memory_whitelist_entry_free(entry); 6090 } 6091 } 6092 } 6093 6094 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 6095 // LE Resolving List Management 6096 if (resolving_list_supported) { 6097 uint16_t i; 6098 switch (hci_stack->le_resolving_list_state) { 6099 case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION: 6100 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 6101 hci_send_cmd(&hci_le_set_address_resolution_enabled, 1); 6102 return true; 6103 case LE_RESOLVING_LIST_READ_SIZE: 6104 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR; 6105 hci_send_cmd(&hci_le_read_resolving_list_size); 6106 return true; 6107 case LE_RESOLVING_LIST_SEND_CLEAR: 6108 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 6109 (void) memset(hci_stack->le_resolving_list_add_entries, 0xff, 6110 sizeof(hci_stack->le_resolving_list_add_entries)); 6111 (void) memset(hci_stack->le_resolving_list_remove_entries, 0, 6112 sizeof(hci_stack->le_resolving_list_remove_entries)); 6113 hci_send_cmd(&hci_le_clear_resolving_list); 6114 return true; 6115 case LE_RESOLVING_LIST_REMOVE_ENTRIES: 6116 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 6117 uint8_t offset = i >> 3; 6118 uint8_t mask = 1 << (i & 7); 6119 if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue; 6120 hci_stack->le_resolving_list_remove_entries[offset] &= ~mask; 6121 bd_addr_t peer_identity_addreses; 6122 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 6123 sm_key_t peer_irk; 6124 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 6125 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 6126 6127 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE 6128 // trigger whitelist entry 'update' (work around for controller bug) 6129 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 6130 while (btstack_linked_list_iterator_has_next(&lit)) { 6131 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit); 6132 if (entry->address_type != peer_identity_addr_type) continue; 6133 if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue; 6134 log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses)); 6135 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER; 6136 } 6137 #endif 6138 6139 hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type, 6140 peer_identity_addreses); 6141 return true; 6142 } 6143 6144 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES; 6145 6146 /* fall through */ 6147 6148 case LE_RESOLVING_LIST_ADD_ENTRIES: 6149 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 6150 uint8_t offset = i >> 3; 6151 uint8_t mask = 1 << (i & 7); 6152 if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue; 6153 hci_stack->le_resolving_list_add_entries[offset] &= ~mask; 6154 bd_addr_t peer_identity_addreses; 6155 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 6156 sm_key_t peer_irk; 6157 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 6158 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 6159 if (btstack_is_null(peer_irk, 16)) continue; 6160 const uint8_t *local_irk = gap_get_persistent_irk(); 6161 // command uses format specifier 'P' that stores 16-byte value without flip 6162 uint8_t local_irk_flipped[16]; 6163 uint8_t peer_irk_flipped[16]; 6164 reverse_128(local_irk, local_irk_flipped); 6165 reverse_128(peer_irk, peer_irk_flipped); 6166 hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses, 6167 peer_irk_flipped, local_irk_flipped); 6168 return true; 6169 } 6170 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 6171 break; 6172 6173 default: 6174 break; 6175 } 6176 } 6177 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 6178 #endif 6179 6180 #ifdef ENABLE_LE_CENTRAL 6181 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6182 // LE Whitelist Management 6183 if (periodic_list_modification_pending){ 6184 // add/remove entries 6185 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 6186 while (btstack_linked_list_iterator_has_next(&lit)){ 6187 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 6188 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){ 6189 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 6190 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address); 6191 return true; 6192 } 6193 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){ 6194 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 6195 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER; 6196 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid); 6197 return true; 6198 } 6199 if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){ 6200 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry); 6201 btstack_memory_periodic_advertiser_list_entry_free(entry); 6202 } 6203 } 6204 } 6205 #endif 6206 #endif 6207 6208 #ifdef ENABLE_LE_CENTRAL 6209 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6210 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 6211 if (hci_stack->le_past_set_default_params){ 6212 hci_stack->le_past_set_default_params = false; 6213 hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters, 6214 hci_stack->le_past_mode, 6215 hci_stack->le_past_skip, 6216 hci_stack->le_past_sync_timeout, 6217 hci_stack->le_past_cte_type); 6218 return true; 6219 } 6220 #endif 6221 #endif 6222 #endif 6223 6224 // post-pone all actions until stack is fully working 6225 if (hci_stack->state != HCI_STATE_WORKING) return false; 6226 6227 // advertisements, active scanning, and creating connections requires random address to be set if using private address 6228 if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false; 6229 6230 // Phase 4: restore state 6231 6232 #ifdef ENABLE_LE_CENTRAL 6233 // re-start scanning 6234 if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){ 6235 hci_stack->le_scanning_active = true; 6236 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6237 if (hci_extended_advertising_supported()){ 6238 hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0); 6239 } else 6240 #endif 6241 { 6242 hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates); 6243 } 6244 return true; 6245 } 6246 #endif 6247 6248 #ifdef ENABLE_LE_CENTRAL 6249 // re-start connecting 6250 if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){ 6251 bd_addr_t null_addr; 6252 memset(null_addr, 0, 6); 6253 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 6254 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 6255 hci_send_cmd(&hci_le_create_connection, 6256 hci_stack->le_connection_scan_interval, // scan interval: 60 ms 6257 hci_stack->le_connection_scan_window, // scan interval: 30 ms 6258 1, // use whitelist 6259 0, // peer address type 6260 null_addr, // peer bd addr 6261 hci_stack->le_connection_own_addr_type, // our addr type: 6262 hci_stack->le_connection_interval_min, // conn interval min 6263 hci_stack->le_connection_interval_max, // conn interval max 6264 hci_stack->le_connection_latency, // conn latency 6265 hci_stack->le_supervision_timeout, // conn latency 6266 hci_stack->le_minimum_ce_length, // min ce length 6267 hci_stack->le_maximum_ce_length // max ce length 6268 ); 6269 return true; 6270 } 6271 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6272 if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){ 6273 switch(hci_stack->le_periodic_sync_request){ 6274 case LE_CONNECTING_DIRECT: 6275 case LE_CONNECTING_WHITELIST: 6276 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT; 6277 hci_send_cmd(&hci_le_periodic_advertising_create_sync, 6278 hci_stack->le_periodic_sync_options, 6279 hci_stack->le_periodic_sync_advertising_sid, 6280 hci_stack->le_periodic_sync_advertiser_address_type, 6281 hci_stack->le_periodic_sync_advertiser_address, 6282 hci_stack->le_periodic_sync_skip, 6283 hci_stack->le_periodic_sync_timeout, 6284 hci_stack->le_periodic_sync_cte_type); 6285 return true; 6286 default: 6287 break; 6288 } 6289 } 6290 #endif 6291 #endif 6292 6293 #ifdef ENABLE_LE_PERIPHERAL 6294 // re-start advertising 6295 if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){ 6296 // check if advertisements should be enabled given 6297 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE; 6298 hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address); 6299 6300 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6301 if (hci_extended_advertising_supported()){ 6302 const uint8_t advertising_handles[] = { 0 }; 6303 const uint16_t durations[] = { 0 }; 6304 const uint16_t max_events[] = { 0 }; 6305 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events); 6306 } else 6307 #endif 6308 { 6309 hci_send_cmd(&hci_le_set_advertise_enable, 1); 6310 } 6311 return true; 6312 } 6313 6314 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6315 if (hci_extended_advertising_supported()) { 6316 btstack_linked_list_iterator_t it; 6317 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 6318 while (btstack_linked_list_iterator_has_next(&it)) { 6319 le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it); 6320 if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){ 6321 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE; 6322 const uint8_t advertising_handles[] = { advertising_set->advertising_handle }; 6323 const uint16_t durations[] = { advertising_set->enable_timeout }; 6324 const uint16_t max_events[] = { advertising_set->enable_max_scan_events }; 6325 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events); 6326 return true; 6327 } 6328 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 6329 if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){ 6330 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 6331 uint8_t enable = 1; 6332 if (advertising_set->periodic_include_adi){ 6333 enable |= 2; 6334 } 6335 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle); 6336 return true; 6337 } 6338 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 6339 } 6340 } 6341 #endif 6342 #endif 6343 6344 return false; 6345 } 6346 6347 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6348 static bool hci_run_iso_tasks(void){ 6349 btstack_linked_list_iterator_t it; 6350 6351 if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) { 6352 return false; 6353 } 6354 6355 // BIG 6356 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 6357 while (btstack_linked_list_iterator_has_next(&it)){ 6358 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 6359 switch (big->state){ 6360 case LE_AUDIO_BIG_STATE_CREATE: 6361 hci_stack->iso_active_operation_group_id = big->params->big_handle; 6362 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS; 6363 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED; 6364 hci_send_cmd(&hci_le_create_big, 6365 big->params->big_handle, 6366 big->params->advertising_handle, 6367 big->params->num_bis, 6368 big->params->sdu_interval_us, 6369 big->params->max_sdu, 6370 big->params->max_transport_latency_ms, 6371 big->params->rtn, 6372 big->params->phy, 6373 big->params->packing, 6374 big->params->framing, 6375 big->params->encryption, 6376 big->params->broadcast_code); 6377 return true; 6378 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 6379 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH; 6380 hci_send_cmd(&hci_le_setup_iso_data_path, big->bis_con_handles[big->state_vars.next_bis], 0, 0, 0, 0, 0, 0, 0, NULL); 6381 return true; 6382 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED: 6383 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED; 6384 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status); 6385 return true; 6386 case LE_AUDIO_BIG_STATE_TERMINATE: 6387 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 6388 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS); 6389 return true; 6390 default: 6391 break; 6392 } 6393 } 6394 6395 // BIG Sync 6396 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 6397 while (btstack_linked_list_iterator_has_next(&it)){ 6398 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 6399 switch (big_sync->state){ 6400 case LE_AUDIO_BIG_STATE_CREATE: 6401 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle; 6402 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS; 6403 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED; 6404 hci_send_cmd(&hci_le_big_create_sync, 6405 big_sync->params->big_handle, 6406 big_sync->params->sync_handle, 6407 big_sync->params->encryption, 6408 big_sync->params->broadcast_code, 6409 big_sync->params->mse, 6410 big_sync->params->big_sync_timeout_10ms, 6411 big_sync->params->num_bis, 6412 big_sync->params->bis_indices); 6413 return true; 6414 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 6415 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH; 6416 hci_send_cmd(&hci_le_setup_iso_data_path, big_sync->bis_con_handles[big_sync->state_vars.next_bis], 1, 0, 0, 0, 0, 0, 0, NULL); 6417 return true; 6418 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED: 6419 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED; 6420 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 6421 return true; 6422 case LE_AUDIO_BIG_STATE_TERMINATE: 6423 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 6424 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 6425 return true; 6426 default: 6427 break; 6428 } 6429 } 6430 6431 // CIG 6432 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs); 6433 while (btstack_linked_list_iterator_has_next(&it)) { 6434 le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it); 6435 uint8_t i; 6436 // Set CIG Parameters 6437 uint8_t cis_id[MAX_NR_CIS]; 6438 uint16_t max_sdu_c_to_p[MAX_NR_CIS]; 6439 uint16_t max_sdu_p_to_c[MAX_NR_CIS]; 6440 uint8_t phy_c_to_p[MAX_NR_CIS]; 6441 uint8_t phy_p_to_c[MAX_NR_CIS]; 6442 uint8_t rtn_c_to_p[MAX_NR_CIS]; 6443 uint8_t rtn_p_to_c[MAX_NR_CIS]; 6444 switch (cig->state) { 6445 case LE_AUDIO_CIG_STATE_CREATE: 6446 hci_stack->iso_active_operation_group_id = cig->params->cig_id; 6447 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6448 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED; 6449 le_audio_cig_params_t * params = cig->params; 6450 for (i = 0; i < params->num_cis; i++) { 6451 le_audio_cis_params_t * cis_params = &cig->params->cis_params[i]; 6452 cis_id[i] = cis_params->cis_id; 6453 max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p; 6454 max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c; 6455 phy_c_to_p[i] = cis_params->phy_c_to_p; 6456 phy_p_to_c[i] = cis_params->phy_p_to_c; 6457 rtn_c_to_p[i] = cis_params->rtn_c_to_p; 6458 rtn_p_to_c[i] = cis_params->rtn_p_to_c; 6459 } 6460 hci_send_cmd(&hci_le_set_cig_parameters, 6461 cig->cig_id, 6462 params->sdu_interval_c_to_p, 6463 params->sdu_interval_p_to_c, 6464 params->worst_case_sca, 6465 params->packing, 6466 params->framing, 6467 params->max_transport_latency_c_to_p, 6468 params->max_transport_latency_p_to_c, 6469 params->num_cis, 6470 cis_id, 6471 max_sdu_c_to_p, 6472 max_sdu_p_to_c, 6473 phy_c_to_p, 6474 phy_p_to_c, 6475 rtn_c_to_p, 6476 rtn_p_to_c 6477 ); 6478 return true; 6479 case LE_AUDIO_CIG_STATE_CREATE_CIS: 6480 hci_stack->iso_active_operation_group_id = cig->params->cig_id; 6481 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6482 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS; 6483 for (i=0;i<cig->num_cis;i++){ 6484 cig->cis_setup_active[i] = true; 6485 } 6486 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles); 6487 return true; 6488 case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH: 6489 while (cig->state_vars.next_cis < (cig->num_cis * 2)){ 6490 // find next path to setup 6491 uint8_t cis_index = cig->state_vars.next_cis >> 1; 6492 if (cig->cis_established[cis_index] == false) { 6493 continue; 6494 } 6495 uint8_t cis_direction = cig->state_vars.next_cis & 1; 6496 bool setup = true; 6497 if (cis_direction == 0){ 6498 // 0 - input - host to controller 6499 // we are central => central to peripheral 6500 setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0; 6501 } else { 6502 // 1 - output - controller to host 6503 // we are central => peripheral to central 6504 setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0; 6505 } 6506 if (setup){ 6507 hci_stack->iso_active_operation_group_id = cig->params->cig_id; 6508 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6509 cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH; 6510 hci_send_cmd(&hci_le_setup_iso_data_path, cig->cis_con_handles[cis_index], cis_direction, 0, 0, 0, 0, 0, 0, NULL); 6511 return true; 6512 } 6513 cig->state_vars.next_cis++; 6514 } 6515 // emit done 6516 cig->state = LE_AUDIO_CIG_STATE_ACTIVE; 6517 default: 6518 break; 6519 } 6520 } 6521 6522 // CIS Accept/Reject 6523 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 6524 while (btstack_linked_list_iterator_has_next(&it)) { 6525 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 6526 hci_con_handle_t con_handle; 6527 switch (iso_stream->state){ 6528 case HCI_ISO_STREAM_W2_ACCEPT: 6529 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED; 6530 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6531 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS; 6532 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->con_handle); 6533 return true; 6534 case HCI_ISO_STREAM_W2_REJECT: 6535 con_handle = iso_stream->con_handle; 6536 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6537 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS; 6538 hci_iso_stream_finalize(iso_stream); 6539 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES); 6540 return true; 6541 case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT: 6542 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS; 6543 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6544 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT; 6545 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 0, 0, 0, 0, 0, 0, 0, NULL); 6546 break; 6547 case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT: 6548 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS; 6549 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS; 6550 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT; 6551 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->con_handle, 1, 0, 0, 0, 0, 0, 0, NULL); 6552 break; 6553 default: 6554 break; 6555 } 6556 } 6557 6558 return false; 6559 } 6560 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 6561 #endif 6562 6563 static bool hci_run_general_pending_commands(void){ 6564 btstack_linked_item_t * it; 6565 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 6566 hci_connection_t * connection = (hci_connection_t *) it; 6567 6568 switch(connection->state){ 6569 case SEND_CREATE_CONNECTION: 6570 switch(connection->address_type){ 6571 #ifdef ENABLE_CLASSIC 6572 case BD_ADDR_TYPE_ACL: 6573 log_info("sending hci_create_connection"); 6574 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch); 6575 break; 6576 #endif 6577 default: 6578 #ifdef ENABLE_BLE 6579 #ifdef ENABLE_LE_CENTRAL 6580 log_info("sending hci_le_create_connection"); 6581 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 6582 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 6583 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6584 if (hci_extended_advertising_supported()) { 6585 uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval }; 6586 uint16_t le_connection_scan_window[1] = { hci_stack->le_connection_scan_window }; 6587 uint16_t le_connection_interval_min[1] = { hci_stack->le_connection_interval_min }; 6588 uint16_t le_connection_interval_max[1] = { hci_stack->le_connection_interval_max }; 6589 uint16_t le_connection_latency[1] = { hci_stack->le_connection_latency }; 6590 uint16_t le_supervision_timeout[1] = { hci_stack->le_supervision_timeout }; 6591 uint16_t le_minimum_ce_length[1] = { hci_stack->le_minimum_ce_length }; 6592 uint16_t le_maximum_ce_length[1] = { hci_stack->le_maximum_ce_length }; 6593 hci_send_cmd(&hci_le_extended_create_connection, 6594 0, // don't use whitelist 6595 hci_stack->le_connection_own_addr_type, // our addr type: 6596 connection->address_type, // peer address type 6597 connection->address, // peer bd addr 6598 1, // initiating PHY - 1M 6599 le_connection_scan_interval, // conn scan interval 6600 le_connection_scan_window, // conn scan windows 6601 le_connection_interval_min, // conn interval min 6602 le_connection_interval_max, // conn interval max 6603 le_connection_latency, // conn latency 6604 le_supervision_timeout, // conn latency 6605 le_minimum_ce_length, // min ce length 6606 le_maximum_ce_length // max ce length 6607 ); } 6608 else 6609 #endif 6610 { 6611 hci_send_cmd(&hci_le_create_connection, 6612 hci_stack->le_connection_scan_interval, // conn scan interval 6613 hci_stack->le_connection_scan_window, // conn scan windows 6614 0, // don't use whitelist 6615 connection->address_type, // peer address type 6616 connection->address, // peer bd addr 6617 hci_stack->le_connection_own_addr_type, // our addr type: 6618 hci_stack->le_connection_interval_min, // conn interval min 6619 hci_stack->le_connection_interval_max, // conn interval max 6620 hci_stack->le_connection_latency, // conn latency 6621 hci_stack->le_supervision_timeout, // conn latency 6622 hci_stack->le_minimum_ce_length, // min ce length 6623 hci_stack->le_maximum_ce_length // max ce length 6624 ); 6625 } 6626 connection->state = SENT_CREATE_CONNECTION; 6627 #endif 6628 #endif 6629 break; 6630 } 6631 return true; 6632 6633 #ifdef ENABLE_CLASSIC 6634 case RECEIVED_CONNECTION_REQUEST: 6635 connection->role = HCI_ROLE_SLAVE; 6636 if (connection->address_type == BD_ADDR_TYPE_ACL){ 6637 log_info("sending hci_accept_connection_request"); 6638 connection->state = ACCEPTED_CONNECTION_REQUEST; 6639 hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy); 6640 return true; 6641 } 6642 break; 6643 #endif 6644 case SEND_DISCONNECT: 6645 connection->state = SENT_DISCONNECT; 6646 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 6647 return true; 6648 6649 default: 6650 break; 6651 } 6652 6653 // no further commands if connection is about to get shut down 6654 if (connection->state == SENT_DISCONNECT) continue; 6655 6656 #ifdef ENABLE_CLASSIC 6657 6658 // Handling link key request requires remote supported features 6659 if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){ 6660 log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL); 6661 connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST); 6662 6663 bool have_link_key = connection->link_key_type != INVALID_LINK_KEY; 6664 bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level); 6665 if (have_link_key && security_level_sufficient){ 6666 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key); 6667 } else { 6668 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 6669 } 6670 return true; 6671 } 6672 6673 if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){ 6674 log_info("denying to pin request"); 6675 connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST); 6676 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 6677 return true; 6678 } 6679 6680 // security assessment requires remote features 6681 if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){ 6682 connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST); 6683 hci_ssp_assess_security_on_io_cap_request(connection); 6684 // no return here as hci_ssp_assess_security_on_io_cap_request only sets AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY or AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY 6685 } 6686 6687 if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){ 6688 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 6689 // set authentication requirements: 6690 // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic) 6691 // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote 6692 uint8_t authreq = hci_stack->ssp_authentication_requirement & 1; 6693 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 6694 authreq |= 1; 6695 } 6696 bool bonding = hci_stack->bondable; 6697 if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){ 6698 // if we have received IO Cap Response, we're in responder role 6699 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 6700 if (bonding && !remote_bonding){ 6701 log_info("Remote not bonding, dropping local flag"); 6702 bonding = false; 6703 } 6704 } 6705 if (bonding){ 6706 if (connection->bonding_flags & BONDING_DEDICATED){ 6707 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 6708 } else { 6709 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 6710 } 6711 } 6712 uint8_t have_oob_data = 0; 6713 #ifdef ENABLE_CLASSIC_PAIRING_OOB 6714 if (connection->classic_oob_c_192 != NULL){ 6715 have_oob_data |= 1; 6716 } 6717 if (connection->classic_oob_c_256 != NULL){ 6718 have_oob_data |= 2; 6719 } 6720 #endif 6721 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq); 6722 return true; 6723 } 6724 6725 if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) { 6726 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 6727 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 6728 return true; 6729 } 6730 6731 #ifdef ENABLE_CLASSIC_PAIRING_OOB 6732 if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){ 6733 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY); 6734 const uint8_t zero[16] = { 0 }; 6735 const uint8_t * r_192 = zero; 6736 const uint8_t * c_192 = zero; 6737 const uint8_t * r_256 = zero; 6738 const uint8_t * c_256 = zero; 6739 // verify P-256 OOB 6740 if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) { 6741 c_256 = connection->classic_oob_c_256; 6742 if (connection->classic_oob_r_256 != NULL) { 6743 r_256 = connection->classic_oob_r_256; 6744 } 6745 } 6746 // verify P-192 OOB 6747 if ((connection->classic_oob_c_192 != NULL)) { 6748 c_192 = connection->classic_oob_c_192; 6749 if (connection->classic_oob_r_192 != NULL) { 6750 r_192 = connection->classic_oob_r_192; 6751 } 6752 } 6753 6754 // assess security 6755 bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4); 6756 bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL); 6757 if (need_level_4 && !can_reach_level_4){ 6758 log_info("Level 4 required, but not possible -> abort"); 6759 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY); 6760 // send oob negative reply 6761 c_256 = NULL; 6762 c_192 = NULL; 6763 } 6764 6765 // Reply 6766 if (c_256 != zero) { 6767 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256); 6768 } else if (c_192 != zero){ 6769 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192); 6770 } else { 6771 hci_stack->classic_oob_con_handle = connection->con_handle; 6772 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address); 6773 } 6774 return true; 6775 } 6776 #endif 6777 6778 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){ 6779 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY); 6780 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 6781 return true; 6782 } 6783 6784 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){ 6785 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY); 6786 hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address); 6787 return true; 6788 } 6789 6790 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){ 6791 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY); 6792 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 6793 return true; 6794 } 6795 6796 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 6797 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 6798 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 6799 connection->state = SENT_DISCONNECT; 6800 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 6801 return true; 6802 } 6803 6804 if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){ 6805 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 6806 connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST; 6807 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 6808 return true; 6809 } 6810 6811 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 6812 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 6813 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 6814 return true; 6815 } 6816 6817 if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){ 6818 connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 6819 hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1); 6820 return true; 6821 } 6822 6823 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){ 6824 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0; 6825 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 6826 return true; 6827 } 6828 6829 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){ 6830 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1; 6831 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1); 6832 return true; 6833 } 6834 6835 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){ 6836 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2; 6837 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2); 6838 return true; 6839 } 6840 #endif 6841 6842 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 6843 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 6844 #ifdef ENABLE_CLASSIC 6845 hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS); 6846 #endif 6847 if (connection->state != SENT_DISCONNECT){ 6848 connection->state = SENT_DISCONNECT; 6849 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE); 6850 return true; 6851 } 6852 } 6853 6854 #ifdef ENABLE_CLASSIC 6855 uint16_t sniff_min_interval; 6856 switch (connection->sniff_min_interval){ 6857 case 0: 6858 break; 6859 case 0xffff: 6860 connection->sniff_min_interval = 0; 6861 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle); 6862 return true; 6863 default: 6864 sniff_min_interval = connection->sniff_min_interval; 6865 connection->sniff_min_interval = 0; 6866 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout); 6867 return true; 6868 } 6869 6870 if (connection->sniff_subrating_max_latency != 0xffff){ 6871 uint16_t max_latency = connection->sniff_subrating_max_latency; 6872 connection->sniff_subrating_max_latency = 0; 6873 hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout); 6874 return true; 6875 } 6876 6877 if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){ 6878 uint8_t service_type = (uint8_t) connection->qos_service_type; 6879 connection->qos_service_type = HCI_SERVICE_TYPE_INVALID; 6880 hci_send_cmd(&hci_qos_setup, connection->con_handle, 0, service_type, connection->qos_token_rate, connection->qos_peak_bandwidth, connection->qos_latency, connection->qos_delay_variation); 6881 return true; 6882 } 6883 6884 if (connection->request_role != HCI_ROLE_INVALID){ 6885 hci_role_t role = connection->request_role; 6886 connection->request_role = HCI_ROLE_INVALID; 6887 hci_send_cmd(&hci_switch_role_command, connection->address, role); 6888 return true; 6889 } 6890 #endif 6891 6892 if (connection->gap_connection_tasks != 0){ 6893 #ifdef ENABLE_CLASSIC 6894 if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){ 6895 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT; 6896 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout); 6897 return true; 6898 } 6899 if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){ 6900 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT; 6901 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout); 6902 return true; 6903 } 6904 #endif 6905 if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){ 6906 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI; 6907 hci_send_cmd(&hci_read_rssi, connection->con_handle); 6908 return true; 6909 } 6910 } 6911 6912 #ifdef ENABLE_BLE 6913 switch (connection->le_con_parameter_update_state){ 6914 // response to L2CAP CON PARAMETER UPDATE REQUEST 6915 case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS: 6916 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6917 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min, 6918 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 6919 0x0000, 0xffff); 6920 return true; 6921 case CON_PARAMETER_UPDATE_REPLY: 6922 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6923 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min, 6924 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 6925 0x0000, 0xffff); 6926 return true; 6927 case CON_PARAMETER_UPDATE_NEGATIVE_REPLY: 6928 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6929 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle, 6930 ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS); 6931 return true; 6932 default: 6933 break; 6934 } 6935 if (connection->le_phy_update_all_phys != 0xffu){ 6936 uint8_t all_phys = connection->le_phy_update_all_phys; 6937 connection->le_phy_update_all_phys = 0xff; 6938 hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options); 6939 return true; 6940 } 6941 #endif 6942 } 6943 return false; 6944 } 6945 6946 static void hci_run(void){ 6947 6948 // stack state sub statemachines 6949 switch (hci_stack->state) { 6950 case HCI_STATE_INITIALIZING: 6951 hci_initializing_run(); 6952 break; 6953 case HCI_STATE_HALTING: 6954 hci_halting_run(); 6955 break; 6956 case HCI_STATE_FALLING_ASLEEP: 6957 hci_falling_asleep_run(); 6958 break; 6959 default: 6960 break; 6961 } 6962 6963 // allow to run after initialization to working transition 6964 if (hci_stack->state != HCI_STATE_WORKING){ 6965 return; 6966 } 6967 6968 bool done; 6969 6970 // send continuation fragments first, as they block the prepared packet buffer 6971 done = hci_run_acl_fragments(); 6972 if (done) return; 6973 6974 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6975 done = hci_run_iso_fragments(); 6976 if (done) return; 6977 #endif 6978 6979 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 6980 // send host num completed packets next as they don't require num_cmd_packets > 0 6981 if (!hci_can_send_comand_packet_transport()) return; 6982 if (hci_stack->host_completed_packets){ 6983 hci_host_num_completed_packets(); 6984 return; 6985 } 6986 #endif 6987 6988 if (!hci_can_send_command_packet_now()) return; 6989 6990 // global/non-connection oriented commands 6991 6992 6993 #ifdef ENABLE_CLASSIC 6994 // general gap classic 6995 done = hci_run_general_gap_classic(); 6996 if (done) return; 6997 #endif 6998 6999 #ifdef ENABLE_BLE 7000 // general gap le 7001 done = hci_run_general_gap_le(); 7002 if (done) return; 7003 7004 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 7005 // ISO related tasks, e.g. BIG create/terminate/sync 7006 done = hci_run_iso_tasks(); 7007 if (done) return; 7008 #endif 7009 #endif 7010 7011 // send pending HCI commands 7012 hci_run_general_pending_commands(); 7013 } 7014 7015 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){ 7016 // house-keeping 7017 7018 #ifdef ENABLE_CLASSIC 7019 bd_addr_t addr; 7020 hci_connection_t * conn; 7021 #endif 7022 #ifdef ENABLE_LE_CENTRAL 7023 uint8_t initiator_filter_policy; 7024 #endif 7025 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 7026 uint8_t i; 7027 uint8_t num_cis; 7028 hci_con_handle_t cis_handle; 7029 uint8_t status; 7030 #endif 7031 7032 uint16_t opcode = little_endian_read_16(packet, 0); 7033 switch (opcode) { 7034 case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE: 7035 hci_stack->loopback_mode = packet[3]; 7036 break; 7037 7038 #ifdef ENABLE_CLASSIC 7039 case HCI_OPCODE_HCI_CREATE_CONNECTION: 7040 reverse_bd_addr(&packet[3], addr); 7041 log_info("Create_connection to %s", bd_addr_to_str(addr)); 7042 7043 // CVE-2020-26555: reject outgoing connection to device with same BD ADDR 7044 if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) { 7045 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR); 7046 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR; 7047 } 7048 7049 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 7050 if (!conn) { 7051 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 7052 if (!conn) { 7053 // notify client that alloc failed 7054 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 7055 return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller 7056 } 7057 conn->state = SEND_CREATE_CONNECTION; 7058 conn->role = HCI_ROLE_MASTER; 7059 } 7060 7061 log_info("conn state %u", conn->state); 7062 // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used 7063 switch (conn->state) { 7064 // if connection active exists 7065 case OPEN: 7066 // and OPEN, emit connection complete command 7067 hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS); 7068 // packet not sent to controller 7069 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 7070 case RECEIVED_DISCONNECTION_COMPLETE: 7071 // create connection triggered in disconnect complete event, let's do it now 7072 break; 7073 case SEND_CREATE_CONNECTION: 7074 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 7075 if (hci_classic_operation_active()){ 7076 return ERROR_CODE_SUCCESS; 7077 } 7078 #endif 7079 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now 7080 break; 7081 default: 7082 // otherwise, just ignore as it is already in the open process 7083 // packet not sent to controller 7084 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 7085 } 7086 conn->state = SENT_CREATE_CONNECTION; 7087 7088 // track outgoing connection 7089 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL; 7090 (void) memcpy(hci_stack->outgoing_addr, addr, 6); 7091 break; 7092 7093 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT) 7094 case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION: 7095 // setup_synchronous_connection? Voice setting at offset 22 7096 // TODO: compare to current setting if sco connection already active 7097 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15); 7098 break; 7099 case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION: 7100 // accept_synchronous_connection? Voice setting at offset 18 7101 // TODO: compare to current setting if sco connection already active 7102 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19); 7103 // track outgoing connection 7104 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO; 7105 reverse_bd_addr(&packet[3], hci_stack->outgoing_addr); 7106 break; 7107 #endif 7108 #endif 7109 7110 #ifdef ENABLE_BLE 7111 #ifdef ENABLE_LE_CENTRAL 7112 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION: 7113 // white list used? 7114 initiator_filter_policy = packet[7]; 7115 switch (initiator_filter_policy) { 7116 case 0: 7117 // whitelist not used 7118 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT; 7119 break; 7120 case 1: 7121 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST; 7122 break; 7123 default: 7124 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy); 7125 break; 7126 } 7127 // track outgoing connection 7128 hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type 7129 reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address 7130 break; 7131 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL: 7132 hci_stack->le_connecting_state = LE_CONNECTING_CANCEL; 7133 break; 7134 #endif 7135 #endif /* ENABLE_BLE */ 7136 default: 7137 break; 7138 } 7139 7140 hci_stack->num_cmd_packets--; 7141 7142 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 7143 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 7144 if (err != 0){ 7145 return ERROR_CODE_HARDWARE_FAILURE; 7146 } 7147 return ERROR_CODE_SUCCESS; 7148 } 7149 7150 // disconnect because of security block 7151 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 7152 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7153 if (!connection) return; 7154 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 7155 } 7156 7157 7158 // Configure Secure Simple Pairing 7159 7160 #ifdef ENABLE_CLASSIC 7161 7162 // enable will enable SSP during init 7163 void gap_ssp_set_enable(int enable){ 7164 hci_stack->ssp_enable = enable; 7165 } 7166 7167 static int hci_local_ssp_activated(void){ 7168 return gap_ssp_supported() && hci_stack->ssp_enable; 7169 } 7170 7171 // if set, BTstack will respond to io capability request using authentication requirement 7172 void gap_ssp_set_io_capability(int io_capability){ 7173 hci_stack->ssp_io_capability = io_capability; 7174 } 7175 void gap_ssp_set_authentication_requirement(int authentication_requirement){ 7176 hci_stack->ssp_authentication_requirement = authentication_requirement; 7177 } 7178 7179 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 7180 void gap_ssp_set_auto_accept(int auto_accept){ 7181 hci_stack->ssp_auto_accept = auto_accept; 7182 } 7183 7184 void gap_secure_connections_enable(bool enable){ 7185 hci_stack->secure_connections_enable = enable; 7186 } 7187 bool gap_secure_connections_active(void){ 7188 return hci_stack->secure_connections_active; 7189 } 7190 7191 #endif 7192 7193 // va_list part of hci_send_cmd 7194 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){ 7195 if (!hci_can_send_command_packet_now()){ 7196 log_error("hci_send_cmd called but cannot send packet now"); 7197 return ERROR_CODE_COMMAND_DISALLOWED; 7198 } 7199 7200 // for HCI INITIALIZATION 7201 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 7202 hci_stack->last_cmd_opcode = cmd->opcode; 7203 7204 hci_reserve_packet_buffer(); 7205 uint8_t * packet = hci_stack->hci_packet_buffer; 7206 uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr); 7207 uint8_t status = hci_send_cmd_packet(packet, size); 7208 7209 // release packet buffer on error or for synchronous transport implementations 7210 if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){ 7211 hci_release_packet_buffer(); 7212 hci_emit_transport_packet_sent(); 7213 } 7214 7215 return status; 7216 } 7217 7218 /** 7219 * pre: numcmds >= 0 - it's allowed to send a command to the controller 7220 */ 7221 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){ 7222 va_list argptr; 7223 va_start(argptr, cmd); 7224 uint8_t status = hci_send_cmd_va_arg(cmd, argptr); 7225 va_end(argptr); 7226 return status; 7227 } 7228 7229 // Create various non-HCI events. 7230 // TODO: generalize, use table similar to hci_create_command 7231 7232 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){ 7233 // dump packet 7234 if (dump) { 7235 hci_dump_packet( HCI_EVENT_PACKET, 1, event, size); 7236 } 7237 7238 // dispatch to all event handlers 7239 btstack_linked_list_iterator_t it; 7240 btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers); 7241 while (btstack_linked_list_iterator_has_next(&it)){ 7242 btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it); 7243 entry->callback(HCI_EVENT_PACKET, 0, event, size); 7244 } 7245 } 7246 7247 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){ 7248 if (!hci_stack->acl_packet_handler) return; 7249 hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size); 7250 } 7251 7252 #ifdef ENABLE_CLASSIC 7253 static void hci_notify_if_sco_can_send_now(void){ 7254 // notify SCO sender if waiting 7255 if (!hci_stack->sco_waiting_for_can_send_now) return; 7256 if (hci_can_send_sco_packet_now()){ 7257 hci_stack->sco_waiting_for_can_send_now = 0; 7258 uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 }; 7259 hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event)); 7260 hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event)); 7261 } 7262 } 7263 7264 // parsing end emitting has been merged to reduce code size 7265 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) { 7266 uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN]; 7267 7268 uint8_t * eir_data; 7269 ad_context_t context; 7270 const uint8_t * name; 7271 uint8_t name_len; 7272 7273 if (size < 3) return; 7274 7275 int event_type = hci_event_packet_get_type(packet); 7276 int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1; // 2 for old event, 1 otherwise 7277 int num_responses = hci_event_inquiry_result_get_num_responses(packet); 7278 7279 switch (event_type){ 7280 case HCI_EVENT_INQUIRY_RESULT: 7281 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 7282 if (size != (3 + (num_responses * 14))) return; 7283 break; 7284 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 7285 if (size != 257) return; 7286 if (num_responses != 1) return; 7287 break; 7288 default: 7289 return; 7290 } 7291 7292 // event[1] is set at the end 7293 int i; 7294 for (i=0; i<num_responses;i++){ 7295 memset(event, 0, sizeof(event)); 7296 event[0] = GAP_EVENT_INQUIRY_RESULT; 7297 uint8_t event_size = 27; // if name is not set by EIR 7298 7299 (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr 7300 event[8] = packet[3 + (num_responses*(6)) + (i*1)]; // page_scan_repetition_mode 7301 (void)memcpy(&event[9], 7302 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)], 7303 3); // class of device 7304 (void)memcpy(&event[12], 7305 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)], 7306 2); // clock offset 7307 7308 switch (event_type){ 7309 case HCI_EVENT_INQUIRY_RESULT: 7310 // 14,15,16,17 = 0, size 18 7311 break; 7312 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 7313 event[14] = 1; 7314 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 7315 // 16,17 = 0, size 18 7316 break; 7317 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 7318 event[14] = 1; 7319 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 7320 // EIR packets only contain a single inquiry response 7321 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)]; 7322 name = NULL; 7323 // Iterate over EIR data 7324 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){ 7325 uint8_t data_type = ad_iterator_get_data_type(&context); 7326 uint8_t data_size = ad_iterator_get_data_len(&context); 7327 const uint8_t * data = ad_iterator_get_data(&context); 7328 // Prefer Complete Local Name over Shortened Local Name 7329 switch (data_type){ 7330 case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME: 7331 if (name) continue; 7332 /* fall through */ 7333 case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME: 7334 name = data; 7335 name_len = data_size; 7336 break; 7337 case BLUETOOTH_DATA_TYPE_DEVICE_ID: 7338 if (data_size != 8) break; 7339 event[16] = 1; 7340 memcpy(&event[17], data, 8); 7341 break; 7342 default: 7343 break; 7344 } 7345 } 7346 if (name){ 7347 event[25] = 1; 7348 // truncate name if needed 7349 int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN); 7350 event[26] = len; 7351 (void)memcpy(&event[27], name, len); 7352 event_size += len; 7353 } 7354 break; 7355 default: 7356 return; 7357 } 7358 event[1] = event_size - 2; 7359 hci_emit_event(event, event_size, 1); 7360 } 7361 } 7362 #endif 7363 7364 void hci_emit_state(void){ 7365 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 7366 uint8_t event[3]; 7367 event[0] = BTSTACK_EVENT_STATE; 7368 event[1] = sizeof(event) - 2u; 7369 event[2] = hci_stack->state; 7370 hci_emit_event(event, sizeof(event), 1); 7371 } 7372 7373 #ifdef ENABLE_CLASSIC 7374 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 7375 uint8_t event[13]; 7376 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 7377 event[1] = sizeof(event) - 2; 7378 event[2] = status; 7379 little_endian_store_16(event, 3, con_handle); 7380 reverse_bd_addr(address, &event[5]); 7381 event[11] = 1; // ACL connection 7382 event[12] = 0; // encryption disabled 7383 hci_emit_event(event, sizeof(event), 1); 7384 } 7385 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 7386 if (disable_l2cap_timeouts) return; 7387 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 7388 uint8_t event[4]; 7389 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 7390 event[1] = sizeof(event) - 2; 7391 little_endian_store_16(event, 2, conn->con_handle); 7392 hci_emit_event(event, sizeof(event), 1); 7393 } 7394 #endif 7395 7396 #ifdef ENABLE_BLE 7397 #ifdef ENABLE_LE_CENTRAL 7398 static void hci_emit_le_connection_complete(uint8_t address_type, const bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 7399 uint8_t event[21]; 7400 event[0] = HCI_EVENT_LE_META; 7401 event[1] = sizeof(event) - 2u; 7402 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 7403 event[3] = status; 7404 little_endian_store_16(event, 4, con_handle); 7405 event[6] = 0; // TODO: role 7406 event[7] = address_type; 7407 reverse_bd_addr(address, &event[8]); 7408 little_endian_store_16(event, 14, 0); // interval 7409 little_endian_store_16(event, 16, 0); // latency 7410 little_endian_store_16(event, 18, 0); // supervision timeout 7411 event[20] = 0; // master clock accuracy 7412 hci_emit_event(event, sizeof(event), 1); 7413 } 7414 #endif 7415 #endif 7416 7417 static void hci_emit_transport_packet_sent(void){ 7418 // notify upper stack that it might be possible to send again 7419 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0}; 7420 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 7421 } 7422 7423 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){ 7424 uint8_t event[6]; 7425 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 7426 event[1] = sizeof(event) - 2u; 7427 event[2] = 0; // status = OK 7428 little_endian_store_16(event, 3, con_handle); 7429 event[5] = reason; 7430 hci_emit_event(event, sizeof(event), 1); 7431 } 7432 7433 static void hci_emit_nr_connections_changed(void){ 7434 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 7435 uint8_t event[3]; 7436 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 7437 event[1] = sizeof(event) - 2u; 7438 event[2] = nr_hci_connections(); 7439 hci_emit_event(event, sizeof(event), 1); 7440 } 7441 7442 static void hci_emit_hci_open_failed(void){ 7443 log_info("BTSTACK_EVENT_POWERON_FAILED"); 7444 uint8_t event[2]; 7445 event[0] = BTSTACK_EVENT_POWERON_FAILED; 7446 event[1] = sizeof(event) - 2u; 7447 hci_emit_event(event, sizeof(event), 1); 7448 } 7449 7450 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 7451 log_info("hci_emit_dedicated_bonding_result %u ", status); 7452 uint8_t event[9]; 7453 int pos = 0; 7454 event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED; 7455 event[pos++] = sizeof(event) - 2u; 7456 event[pos++] = status; 7457 reverse_bd_addr(address, &event[pos]); 7458 hci_emit_event(event, sizeof(event), 1); 7459 } 7460 7461 7462 #ifdef ENABLE_CLASSIC 7463 7464 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 7465 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 7466 uint8_t event[5]; 7467 int pos = 0; 7468 event[pos++] = GAP_EVENT_SECURITY_LEVEL; 7469 event[pos++] = sizeof(event) - 2; 7470 little_endian_store_16(event, 2, con_handle); 7471 pos += 2; 7472 event[pos++] = level; 7473 hci_emit_event(event, sizeof(event), 1); 7474 } 7475 7476 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 7477 if (!connection) return LEVEL_0; 7478 if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 7479 // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key 7480 if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0; 7481 if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0; 7482 gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type); 7483 // LEVEL 4 always requires 128 bit encrytion key size 7484 if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){ 7485 security_level = LEVEL_3; 7486 } 7487 return security_level; 7488 } 7489 7490 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){ 7491 uint8_t event[4]; 7492 event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED; 7493 event[1] = sizeof(event) - 2; 7494 event[2] = discoverable; 7495 event[3] = connectable; 7496 hci_emit_event(event, sizeof(event), 1); 7497 } 7498 7499 // query if remote side supports eSCO 7500 bool hci_remote_esco_supported(hci_con_handle_t con_handle){ 7501 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7502 if (!connection) return false; 7503 return (connection->remote_supported_features[0] & 1) != 0; 7504 } 7505 7506 static bool hci_ssp_supported(hci_connection_t * connection){ 7507 const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST; 7508 return (connection->bonding_flags & mask) == mask; 7509 } 7510 7511 // query if remote side supports SSP 7512 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){ 7513 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7514 if (!connection) return false; 7515 return hci_ssp_supported(connection) ? 1 : 0; 7516 } 7517 7518 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){ 7519 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 7520 } 7521 7522 /** 7523 * Check if remote supported features query has completed 7524 */ 7525 bool hci_remote_features_available(hci_con_handle_t handle){ 7526 hci_connection_t * connection = hci_connection_for_handle(handle); 7527 if (!connection) return false; 7528 return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0; 7529 } 7530 7531 /** 7532 * Trigger remote supported features query 7533 */ 7534 7535 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){ 7536 if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){ 7537 connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0; 7538 } 7539 } 7540 7541 void hci_remote_features_query(hci_con_handle_t con_handle){ 7542 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7543 if (!connection) return; 7544 hci_trigger_remote_features_for_connection(connection); 7545 hci_run(); 7546 } 7547 7548 // GAP API 7549 /** 7550 * @bbrief enable/disable bonding. default is enabled 7551 * @praram enabled 7552 */ 7553 void gap_set_bondable_mode(int enable){ 7554 hci_stack->bondable = enable ? 1 : 0; 7555 } 7556 /** 7557 * @brief Get bondable mode. 7558 * @return 1 if bondable 7559 */ 7560 int gap_get_bondable_mode(void){ 7561 return hci_stack->bondable; 7562 } 7563 7564 /** 7565 * @brief map link keys to security levels 7566 */ 7567 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 7568 switch (link_key_type){ 7569 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7570 return LEVEL_4; 7571 case COMBINATION_KEY: 7572 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 7573 return LEVEL_3; 7574 default: 7575 return LEVEL_2; 7576 } 7577 } 7578 7579 /** 7580 * @brief map link keys to secure connection yes/no 7581 */ 7582 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){ 7583 switch (link_key_type){ 7584 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7585 case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7586 return true; 7587 default: 7588 return false; 7589 } 7590 } 7591 7592 /** 7593 * @brief map link keys to authenticated 7594 */ 7595 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){ 7596 switch (link_key_type){ 7597 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7598 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 7599 return true; 7600 default: 7601 return false; 7602 } 7603 } 7604 7605 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 7606 log_info("gap_mitm_protection_required_for_security_level %u", level); 7607 return level > LEVEL_2; 7608 } 7609 7610 /** 7611 * @brief get current security level 7612 */ 7613 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 7614 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7615 if (!connection) return LEVEL_0; 7616 return gap_security_level_for_connection(connection); 7617 } 7618 7619 /** 7620 * @brief request connection to device to 7621 * @result GAP_AUTHENTICATION_RESULT 7622 */ 7623 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 7624 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7625 if (!connection){ 7626 hci_emit_security_level(con_handle, LEVEL_0); 7627 return; 7628 } 7629 7630 btstack_assert(hci_is_le_connection(connection) == false); 7631 7632 // Core Spec 5.2, GAP 5.2.2: "When in Secure Connections Only mode, all services (except those allowed to have Security Mode 4, Level 0) 7633 // available on the BR/EDR physical transport require Security Mode 4, Level 4 " 7634 if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){ 7635 requested_level = LEVEL_4; 7636 } 7637 7638 gap_security_level_t current_level = gap_security_level(con_handle); 7639 log_info("gap_request_security_level requested level %u, planned level %u, current level %u", 7640 requested_level, connection->requested_security_level, current_level); 7641 7642 // authentication active if authentication request was sent or planned level > 0 7643 bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0); 7644 if (authentication_active){ 7645 // authentication already active 7646 if (connection->requested_security_level < requested_level){ 7647 // increase requested level as new level is higher 7648 // TODO: handle re-authentication when done 7649 connection->requested_security_level = requested_level; 7650 } 7651 } else { 7652 // no request active, notify if security sufficient 7653 if (requested_level <= current_level){ 7654 hci_emit_security_level(con_handle, current_level); 7655 return; 7656 } 7657 7658 // store request 7659 connection->requested_security_level = requested_level; 7660 7661 // start to authenticate connection 7662 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 7663 7664 // request remote features if not already active, also trigger hci_run 7665 hci_remote_features_query(con_handle); 7666 } 7667 } 7668 7669 /** 7670 * @brief start dedicated bonding with device. disconnect after bonding 7671 * @param device 7672 * @param request MITM protection 7673 * @result GAP_DEDICATED_BONDING_COMPLETE 7674 */ 7675 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 7676 7677 // create connection state machine 7678 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL); 7679 7680 if (!connection){ 7681 return BTSTACK_MEMORY_ALLOC_FAILED; 7682 } 7683 7684 // delete linkn key 7685 gap_drop_link_key_for_bd_addr(device); 7686 7687 // configure LEVEL_2/3, dedicated bonding 7688 connection->state = SEND_CREATE_CONNECTION; 7689 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 7690 log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level); 7691 connection->bonding_flags = BONDING_DEDICATED; 7692 7693 // wait for GAP Security Result and send GAP Dedicated Bonding complete 7694 7695 // handle: connnection failure (connection complete != ok) 7696 // handle: authentication failure 7697 // handle: disconnect on done 7698 7699 hci_run(); 7700 7701 return 0; 7702 } 7703 7704 void gap_set_local_name(const char * local_name){ 7705 hci_stack->local_name = local_name; 7706 hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME; 7707 // also update EIR if not set by user 7708 if (hci_stack->eir_data == NULL){ 7709 hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA; 7710 } 7711 hci_run(); 7712 } 7713 #endif 7714 7715 7716 #ifdef ENABLE_BLE 7717 7718 #ifdef ENABLE_LE_CENTRAL 7719 void gap_start_scan(void){ 7720 hci_stack->le_scanning_enabled = true; 7721 hci_run(); 7722 } 7723 7724 void gap_stop_scan(void){ 7725 hci_stack->le_scanning_enabled = false; 7726 hci_run(); 7727 } 7728 7729 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){ 7730 hci_stack->le_scan_type = scan_type; 7731 hci_stack->le_scan_filter_policy = scanning_filter_policy; 7732 hci_stack->le_scan_interval = scan_interval; 7733 hci_stack->le_scan_window = scan_window; 7734 hci_stack->le_scanning_param_update = true; 7735 hci_run(); 7736 } 7737 7738 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 7739 gap_set_scan_params(scan_type, scan_interval, scan_window, 0); 7740 } 7741 7742 void gap_set_scan_duplicate_filter(bool enabled){ 7743 hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0; 7744 } 7745 7746 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){ 7747 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 7748 if (!conn){ 7749 // disallow if le connection is already outgoing 7750 if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 7751 log_error("le connection already active"); 7752 return ERROR_CODE_COMMAND_DISALLOWED; 7753 } 7754 7755 log_info("gap_connect: no connection exists yet, creating context"); 7756 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 7757 if (!conn){ 7758 // notify client that alloc failed 7759 hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 7760 log_info("gap_connect: failed to alloc hci_connection_t"); 7761 return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller 7762 } 7763 7764 // set le connecting state 7765 if (hci_is_le_connection_type(addr_type)){ 7766 hci_stack->le_connecting_request = LE_CONNECTING_DIRECT; 7767 } 7768 7769 conn->state = SEND_CREATE_CONNECTION; 7770 log_info("gap_connect: send create connection next"); 7771 hci_run(); 7772 return ERROR_CODE_SUCCESS; 7773 } 7774 7775 if (!hci_is_le_connection(conn) || 7776 (conn->state == SEND_CREATE_CONNECTION) || 7777 (conn->state == SENT_CREATE_CONNECTION)) { 7778 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED); 7779 log_error("gap_connect: classic connection or connect is already being created"); 7780 return GATT_CLIENT_IN_WRONG_STATE; 7781 } 7782 7783 // check if connection was just disconnected 7784 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 7785 log_info("gap_connect: send create connection (again)"); 7786 conn->state = SEND_CREATE_CONNECTION; 7787 hci_run(); 7788 return ERROR_CODE_SUCCESS; 7789 } 7790 7791 log_info("gap_connect: context exists with state %u", conn->state); 7792 hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS); 7793 hci_run(); 7794 return ERROR_CODE_SUCCESS; 7795 } 7796 7797 // @assumption: only a single outgoing LE Connection exists 7798 static hci_connection_t * gap_get_outgoing_connection(void){ 7799 btstack_linked_item_t *it; 7800 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 7801 hci_connection_t * conn = (hci_connection_t *) it; 7802 if (!hci_is_le_connection(conn)) continue; 7803 switch (conn->state){ 7804 case SEND_CREATE_CONNECTION: 7805 case SENT_CREATE_CONNECTION: 7806 return conn; 7807 default: 7808 break; 7809 }; 7810 } 7811 return NULL; 7812 } 7813 7814 uint8_t gap_connect_cancel(void){ 7815 hci_connection_t * conn; 7816 switch (hci_stack->le_connecting_request){ 7817 case LE_CONNECTING_IDLE: 7818 break; 7819 case LE_CONNECTING_WHITELIST: 7820 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 7821 hci_run(); 7822 break; 7823 case LE_CONNECTING_DIRECT: 7824 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 7825 conn = gap_get_outgoing_connection(); 7826 if (conn == NULL){ 7827 hci_run(); 7828 } else { 7829 switch (conn->state){ 7830 case SEND_CREATE_CONNECTION: 7831 // skip sending create connection and emit event instead 7832 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 7833 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 7834 btstack_memory_hci_connection_free( conn ); 7835 break; 7836 case SENT_CREATE_CONNECTION: 7837 // let hci_run_general_gap_le cancel outgoing connection 7838 hci_run(); 7839 break; 7840 default: 7841 break; 7842 } 7843 } 7844 break; 7845 default: 7846 btstack_unreachable(); 7847 break; 7848 } 7849 return ERROR_CODE_SUCCESS; 7850 } 7851 7852 /** 7853 * @brief Set connection parameters for outgoing connections 7854 * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms 7855 * @param conn_scan_window (unit: 0.625 msec), default: 30 ms 7856 * @param conn_interval_min (unit: 1.25ms), default: 10 ms 7857 * @param conn_interval_max (unit: 1.25ms), default: 30 ms 7858 * @param conn_latency, default: 4 7859 * @param supervision_timeout (unit: 10ms), default: 720 ms 7860 * @param min_ce_length (unit: 0.625ms), default: 10 ms 7861 * @param max_ce_length (unit: 0.625ms), default: 30 ms 7862 */ 7863 7864 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window, 7865 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, 7866 uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){ 7867 hci_stack->le_connection_scan_interval = conn_scan_interval; 7868 hci_stack->le_connection_scan_window = conn_scan_window; 7869 hci_stack->le_connection_interval_min = conn_interval_min; 7870 hci_stack->le_connection_interval_max = conn_interval_max; 7871 hci_stack->le_connection_latency = conn_latency; 7872 hci_stack->le_supervision_timeout = supervision_timeout; 7873 hci_stack->le_minimum_ce_length = min_ce_length; 7874 hci_stack->le_maximum_ce_length = max_ce_length; 7875 } 7876 #endif 7877 7878 /** 7879 * @brief Updates the connection parameters for a given LE connection 7880 * @param handle 7881 * @param conn_interval_min (unit: 1.25ms) 7882 * @param conn_interval_max (unit: 1.25ms) 7883 * @param conn_latency 7884 * @param supervision_timeout (unit: 10ms) 7885 * @return 0 if ok 7886 */ 7887 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 7888 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 7889 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7890 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7891 connection->le_conn_interval_min = conn_interval_min; 7892 connection->le_conn_interval_max = conn_interval_max; 7893 connection->le_conn_latency = conn_latency; 7894 connection->le_supervision_timeout = supervision_timeout; 7895 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 7896 hci_run(); 7897 return 0; 7898 } 7899 7900 /** 7901 * @brief Request an update of the connection parameter for a given LE connection 7902 * @param handle 7903 * @param conn_interval_min (unit: 1.25ms) 7904 * @param conn_interval_max (unit: 1.25ms) 7905 * @param conn_latency 7906 * @param supervision_timeout (unit: 10ms) 7907 * @return 0 if ok 7908 */ 7909 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min, 7910 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 7911 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7912 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7913 connection->le_conn_interval_min = conn_interval_min; 7914 connection->le_conn_interval_max = conn_interval_max; 7915 connection->le_conn_latency = conn_latency; 7916 connection->le_supervision_timeout = supervision_timeout; 7917 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST; 7918 uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0}; 7919 hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0); 7920 return 0; 7921 } 7922 7923 #ifdef ENABLE_LE_PERIPHERAL 7924 7925 /** 7926 * @brief Set Advertisement Data 7927 * @param advertising_data_length 7928 * @param advertising_data (max 31 octets) 7929 * @note data is not copied, pointer has to stay valid 7930 */ 7931 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){ 7932 hci_stack->le_advertisements_data_len = advertising_data_length; 7933 hci_stack->le_advertisements_data = advertising_data; 7934 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 7935 hci_run(); 7936 } 7937 7938 /** 7939 * @brief Set Scan Response Data 7940 * @param advertising_data_length 7941 * @param advertising_data (max 31 octets) 7942 * @note data is not copied, pointer has to stay valid 7943 */ 7944 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){ 7945 hci_stack->le_scan_response_data_len = scan_response_data_length; 7946 hci_stack->le_scan_response_data = scan_response_data; 7947 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 7948 hci_run(); 7949 } 7950 7951 /** 7952 * @brief Set Advertisement Parameters 7953 * @param adv_int_min 7954 * @param adv_int_max 7955 * @param adv_type 7956 * @param direct_address_type 7957 * @param direct_address 7958 * @param channel_map 7959 * @param filter_policy 7960 * 7961 * @note internal use. use gap_advertisements_set_params from gap_le.h instead. 7962 */ 7963 void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 7964 uint8_t direct_address_typ, bd_addr_t direct_address, 7965 uint8_t channel_map, uint8_t filter_policy) { 7966 7967 hci_stack->le_advertisements_interval_min = adv_int_min; 7968 hci_stack->le_advertisements_interval_max = adv_int_max; 7969 hci_stack->le_advertisements_type = adv_type; 7970 hci_stack->le_advertisements_direct_address_type = direct_address_typ; 7971 hci_stack->le_advertisements_channel_map = channel_map; 7972 hci_stack->le_advertisements_filter_policy = filter_policy; 7973 (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address, 7974 6); 7975 7976 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 7977 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET; 7978 hci_run(); 7979 } 7980 7981 /** 7982 * @brief Enable/Disable Advertisements 7983 * @param enabled 7984 */ 7985 void gap_advertisements_enable(int enabled){ 7986 if (enabled == 0){ 7987 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED; 7988 } else { 7989 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED; 7990 } 7991 hci_update_advertisements_enabled_for_current_roles(); 7992 hci_run(); 7993 } 7994 7995 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 7996 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){ 7997 btstack_linked_list_iterator_t it; 7998 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 7999 while (btstack_linked_list_iterator_has_next(&it)){ 8000 le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it); 8001 if ( item->advertising_handle == advertising_handle ) { 8002 return item; 8003 } 8004 } 8005 return NULL; 8006 } 8007 8008 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){ 8009 // find free advertisement handle 8010 uint8_t advertisement_handle; 8011 for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){ 8012 if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break; 8013 } 8014 if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 8015 // clear 8016 memset(storage, 0, sizeof(le_advertising_set_t)); 8017 // copy params 8018 storage->advertising_handle = advertisement_handle; 8019 memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t)); 8020 // add to list 8021 bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage); 8022 if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 8023 *out_advertising_handle = advertisement_handle; 8024 // set tasks and start 8025 storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS; 8026 hci_run(); 8027 return ERROR_CODE_SUCCESS; 8028 } 8029 8030 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){ 8031 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8032 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8033 memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t)); 8034 // set tasks and start 8035 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 8036 hci_run(); 8037 return ERROR_CODE_SUCCESS; 8038 } 8039 8040 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){ 8041 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8042 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8043 memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t)); 8044 return ERROR_CODE_SUCCESS; 8045 } 8046 8047 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){ 8048 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8049 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8050 memcpy(advertising_set->random_address, random_address, 6); 8051 // set tasks and start 8052 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 8053 hci_run(); 8054 return ERROR_CODE_SUCCESS; 8055 } 8056 8057 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){ 8058 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8059 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8060 advertising_set->adv_data = advertising_data; 8061 advertising_set->adv_data_len = advertising_data_length; 8062 // set tasks and start 8063 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 8064 hci_run(); 8065 return ERROR_CODE_SUCCESS; 8066 } 8067 8068 uint8_t gap_extended_advertising_set_scan_response_data(uint8_t advertising_handle, uint16_t scan_response_data_length, const uint8_t * scan_response_data){ 8069 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8070 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8071 advertising_set->scan_data = scan_response_data; 8072 advertising_set->scan_data_len = scan_response_data_length; 8073 // set tasks and start 8074 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 8075 hci_run(); 8076 return ERROR_CODE_SUCCESS; 8077 } 8078 8079 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){ 8080 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8081 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8082 advertising_set->enable_timeout = timeout; 8083 advertising_set->enable_max_scan_events = num_extended_advertising_events; 8084 // set tasks and start 8085 advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED; 8086 hci_run(); 8087 return ERROR_CODE_SUCCESS; 8088 } 8089 8090 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){ 8091 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8092 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8093 // set tasks and start 8094 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED; 8095 hci_run(); 8096 return ERROR_CODE_SUCCESS; 8097 } 8098 8099 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){ 8100 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8101 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8102 // set tasks and start 8103 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET; 8104 hci_run(); 8105 return ERROR_CODE_SUCCESS; 8106 } 8107 8108 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 8109 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){ 8110 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8111 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8112 // periodic advertising requires neither connectable, scannable, legacy or anonymous 8113 if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8114 memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t)); 8115 // set tasks and start 8116 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS; 8117 hci_run(); 8118 return ERROR_CODE_SUCCESS; 8119 } 8120 8121 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){ 8122 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8123 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8124 memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t)); 8125 return ERROR_CODE_SUCCESS; 8126 } 8127 8128 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){ 8129 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8130 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8131 advertising_set->periodic_data = periodic_data; 8132 advertising_set->periodic_data_len = periodic_data_length; 8133 // set tasks and start 8134 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA; 8135 hci_run(); 8136 return ERROR_CODE_SUCCESS; 8137 } 8138 8139 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){ 8140 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8141 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8142 // set tasks and start 8143 advertising_set->periodic_include_adi = include_adi; 8144 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED; 8145 hci_run(); 8146 return ERROR_CODE_SUCCESS; 8147 } 8148 8149 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){ 8150 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 8151 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8152 // set tasks and start 8153 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED; 8154 hci_run(); 8155 return ERROR_CODE_SUCCESS; 8156 } 8157 8158 uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){ 8159 hci_stack->le_past_mode = mode; 8160 hci_stack->le_past_skip = skip; 8161 hci_stack->le_past_sync_timeout = sync_timeout; 8162 hci_stack->le_past_cte_type = cte_type; 8163 hci_stack->le_past_set_default_params = true; 8164 hci_run(); 8165 return ERROR_CODE_SUCCESS; 8166 } 8167 8168 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 8169 8170 #endif 8171 8172 #endif 8173 8174 void hci_le_set_own_address_type(uint8_t own_address_type){ 8175 log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type); 8176 if (own_address_type == hci_stack->le_own_addr_type) return; 8177 hci_stack->le_own_addr_type = own_address_type; 8178 8179 #ifdef ENABLE_LE_PERIPHERAL 8180 // update advertisement parameters, too 8181 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 8182 hci_run(); 8183 #endif 8184 #ifdef ENABLE_LE_CENTRAL 8185 // note: we don't update scan parameters or modify ongoing connection attempts 8186 #endif 8187 } 8188 8189 void hci_le_random_address_set(const bd_addr_t random_address){ 8190 memcpy(hci_stack->le_random_address, random_address, 6); 8191 hci_stack->le_random_address_set = true; 8192 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 8193 hci_run(); 8194 } 8195 8196 #endif 8197 8198 uint8_t gap_disconnect(hci_con_handle_t handle){ 8199 hci_connection_t * conn = hci_connection_for_handle(handle); 8200 if (!conn){ 8201 hci_emit_disconnection_complete(handle, 0); 8202 return 0; 8203 } 8204 // ignore if already disconnected 8205 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 8206 return 0; 8207 } 8208 conn->state = SEND_DISCONNECT; 8209 hci_run(); 8210 return 0; 8211 } 8212 8213 int gap_read_rssi(hci_con_handle_t con_handle){ 8214 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8215 if (hci_connection == NULL) return 0; 8216 hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI; 8217 hci_run(); 8218 return 1; 8219 } 8220 8221 /** 8222 * @brief Get connection type 8223 * @param con_handle 8224 * @result connection_type 8225 */ 8226 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){ 8227 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 8228 if (!conn) return GAP_CONNECTION_INVALID; 8229 switch (conn->address_type){ 8230 case BD_ADDR_TYPE_LE_PUBLIC: 8231 case BD_ADDR_TYPE_LE_RANDOM: 8232 return GAP_CONNECTION_LE; 8233 case BD_ADDR_TYPE_SCO: 8234 return GAP_CONNECTION_SCO; 8235 case BD_ADDR_TYPE_ACL: 8236 return GAP_CONNECTION_ACL; 8237 default: 8238 return GAP_CONNECTION_INVALID; 8239 } 8240 } 8241 8242 hci_role_t gap_get_role(hci_con_handle_t connection_handle){ 8243 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 8244 if (!conn) return HCI_ROLE_INVALID; 8245 return (hci_role_t) conn->role; 8246 } 8247 8248 8249 #ifdef ENABLE_CLASSIC 8250 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){ 8251 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8252 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8253 conn->request_role = role; 8254 hci_run(); 8255 return ERROR_CODE_SUCCESS; 8256 } 8257 #endif 8258 8259 #ifdef ENABLE_BLE 8260 8261 uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){ 8262 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8263 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8264 8265 conn->le_phy_update_all_phys = all_phys; 8266 conn->le_phy_update_tx_phys = tx_phys; 8267 conn->le_phy_update_rx_phys = rx_phys; 8268 conn->le_phy_update_phy_options = phy_options; 8269 8270 hci_run(); 8271 8272 return 0; 8273 } 8274 8275 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 8276 // check if already in list 8277 btstack_linked_list_iterator_t it; 8278 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 8279 while (btstack_linked_list_iterator_has_next(&it)) { 8280 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it); 8281 if (entry->address_type != address_type) { 8282 continue; 8283 } 8284 if (memcmp(entry->address, address, 6) != 0) { 8285 continue; 8286 } 8287 // disallow if already scheduled to add 8288 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){ 8289 return ERROR_CODE_COMMAND_DISALLOWED; 8290 } 8291 // still on controller, but scheduled to remove -> re-add 8292 entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER; 8293 return ERROR_CODE_SUCCESS; 8294 } 8295 // alloc and add to list 8296 whitelist_entry_t * entry = btstack_memory_whitelist_entry_get(); 8297 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 8298 entry->address_type = address_type; 8299 (void)memcpy(entry->address, address, 6); 8300 entry->state = LE_WHITELIST_ADD_TO_CONTROLLER; 8301 btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry); 8302 return ERROR_CODE_SUCCESS; 8303 } 8304 8305 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 8306 btstack_linked_list_iterator_t it; 8307 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 8308 while (btstack_linked_list_iterator_has_next(&it)){ 8309 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 8310 if (entry->address_type != address_type) { 8311 continue; 8312 } 8313 if (memcmp(entry->address, address, 6) != 0) { 8314 continue; 8315 } 8316 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 8317 // remove from controller if already present 8318 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 8319 } else { 8320 // directly remove entry from whitelist 8321 btstack_linked_list_iterator_remove(&it); 8322 btstack_memory_whitelist_entry_free(entry); 8323 } 8324 return ERROR_CODE_SUCCESS; 8325 } 8326 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8327 } 8328 8329 static void hci_whitelist_clear(void){ 8330 btstack_linked_list_iterator_t it; 8331 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 8332 while (btstack_linked_list_iterator_has_next(&it)){ 8333 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 8334 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 8335 // remove from controller if already present 8336 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 8337 continue; 8338 } 8339 // directly remove entry from whitelist 8340 btstack_linked_list_iterator_remove(&it); 8341 btstack_memory_whitelist_entry_free(entry); 8342 } 8343 } 8344 8345 // free all entries unconditionally 8346 static void hci_whitelist_free(void){ 8347 btstack_linked_list_iterator_t lit; 8348 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 8349 while (btstack_linked_list_iterator_has_next(&lit)){ 8350 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 8351 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 8352 btstack_memory_whitelist_entry_free(entry); 8353 } 8354 } 8355 8356 /** 8357 * @brief Clear Whitelist 8358 * @return 0 if ok 8359 */ 8360 uint8_t gap_whitelist_clear(void){ 8361 hci_whitelist_clear(); 8362 hci_run(); 8363 return ERROR_CODE_SUCCESS; 8364 } 8365 8366 /** 8367 * @brief Add Device to Whitelist 8368 * @param address_typ 8369 * @param address 8370 * @return 0 if ok 8371 */ 8372 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 8373 uint8_t status = hci_whitelist_add(address_type, address); 8374 if (status){ 8375 return status; 8376 } 8377 hci_run(); 8378 return ERROR_CODE_SUCCESS; 8379 } 8380 8381 /** 8382 * @brief Remove Device from Whitelist 8383 * @param address_typ 8384 * @param address 8385 * @return 0 if ok 8386 */ 8387 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 8388 uint8_t status = hci_whitelist_remove(address_type, address); 8389 if (status){ 8390 return status; 8391 } 8392 hci_run(); 8393 return ERROR_CODE_SUCCESS; 8394 } 8395 8396 #ifdef ENABLE_LE_CENTRAL 8397 /** 8398 * @brief Connect with Whitelist 8399 * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions 8400 * @return - if ok 8401 */ 8402 uint8_t gap_connect_with_whitelist(void){ 8403 if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 8404 return ERROR_CODE_COMMAND_DISALLOWED; 8405 } 8406 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 8407 hci_run(); 8408 return ERROR_CODE_SUCCESS; 8409 } 8410 8411 /** 8412 * @brief Auto Connection Establishment - Start Connecting to device 8413 * @param address_typ 8414 * @param address 8415 * @return 0 if ok 8416 */ 8417 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){ 8418 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 8419 return ERROR_CODE_COMMAND_DISALLOWED; 8420 } 8421 8422 uint8_t status = hci_whitelist_add(address_type, address); 8423 if (status == BTSTACK_MEMORY_ALLOC_FAILED) { 8424 return status; 8425 } 8426 8427 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 8428 8429 hci_run(); 8430 return ERROR_CODE_SUCCESS; 8431 } 8432 8433 /** 8434 * @brief Auto Connection Establishment - Stop Connecting to device 8435 * @param address_typ 8436 * @param address 8437 * @return 0 if ok 8438 */ 8439 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){ 8440 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 8441 return ERROR_CODE_COMMAND_DISALLOWED; 8442 } 8443 8444 hci_whitelist_remove(address_type, address); 8445 if (btstack_linked_list_empty(&hci_stack->le_whitelist)){ 8446 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 8447 } 8448 hci_run(); 8449 return 0; 8450 } 8451 8452 /** 8453 * @brief Auto Connection Establishment - Stop everything 8454 * @note Convenience function to stop all active auto connection attempts 8455 */ 8456 uint8_t gap_auto_connection_stop_all(void){ 8457 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) { 8458 return ERROR_CODE_COMMAND_DISALLOWED; 8459 } 8460 hci_whitelist_clear(); 8461 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 8462 hci_run(); 8463 return ERROR_CODE_SUCCESS; 8464 } 8465 8466 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){ 8467 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8468 if (!conn) return 0; 8469 return conn->le_connection_interval; 8470 } 8471 #endif 8472 #endif 8473 8474 #ifdef ENABLE_CLASSIC 8475 /** 8476 * @brief Set Extended Inquiry Response data 8477 * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup 8478 * @note has to be done before stack starts up 8479 */ 8480 void gap_set_extended_inquiry_response(const uint8_t * data){ 8481 hci_stack->eir_data = data; 8482 hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA; 8483 hci_run(); 8484 } 8485 8486 /** 8487 * @brief Start GAP Classic Inquiry 8488 * @param duration in 1.28s units 8489 * @return 0 if ok 8490 * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE 8491 */ 8492 int gap_inquiry_start(uint8_t duration_in_1280ms_units){ 8493 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 8494 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8495 if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){ 8496 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8497 } 8498 hci_stack->inquiry_state = duration_in_1280ms_units; 8499 hci_stack->inquiry_max_period_length = 0; 8500 hci_stack->inquiry_min_period_length = 0; 8501 hci_run(); 8502 return 0; 8503 } 8504 8505 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){ 8506 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 8507 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8508 if (duration < GAP_INQUIRY_DURATION_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8509 if (duration > GAP_INQUIRY_DURATION_MAX) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8510 if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;; 8511 if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;; 8512 8513 hci_stack->inquiry_state = duration; 8514 hci_stack->inquiry_max_period_length = max_period_length; 8515 hci_stack->inquiry_min_period_length = min_period_length; 8516 hci_run(); 8517 return 0; 8518 } 8519 8520 /** 8521 * @brief Stop GAP Classic Inquiry 8522 * @return 0 if ok 8523 */ 8524 int gap_inquiry_stop(void){ 8525 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) { 8526 // emit inquiry complete event, before it even started 8527 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 8528 hci_emit_event(event, sizeof(event), 1); 8529 return 0; 8530 } 8531 switch (hci_stack->inquiry_state){ 8532 case GAP_INQUIRY_STATE_ACTIVE: 8533 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL; 8534 hci_run(); 8535 return ERROR_CODE_SUCCESS; 8536 case GAP_INQUIRY_STATE_PERIODIC: 8537 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC; 8538 hci_run(); 8539 return ERROR_CODE_SUCCESS; 8540 default: 8541 return ERROR_CODE_COMMAND_DISALLOWED; 8542 } 8543 } 8544 8545 void gap_inquiry_set_lap(uint32_t lap){ 8546 hci_stack->inquiry_lap = lap; 8547 } 8548 8549 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){ 8550 hci_stack->inquiry_scan_interval = inquiry_scan_interval; 8551 hci_stack->inquiry_scan_window = inquiry_scan_window; 8552 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY; 8553 hci_run(); 8554 } 8555 8556 8557 /** 8558 * @brief Remote Name Request 8559 * @param addr 8560 * @param page_scan_repetition_mode 8561 * @param clock_offset only used when bit 15 is set 8562 * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 8563 */ 8564 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){ 8565 if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8566 (void)memcpy(hci_stack->remote_name_addr, addr, 6); 8567 hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode; 8568 hci_stack->remote_name_clock_offset = clock_offset; 8569 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND; 8570 hci_run(); 8571 return 0; 8572 } 8573 8574 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){ 8575 hci_stack->gap_pairing_state = state; 8576 (void)memcpy(hci_stack->gap_pairing_addr, addr, 6); 8577 hci_run(); 8578 return 0; 8579 } 8580 8581 /** 8582 * @brief Legacy Pairing Pin Code Response for binary data / non-strings 8583 * @param addr 8584 * @param pin_data 8585 * @param pin_len 8586 * @return 0 if ok 8587 */ 8588 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){ 8589 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8590 hci_stack->gap_pairing_input.gap_pairing_pin = pin_data; 8591 hci_stack->gap_pairing_pin_len = pin_len; 8592 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN); 8593 } 8594 8595 /** 8596 * @brief Legacy Pairing Pin Code Response 8597 * @param addr 8598 * @param pin 8599 * @return 0 if ok 8600 */ 8601 int gap_pin_code_response(const bd_addr_t addr, const char * pin){ 8602 return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin)); 8603 } 8604 8605 /** 8606 * @brief Abort Legacy Pairing 8607 * @param addr 8608 * @param pin 8609 * @return 0 if ok 8610 */ 8611 int gap_pin_code_negative(bd_addr_t addr){ 8612 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8613 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE); 8614 } 8615 8616 /** 8617 * @brief SSP Passkey Response 8618 * @param addr 8619 * @param passkey 8620 * @return 0 if ok 8621 */ 8622 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){ 8623 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8624 hci_stack->gap_pairing_input.gap_pairing_passkey = passkey; 8625 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY); 8626 } 8627 8628 /** 8629 * @brief Abort SSP Passkey Entry/Pairing 8630 * @param addr 8631 * @param pin 8632 * @return 0 if ok 8633 */ 8634 int gap_ssp_passkey_negative(const bd_addr_t addr){ 8635 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8636 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE); 8637 } 8638 8639 /** 8640 * @brief Accept SSP Numeric Comparison 8641 * @param addr 8642 * @param passkey 8643 * @return 0 if ok 8644 */ 8645 int gap_ssp_confirmation_response(const bd_addr_t addr){ 8646 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8647 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION); 8648 } 8649 8650 /** 8651 * @brief Abort SSP Numeric Comparison/Pairing 8652 * @param addr 8653 * @param pin 8654 * @return 0 if ok 8655 */ 8656 int gap_ssp_confirmation_negative(const bd_addr_t addr){ 8657 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8658 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE); 8659 } 8660 8661 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY) 8662 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){ 8663 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8664 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8665 connectionSetAuthenticationFlags(conn, flag); 8666 hci_run(); 8667 return ERROR_CODE_SUCCESS; 8668 } 8669 #endif 8670 8671 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 8672 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){ 8673 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 8674 } 8675 8676 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){ 8677 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 8678 } 8679 #endif 8680 8681 #ifdef ENABLE_CLASSIC_PAIRING_OOB 8682 /** 8683 * @brief Report Remote OOB Data 8684 * @param bd_addr 8685 * @param c_192 Simple Pairing Hash C derived from P-192 public key 8686 * @param r_192 Simple Pairing Randomizer derived from P-192 public key 8687 * @param c_256 Simple Pairing Hash C derived from P-256 public key 8688 * @param r_256 Simple Pairing Randomizer derived from P-256 public key 8689 */ 8690 uint8_t gap_ssp_remote_oob_data(const bd_addr_t addr, const uint8_t * c_192, const uint8_t * r_192, const uint8_t * c_256, const uint8_t * r_256){ 8691 hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8692 if (connection == NULL) { 8693 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8694 } 8695 connection->classic_oob_c_192 = c_192; 8696 connection->classic_oob_r_192 = r_192; 8697 8698 // ignore P-256 if not supported by us 8699 if (hci_stack->secure_connections_active){ 8700 connection->classic_oob_c_256 = c_256; 8701 connection->classic_oob_r_256 = r_256; 8702 } 8703 8704 return ERROR_CODE_SUCCESS; 8705 } 8706 /** 8707 * @brief Generate new OOB data 8708 * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures 8709 */ 8710 void gap_ssp_generate_oob_data(void){ 8711 hci_stack->classic_read_local_oob_data = true; 8712 hci_run(); 8713 } 8714 8715 #endif 8716 8717 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY 8718 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){ 8719 hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8720 if (connection == NULL) { 8721 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8722 } 8723 8724 memcpy(connection->link_key, link_key, sizeof(link_key_t)); 8725 connection->link_key_type = type; 8726 8727 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST); 8728 } 8729 8730 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY 8731 /** 8732 * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on. 8733 * @param inquiry_mode see bluetooth_defines.h 8734 */ 8735 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){ 8736 hci_stack->inquiry_mode = inquiry_mode; 8737 } 8738 8739 /** 8740 * @brief Configure Voice Setting for use with SCO data in HSP/HFP 8741 */ 8742 void hci_set_sco_voice_setting(uint16_t voice_setting){ 8743 hci_stack->sco_voice_setting = voice_setting; 8744 } 8745 8746 /** 8747 * @brief Get SCO Voice Setting 8748 * @return current voice setting 8749 */ 8750 uint16_t hci_get_sco_voice_setting(void){ 8751 return hci_stack->sco_voice_setting; 8752 } 8753 8754 static int hci_have_usb_transport(void){ 8755 if (!hci_stack->hci_transport) return 0; 8756 const char * transport_name = hci_stack->hci_transport->name; 8757 if (!transport_name) return 0; 8758 return (transport_name[0] == 'H') && (transport_name[1] == '2'); 8759 } 8760 8761 /** @brief Get SCO packet length for current SCO Voice setting 8762 * @note Using SCO packets of the exact length is required for USB transfer 8763 * @return Length of SCO packets in bytes (not audio frames) 8764 */ 8765 uint16_t hci_get_sco_packet_length(void){ 8766 uint16_t sco_packet_length = 0; 8767 8768 #ifdef ENABLE_SCO_OVER_HCI 8769 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 8770 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 8771 8772 if (hci_have_usb_transport()){ 8773 // see Core Spec for H2 USB Transfer. 8774 // 3 byte SCO header + 24 bytes per connection 8775 int num_sco_connections = btstack_max(1, hci_number_sco_connections()); 8776 sco_packet_length = 3 + 24 * num_sco_connections * multiplier; 8777 } else { 8778 // 3 byte SCO header + SCO packet size over the air (60 bytes) 8779 sco_packet_length = 3 + 60 * multiplier; 8780 // assert that it still fits inside an SCO buffer 8781 if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){ 8782 sco_packet_length = 3 + 60; 8783 } 8784 } 8785 #endif 8786 8787 #ifdef HAVE_SCO_TRANSPORT 8788 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 8789 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 8790 sco_packet_length = 3 + 60 * multiplier; 8791 #endif 8792 return sco_packet_length; 8793 } 8794 8795 /** 8796 * @brief Sets the master/slave policy 8797 * @param policy (0: attempt to become master, 1: let connecting device decide) 8798 */ 8799 void hci_set_master_slave_policy(uint8_t policy){ 8800 hci_stack->master_slave_policy = policy; 8801 } 8802 8803 #endif 8804 8805 HCI_STATE hci_get_state(void){ 8806 return hci_stack->state; 8807 } 8808 8809 #ifdef ENABLE_CLASSIC 8810 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){ 8811 hci_stack->gap_classic_accept_callback = accept_callback; 8812 } 8813 #endif 8814 8815 /** 8816 * @brief Set callback for Bluetooth Hardware Error 8817 */ 8818 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){ 8819 hci_stack->hardware_error_callback = fn; 8820 } 8821 8822 void hci_disconnect_all(void){ 8823 btstack_linked_list_iterator_t it; 8824 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 8825 while (btstack_linked_list_iterator_has_next(&it)){ 8826 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 8827 if (con->state == SENT_DISCONNECT) continue; 8828 con->state = SEND_DISCONNECT; 8829 } 8830 hci_run(); 8831 } 8832 8833 uint16_t hci_get_manufacturer(void){ 8834 return hci_stack->manufacturer; 8835 } 8836 8837 #ifdef ENABLE_BLE 8838 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 8839 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 8840 if (!hci_con) return NULL; 8841 return &hci_con->sm_connection; 8842 } 8843 8844 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build 8845 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated 8846 #endif 8847 8848 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){ 8849 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8850 if (hci_connection == NULL) return 0; 8851 if (hci_is_le_connection(hci_connection)){ 8852 #ifdef ENABLE_BLE 8853 sm_connection_t * sm_conn = &hci_connection->sm_connection; 8854 if (sm_conn->sm_connection_encrypted) { 8855 return sm_conn->sm_actual_encryption_key_size; 8856 } 8857 #endif 8858 } else { 8859 #ifdef ENABLE_CLASSIC 8860 if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){ 8861 return hci_connection->encryption_key_size; 8862 } 8863 #endif 8864 } 8865 return 0; 8866 } 8867 8868 bool gap_authenticated(hci_con_handle_t con_handle){ 8869 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8870 if (hci_connection == NULL) return false; 8871 8872 switch (hci_connection->address_type){ 8873 #ifdef ENABLE_BLE 8874 case BD_ADDR_TYPE_LE_PUBLIC: 8875 case BD_ADDR_TYPE_LE_RANDOM: 8876 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 8877 return hci_connection->sm_connection.sm_connection_authenticated != 0; 8878 #endif 8879 #ifdef ENABLE_CLASSIC 8880 case BD_ADDR_TYPE_SCO: 8881 case BD_ADDR_TYPE_ACL: 8882 return gap_authenticated_for_link_key_type(hci_connection->link_key_type); 8883 #endif 8884 default: 8885 return false; 8886 } 8887 } 8888 8889 bool gap_secure_connection(hci_con_handle_t con_handle){ 8890 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8891 if (hci_connection == NULL) return 0; 8892 8893 switch (hci_connection->address_type){ 8894 #ifdef ENABLE_BLE 8895 case BD_ADDR_TYPE_LE_PUBLIC: 8896 case BD_ADDR_TYPE_LE_RANDOM: 8897 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated 8898 return hci_connection->sm_connection.sm_connection_sc != 0; 8899 #endif 8900 #ifdef ENABLE_CLASSIC 8901 case BD_ADDR_TYPE_SCO: 8902 case BD_ADDR_TYPE_ACL: 8903 return gap_secure_connection_for_link_key_type(hci_connection->link_key_type); 8904 #endif 8905 default: 8906 return false; 8907 } 8908 } 8909 8910 bool gap_bonded(hci_con_handle_t con_handle){ 8911 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8912 if (hci_connection == NULL) return 0; 8913 8914 #ifdef ENABLE_CLASSIC 8915 link_key_t link_key; 8916 link_key_type_t link_key_type; 8917 #endif 8918 switch (hci_connection->address_type){ 8919 #ifdef ENABLE_BLE 8920 case BD_ADDR_TYPE_LE_PUBLIC: 8921 case BD_ADDR_TYPE_LE_RANDOM: 8922 return hci_connection->sm_connection.sm_le_db_index >= 0; 8923 #endif 8924 #ifdef ENABLE_CLASSIC 8925 case BD_ADDR_TYPE_SCO: 8926 case BD_ADDR_TYPE_ACL: 8927 return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type); 8928 #endif 8929 default: 8930 return false; 8931 } 8932 } 8933 8934 #ifdef ENABLE_BLE 8935 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){ 8936 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 8937 if (!sm_conn) return AUTHORIZATION_UNKNOWN; // wrong connection 8938 if (!sm_conn->sm_connection_encrypted) return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized 8939 if (!sm_conn->sm_connection_authenticated) return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized 8940 return sm_conn->sm_connection_authorization_state; 8941 } 8942 #endif 8943 8944 #ifdef ENABLE_CLASSIC 8945 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){ 8946 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8947 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8948 conn->sniff_min_interval = sniff_min_interval; 8949 conn->sniff_max_interval = sniff_max_interval; 8950 conn->sniff_attempt = sniff_attempt; 8951 conn->sniff_timeout = sniff_timeout; 8952 hci_run(); 8953 return 0; 8954 } 8955 8956 /** 8957 * @brief Exit Sniff mode 8958 * @param con_handle 8959 @ @return 0 if ok 8960 */ 8961 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){ 8962 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8963 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8964 conn->sniff_min_interval = 0xffff; 8965 hci_run(); 8966 return 0; 8967 } 8968 8969 uint8_t gap_sniff_subrating_configure(hci_con_handle_t con_handle, uint16_t max_latency, uint16_t min_remote_timeout, uint16_t min_local_timeout){ 8970 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8971 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8972 conn->sniff_subrating_max_latency = max_latency; 8973 conn->sniff_subrating_min_remote_timeout = min_remote_timeout; 8974 conn->sniff_subrating_min_local_timeout = min_local_timeout; 8975 hci_run(); 8976 return ERROR_CODE_SUCCESS; 8977 } 8978 8979 uint8_t gap_qos_set(hci_con_handle_t con_handle, hci_service_type_t service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation){ 8980 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8981 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8982 conn->qos_service_type = service_type; 8983 conn->qos_token_rate = token_rate; 8984 conn->qos_peak_bandwidth = peak_bandwidth; 8985 conn->qos_latency = latency; 8986 conn->qos_delay_variation = delay_variation; 8987 hci_run(); 8988 return ERROR_CODE_SUCCESS; 8989 } 8990 8991 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){ 8992 hci_stack->new_page_scan_interval = page_scan_interval; 8993 hci_stack->new_page_scan_window = page_scan_window; 8994 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY; 8995 hci_run(); 8996 } 8997 8998 void gap_set_page_scan_type(page_scan_type_t page_scan_type){ 8999 hci_stack->new_page_scan_type = (uint8_t) page_scan_type; 9000 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE; 9001 hci_run(); 9002 } 9003 9004 void gap_set_page_timeout(uint16_t page_timeout){ 9005 hci_stack->page_timeout = page_timeout; 9006 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT; 9007 hci_run(); 9008 } 9009 9010 #endif 9011 9012 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 9013 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){ 9014 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 9015 if (le_device_db_index >= le_device_db_max_count()) return; 9016 uint8_t offset = le_device_db_index >> 3; 9017 uint8_t mask = 1 << (le_device_db_index & 7); 9018 hci_stack->le_resolving_list_add_entries[offset] |= mask; 9019 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 9020 // note: go back to remove entries, otherwise, a remove + add will skip the add 9021 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 9022 } 9023 } 9024 9025 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){ 9026 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 9027 if (le_device_db_index >= le_device_db_max_count()) return; 9028 uint8_t offset = le_device_db_index >> 3; 9029 uint8_t mask = 1 << (le_device_db_index & 7); 9030 hci_stack->le_resolving_list_remove_entries[offset] |= mask; 9031 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 9032 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 9033 } 9034 } 9035 9036 uint8_t gap_load_resolving_list_from_le_device_db(void){ 9037 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){ 9038 return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 9039 } 9040 if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){ 9041 // restart le resolving list update 9042 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 9043 } 9044 return ERROR_CODE_SUCCESS; 9045 } 9046 #endif 9047 9048 #ifdef ENABLE_BLE 9049 #ifdef ENABLE_LE_CENTRAL 9050 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 9051 9052 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 9053 // check if already in list 9054 btstack_linked_list_iterator_t it; 9055 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 9056 while (btstack_linked_list_iterator_has_next(&it)) { 9057 periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it); 9058 if (entry->sid != advertising_sid) { 9059 continue; 9060 } 9061 if (entry->address_type != address_type) { 9062 continue; 9063 } 9064 if (memcmp(entry->address, address, 6) != 0) { 9065 continue; 9066 } 9067 // disallow if already scheduled to add 9068 if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){ 9069 return ERROR_CODE_COMMAND_DISALLOWED; 9070 } 9071 // still on controller, but scheduled to remove -> re-add 9072 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 9073 return ERROR_CODE_SUCCESS; 9074 } 9075 // alloc and add to list 9076 periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get(); 9077 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 9078 entry->sid = advertising_sid; 9079 entry->address_type = address_type; 9080 (void)memcpy(entry->address, address, 6); 9081 entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 9082 btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry); 9083 return ERROR_CODE_SUCCESS; 9084 } 9085 9086 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 9087 btstack_linked_list_iterator_t it; 9088 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 9089 while (btstack_linked_list_iterator_has_next(&it)){ 9090 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it); 9091 if (entry->sid != advertising_sid) { 9092 continue; 9093 } 9094 if (entry->address_type != address_type) { 9095 continue; 9096 } 9097 if (memcmp(entry->address, address, 6) != 0) { 9098 continue; 9099 } 9100 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){ 9101 // remove from controller if already present 9102 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 9103 } else { 9104 // directly remove entry from whitelist 9105 btstack_linked_list_iterator_remove(&it); 9106 btstack_memory_periodic_advertiser_list_entry_free(entry); 9107 } 9108 return ERROR_CODE_SUCCESS; 9109 } 9110 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9111 } 9112 9113 static void hci_periodic_advertiser_list_clear(void){ 9114 btstack_linked_list_iterator_t it; 9115 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 9116 while (btstack_linked_list_iterator_has_next(&it)){ 9117 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it); 9118 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){ 9119 // remove from controller if already present 9120 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 9121 continue; 9122 } 9123 // directly remove entry from whitelist 9124 btstack_linked_list_iterator_remove(&it); 9125 btstack_memory_periodic_advertiser_list_entry_free(entry); 9126 } 9127 } 9128 9129 // free all entries unconditionally 9130 static void hci_periodic_advertiser_list_free(void){ 9131 btstack_linked_list_iterator_t lit; 9132 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 9133 while (btstack_linked_list_iterator_has_next(&lit)){ 9134 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 9135 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry); 9136 btstack_memory_periodic_advertiser_list_entry_free(entry); 9137 } 9138 } 9139 9140 uint8_t gap_periodic_advertiser_list_clear(void){ 9141 hci_periodic_advertiser_list_clear(); 9142 hci_run(); 9143 return ERROR_CODE_SUCCESS; 9144 } 9145 9146 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 9147 uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid); 9148 if (status){ 9149 return status; 9150 } 9151 hci_run(); 9152 return ERROR_CODE_SUCCESS; 9153 } 9154 9155 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 9156 uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid); 9157 if (status){ 9158 return status; 9159 } 9160 hci_run(); 9161 return ERROR_CODE_SUCCESS; 9162 } 9163 9164 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type, 9165 bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){ 9166 // abort if already active 9167 if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) { 9168 return ERROR_CODE_COMMAND_DISALLOWED; 9169 } 9170 // store request 9171 hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT; 9172 hci_stack->le_periodic_sync_options = options; 9173 hci_stack->le_periodic_sync_advertising_sid = advertising_sid; 9174 hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type; 9175 memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6); 9176 hci_stack->le_periodic_sync_skip = skip; 9177 hci_stack->le_periodic_sync_timeout = sync_timeout; 9178 hci_stack->le_periodic_sync_cte_type = sync_cte_type; 9179 9180 hci_run(); 9181 return ERROR_CODE_SUCCESS; 9182 } 9183 9184 uint8_t gap_periodic_advertising_create_sync_cancel(void){ 9185 // abort if not requested 9186 if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) { 9187 return ERROR_CODE_COMMAND_DISALLOWED; 9188 } 9189 hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE; 9190 hci_run(); 9191 return ERROR_CODE_SUCCESS; 9192 } 9193 9194 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){ 9195 if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){ 9196 return ERROR_CODE_COMMAND_DISALLOWED; 9197 } 9198 hci_stack->le_periodic_terminate_sync_handle = sync_handle; 9199 hci_run(); 9200 return ERROR_CODE_SUCCESS; 9201 } 9202 9203 #endif 9204 #endif 9205 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 9206 static uint8_t hci_iso_stream_create(hci_iso_type_t iso_type, hci_con_handle_t con_handle, uint8_t group_id, 9207 hci_iso_stream_state_t state) { 9208 hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get(); 9209 if (iso_stream == NULL){ 9210 return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 9211 } else { 9212 iso_stream->iso_type = iso_type; 9213 iso_stream->state = state; 9214 iso_stream->con_handle = con_handle; 9215 iso_stream->group_id = group_id; 9216 btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream); 9217 return ERROR_CODE_SUCCESS; 9218 } 9219 } 9220 9221 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){ 9222 btstack_linked_list_iterator_t it; 9223 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 9224 while (btstack_linked_list_iterator_has_next(&it)){ 9225 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 9226 if (iso_stream->con_handle == con_handle ) { 9227 return iso_stream; 9228 } 9229 } 9230 return NULL; 9231 } 9232 9233 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){ 9234 log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->con_handle, iso_stream->group_id); 9235 btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream); 9236 btstack_memory_hci_iso_stream_free(iso_stream); 9237 } 9238 9239 static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) { 9240 btstack_linked_list_iterator_t it; 9241 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 9242 while (btstack_linked_list_iterator_has_next(&it)){ 9243 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 9244 if ((iso_stream->group_id == group_id) && 9245 (iso_stream->iso_type == iso_type)){ 9246 btstack_linked_list_iterator_remove(&it); 9247 btstack_memory_hci_iso_stream_free(iso_stream); 9248 } 9249 } 9250 } 9251 9252 static void hci_iso_stream_requested_finalize(uint8_t group_id) { 9253 btstack_linked_list_iterator_t it; 9254 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 9255 while (btstack_linked_list_iterator_has_next(&it)){ 9256 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 9257 if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) && 9258 (iso_stream->group_id == group_id)){ 9259 btstack_linked_list_iterator_remove(&it); 9260 btstack_memory_hci_iso_stream_free(iso_stream); 9261 } 9262 } 9263 } 9264 static void hci_iso_stream_requested_confirm(uint8_t big_handle){ 9265 btstack_linked_list_iterator_t it; 9266 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 9267 while (btstack_linked_list_iterator_has_next(&it)){ 9268 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 9269 if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) { 9270 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED; 9271 } 9272 } 9273 } 9274 9275 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){ 9276 uint8_t sdu_ts_flag = (packet[1] >> 6) & 1; 9277 uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4); 9278 uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff; 9279 return (sdu_len_offset + 2 + sdu_len) == size; 9280 } 9281 9282 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){ 9283 if (hci_stack->iso_packet_handler == NULL) { 9284 return; 9285 } 9286 if (size < 4) { 9287 return; 9288 } 9289 9290 // parse header 9291 uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0); 9292 uint16_t iso_data_len = little_endian_read_16(packet, 2); 9293 hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff); 9294 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle); 9295 uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3; 9296 9297 // assert packet is complete 9298 if ((iso_data_len + 4u) != size){ 9299 return; 9300 } 9301 9302 if ((pb_flag & 0x01) == 0){ 9303 if (pb_flag == 0x02){ 9304 // The ISO_Data_Load field contains a header and a complete SDU. 9305 if (hci_iso_sdu_complete(packet, size)) { 9306 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size); 9307 } 9308 } else { 9309 // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU. 9310 if (iso_stream == NULL){ 9311 return; 9312 } 9313 if (size > HCI_ISO_PAYLOAD_SIZE){ 9314 return; 9315 } 9316 memcpy(iso_stream->reassembly_buffer, packet, size); 9317 // fix pb_flag 9318 iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20; 9319 iso_stream->reassembly_pos = size; 9320 } 9321 } else { 9322 // iso_data_load contains continuation or last fragment of an SDU 9323 uint8_t ts_flag = (conn_handle_and_flags >> 14) & 1; 9324 if (ts_flag != 0){ 9325 return; 9326 } 9327 // append fragment 9328 if (iso_stream == NULL){ 9329 return; 9330 } 9331 if (iso_stream->reassembly_pos == 0){ 9332 return; 9333 } 9334 if ((iso_stream->reassembly_pos + iso_data_len) > size){ 9335 // reset reassembly buffer 9336 iso_stream->reassembly_pos = 0; 9337 return; 9338 } 9339 memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len); 9340 iso_stream->reassembly_pos += iso_data_len; 9341 9342 // deliver if last fragment and SDU complete 9343 if (pb_flag == 0x03){ 9344 if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){ 9345 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos); 9346 } 9347 iso_stream->reassembly_pos = 0; 9348 } 9349 } 9350 } 9351 9352 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){ 9353 uint8_t event [6 + (MAX_NR_BIS * 2)]; 9354 uint16_t pos = 0; 9355 event[pos++] = HCI_EVENT_META_GAP; 9356 event[pos++] = 4 + (2 * big->num_bis); 9357 event[pos++] = GAP_SUBEVENT_BIG_CREATED; 9358 event[pos++] = status; 9359 event[pos++] = big->big_handle; 9360 event[pos++] = big->num_bis; 9361 uint8_t i; 9362 for (i=0;i<big->num_bis;i++){ 9363 little_endian_store_16(event, pos, big->bis_con_handles[i]); 9364 pos += 2; 9365 } 9366 hci_emit_event(event, pos, 0); 9367 } 9368 9369 static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){ 9370 uint8_t event [6 + (MAX_NR_CIS * 2)]; 9371 uint16_t pos = 0; 9372 event[pos++] = HCI_EVENT_META_GAP; 9373 event[pos++] = 4 + (2 * cig->num_cis); 9374 event[pos++] = GAP_SUBEVENT_CIG_CREATED; 9375 event[pos++] = status; 9376 event[pos++] = cig->cig_id; 9377 event[pos++] = cig->num_cis; 9378 uint8_t i; 9379 for (i=0;i<cig->num_cis;i++){ 9380 little_endian_store_16(event, pos, cig->cis_con_handles[i]); 9381 pos += 2; 9382 } 9383 hci_emit_event(event, pos, 0); 9384 } 9385 9386 static void 9387 hci_emit_cis_created(uint8_t cig_id, hci_con_handle_t cis_con_handle, uint8_t status) { 9388 uint8_t event [7]; 9389 uint16_t pos = 0; 9390 event[pos++] = HCI_EVENT_META_GAP; 9391 event[pos++] = 5; 9392 event[pos++] = GAP_SUBEVENT_CIS_CREATED; 9393 event[pos++] = status; 9394 event[pos++] = cig_id; 9395 little_endian_store_16(event, pos, cis_con_handle); 9396 pos += 2; 9397 hci_emit_event(event, pos, 0); 9398 } 9399 9400 static void hci_emit_big_terminated(const le_audio_big_t * big){ 9401 uint8_t event [4]; 9402 uint16_t pos = 0; 9403 event[pos++] = HCI_EVENT_META_GAP; 9404 event[pos++] = 2; 9405 event[pos++] = GAP_SUBEVENT_BIG_TERMINATED; 9406 event[pos++] = big->big_handle; 9407 hci_emit_event(event, pos, 0); 9408 } 9409 9410 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){ 9411 uint8_t event [6 + (MAX_NR_BIS * 2)]; 9412 uint16_t pos = 0; 9413 event[pos++] = HCI_EVENT_META_GAP; 9414 event[pos++] = 4; 9415 event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED; 9416 event[pos++] = status; 9417 event[pos++] = big_sync->big_handle; 9418 event[pos++] = big_sync->num_bis; 9419 uint8_t i; 9420 for (i=0;i<big_sync->num_bis;i++){ 9421 little_endian_store_16(event, pos, big_sync->bis_con_handles[i]); 9422 pos += 2; 9423 } 9424 hci_emit_event(event, pos, 0); 9425 } 9426 9427 static void hci_emit_big_sync_stopped(uint8_t big_handle){ 9428 uint8_t event [4]; 9429 uint16_t pos = 0; 9430 event[pos++] = HCI_EVENT_META_GAP; 9431 event[pos++] = 2; 9432 event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED; 9433 event[pos++] = big_handle; 9434 hci_emit_event(event, pos, 0); 9435 } 9436 9437 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) { 9438 uint8_t event[6]; 9439 uint16_t pos = 0; 9440 event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW; 9441 event[pos++] = sizeof(event) - 2; 9442 event[pos++] = big->big_handle; 9443 event[pos++] = bis_index; 9444 little_endian_store_16(event, pos, big->bis_con_handles[bis_index]); 9445 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 9446 } 9447 9448 static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) { 9449 uint8_t event[4]; 9450 uint16_t pos = 0; 9451 event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW; 9452 event[pos++] = sizeof(event) - 2; 9453 little_endian_store_16(event, pos, cis_con_handle); 9454 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 9455 } 9456 9457 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){ 9458 btstack_linked_list_iterator_t it; 9459 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9460 while (btstack_linked_list_iterator_has_next(&it)){ 9461 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9462 if ( big->big_handle == big_handle ) { 9463 return big; 9464 } 9465 } 9466 return NULL; 9467 } 9468 9469 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){ 9470 btstack_linked_list_iterator_t it; 9471 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 9472 while (btstack_linked_list_iterator_has_next(&it)){ 9473 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 9474 if ( big_sync->big_handle == big_handle ) { 9475 return big_sync; 9476 } 9477 } 9478 return NULL; 9479 } 9480 9481 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){ 9482 hci_stack->iso_packets_to_queue = num_packets; 9483 } 9484 9485 static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){ 9486 btstack_linked_list_iterator_t it; 9487 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs); 9488 while (btstack_linked_list_iterator_has_next(&it)){ 9489 le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it); 9490 if ( cig->cig_id == cig_id ) { 9491 return cig; 9492 } 9493 } 9494 return NULL; 9495 } 9496 9497 static void hci_iso_notify_can_send_now(void){ 9498 9499 // BIG 9500 9501 btstack_linked_list_iterator_t it; 9502 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9503 while (btstack_linked_list_iterator_has_next(&it)){ 9504 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9505 // track number completed packet timestamps 9506 if (big->num_completed_timestamp_current_valid){ 9507 big->num_completed_timestamp_current_valid = false; 9508 if (big->num_completed_timestamp_previous_valid){ 9509 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling 9510 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000; 9511 int32_t num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms, 9512 big->num_completed_timestamp_previous_ms); 9513 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){ 9514 // to catch up, skip packet on all BIS 9515 uint8_t i; 9516 for (i=0;i<big->num_bis;i++){ 9517 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9518 if (iso_stream){ 9519 iso_stream->num_packets_to_skip++; 9520 } 9521 } 9522 } 9523 } 9524 big->num_completed_timestamp_previous_valid = true; 9525 big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms; 9526 } 9527 9528 if (big->can_send_now_requested){ 9529 // check if no outgoing iso packets pending and no can send now have to be emitted 9530 uint8_t i; 9531 bool can_send = true; 9532 uint8_t num_iso_queued_minimum = 0; 9533 for (i=0;i<big->num_bis;i++){ 9534 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9535 if (iso_stream == NULL) continue; 9536 // handle case where individual ISO packet was sent too late: 9537 // for each additionally queued packet, a new one needs to get skipped 9538 if (i==0){ 9539 num_iso_queued_minimum = iso_stream->num_packets_sent; 9540 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){ 9541 uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum; 9542 iso_stream->num_packets_to_skip += num_packets_to_skip; 9543 iso_stream->num_packets_sent -= num_packets_to_skip; 9544 } 9545 // check if we can send now 9546 if ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){ 9547 can_send = false; 9548 break; 9549 } 9550 } 9551 if (can_send){ 9552 // propagate can send now to individual streams 9553 big->can_send_now_requested = false; 9554 for (i=0;i<big->num_bis;i++){ 9555 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9556 iso_stream->emit_ready_to_send = true; 9557 } 9558 } 9559 } 9560 } 9561 9562 if (hci_stack->hci_packet_buffer_reserved) return; 9563 9564 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9565 while (btstack_linked_list_iterator_has_next(&it)){ 9566 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9567 // report bis ready 9568 uint8_t i; 9569 for (i=0;i<big->num_bis;i++){ 9570 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9571 if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){ 9572 iso_stream->emit_ready_to_send = false; 9573 hci_emit_bis_can_send_now(big, i); 9574 break; 9575 } 9576 } 9577 } 9578 9579 // CIS 9580 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 9581 while (btstack_linked_list_iterator_has_next(&it)) { 9582 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 9583 if ((iso_stream->can_send_now_requested) && 9584 (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){ 9585 iso_stream->can_send_now_requested = false; 9586 hci_emit_cis_can_send_now(iso_stream->con_handle); 9587 } 9588 } 9589 } 9590 9591 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){ 9592 if (hci_big_for_handle(big_params->big_handle) != NULL){ 9593 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9594 } 9595 if (big_params->num_bis == 0){ 9596 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9597 } 9598 if (big_params->num_bis > MAX_NR_BIS){ 9599 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9600 } 9601 9602 // reserve ISO Streams 9603 uint8_t i; 9604 uint8_t status = ERROR_CODE_SUCCESS; 9605 for (i=0;i<big_params->num_bis;i++){ 9606 status = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_CON_HANDLE_INVALID, big_params->big_handle, 9607 HCI_ISO_STREAM_STATE_REQUESTED); 9608 if (status != ERROR_CODE_SUCCESS) { 9609 break; 9610 } 9611 } 9612 9613 // free structs on error 9614 if (status != ERROR_CODE_SUCCESS){ 9615 hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_params->big_handle); 9616 return status; 9617 } 9618 9619 le_audio_big_t * big = storage; 9620 big->big_handle = big_params->big_handle; 9621 big->params = big_params; 9622 big->state = LE_AUDIO_BIG_STATE_CREATE; 9623 big->num_bis = big_params->num_bis; 9624 btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 9625 9626 hci_run(); 9627 9628 return ERROR_CODE_SUCCESS; 9629 } 9630 9631 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){ 9632 if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){ 9633 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9634 } 9635 if (big_sync_params->num_bis == 0){ 9636 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9637 } 9638 if (big_sync_params->num_bis > MAX_NR_BIS){ 9639 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9640 } 9641 9642 le_audio_big_sync_t * big_sync = storage; 9643 big_sync->big_handle = big_sync_params->big_handle; 9644 big_sync->params = big_sync_params; 9645 big_sync->state = LE_AUDIO_BIG_STATE_CREATE; 9646 big_sync->num_bis = big_sync_params->num_bis; 9647 btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 9648 9649 hci_run(); 9650 9651 return ERROR_CODE_SUCCESS; 9652 } 9653 9654 uint8_t gap_big_terminate(uint8_t big_handle){ 9655 le_audio_big_t * big = hci_big_for_handle(big_handle); 9656 if (big == NULL){ 9657 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9658 } 9659 switch (big->state){ 9660 case LE_AUDIO_BIG_STATE_CREATE: 9661 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 9662 hci_emit_big_terminated(big); 9663 break; 9664 case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH: 9665 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE; 9666 break; 9667 case LE_AUDIO_BIG_STATE_W4_ESTABLISHED: 9668 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 9669 case LE_AUDIO_BIG_STATE_ACTIVE: 9670 big->state = LE_AUDIO_BIG_STATE_TERMINATE; 9671 hci_run(); 9672 break; 9673 default: 9674 return ERROR_CODE_COMMAND_DISALLOWED; 9675 } 9676 return ERROR_CODE_SUCCESS; 9677 } 9678 9679 uint8_t gap_big_sync_terminate(uint8_t big_handle){ 9680 le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle); 9681 if (big_sync == NULL){ 9682 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9683 } 9684 switch (big_sync->state){ 9685 case LE_AUDIO_BIG_STATE_CREATE: 9686 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 9687 hci_emit_big_sync_stopped(big_handle); 9688 break; 9689 case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH: 9690 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE; 9691 break; 9692 case LE_AUDIO_BIG_STATE_W4_ESTABLISHED: 9693 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 9694 case LE_AUDIO_BIG_STATE_ACTIVE: 9695 big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE; 9696 hci_run(); 9697 break; 9698 default: 9699 return ERROR_CODE_COMMAND_DISALLOWED; 9700 } 9701 return ERROR_CODE_SUCCESS; 9702 } 9703 9704 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){ 9705 le_audio_big_t * big = hci_big_for_handle(big_handle); 9706 if (big == NULL){ 9707 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9708 } 9709 if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){ 9710 return ERROR_CODE_COMMAND_DISALLOWED; 9711 } 9712 big->can_send_now_requested = true; 9713 hci_iso_notify_can_send_now(); 9714 return ERROR_CODE_SUCCESS; 9715 } 9716 9717 uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){ 9718 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle); 9719 if (iso_stream == NULL){ 9720 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9721 } 9722 if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) { 9723 return ERROR_CODE_COMMAND_DISALLOWED; 9724 } 9725 iso_stream->can_send_now_requested = true; 9726 hci_iso_notify_can_send_now(); 9727 return ERROR_CODE_SUCCESS; 9728 } 9729 9730 uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){ 9731 if (hci_cig_for_id(cig_params->cig_id) != NULL){ 9732 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9733 } 9734 if (cig_params->num_cis == 0){ 9735 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9736 } 9737 if (cig_params->num_cis > MAX_NR_BIS){ 9738 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9739 } 9740 9741 // reserve ISO Streams 9742 uint8_t i; 9743 uint8_t status = ERROR_CODE_SUCCESS; 9744 for (i=0;i<cig_params->num_cis;i++){ 9745 status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_CON_HANDLE_INVALID, cig_params->cig_id, 9746 HCI_ISO_STREAM_STATE_REQUESTED); 9747 if (status != ERROR_CODE_SUCCESS) { 9748 break; 9749 } 9750 } 9751 9752 // free structs on error 9753 if (status != ERROR_CODE_SUCCESS){ 9754 hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id); 9755 return status; 9756 } 9757 9758 le_audio_cig_t * cig = storage; 9759 cig->cig_id = cig_params->cig_id; 9760 cig->num_cis = cig_params->num_cis; 9761 cig->params = cig_params; 9762 cig->state = LE_AUDIO_CIG_STATE_CREATE; 9763 for (i=0;i<cig->num_cis;i++){ 9764 cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID; 9765 cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID; 9766 } 9767 btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig); 9768 9769 hci_run(); 9770 9771 return ERROR_CODE_SUCCESS; 9772 } 9773 9774 uint8_t gap_cis_create(uint8_t cig_handle, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){ 9775 le_audio_cig_t * cig = hci_cig_for_id(cig_handle); 9776 if (cig == NULL){ 9777 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9778 } 9779 9780 if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){ 9781 return ERROR_CODE_COMMAND_DISALLOWED; 9782 } 9783 9784 // store ACL Connection Handles 9785 uint8_t i; 9786 for (i=0;i<cig->num_cis;i++){ 9787 // check that all con handles exit 9788 hci_con_handle_t cis_handle = cis_con_handles[i]; 9789 uint8_t j; 9790 bool found = false; 9791 for (j=0;j<cig->num_cis;j++){ 9792 if (cig->cis_con_handles[j] == cis_handle){ 9793 cig->acl_con_handles[j] = acl_con_handles[j]; 9794 found = true; 9795 break; 9796 } 9797 } 9798 if (!found){ 9799 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9800 } 9801 } 9802 9803 cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS; 9804 hci_run(); 9805 9806 return ERROR_CODE_SUCCESS; 9807 } 9808 9809 static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_con_handle, hci_iso_stream_state_t state){ 9810 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle); 9811 if (iso_stream != NULL){ 9812 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9813 } 9814 9815 uint8_t status = hci_iso_stream_create(HCI_ISO_TYPE_CIS, cis_con_handle, 9816 HCI_ISO_GROUP_ID_INVALID, state); 9817 if (status == ERROR_CODE_SUCCESS){ 9818 return status; 9819 } 9820 9821 hci_run(); 9822 return ERROR_CODE_SUCCESS; 9823 } 9824 9825 uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){ 9826 return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT); 9827 } 9828 9829 uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){ 9830 return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT); 9831 } 9832 9833 9834 #endif 9835 #endif /* ENABLE_BLE */ 9836 9837 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION 9838 void hci_setup_test_connections_fuzz(void){ 9839 hci_connection_t * conn; 9840 9841 // default address: 66:55:44:33:00:01 9842 bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00}; 9843 9844 // setup Controller info 9845 hci_stack->num_cmd_packets = 255; 9846 hci_stack->acl_packets_total_num = 255; 9847 9848 // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01 9849 addr[5] = 0x01; 9850 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 9851 conn->con_handle = addr[5]; 9852 conn->role = HCI_ROLE_SLAVE; 9853 conn->state = RECEIVED_CONNECTION_REQUEST; 9854 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9855 9856 // setup incoming Classic SCO connection with con handle 0x0002 9857 addr[5] = 0x02; 9858 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 9859 conn->con_handle = addr[5]; 9860 conn->role = HCI_ROLE_SLAVE; 9861 conn->state = RECEIVED_CONNECTION_REQUEST; 9862 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9863 9864 // setup ready Classic ACL connection with con handle 0x0003 9865 addr[5] = 0x03; 9866 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 9867 conn->con_handle = addr[5]; 9868 conn->role = HCI_ROLE_SLAVE; 9869 conn->state = OPEN; 9870 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9871 9872 // setup ready Classic SCO connection with con handle 0x0004 9873 addr[5] = 0x04; 9874 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 9875 conn->con_handle = addr[5]; 9876 conn->role = HCI_ROLE_SLAVE; 9877 conn->state = OPEN; 9878 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9879 9880 // setup ready LE ACL connection with con handle 0x005 and public address 9881 addr[5] = 0x05; 9882 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC); 9883 conn->con_handle = addr[5]; 9884 conn->role = HCI_ROLE_SLAVE; 9885 conn->state = OPEN; 9886 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9887 conn->sm_connection.sm_connection_encrypted = 1; 9888 } 9889 9890 void hci_free_connections_fuzz(void){ 9891 btstack_linked_list_iterator_t it; 9892 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 9893 while (btstack_linked_list_iterator_has_next(&it)){ 9894 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 9895 btstack_linked_list_iterator_remove(&it); 9896 btstack_memory_hci_connection_free(con); 9897 } 9898 } 9899 void hci_simulate_working_fuzz(void){ 9900 hci_stack->le_scanning_param_update = false; 9901 hci_init_done(); 9902 hci_stack->num_cmd_packets = 255; 9903 } 9904 #endif 9905