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