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