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