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