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