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