xref: /btstack/src/hci.c (revision c769c85c1185690c32607ded8e80fdc18f839a4e)
11f504dbdSmatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
232fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
242fca4dadSMilanka Ringwald  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "hci.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
411f504dbdSmatthias.ringwald  *  hci.c
421f504dbdSmatthias.ringwald  *
431f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
441f504dbdSmatthias.ringwald  *
451f504dbdSmatthias.ringwald  */
461f504dbdSmatthias.ringwald 
477907f069SMatthias Ringwald #include "btstack_config.h"
4828171530Smatthias.ringwald 
497f2435e6Smatthias.ringwald 
5006b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
51aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
528f2a52f4SMatthias Ringwald #include "btstack_run_loop_embedded.h"
53a484130cSMatthias Ringwald #endif
5406b9e820SMatthias Ringwald #endif
55a484130cSMatthias Ringwald 
56a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
57472a5742SMatthias Ringwald #include "gap.h"
5821debf25SMatthias Ringwald #include "ble/le_device_db.h"
5945c102fdSMatthias Ringwald #endif
6045c102fdSMatthias Ringwald 
6193b8dc03Smatthias.ringwald #include <stdarg.h>
6293b8dc03Smatthias.ringwald #include <string.h>
635838a2edSMatthias Ringwald #include <inttypes.h>
647f2435e6Smatthias.ringwald 
6516ece135SMatthias Ringwald #include "btstack_debug.h"
660e2df43fSMatthias Ringwald #include "btstack_event.h"
674a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
684a3574a1SMatthias Ringwald #include "btstack_memory.h"
6961f37892SMatthias Ringwald #include "bluetooth_company_id.h"
701cfb383eSMatthias Ringwald #include "bluetooth_data_types.h"
714a3574a1SMatthias Ringwald #include "gap.h"
724a3574a1SMatthias Ringwald #include "hci.h"
734a3574a1SMatthias Ringwald #include "hci_cmd.h"
74d8905019Smatthias.ringwald #include "hci_dump.h"
751cfb383eSMatthias Ringwald #include "ad_parser.h"
7693b8dc03Smatthias.ringwald 
778ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
788ad9cf99SMatthias Ringwald #include <stdio.h>  // sprintf
798ad9cf99SMatthias Ringwald #endif
808ad9cf99SMatthias Ringwald 
812b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
822b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_NUM
832b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
842b838201SMatthias Ringwald #endif
852b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_LEN
862b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
872b838201SMatthias Ringwald #endif
882b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_NUM
892b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
902b838201SMatthias Ringwald #endif
912b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_LEN
922b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
932b838201SMatthias Ringwald #endif
942b838201SMatthias Ringwald #endif
951b0e3922Smatthias.ringwald 
96616cfd90SMatthias Ringwald #ifndef MAX_NR_CONTROLLER_ACL_BUFFERS
97616cfd90SMatthias Ringwald #define MAX_NR_CONTROLLER_ACL_BUFFERS 255
98616cfd90SMatthias Ringwald #endif
99616cfd90SMatthias Ringwald #ifndef MAX_NR_CONTROLLER_SCO_PACKETS
100616cfd90SMatthias Ringwald #define MAX_NR_CONTROLLER_SCO_PACKETS 255
101616cfd90SMatthias Ringwald #endif
102616cfd90SMatthias Ringwald 
1036bcf18c2SMatthias Ringwald #ifndef HCI_ACL_CHUNK_SIZE_ALIGNMENT
1046bcf18c2SMatthias Ringwald #define HCI_ACL_CHUNK_SIZE_ALIGNMENT 1
1056bcf18c2SMatthias Ringwald #endif
1066bcf18c2SMatthias Ringwald 
107aa81e641SMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
108aa81e641SMatthias Ringwald #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."
109aa81e641SMatthias Ringwald #endif
110aa81e641SMatthias Ringwald 
1111e20a53eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
1121e20a53eSMatthias Ringwald #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."
1131e20a53eSMatthias Ringwald #endif
1141e20a53eSMatthias Ringwald 
115169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
11662473419SMatthias Ringwald 
11762473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
118659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
11962473419SMatthias Ringwald #endif
120ee091cf1Smatthias.ringwald 
1211cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1221cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1231cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1241cfb383eSMatthias Ringwald #endif
1251cfb383eSMatthias Ringwald 
126f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
127f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN       0x01
128f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX       0x30
12930199e24SMatthias Ringwald #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02
13030199e24SMatthias Ringwald #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03
131beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE         0x00
132beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
133beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE       0x81
134beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
135beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
13630199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_PERIODIC     0x84
13730199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85
138f5875de5SMatthias Ringwald 
139b7f1ee76SMatthias Ringwald // GAP Remote Name Request
140b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
141b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
142b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
143b7f1ee76SMatthias Ringwald 
1440a51f88bSMatthias Ringwald // GAP Pairing
1450a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1460a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1470a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1480a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1490a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1500a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1510a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
152cc15bb2cSMatthias Ringwald #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
1530a51f88bSMatthias Ringwald 
15425e46151SMatthias Ringwald //
1559ce37759SMatthias Ringwald // compact storage of relevant supported HCI Commands.
1569ce37759SMatthias Ringwald // X-Macro below provides enumeration and mapping table into the supported
15725e46151SMatthias Ringwald // commands bitmap (64 bytes) from HCI Read Local Supported Commands
15825e46151SMatthias Ringwald //
15925e46151SMatthias Ringwald 
16025e46151SMatthias Ringwald // format: command name, byte offset, bit nr in 64-byte supported commands
1618c021356SMatthias Ringwald // currently stored in 32-bit variable
16225e46151SMatthias Ringwald #define SUPPORTED_HCI_COMMANDS \
163a858a414SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES         ,  2, 6) \
16425e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \
1659ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE                      , 14, 7) \
16625e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \
1679ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE              , 20, 4) \
168ff7d1758SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2                 , 22, 2) \
1699ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED               , 24, 6) \
1704639b1e4SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_REMOTE_FEATURES               , 27, 5) \
1719ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \
1729ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST         , 32, 3) \
1739ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND  , 32, 6) \
17425e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \
17525e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE      , 35, 1) \
176a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH           , 35, 3) \
1779ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY                    , 35, 5) \
178d0753e0fSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE    , 36, 5) \
17979b7ea2dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2                , 41, 5) \
180e1f9b11fSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_HOST_FEATURE_V1                , 44, 1) \
181a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE           , 45, 7) \
18225e46151SMatthias Ringwald 
18325e46151SMatthias Ringwald // enumerate supported commands
18425e46151SMatthias Ringwald #define X(name, offset, bit) name,
18525e46151SMatthias Ringwald enum {
18625e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS
18725e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS_COUNT
18825e46151SMatthias Ringwald };
18925e46151SMatthias Ringwald #undef X
19025e46151SMatthias Ringwald 
191b83d5eabSMatthias Ringwald // prototypes
19235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
193758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
19471fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable);
19535454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
19620dcdd22SMatthias Ringwald static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
19767aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
19835454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
19935454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
200a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
20135454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
202ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
20396a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
20452db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
2059784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
20652db98b2SMatthias Ringwald #endif
2071cfb383eSMatthias Ringwald 
2087586ee35S[email protected] static int  hci_power_control_on(void);
2097586ee35S[email protected] static void hci_power_control_off(void);
2106da48142SSean Wilson static void hci_state_reset(void);
211685ec254SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds);
212fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
213fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
214b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
215b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
216b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
217b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
2189da9850bSMatthias Ringwald static void hci_emit_btstack_event(uint8_t * event, uint16_t size, int dump);
219b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
22095d71764SMatthias Ringwald static void hci_run(void);
221617c03d6SMatthias Ringwald static bool hci_is_le_connection(hci_connection_t * connection);
222ed208344SMatthias Ringwald static uint8_t hci_send_prepared_cmd_packet(void);
2236a5ffed8SMatthias Ringwald 
2246a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
225f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
226dbe0d85cSMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection);
2276a5ffed8SMatthias Ringwald #endif
2285d509858SMatthias Ringwald 
229a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
230137a570aSMatthias Ringwald static bool hci_run_general_gap_le(void);
231137a570aSMatthias Ringwald static void gap_privacy_clients_handle_ready(void);
232137a570aSMatthias Ringwald static void gap_privacy_clients_notify(bd_addr_t new_random_address);
233e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23439677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
235384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
236667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
237ca0d6e5aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_le_connection(void);
238c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void);
23991097d83SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
24091097d83SMatthias Ringwald static void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size);
24191097d83SMatthias Ringwald #endif
2425d509858SMatthias Ringwald #endif
24325df6c61SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
244ee54aff5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
24525df6c61SMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle);
246033393eeSBob Abeles static uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len);
247ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
248ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
2494ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
250969d876aSMatthias Ringwald 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);
2514ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream);
252778463d0SMatthias Ringwald static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id);
25315a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle);
25415a15be3SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t big_handle);
25515a15be3SMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle);
256750818acSMatthias Ringwald static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size);
2577aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle);
258d3a89d91SMatthias Ringwald static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id);
2595ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void);
2607aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status);
2617aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big);
2622a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status);
263d04a9afcSMatthias Ringwald static void hci_emit_big_sync_stopped(uint8_t big_handle);
264d3a89d91SMatthias Ringwald static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status);
26514045fdbSMatthias Ringwald static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status);
2662a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle);
2674ae8623eSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
268ee54aff5SMatthias Ringwald #endif /* ENABLE_BLE */
269758b46ceSmatthias.ringwald 
27006b35ec0Smatthias.ringwald // the STACK is here
2713a9fb326S[email protected] #ifndef HAVE_MALLOC
2723a9fb326S[email protected] static hci_stack_t   hci_stack_static;
2733a9fb326S[email protected] #endif
2743a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
27516833f0aSmatthias.ringwald 
2761c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
27763168530SMatthias Ringwald // default name
27863168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
27963168530SMatthias Ringwald 
28066fb9560S[email protected] // test helper
28166fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
2821c9e5e9dSMatthias Ringwald #endif
28366fb9560S[email protected] 
284aee5d5c1SMatthias Ringwald // reset connection state on create and on reconnect
285aee5d5c1SMatthias Ringwald // don't overwrite addr, con handle, role
286aee5d5c1SMatthias Ringwald static void hci_connection_init(hci_connection_t * conn){
2878daf94bcSMatthias Ringwald     conn->authentication_flags = AUTH_FLAG_NONE;
28896a45072S[email protected]     conn->bonding_flags = 0;
28996a45072S[email protected]     conn->requested_security_level = LEVEL_0;
2908ce18681SMatthias Ringwald     conn->link_key_type = INVALID_LINK_KEY;
29152db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
29288a03c8dSMatthias Ringwald     conn->request_role = HCI_ROLE_INVALID;
293140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = 0xffff;
294965a4ccfSMatthias Ringwald     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
29591a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
29691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
29796a45072S[email protected]     hci_connection_timestamp(conn);
29852db98b2SMatthias Ringwald #endif
29996a45072S[email protected]     conn->acl_recombination_length = 0;
30096a45072S[email protected]     conn->acl_recombination_pos = 0;
301ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
302760b20efSMatthias Ringwald 
303da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
304b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
305b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
306b90f6e0aSMatthias Ringwald #endif
3070f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
3080f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
3090f3b27c5SMatthias Ringwald #endif
310cb439cf1SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
311cb439cf1SMatthias Ringwald     conn->classic_oob_c_192 = NULL;
312cb439cf1SMatthias Ringwald     conn->classic_oob_r_192 = NULL;
313cb439cf1SMatthias Ringwald     conn->classic_oob_c_256 = NULL;
314cb439cf1SMatthias Ringwald     conn->classic_oob_r_256 = NULL;
315cb439cf1SMatthias Ringwald #endif
3164dcab8b6SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
3174dcab8b6SMatthias Ringwald     conn->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
3184dcab8b6SMatthias Ringwald     conn->le_past_advertising_handle = 0xff;
3194dcab8b6SMatthias Ringwald #endif
320aee5d5c1SMatthias Ringwald }
321aee5d5c1SMatthias Ringwald 
322aee5d5c1SMatthias Ringwald /**
323aee5d5c1SMatthias Ringwald  * create connection for given address
324aee5d5c1SMatthias Ringwald  *
325aee5d5c1SMatthias Ringwald  * @return connection OR NULL, if no memory left
326aee5d5c1SMatthias Ringwald  */
32788f925b1SMatthias Ringwald static hci_connection_t *
32888f925b1SMatthias Ringwald create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type, hci_role_t role) {
329aee5d5c1SMatthias Ringwald     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
330aee5d5c1SMatthias Ringwald 
331aee5d5c1SMatthias Ringwald     hci_connection_t * conn = btstack_memory_hci_connection_get();
332aee5d5c1SMatthias Ringwald     if (!conn) return NULL;
333aee5d5c1SMatthias Ringwald     hci_connection_init(conn);
334aee5d5c1SMatthias Ringwald 
335aee5d5c1SMatthias Ringwald     bd_addr_copy(conn->address, addr);
336aee5d5c1SMatthias Ringwald     conn->address_type = addr_type;
337aee5d5c1SMatthias Ringwald     conn->con_handle = HCI_CON_HANDLE_INVALID;
33888f925b1SMatthias Ringwald     conn->role = role;
339665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
340aee5d5c1SMatthias Ringwald 
34196a45072S[email protected]     return conn;
34296a45072S[email protected] }
34366fb9560S[email protected] 
344da886c03S[email protected] 
345da886c03S[email protected] /**
346da886c03S[email protected]  * get le connection parameter range
347da886c03S[email protected] *
348da886c03S[email protected]  * @return le connection parameter range struct
349da886c03S[email protected]  */
3504ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
3514ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
352da886c03S[email protected] }
353da886c03S[email protected] 
354da886c03S[email protected] /**
355da886c03S[email protected]  * set le connection parameter range
356da886c03S[email protected]  *
357da886c03S[email protected]  */
358da886c03S[email protected] 
3594ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
3604ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
361da886c03S[email protected] }
362da886c03S[email protected] 
363da886c03S[email protected] /**
36473cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
36573cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
36673cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
36773cd8a2aSMatthias Ringwald  * @param conn_latency
36873cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
3696b65794dSMilanka Ringwald  * @return 1 if included
37073cd8a2aSMatthias Ringwald  */
37173cd8a2aSMatthias Ringwald 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){
37273cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
37373cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
37473cd8a2aSMatthias Ringwald 
37573cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
37673cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
37773cd8a2aSMatthias Ringwald 
37873cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
37973cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
38073cd8a2aSMatthias Ringwald 
38173cd8a2aSMatthias Ringwald     return 1;
38273cd8a2aSMatthias Ringwald }
38373cd8a2aSMatthias Ringwald 
38473cd8a2aSMatthias Ringwald /**
3852b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
3862b6ab3e6SMatthias Ringwald  * @note: default: 1
3872b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
3882b6ab3e6SMatthias Ringwald  */
389d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3902b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
3912b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
3922b6ab3e6SMatthias Ringwald }
393d4e4907bSMatthias Ringwald #endif
3942b6ab3e6SMatthias Ringwald 
3952b6ab3e6SMatthias Ringwald /**
396da886c03S[email protected]  * get hci connections iterator
397da886c03S[email protected]  *
398da886c03S[email protected]  * @return hci connections iterator
399da886c03S[email protected]  */
400da886c03S[email protected] 
401665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
402665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
403da886c03S[email protected] }
404da886c03S[email protected] 
40597addcc5Smatthias.ringwald /**
406ee091cf1Smatthias.ringwald  * get connection for a given handle
407ee091cf1Smatthias.ringwald  *
408ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
409ee091cf1Smatthias.ringwald  */
4105061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
411665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
412665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
413665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
414665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
4153ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
416da886c03S[email protected]             return item;
417ee091cf1Smatthias.ringwald         }
418ee091cf1Smatthias.ringwald     }
419ee091cf1Smatthias.ringwald     return NULL;
420ee091cf1Smatthias.ringwald }
421ee091cf1Smatthias.ringwald 
42296a45072S[email protected] /**
42396a45072S[email protected]  * get connection for given address
42496a45072S[email protected]  *
42596a45072S[email protected]  * @return connection OR NULL, if not found
42696a45072S[email protected]  */
427667ba9d1SMatthias Ringwald hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
428665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
429665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
430665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
431665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
43296a45072S[email protected]         if (connection->address_type != addr_type)  continue;
43396a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
43462bda3fbS[email protected]         return connection;
43562bda3fbS[email protected]     }
43662bda3fbS[email protected]     return NULL;
43762bda3fbS[email protected] }
43862bda3fbS[email protected] 
439d5f71a7eSMatthias Ringwald #ifdef ENABLE_CLASSIC
440d5f71a7eSMatthias Ringwald 
4413e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
4423e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
4433e5e0926SMatthias Ringwald }
44452db98b2SMatthias Ringwald 
445228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
446228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
447228e430cSMatthias Ringwald }
448228e430cSMatthias Ringwald 
449ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
450ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
451ee752bb8SMatthias Ringwald     int connections = 0;
452ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
453ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
454ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
455ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
456ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
457ee752bb8SMatthias Ringwald         connections++;
458ee752bb8SMatthias Ringwald     }
459ee752bb8SMatthias Ringwald     return connections;
460ee752bb8SMatthias Ringwald }
461ee752bb8SMatthias Ringwald #endif
462ee752bb8SMatthias Ringwald 
463ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
46491a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
465aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
466528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
467c785ef68Smatthias.ringwald         // connections might be timed out
468c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
469c785ef68Smatthias.ringwald     }
470f316a845SMatthias Ringwald #else
471c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
4725f26aadcSMatthias Ringwald         // connections might be timed out
4735f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
4745f26aadcSMatthias Ringwald     }
4755f26aadcSMatthias Ringwald #endif
476c785ef68Smatthias.ringwald }
477ee091cf1Smatthias.ringwald 
478ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
479aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
480528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
481f316a845SMatthias Ringwald #else
482528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
4835f26aadcSMatthias Ringwald #endif
484ee091cf1Smatthias.ringwald }
485ee091cf1Smatthias.ringwald 
48643bfb1bdSmatthias.ringwald /**
48780ca58a0Smatthias.ringwald  * add authentication flags and reset timer
48896a45072S[email protected]  * @note: assumes classic connection
489a086dc35SMatthias Ringwald  * @note: bd_addr is passed in as little endian uint8_t * as it is called from parsing packets
4907fde4af9Smatthias.ringwald  */
4917fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
4927fde4af9Smatthias.ringwald     bd_addr_t addr;
493724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
494f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4957fde4af9Smatthias.ringwald     if (conn) {
49628ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
49780ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
4987fde4af9Smatthias.ringwald     }
4997fde4af9Smatthias.ringwald }
5007fde4af9Smatthias.ringwald 
5011714cbbdSMatthias Ringwald static bool hci_pairing_active(hci_connection_t * hci_connection){
5028daf94bcSMatthias Ringwald     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
5031714cbbdSMatthias Ringwald }
5041714cbbdSMatthias Ringwald 
5051714cbbdSMatthias Ringwald static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
5061714cbbdSMatthias Ringwald     if (hci_pairing_active(hci_connection)) return;
5071714cbbdSMatthias Ringwald     if (ssp){
5088daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
5091714cbbdSMatthias Ringwald     } else {
5108daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
5111714cbbdSMatthias Ringwald     }
5121714cbbdSMatthias Ringwald     // if we are initiator, we have sent an HCI Authenticate Request
5131714cbbdSMatthias Ringwald     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
5141714cbbdSMatthias Ringwald 
5155a561920SMatthias Ringwald     // if we are responder, use minimal service security level as required level
5165a561920SMatthias Ringwald     if (!initiator){
517acadfdd0SMatthias Ringwald         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);
5185a561920SMatthias Ringwald     }
5195a561920SMatthias Ringwald 
5205a561920SMatthias Ringwald     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
52177208d90SMatthias Ringwald 
52277208d90SMatthias Ringwald     uint8_t event[12];
52377208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_STARTED;
52477208d90SMatthias Ringwald     event[1] = 10;
525bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
5264159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
52777208d90SMatthias Ringwald     event[10] = (uint8_t) ssp;
52877208d90SMatthias Ringwald     event[11] = (uint8_t) initiator;
5299da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
5301714cbbdSMatthias Ringwald }
5311714cbbdSMatthias Ringwald 
5321714cbbdSMatthias Ringwald static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
5333c439ac4SMatthias Ringwald     hci_connection->requested_security_level = LEVEL_0;
5341714cbbdSMatthias Ringwald     if (!hci_pairing_active(hci_connection)) return;
5358daf94bcSMatthias Ringwald     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
5361e7371deSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
537cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_192 = NULL;
538cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_192 = NULL;
539cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_256 = NULL;
540cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_256 = NULL;
5411e7371deSMatthias Ringwald #endif
5421714cbbdSMatthias Ringwald     log_info("pairing complete, status %02x", status);
54377208d90SMatthias Ringwald 
5443176c896SMatthias Ringwald     uint8_t event[11];
54577208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_COMPLETE;
54677208d90SMatthias Ringwald     event[1] = 9;
547bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
5484159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
54977208d90SMatthias Ringwald     event[10] = status;
5509da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
5515999ee11SMatthias Ringwald 
5525999ee11SMatthias Ringwald     // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted
5535999ee11SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){
5545999ee11SMatthias Ringwald         hci_connection->bonding_flags &= ~BONDING_DEDICATED;
5555999ee11SMatthias Ringwald         hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
5565999ee11SMatthias Ringwald         hci_connection->bonding_status = status;
5575999ee11SMatthias Ringwald     }
5581714cbbdSMatthias Ringwald }
5591714cbbdSMatthias Ringwald 
56020dcdd22SMatthias Ringwald bool hci_authentication_active_for_handle(hci_con_handle_t handle){
5615061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
56220dcdd22SMatthias Ringwald     if (!conn) return false;
56320dcdd22SMatthias Ringwald     return hci_pairing_active(conn);
56480ca58a0Smatthias.ringwald }
56580ca58a0Smatthias.ringwald 
56615a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
56755597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5682bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
569a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
570c12e46e7Smatthias.ringwald }
57155597469SMatthias Ringwald 
57255597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
57355597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5742bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
57555597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
576c12e46e7Smatthias.ringwald }
5771b6fb31bSMatthias Ringwald 
578e8ad470fSMatthias Ringwald bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
579e8ad470fSMatthias Ringwald 	if (!hci_stack->link_key_db) return false;
58076b0318eSMatthias Ringwald 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
58176b0318eSMatthias Ringwald 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
58276b0318eSMatthias Ringwald 	return result;
583e8ad470fSMatthias Ringwald }
584e8ad470fSMatthias Ringwald 
585ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
586ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
587ceecb9d9SMatthias Ringwald     link_key_t link_key;
588ceecb9d9SMatthias Ringwald     link_key_type_t type;
589ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
590ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
591ceecb9d9SMatthias Ringwald     if (!ok) {
592ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
593ceecb9d9SMatthias Ringwald         return;
594ceecb9d9SMatthias Ringwald     }
595ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
596ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
597ceecb9d9SMatthias Ringwald     }
598ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
599ceecb9d9SMatthias Ringwald }
600ceecb9d9SMatthias Ringwald 
6011b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
6021b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
6031b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
6041b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
6051b6fb31bSMatthias Ringwald }
6061b6fb31bSMatthias Ringwald 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){
6071b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
6081b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
6091b6fb31bSMatthias Ringwald }
6101b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
6111b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
6121b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
6131b6fb31bSMatthias Ringwald }
61435454696SMatthias Ringwald #endif
615c12e46e7Smatthias.ringwald 
6168e97a820SMatthias Ringwald bool hci_is_le_connection_type(bd_addr_type_t address_type){
617eb8076ddSMatthias Ringwald     switch (address_type){
618ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
619ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6203739bc96SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
6213739bc96SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
622eb8076ddSMatthias Ringwald             return true;
623ce41473eSMatthias Ringwald         default:
624eb8076ddSMatthias Ringwald             return false;
625ce41473eSMatthias Ringwald     }
6260bf6344aS[email protected] }
6270bf6344aS[email protected] 
6280890cf2bSMatthias Ringwald bool hci_is_le_identity_address_type(bd_addr_type_t address_type){
6290890cf2bSMatthias Ringwald     switch (address_type){
6300890cf2bSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
6310890cf2bSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
6320890cf2bSMatthias Ringwald             return true;
6330890cf2bSMatthias Ringwald         default:
6340890cf2bSMatthias Ringwald             return false;
6350890cf2bSMatthias Ringwald     }
6360890cf2bSMatthias Ringwald }
6370890cf2bSMatthias Ringwald 
638617c03d6SMatthias Ringwald static bool hci_is_le_connection(hci_connection_t * connection){
639eb8076ddSMatthias Ringwald     return hci_is_le_connection_type(connection->address_type);
640eb8076ddSMatthias Ringwald }
641eb8076ddSMatthias Ringwald 
6427fde4af9Smatthias.ringwald /**
64343bfb1bdSmatthias.ringwald  * count connections
64443bfb1bdSmatthias.ringwald  */
64540d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
64656c253c9Smatthias.ringwald     int count = 0;
647665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
648a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
64915a27967SMatthias Ringwald         count++;
65015a27967SMatthias Ringwald     }
65143bfb1bdSmatthias.ringwald     return count;
65243bfb1bdSmatthias.ringwald }
653c8e4258aSmatthias.ringwald 
6548f733c6fSMatthias Ringwald uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
655ee303eddS[email protected] 
656f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
657f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
658ee303eddS[email protected] 
659665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
660a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
661998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
662ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
663ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
664ce41473eSMatthias Ringwald         }
665f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
666ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
667ee303eddS[email protected]         }
668ee303eddS[email protected]     }
669d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
670ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
671ee303eddS[email protected]     int free_slots_le = 0;
672ee303eddS[email protected] 
673ee303eddS[email protected]     if (free_slots_classic < 0){
6749da54300S[email protected]         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);
675998906cdSmatthias.ringwald         return 0;
676998906cdSmatthias.ringwald     }
677ee303eddS[email protected] 
678ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
679ee303eddS[email protected]         // if we have LE slots, they are used
680ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
681ee303eddS[email protected]         if (free_slots_le < 0){
6829da54300S[email protected]             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);
683ee303eddS[email protected]             return 0;
684998906cdSmatthias.ringwald         }
685ee303eddS[email protected]     } else {
686ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
687ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
688ee303eddS[email protected]         if (free_slots_classic < 0){
6899da54300S[email protected]             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);
690ee303eddS[email protected]             return 0;
691ee303eddS[email protected]         }
692ee303eddS[email protected]     }
693ee303eddS[email protected] 
694ee303eddS[email protected]     switch (address_type){
695ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
6962125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
697ee303eddS[email protected]             return 0;
698ee303eddS[email protected] 
699f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
7008f733c6fSMatthias Ringwald             return (uint16_t) free_slots_classic;
701ee303eddS[email protected] 
702ee303eddS[email protected]         default:
7038f733c6fSMatthias Ringwald            if (hci_stack->le_acl_packets_total_num > 0){
7048f733c6fSMatthias Ringwald                return (uint16_t) free_slots_le;
705ee303eddS[email protected]            }
7068f733c6fSMatthias Ringwald            return (uint16_t) free_slots_classic;
707cb00d3aaS[email protected]     }
708998906cdSmatthias.ringwald }
709998906cdSmatthias.ringwald 
7102125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
7112125de09SMatthias Ringwald     // get connection type
7122125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7132125de09SMatthias Ringwald     if (!connection){
7142125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
7152125de09SMatthias Ringwald         return 0;
7162125de09SMatthias Ringwald     }
7172125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
7182125de09SMatthias Ringwald }
7192125de09SMatthias Ringwald 
72035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
721701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
722f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
723665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
724760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
725760b20efSMatthias Ringwald         // explicit flow control
726665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
727e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
728ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
729ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
730e35edcc1S[email protected]         }
731e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
732701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
73344d0e3d5S[email protected]             return 0;
73444d0e3d5S[email protected]         }
735e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
73649205f5dSMatthias Ringwald     } else {
737fa7f2dfdSMatthias Ringwald         // implicit flow control
7386f28d2eeSMatthias Ringwald         int num_ready = 0;
7396f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
7406f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
7416f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
7426f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
7436f28d2eeSMatthias Ringwald             num_ready++;
74449205f5dSMatthias Ringwald         }
7456f28d2eeSMatthias Ringwald         return num_ready;
7466f28d2eeSMatthias Ringwald     }
747e35edcc1S[email protected] }
74835454696SMatthias Ringwald #endif
74944d0e3d5S[email protected] 
7502b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
751a086dc35SMatthias Ringwald static int hci_can_send_command_packet_transport(void){
752ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
753ac928cc2S[email protected] 
754ac928cc2S[email protected]     // check for async hci transport implementations
755ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
756ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
757ac928cc2S[email protected]             return 0;
758ac928cc2S[email protected]         }
759ac928cc2S[email protected]     }
7602b838201SMatthias Ringwald     return 1;
7612b838201SMatthias Ringwald }
762ac928cc2S[email protected] 
7632b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
7641972f31fSMatthias Ringwald bool hci_can_send_command_packet_now(void){
765a086dc35SMatthias Ringwald     if (hci_can_send_command_packet_transport() == 0) return false;
7664ea43905SMatthias Ringwald     return hci_stack->num_cmd_packets > 0u;
767ac928cc2S[email protected] }
768ac928cc2S[email protected] 
7699d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
770ac928cc2S[email protected]     // check for async hci transport implementations
7711972f31fSMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return true;
7729d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
773ac928cc2S[email protected] }
7749d04d3a7SMatthias Ringwald 
7751972f31fSMatthias Ringwald static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
7761972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
7779d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
778ac928cc2S[email protected] }
7799d04d3a7SMatthias Ringwald 
7801972f31fSMatthias Ringwald bool hci_can_send_acl_le_packet_now(void){
7811972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
7829d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
7839d04d3a7SMatthias Ringwald }
7849d04d3a7SMatthias Ringwald 
7851972f31fSMatthias Ringwald bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
7861972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
787e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
788ac928cc2S[email protected] }
789ac928cc2S[email protected] 
7901972f31fSMatthias Ringwald bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
7911972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
792ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
7936b4af23dS[email protected] }
7946b4af23dS[email protected] 
79535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7961972f31fSMatthias Ringwald bool hci_can_send_acl_classic_packet_now(void){
7971972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
798f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
79935454696SMatthias Ringwald }
80035454696SMatthias Ringwald 
8011972f31fSMatthias Ringwald bool hci_can_send_prepared_sco_packet_now(void){
8021972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
803f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
804f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
805f234b250SMatthias Ringwald     } else {
806701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
80744d0e3d5S[email protected]     }
808f234b250SMatthias Ringwald }
80944d0e3d5S[email protected] 
8101972f31fSMatthias Ringwald bool hci_can_send_sco_packet_now(void){
8111972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
812701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
81344d0e3d5S[email protected] }
81444d0e3d5S[email protected] 
815d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
816d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
817d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
818d057580eSMatthias Ringwald }
81935454696SMatthias Ringwald #endif
820d057580eSMatthias Ringwald 
82195d71764SMatthias Ringwald // used for internal checks in l2cap.c
82202c7fc01SMatthias Ringwald bool hci_is_packet_buffer_reserved(void){
823c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
824c8b9416aS[email protected] }
825c8b9416aS[email protected] 
8268f4649e3SMatthias Ringwald void hci_reserve_packet_buffer(void){
8275d350981SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved == false);
82802c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = true;
8296b4af23dS[email protected] }
8306b4af23dS[email protected] 
83168a0fcf7S[email protected] void hci_release_packet_buffer(void){
8325d350981SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
83302c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
8345daaa52eSMatthias Ringwald     hci_emit_transport_packet_sent();
83568a0fcf7S[email protected] }
83668a0fcf7S[email protected] 
8376b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
8387f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
8396b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
8406b4af23dS[email protected] }
8416b4af23dS[email protected] 
8428ad9cf99SMatthias Ringwald // used for debugging
8438ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
8448ad9cf99SMatthias Ringwald static void hci_controller_dump_packets(void){
8458ad9cf99SMatthias Ringwald     // format: "{handle:04x}:{count:02d} "
8468ad9cf99SMatthias Ringwald     char summaries[3][7 * 8 + 1];
8478ad9cf99SMatthias Ringwald     uint16_t totals[3];
8488ad9cf99SMatthias Ringwald     uint8_t index;
8498ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8508ad9cf99SMatthias Ringwald         summaries[index][0] = 0;
8518ad9cf99SMatthias Ringwald         totals[index] = 0;
8528ad9cf99SMatthias Ringwald     }
8538ad9cf99SMatthias Ringwald     btstack_linked_item_t *it;
8548ad9cf99SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8558ad9cf99SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
8568ad9cf99SMatthias Ringwald         switch (connection->address_type){
8578ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_ACL:
8588ad9cf99SMatthias Ringwald                 index = 0;
8598ad9cf99SMatthias Ringwald                 break;
8608ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_SCO:
8618ad9cf99SMatthias Ringwald                 index = 2;
8628ad9cf99SMatthias Ringwald                 break;
8638ad9cf99SMatthias Ringwald             default:
8648ad9cf99SMatthias Ringwald                 index = 1;
865ce7ca7c8SMatthias Ringwald                 break;
8668ad9cf99SMatthias Ringwald         }
8678ad9cf99SMatthias Ringwald         totals[index] += connection->num_packets_sent;
8688ad9cf99SMatthias Ringwald         char item_text[10];
8698ad9cf99SMatthias Ringwald         sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent);
8708ad9cf99SMatthias Ringwald         btstack_strcat(summaries[index], sizeof(summaries[0]), item_text);
8718ad9cf99SMatthias Ringwald     }
8728ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8738ad9cf99SMatthias Ringwald         if (summaries[index][0] == 0){
8748ad9cf99SMatthias Ringwald             summaries[index][0] = '-';
8758ad9cf99SMatthias Ringwald             summaries[index][1] = 0;
8768ad9cf99SMatthias Ringwald         }
8778ad9cf99SMatthias Ringwald     }
8788ad9cf99SMatthias Ringwald     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]);
8798ad9cf99SMatthias Ringwald }
8808ad9cf99SMatthias Ringwald #endif
8818ad9cf99SMatthias Ringwald 
8823e2050f7SMatthias Ringwald static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
883452cf3bbS[email protected] 
884452cf3bbS[email protected]     // 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);
885452cf3bbS[email protected] 
886452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
887452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
8884ea43905SMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
889452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
890452cf3bbS[email protected]     }
891452cf3bbS[email protected] 
8920f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
893fcf88f47SMatthias Ringwald     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
8940f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
8950f3b27c5SMatthias Ringwald     }
8960f3b27c5SMatthias Ringwald #endif
897452cf3bbS[email protected] 
898d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
899d999b54eSMatthias Ringwald 
9003e2050f7SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
901a086dc35SMatthias Ringwald     // multiple packets could be sent on a synchronous HCI transport
902ff3cc4a5SMatthias Ringwald     while (true){
903452cf3bbS[email protected] 
904d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
905d999b54eSMatthias Ringwald 
906452cf3bbS[email protected]         // get current data
9074ea43905SMatthias Ringwald         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
908452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
9091979f09cSMatthias Ringwald         bool more_fragments = false;
910452cf3bbS[email protected] 
911452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
912452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
9131979f09cSMatthias Ringwald             more_fragments = true;
9146bcf18c2SMatthias Ringwald             current_acl_data_packet_length = max_acl_data_packet_length & (~(HCI_ACL_CHUNK_SIZE_ALIGNMENT-1));
915452cf3bbS[email protected]         }
916452cf3bbS[email protected] 
917a086dc35SMatthias Ringwald         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragment)
9184ea43905SMatthias Ringwald         if (acl_header_pos > 0u){
919f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
9204ea43905SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
921f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
922452cf3bbS[email protected]         }
923452cf3bbS[email protected] 
924452cf3bbS[email protected]         // update header len
9254ea43905SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
926452cf3bbS[email protected] 
927452cf3bbS[email protected]         // count packet
928ce41473eSMatthias Ringwald         connection->num_packets_sent++;
9291979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
930d999b54eSMatthias Ringwald 
931d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
932d999b54eSMatthias Ringwald         if (more_fragments){
933d999b54eSMatthias Ringwald             // update start of next fragment to send
934d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
935d999b54eSMatthias Ringwald         } else {
936d999b54eSMatthias Ringwald             // done
937d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
938d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
939d999b54eSMatthias Ringwald         }
940452cf3bbS[email protected] 
941452cf3bbS[email protected]         // send packet
942452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
943452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
9445bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
94581d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
9463e2050f7SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
9473e2050f7SMatthias Ringwald         if (err != 0){
9483e2050f7SMatthias Ringwald             // no error from HCI Transport expected
9493e2050f7SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
950a84946b2SMatthias Ringwald             break;
9513e2050f7SMatthias Ringwald         }
952452cf3bbS[email protected] 
9538ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
9548ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
9558ad9cf99SMatthias Ringwald #endif
9568ad9cf99SMatthias Ringwald 
9571979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
958d999b54eSMatthias Ringwald 
959452cf3bbS[email protected]         // done yet?
960452cf3bbS[email protected]         if (!more_fragments) break;
961452cf3bbS[email protected] 
962452cf3bbS[email protected]         // can send more?
9633e2050f7SMatthias Ringwald         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
964452cf3bbS[email protected]     }
965452cf3bbS[email protected] 
966d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
967452cf3bbS[email protected] 
968d051460cS[email protected]     // release buffer now for synchronous transport
969203bace6S[email protected]     if (hci_transport_synchronous()){
97081d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
971452cf3bbS[email protected]         hci_release_packet_buffer();
972452cf3bbS[email protected]     }
973452cf3bbS[email protected] 
9743e2050f7SMatthias Ringwald     return status;
975452cf3bbS[email protected] }
976452cf3bbS[email protected] 
977826f7347S[email protected] // pre: caller has reserved the packet buffer
9783e2050f7SMatthias Ringwald uint8_t hci_send_acl_packet_buffer(int size){
9793e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
980826f7347S[email protected] 
981d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
982d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
983d713a683S[email protected] 
9845061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
98597b61c7bS[email protected]     if (!connection) {
9865fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
98797b61c7bS[email protected]         hci_release_packet_buffer();
9883e2050f7SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
98997b61c7bS[email protected]     }
99052db98b2SMatthias Ringwald 
99179a2851bSMilanka Ringwald     // check for free places on Bluetooth module
99279a2851bSMilanka Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
99379a2851bSMilanka Ringwald         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
99479a2851bSMilanka Ringwald         hci_release_packet_buffer();
99579a2851bSMilanka Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
99679a2851bSMilanka Ringwald     }
99779a2851bSMilanka Ringwald 
99852db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
99956cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
100052db98b2SMatthias Ringwald #endif
100156cf178bSmatthias.ringwald 
1002452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
10037856c818Smatthias.ringwald 
1004452cf3bbS[email protected]     // setup data
1005452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
1006452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
10076218e6f1Smatthias.ringwald 
1008452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
1009ee091cf1Smatthias.ringwald }
1010ee091cf1Smatthias.ringwald 
101135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
101244d0e3d5S[email protected] // pre: caller has reserved the packet buffer
10133e2050f7SMatthias Ringwald uint8_t hci_send_sco_packet_buffer(int size){
10143e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
101544d0e3d5S[email protected] 
101644d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
10174b3e1e19SMatthias Ringwald 
10184b3e1e19SMatthias Ringwald     // skip checks in loopback mode
10194b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
102044d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
102144d0e3d5S[email protected] 
102244d0e3d5S[email protected]         // check for free places on Bluetooth module
1023701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
1024cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
102544d0e3d5S[email protected]             hci_release_packet_buffer();
102644d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
102744d0e3d5S[email protected]         }
102844d0e3d5S[email protected] 
1029e35edcc1S[email protected]         // track send packet in connection struct
1030e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
1031e35edcc1S[email protected]         if (!connection) {
1032e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
1033e35edcc1S[email protected]             hci_release_packet_buffer();
10343e2050f7SMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1035e35edcc1S[email protected]         }
1036f234b250SMatthias Ringwald 
1037f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
1038f234b250SMatthias Ringwald             // token used
10391972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = false;
1040f234b250SMatthias Ringwald         } else {
1041760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
1042ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
10436f28d2eeSMatthias Ringwald             } else {
1044e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
1045760b20efSMatthias Ringwald             }
10464b3e1e19SMatthias Ringwald         }
1047f234b250SMatthias Ringwald     }
104844d0e3d5S[email protected] 
104944d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
1050543e835cSMatthias Ringwald 
105143149fc9SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
105243149fc9SMatthias Ringwald     hci_stack->sco_transport->send_packet(packet, size);
105343149fc9SMatthias Ringwald     hci_release_packet_buffer();
105443149fc9SMatthias Ringwald     hci_emit_transport_packet_sent();
105543149fc9SMatthias Ringwald 
105643149fc9SMatthias Ringwald     return 0;
105743149fc9SMatthias Ringwald #else
105843149fc9SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
1059a84946b2SMatthias Ringwald     uint8_t status;
1060a84946b2SMatthias Ringwald     if (err == 0){
1061a84946b2SMatthias Ringwald         status = ERROR_CODE_SUCCESS;
1062a84946b2SMatthias Ringwald     } else {
1063a84946b2SMatthias Ringwald         status = ERROR_CODE_HARDWARE_FAILURE;
1064a84946b2SMatthias Ringwald     }
1065a84946b2SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
1066543e835cSMatthias Ringwald         hci_release_packet_buffer();
1067543e835cSMatthias Ringwald     }
1068a84946b2SMatthias Ringwald     return status;
106943149fc9SMatthias Ringwald #endif
107044d0e3d5S[email protected] }
107135454696SMatthias Ringwald #endif
107244d0e3d5S[email protected] 
10730a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
107468ab6207SMatthias Ringwald static uint8_t hci_send_iso_packet_fragments(void){
107568ab6207SMatthias Ringwald 
107668ab6207SMatthias Ringwald     uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length;
107768ab6207SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
107868ab6207SMatthias Ringwald     // multiple packets could be send on a synchronous HCI transport
107968ab6207SMatthias Ringwald     while (true){
108068ab6207SMatthias Ringwald 
108168ab6207SMatthias Ringwald         // get current data
108268ab6207SMatthias Ringwald         const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u;
108368ab6207SMatthias Ringwald         int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos;
108468ab6207SMatthias Ringwald         bool more_fragments = false;
108568ab6207SMatthias Ringwald 
108668ab6207SMatthias Ringwald         // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
108768ab6207SMatthias Ringwald         if (current_iso_data_packet_length > max_iso_data_packet_length){
108868ab6207SMatthias Ringwald             more_fragments = true;
108968ab6207SMatthias Ringwald             current_iso_data_packet_length = max_iso_data_packet_length;
109068ab6207SMatthias Ringwald         }
109168ab6207SMatthias Ringwald 
109268ab6207SMatthias Ringwald         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
109368ab6207SMatthias Ringwald         uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
109468ab6207SMatthias Ringwald         uint8_t pb_flags;
109568ab6207SMatthias Ringwald         if (iso_header_pos == 0u){
109668ab6207SMatthias Ringwald             // first fragment, keep TS field
109768ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x00 : 0x02;
109868ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u);
109968ab6207SMatthias Ringwald         } else {
110068ab6207SMatthias Ringwald             // later fragment, drop TS field
110168ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x01 : 0x03;
110268ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u);
110368ab6207SMatthias Ringwald         }
110468ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags);
110568ab6207SMatthias Ringwald 
110668ab6207SMatthias Ringwald         // update header len
110768ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length);
110868ab6207SMatthias Ringwald 
110968ab6207SMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
111068ab6207SMatthias Ringwald         if (more_fragments){
111168ab6207SMatthias Ringwald             // update start of next fragment to send
111268ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos += current_iso_data_packet_length;
111368ab6207SMatthias Ringwald         } else {
111468ab6207SMatthias Ringwald             // done
111568ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos = 0;
111668ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_total_size = 0;
111768ab6207SMatthias Ringwald         }
111868ab6207SMatthias Ringwald 
111968ab6207SMatthias Ringwald         // send packet
112068ab6207SMatthias Ringwald         uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos];
112168ab6207SMatthias Ringwald         const int size = current_iso_data_packet_length + 4;
112268ab6207SMatthias Ringwald         hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size);
112368ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = true;
112468ab6207SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size);
112568ab6207SMatthias Ringwald         if (err != 0){
112668ab6207SMatthias Ringwald             // no error from HCI Transport expected
112768ab6207SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
112868ab6207SMatthias Ringwald         }
112968ab6207SMatthias Ringwald 
113068ab6207SMatthias Ringwald         // done yet?
113168ab6207SMatthias Ringwald         if (!more_fragments) break;
113268ab6207SMatthias Ringwald 
113368ab6207SMatthias Ringwald         // can send more?
113468ab6207SMatthias Ringwald         if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false;
113568ab6207SMatthias Ringwald     }
113668ab6207SMatthias Ringwald 
113768ab6207SMatthias Ringwald     // release buffer now for synchronous transport
113868ab6207SMatthias Ringwald     if (hci_transport_synchronous()){
113968ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = false;
114068ab6207SMatthias Ringwald         hci_release_packet_buffer();
114168ab6207SMatthias Ringwald         hci_emit_transport_packet_sent();
114268ab6207SMatthias Ringwald     }
114368ab6207SMatthias Ringwald 
114468ab6207SMatthias Ringwald     return status;
114568ab6207SMatthias Ringwald }
114668ab6207SMatthias Ringwald 
1147ace08712SMatthias Ringwald uint8_t hci_send_iso_packet_buffer(uint16_t size){
1148ace08712SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1149ace08712SMatthias Ringwald 
1150e5413aa0SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff;
1151e5413aa0SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle);
1152e5413aa0SMatthias Ringwald     if (iso_stream == NULL){
1153977f918dSMatthias Ringwald         hci_release_packet_buffer();
1154977f918dSMatthias Ringwald         hci_iso_notify_can_send_now();
1155e5413aa0SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1156e5413aa0SMatthias Ringwald     }
1157e5413aa0SMatthias Ringwald 
1158e5413aa0SMatthias Ringwald     // TODO: check for space on controller
1159e5413aa0SMatthias Ringwald 
1160977f918dSMatthias Ringwald     // skip iso packets if needed
1161977f918dSMatthias Ringwald     if (iso_stream->num_packets_to_skip > 0){
1162977f918dSMatthias Ringwald         iso_stream->num_packets_to_skip--;
1163977f918dSMatthias Ringwald         // pretend it was processed and trigger next one
1164977f918dSMatthias Ringwald         hci_release_packet_buffer();
1165977f918dSMatthias Ringwald         hci_iso_notify_can_send_now();
1166977f918dSMatthias Ringwald         return ERROR_CODE_SUCCESS;
1167977f918dSMatthias Ringwald     }
1168977f918dSMatthias Ringwald 
1169e5413aa0SMatthias Ringwald     // track outgoing packet sent
1170e5413aa0SMatthias Ringwald     log_info("Outgoing ISO packet for con handle 0x%04x", con_handle);
1171e5413aa0SMatthias Ringwald     iso_stream->num_packets_sent++;
1172e5413aa0SMatthias Ringwald 
117368ab6207SMatthias Ringwald     // setup data
117468ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_total_size = size;
117568ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_pos = 4;   // start of L2CAP packet
117668ab6207SMatthias Ringwald 
117768ab6207SMatthias Ringwald     return hci_send_iso_packet_fragments();
1178ace08712SMatthias Ringwald }
1179ace08712SMatthias Ringwald #endif
1180ace08712SMatthias Ringwald 
1181c3b46f5aSMatthias Ringwald static void acl_handler(uint8_t *packet, uint16_t size){
1182e76a89eeS[email protected] 
11837856c818Smatthias.ringwald     // get info
11847856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
11855061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
11867856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
11877856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
11887856c818Smatthias.ringwald 
11897856c818Smatthias.ringwald     // ignore non-registered handle
11907856c818Smatthias.ringwald     if (!conn){
1191c3b46f5aSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , con_handle);
11927856c818Smatthias.ringwald         return;
11937856c818Smatthias.ringwald     }
11947856c818Smatthias.ringwald 
1195e76a89eeS[email protected]     // assert packet is complete
11964ea43905SMatthias Ringwald     if ((acl_length + 4u) != size){
1197c3b46f5aSMatthias Ringwald         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
1198e76a89eeS[email protected]         return;
1199e76a89eeS[email protected]     }
1200e76a89eeS[email protected] 
120152db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
12027856c818Smatthias.ringwald     // update idle timestamp
12037856c818Smatthias.ringwald     hci_connection_timestamp(conn);
120452db98b2SMatthias Ringwald #endif
12057856c818Smatthias.ringwald 
12062b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
12072b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
12082b838201SMatthias Ringwald     conn->num_packets_completed++;
12092b838201SMatthias Ringwald #endif
12102b838201SMatthias Ringwald 
12117856c818Smatthias.ringwald     // handle different packet types
12124ea43905SMatthias Ringwald     switch (acl_flags & 0x03u) {
12137856c818Smatthias.ringwald 
12147856c818Smatthias.ringwald         case 0x01: // continuation fragment
12157856c818Smatthias.ringwald 
12160ca847afS[email protected]             // sanity checks
12174ea43905SMatthias Ringwald             if (conn->acl_recombination_pos == 0u) {
12189da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
12197856c818Smatthias.ringwald                 return;
12207856c818Smatthias.ringwald             }
12214ea43905SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
12220ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
12230ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
12240ca847afS[email protected]                 conn->acl_recombination_pos = 0;
12250ca847afS[email protected]                 return;
12260ca847afS[email protected]             }
12277856c818Smatthias.ringwald 
12287856c818Smatthias.ringwald             // append fragment payload (header already stored)
12296535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
12306535961aSMatthias Ringwald                          &packet[4], acl_length);
12317856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
12327856c818Smatthias.ringwald 
12337856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
12344ea43905SMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
1235d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
12367856c818Smatthias.ringwald                 // reset recombination buffer
12377856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
12387856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
12397856c818Smatthias.ringwald             }
12407856c818Smatthias.ringwald             break;
12417856c818Smatthias.ringwald 
12427856c818Smatthias.ringwald         case 0x02: { // first fragment
12437856c818Smatthias.ringwald 
124423a77e1aS[email protected]             // sanity check
124523a77e1aS[email protected]             if (conn->acl_recombination_pos) {
124660737d2bSMatthias Ringwald                 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet
124760737d2bSMatthias Ringwald                 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){
124860737d2bSMatthias Ringwald                     log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle);
124960737d2bSMatthias Ringwald                 }
125023a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
125123a77e1aS[email protected]             }
125223a77e1aS[email protected] 
12537856c818Smatthias.ringwald             // peek into L2CAP packet!
12547856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
12557856c818Smatthias.ringwald 
12567856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
12574ea43905SMatthias Ringwald             if (acl_length >= (l2cap_length + 4u)){
12587856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
12599244e83cSMatthias Ringwald                 hci_emit_acl_packet(packet, l2cap_length + 8u);
12607856c818Smatthias.ringwald             } else {
12610ca847afS[email protected] 
12620ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
12630ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
12640ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
12650ca847afS[email protected]                     return;
12660ca847afS[email protected]                 }
12670ca847afS[email protected] 
12687856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
12696535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
12704ea43905SMatthias Ringwald                              packet, acl_length + 4u);
12714ea43905SMatthias Ringwald                 conn->acl_recombination_pos    = acl_length + 4u;
12727856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
12734ea43905SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
12747856c818Smatthias.ringwald             }
12757856c818Smatthias.ringwald             break;
12767856c818Smatthias.ringwald 
12777856c818Smatthias.ringwald         }
12787856c818Smatthias.ringwald         default:
1279c3b46f5aSMatthias Ringwald             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
12807856c818Smatthias.ringwald             return;
12817856c818Smatthias.ringwald     }
128294ab26f8Smatthias.ringwald 
128394ab26f8Smatthias.ringwald     // execute main loop
128494ab26f8Smatthias.ringwald     hci_run();
128516833f0aSmatthias.ringwald }
128622909952Smatthias.ringwald 
12871ab2dc58SMatthias Ringwald static void hci_connection_stop_timer(hci_connection_t * conn){
12881ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
12891ab2dc58SMatthias Ringwald #ifdef ENABLE_CLASSIC
12901ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout_sco);
12911ab2dc58SMatthias Ringwald #endif
12921ab2dc58SMatthias Ringwald }
12931ab2dc58SMatthias Ringwald 
129467a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
12959da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
12963c4d4b90Smatthias.ringwald 
1297b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1298cb70c5abSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1299cb70c5abSMatthias Ringwald     bd_addr_type_t addr_type = conn->address_type;
1300cb70c5abSMatthias Ringwald #endif
1301cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1302cb70c5abSMatthias Ringwald     hci_con_handle_t con_handle = conn->con_handle;
1303ee752bb8SMatthias Ringwald #endif
1304b3264428SMatthias Ringwald #endif
1305ee752bb8SMatthias Ringwald 
13061ab2dc58SMatthias Ringwald     hci_connection_stop_timer(conn);
1307c785ef68Smatthias.ringwald 
1308665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1309a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
13103c4d4b90Smatthias.ringwald 
13113c4d4b90Smatthias.ringwald     // now it's gone
1312c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
1313ee752bb8SMatthias Ringwald 
1314b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1315034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1316ee752bb8SMatthias Ringwald     // update SCO
1317cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1318ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1319ee752bb8SMatthias Ringwald     }
1320034e9b53SMatthias Ringwald #endif
1321cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1322cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1323cb70c5abSMatthias Ringwald         hci_stack->sco_transport->close(con_handle);
1324cb70c5abSMatthias Ringwald     }
1325cb70c5abSMatthias Ringwald #endif
1326b3264428SMatthias Ringwald #endif
1327c7e0c5f6Smatthias.ringwald }
1328c7e0c5f6Smatthias.ringwald 
132935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
133035454696SMatthias Ringwald 
133129e39de4SMatthias Ringwald static const uint16_t hci_acl_packet_type_sizes[] = {
13328f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
13338f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
13348f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
13358f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
13368f8108aaSmatthias.ringwald };
133729e39de4SMatthias Ringwald static const uint8_t hci_acl_packet_type_feature_requirement_bit[] = {
133865389bfcS[email protected]      0, // 3 slot packets
133965389bfcS[email protected]      1, // 5 slot packets
134065389bfcS[email protected]     25, // EDR 2 mpbs
134165389bfcS[email protected]     26, // EDR 3 mbps
1342a086dc35SMatthias Ringwald     39, // 3 slot EDR packtes
134365389bfcS[email protected]     40, // 5 slot EDR packet
134465389bfcS[email protected] };
134529e39de4SMatthias Ringwald static const uint16_t hci_acl_packet_type_feature_packet_mask[] = {
134665389bfcS[email protected]     0x0f00, // 3 slot packets
134765389bfcS[email protected]     0xf000, // 5 slot packets
134865389bfcS[email protected]     0x1102, // EDR 2 mpbs
134965389bfcS[email protected]     0x2204, // EDR 3 mbps
1350a086dc35SMatthias Ringwald     0x0300, // 3 slot EDR packtes
135165389bfcS[email protected]     0x3000, // 5 slot EDR packet
135265389bfcS[email protected] };
13538f8108aaSmatthias.ringwald 
135465389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
135565389bfcS[email protected]     // enable packet types based on size
13568f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
1357f16a69bbS[email protected]     unsigned int i;
13588f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
135929e39de4SMatthias Ringwald         if (hci_acl_packet_type_sizes[i] == 0) continue;
136029e39de4SMatthias Ringwald         if (hci_acl_packet_type_sizes[i] <= buffer_size){
13618f8108aaSmatthias.ringwald             packet_types |= 1 << i;
13628f8108aaSmatthias.ringwald         }
13638f8108aaSmatthias.ringwald     }
136465389bfcS[email protected]     // disable packet types due to missing local supported features
136529e39de4SMatthias Ringwald     for (i=0;i<sizeof(hci_acl_packet_type_feature_requirement_bit); i++){
136629e39de4SMatthias Ringwald         unsigned int bit_idx = hci_acl_packet_type_feature_requirement_bit[i];
136765389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
136865389bfcS[email protected]         if (feature_set) continue;
136929e39de4SMatthias Ringwald         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_acl_packet_type_feature_packet_mask[i]);
137029e39de4SMatthias Ringwald         packet_types &= ~hci_acl_packet_type_feature_packet_mask[i];
137165389bfcS[email protected]     }
13728f8108aaSmatthias.ringwald     return packet_types;
13738f8108aaSmatthias.ringwald }
13748f8108aaSmatthias.ringwald 
13758f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
1376028ead5eSMatthias Ringwald     uint16_t active_packet_types = (hci_stack->usable_packet_types_acl &  hci_stack->enabled_packet_types_acl);
137729e39de4SMatthias Ringwald     // flip bits for "may not be used"
1378028ead5eSMatthias Ringwald     return  active_packet_types ^ 0x3306;
1379028ead5eSMatthias Ringwald }
1380028ead5eSMatthias Ringwald 
1381028ead5eSMatthias Ringwald void hci_enable_acl_packet_types(uint16_t packet_types){
1382028ead5eSMatthias Ringwald     hci_stack->enabled_packet_types_acl = packet_types;
13838f8108aaSmatthias.ringwald }
138429e39de4SMatthias Ringwald 
1385c92ca2c8SMatthias Ringwald static const struct {
1386c92ca2c8SMatthias Ringwald     uint8_t feature_index;
1387c92ca2c8SMatthias Ringwald     uint16_t feature_packet_mask;
1388c92ca2c8SMatthias Ringwald } hci_sco_packet_type_feature_requirements[] = {
1389c92ca2c8SMatthias Ringwald         { 12, SCO_PACKET_TYPES_HV2 },                           // HV2 packets
1390c92ca2c8SMatthias Ringwald         { 13, SCO_PACKET_TYPES_HV3 },                           // HV3 packets
1391c92ca2c8SMatthias Ringwald         { 31, SCO_PACKET_TYPES_ESCO },                          // eSCO links (EV3 packets)
1392c92ca2c8SMatthias Ringwald         { 32, SCO_PACKET_TYPES_EV4 },                           // EV4 packets
1393c92ca2c8SMatthias Ringwald         { 45, SCO_PACKET_TYPES_2EV3 | SCO_PACKET_TYPES_2EV5 },  // EDR eSCO 2 Mb/s
1394c92ca2c8SMatthias Ringwald         { 46, SCO_PACKET_TYPES_3EV3 | SCO_PACKET_TYPES_3EV5 },  // EDR eSCO 3 Mb/s
13956afff830SMatthias Ringwald         { 47, SCO_PACKET_TYPES_2EV5 | SCO_PACKET_TYPES_3EV5 },  // 3-slot EDR eSCO packets, 2-EV3/3-EV3 use single slot
1396c92ca2c8SMatthias Ringwald };
1397c92ca2c8SMatthias Ringwald 
1398d7891039SMatthias Ringwald // map packet types to payload length, prefer eSCO over SCO and large over small packets
1399d7891039SMatthias Ringwald static const struct {
1400d7891039SMatthias Ringwald     uint16_t type;
1401d7891039SMatthias Ringwald     uint16_t payload_length;
1402d7891039SMatthias Ringwald } hci_sco_packet_type_to_payload_length[] = {
1403d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_3EV5, HCI_SCO_3EV5_SIZE}, // 540
1404d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_2EV5, HCI_SCO_2EV5_SIZE}, // 360
1405d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV5,  HCI_SCO_EV5_SIZE},  // 180
1406d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV4,  HCI_SCO_EV4_SIZE},  // 120
1407d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_3EV3, HCI_SCO_3EV3_SIZE}, //  90
1408d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_2EV3, HCI_SCO_2EV3_SIZE}, //  60
1409d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV3,  HCI_SCO_EV3_SIZE},  //  30
1410d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV3,  HCI_SCO_HV3_SIZE},  //  30
1411d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV2,  HCI_SCO_HV2_SIZE},  //  20
1412d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV1,  HCI_SCO_HV1_SIZE}   //  10
1413d7891039SMatthias Ringwald };
1414d7891039SMatthias Ringwald 
1415c92ca2c8SMatthias Ringwald static uint16_t hci_sco_packet_types_for_features(const uint8_t * local_supported_features){
1416c92ca2c8SMatthias Ringwald     uint16_t packet_types = SCO_PACKET_TYPES_ALL;
1417c92ca2c8SMatthias Ringwald     unsigned int i;
1418c92ca2c8SMatthias Ringwald     // disable packet types due to missing local supported features
1419c92ca2c8SMatthias Ringwald     for (i=0;i<(sizeof(hci_sco_packet_type_feature_requirements)/sizeof(hci_sco_packet_type_feature_requirements[0])); i++){
1420c92ca2c8SMatthias Ringwald         unsigned int bit_idx = hci_sco_packet_type_feature_requirements[i].feature_index;
1421c92ca2c8SMatthias Ringwald         bool feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1422c92ca2c8SMatthias Ringwald         if (feature_set) continue;
1423c92ca2c8SMatthias Ringwald         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);
1424c92ca2c8SMatthias Ringwald         packet_types &= ~hci_sco_packet_type_feature_requirements[i].feature_packet_mask;
1425c92ca2c8SMatthias Ringwald     }
1426c92ca2c8SMatthias Ringwald     return packet_types;
1427c92ca2c8SMatthias Ringwald }
1428c92ca2c8SMatthias Ringwald 
1429c92ca2c8SMatthias Ringwald uint16_t hci_usable_sco_packet_types(void){
1430c92ca2c8SMatthias Ringwald     return hci_stack->usable_packet_types_sco;
1431c92ca2c8SMatthias Ringwald }
1432c92ca2c8SMatthias Ringwald 
1433d7891039SMatthias Ringwald static uint16_t hci_sco_payload_length_for_packet_types(uint16_t packet_types){
1434d7891039SMatthias Ringwald     uint8_t i;
1435d7891039SMatthias Ringwald     for (i=0;i<sizeof(hci_sco_packet_type_to_payload_length)/sizeof(hci_sco_packet_type_to_payload_length[0]);i++){
1436d7891039SMatthias Ringwald         if ((hci_sco_packet_type_to_payload_length[i].type & packet_types) != 0){
1437d7891039SMatthias Ringwald             return hci_sco_packet_type_to_payload_length[i].payload_length;
1438d7891039SMatthias Ringwald         }
1439d7891039SMatthias Ringwald     }
1440d7891039SMatthias Ringwald     return 0;
1441d7891039SMatthias Ringwald }
1442d7891039SMatthias Ringwald 
144335454696SMatthias Ringwald #endif
14448f8108aaSmatthias.ringwald 
1445facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
14467dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
14473a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
14487dc17943Smatthias.ringwald }
14497dc17943Smatthias.ringwald 
1450f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
14513a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
14527dc17943Smatthias.ringwald }
14537dc17943Smatthias.ringwald 
145406b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
145520dcdd22SMatthias Ringwald bool hci_extended_sco_link_supported(void){
14563e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
14573e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
14583e68d23dSMatthias Ringwald }
145906b9e820SMatthias Ringwald #endif
14603e68d23dSMatthias Ringwald 
146120dcdd22SMatthias Ringwald bool hci_non_flushable_packet_boundary_flag_supported(void){
14626ac9a97eS[email protected]     // No. 54, byte 6, bit 6
14634ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
14646ac9a97eS[email protected] }
14656ac9a97eS[email protected] 
14669885fb2dSMatthias Ringwald #ifdef ENABLE_CLASSIC
146757514786SMatthias Ringwald static bool gap_ssp_supported(void){
14686ac9a97eS[email protected]     // No. 51, byte 6, bit 3
14694ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1470f5d8d141S[email protected] }
14719885fb2dSMatthias Ringwald #endif
1472f5d8d141S[email protected] 
1473ad58a385SMatthias Ringwald bool hci_classic_supported(void){
147435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
14756ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
14763a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
147735454696SMatthias Ringwald #else
147857514786SMatthias Ringwald     return false;
147935454696SMatthias Ringwald #endif
1480f5d8d141S[email protected] }
1481f5d8d141S[email protected] 
1482ad58a385SMatthias Ringwald bool hci_le_supported(void){
1483a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
14846ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
14854ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1486f5d8d141S[email protected] #else
148757514786SMatthias Ringwald     return false;
1488f5d8d141S[email protected] #endif
1489f5d8d141S[email protected] }
1490f5d8d141S[email protected] 
14911ffa425cSMatthias Ringwald static bool hci_command_supported(uint8_t command_index){
14921ffa425cSMatthias Ringwald     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
14931ffa425cSMatthias Ringwald }
14941ffa425cSMatthias Ringwald 
1495b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1496b95a5a35SMatthias Ringwald 
149763671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
149822f987e4SMatthias Ringwald bool hci_le_extended_advertising_supported(void){
149963671e69SMatthias Ringwald     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
150063671e69SMatthias Ringwald }
150163671e69SMatthias Ringwald #endif
150263671e69SMatthias Ringwald 
1503f5873674SMatthias Ringwald static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
15046bcfa632SMatthias Ringwald     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
15056bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
150669a97523S[email protected]     } else {
15076bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
150869a97523S[email protected]     }
150969a97523S[email protected] }
151069a97523S[email protected] 
15116bcfa632SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
15126bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
15136bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
15146bcfa632SMatthias Ringwald }
15156bcfa632SMatthias Ringwald 
15166bcfa632SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
15176bcfa632SMatthias Ringwald void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
15186bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_advertisements_own_addr_type;
15196bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
152036916f81SDirk Helbig }
1521efc77985SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1522efc77985SMatthias Ringwald void gap_le_get_own_advertising_set_address(uint8_t * addr_type, bd_addr_t addr, uint8_t advertising_handle){
1523efc77985SMatthias Ringwald     if (advertising_handle == 0){
1524efc77985SMatthias Ringwald         gap_le_get_own_advertisements_address(addr_type, addr);
1525efc77985SMatthias Ringwald     } else {
1526efc77985SMatthias Ringwald         le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
1527efc77985SMatthias Ringwald         if (advertising_set != NULL){
1528efc77985SMatthias Ringwald             switch (advertising_set->extended_params.own_address_type){
1529efc77985SMatthias Ringwald                 case BD_ADDR_TYPE_LE_PUBLIC:
1530efc77985SMatthias Ringwald                     *addr_type = BD_ADDR_TYPE_LE_PUBLIC;
1531efc77985SMatthias Ringwald                     memcpy(addr, hci_stack->local_bd_addr, 6);
1532efc77985SMatthias Ringwald                     break;
1533efc77985SMatthias Ringwald                 case BD_ADDR_TYPE_LE_RANDOM:
1534efc77985SMatthias Ringwald                     *addr_type = BD_ADDR_TYPE_LE_RANDOM;
1535efc77985SMatthias Ringwald                     memcpy(addr, advertising_set->random_address, 6);
1536efc77985SMatthias Ringwald                     break;
1537efc77985SMatthias Ringwald                 case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
1538efc77985SMatthias Ringwald                 case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
1539efc77985SMatthias Ringwald                     // do nothing as random address was already set from enhanced connection complete
1540efc77985SMatthias Ringwald                     break;
1541efc77985SMatthias Ringwald                 default:
1542efc77985SMatthias Ringwald                     break;
1543efc77985SMatthias Ringwald             }
1544efc77985SMatthias Ringwald         }
1545efc77985SMatthias Ringwald     }
154636916f81SDirk Helbig }
1547efc77985SMatthias Ringwald #endif
15486bcfa632SMatthias Ringwald #endif
15496bcfa632SMatthias Ringwald 
1550e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
15516bcfa632SMatthias Ringwald 
15526bcfa632SMatthias Ringwald /**
15536bcfa632SMatthias Ringwald  * @brief Get own addr type and address used for LE connections (Central)
15546bcfa632SMatthias Ringwald  */
15556bcfa632SMatthias Ringwald void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
15566bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_connection_own_addr_type;
15576bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
15586bcfa632SMatthias Ringwald }
15596bcfa632SMatthias Ringwald 
1560384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
15619ec2630cSMatthias Ringwald 
1562a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1563a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset];
1564d1dc057bS[email protected]     offset += 1;
1565d1dc057bS[email protected] 
1566a0698cb4SMatthias Ringwald     uint16_t i;
156703fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1568a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
156933e6948bSMatthias Ringwald         // sanity checks on data_length:
157033e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
157133e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
15724ea43905SMatthias Ringwald         if ((offset + 9u + data_length + 1u) > size)    return;
157333e6948bSMatthias Ringwald         // setup event
15744ea43905SMatthias Ringwald         uint8_t event_size = 10u + data_length;
1575a0698cb4SMatthias Ringwald         uint16_t pos = 0;
1576045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
157757c9da5bS[email protected]         event[pos++] = event_size;
15786535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1579d1dc057bS[email protected]         offset += 8;
1580d1dc057bS[email protected]         pos += 8;
1581d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
158233e6948bSMatthias Ringwald         event[pos++] = data_length;
158333e6948bSMatthias Ringwald         offset++;
15846535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
158557c9da5bS[email protected]         pos +=    data_length;
15864ea43905SMatthias Ringwald         offset += data_length + 1u; // rssi
15879da9850bSMatthias Ringwald         hci_emit_btstack_event(event, pos, 1);
158857c9da5bS[email protected]     }
158957c9da5bS[email protected] }
1590a0698cb4SMatthias Ringwald 
1591a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1592033393eeSBob Abeles static void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1593a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1594a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset++];
1595c95a0fc7SMatthias Ringwald     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1596a0698cb4SMatthias Ringwald     uint8_t i;
1597a0698cb4SMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
1598a0698cb4SMatthias Ringwald         // sanity checks on data_length:
1599a0698cb4SMatthias Ringwald         uint16_t data_length = packet[offset + 23];
160043ce0351SMatthias Ringwald         if (data_length > LE_EXTENDED_ADVERTISING_DATA_SIZE) return;
1601a0698cb4SMatthias Ringwald         if ((offset + 24u + data_length) > size)    return;
1602a0698cb4SMatthias Ringwald         uint16_t event_type = little_endian_read_16(packet, offset);
1603a0698cb4SMatthias Ringwald         offset += 2;
1604a0698cb4SMatthias Ringwald         if ((event_type & 0x10) != 0) {
1605a0698cb4SMatthias Ringwald            // setup legacy event
1606a0698cb4SMatthias Ringwald             uint8_t legacy_event_type;
1607a0698cb4SMatthias Ringwald             switch (event_type){
160836916f81SDirk Helbig                 case 0x13: // 0b0010011
1609a0698cb4SMatthias Ringwald                     // ADV_IND
1610a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1611a0698cb4SMatthias Ringwald                     break;
161236916f81SDirk Helbig                 case 0x15: // 0b0010101
1613a0698cb4SMatthias Ringwald                     // ADV_DIRECT_IND
1614a0698cb4SMatthias Ringwald                     legacy_event_type = 1;
1615a0698cb4SMatthias Ringwald                     break;
161636916f81SDirk Helbig                 case 0x12: // 0b0010010
1617a0698cb4SMatthias Ringwald                     // ADV_SCAN_IND
1618a0698cb4SMatthias Ringwald                     legacy_event_type = 2;
1619a0698cb4SMatthias Ringwald                     break;
162036916f81SDirk Helbig                 case 0x10: // 0b0010000:
1621a0698cb4SMatthias Ringwald                     // ADV_NONCONN_IND
1622a0698cb4SMatthias Ringwald                     legacy_event_type = 3;
1623a0698cb4SMatthias Ringwald                     break;
162436916f81SDirk Helbig                 case 0x1B: // 0b0011011
162536916f81SDirk Helbig                 case 0x1A: // 0b0011010
1626a0698cb4SMatthias Ringwald                     // SCAN_RSP
1627a0698cb4SMatthias Ringwald                     legacy_event_type = 4;
1628a0698cb4SMatthias Ringwald                     break;
1629a0698cb4SMatthias Ringwald                 default:
1630a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1631a0698cb4SMatthias Ringwald                     break;
1632a0698cb4SMatthias Ringwald             }
1633a0698cb4SMatthias Ringwald             uint16_t pos = 0;
1634a0698cb4SMatthias Ringwald             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1635a0698cb4SMatthias Ringwald             event[pos++] = 10u + data_length;
1636a0698cb4SMatthias Ringwald             event[pos++] = legacy_event_type;
1637a0698cb4SMatthias Ringwald             // copy address type + address
1638a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1639a0698cb4SMatthias Ringwald             offset += 7;
1640a0698cb4SMatthias Ringwald             pos += 7;
1641a0698cb4SMatthias Ringwald             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1642a0698cb4SMatthias Ringwald             offset += 4;
1643a0698cb4SMatthias Ringwald             // copy rssi
1644a0698cb4SMatthias Ringwald             event[pos++] = packet[offset++];
1645a0698cb4SMatthias Ringwald             // skip periodic advertising interval and direct address
1646a0698cb4SMatthias Ringwald             offset += 9;
1647a0698cb4SMatthias Ringwald             // copy data len + data;
1648a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1649a0698cb4SMatthias Ringwald             pos    += 1 +data_length;
1650a0698cb4SMatthias Ringwald             offset += 1+ data_length;
16519da9850bSMatthias Ringwald             hci_emit_btstack_event(event, pos, 1);
1652a0698cb4SMatthias Ringwald         } else {
1653c95a0fc7SMatthias Ringwald             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1654c95a0fc7SMatthias Ringwald             uint8_t report_len = 24 + data_length;
1655c95a0fc7SMatthias Ringwald             event[1] = report_len;
16560f7610adSMatthias Ringwald             little_endian_store_16(event, 2, event_type);
16570f7610adSMatthias Ringwald             memcpy(&event[4], &packet[offset], report_len);
1658c95a0fc7SMatthias Ringwald             offset += report_len;
16599da9850bSMatthias Ringwald             hci_emit_btstack_event(event, 2 + report_len, 1);
1660a0698cb4SMatthias Ringwald         }
1661a0698cb4SMatthias Ringwald     }
1662a0698cb4SMatthias Ringwald }
1663a0698cb4SMatthias Ringwald #endif
1664a0698cb4SMatthias Ringwald 
1665b2f949feS[email protected] #endif
1666e8c8828eSMatthias Ringwald #endif
166757c9da5bS[email protected] 
16682b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
16692b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1670bbc366e6SMatthias Ringwald static void hci_update_advertisements_enabled_for_current_roles(void){
1671a408e724SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
16722b6ab3e6SMatthias Ringwald         // get number of active le slave connections
16732b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
16742b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
16752b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
16762b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
16772b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
16782b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
16792b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
16802b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
16812b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
16822b6ab3e6SMatthias Ringwald             num_slave_connections++;
16832b6ab3e6SMatthias Ringwald         }
16842b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1685bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1686bbc366e6SMatthias Ringwald     } else {
1687bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = false;
16882b6ab3e6SMatthias Ringwald     }
16892b6ab3e6SMatthias Ringwald }
16902b6ab3e6SMatthias Ringwald #endif
16912b6ab3e6SMatthias Ringwald #endif
16922b6ab3e6SMatthias Ringwald 
169359d59ecfSMatthias Ringwald #ifdef ENABLE_CLASSIC
169459d59ecfSMatthias Ringwald static void gap_run_set_local_name(void){
169559d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
169659d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
169759d59ecfSMatthias Ringwald     // construct HCI Command and send
169859d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_local_name.opcode;
169959d59ecfSMatthias Ringwald     packet[0] = opcode & 0xff;
170059d59ecfSMatthias Ringwald     packet[1] = opcode >> 8;
170159d59ecfSMatthias Ringwald     packet[2] = DEVICE_NAME_LEN;
170259d59ecfSMatthias Ringwald     memset(&packet[3], 0, DEVICE_NAME_LEN);
170359d59ecfSMatthias Ringwald     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
170459d59ecfSMatthias Ringwald     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
170559d59ecfSMatthias Ringwald     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
170659d59ecfSMatthias Ringwald     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
170759d59ecfSMatthias Ringwald     // expand '00:00:00:00:00:00' in name with bd_addr
170859d59ecfSMatthias Ringwald     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
1709ca6804fdSMatthias Ringwald     hci_send_prepared_cmd_packet();
171059d59ecfSMatthias Ringwald }
171159d59ecfSMatthias Ringwald 
171259d59ecfSMatthias Ringwald static void gap_run_set_eir_data(void){
171359d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
171459d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
171559d59ecfSMatthias Ringwald     // construct HCI Command in-place and send
171659d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
171759d59ecfSMatthias Ringwald     uint16_t offset = 0;
171859d59ecfSMatthias Ringwald     packet[offset++] = opcode & 0xff;
171959d59ecfSMatthias Ringwald     packet[offset++] = opcode >> 8;
172059d59ecfSMatthias Ringwald     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
172159d59ecfSMatthias Ringwald     packet[offset++] = 0;  // FEC not required
172259d59ecfSMatthias Ringwald     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
172359d59ecfSMatthias Ringwald     if (hci_stack->eir_data){
172459d59ecfSMatthias Ringwald         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
172559d59ecfSMatthias Ringwald         ad_context_t context;
172659d59ecfSMatthias Ringwald         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
172759d59ecfSMatthias Ringwald             uint8_t data_type   = ad_iterator_get_data_type(&context);
172859d59ecfSMatthias Ringwald             uint8_t size        = ad_iterator_get_data_len(&context);
172959d59ecfSMatthias Ringwald             const uint8_t *data = ad_iterator_get_data(&context);
173059d59ecfSMatthias Ringwald             // copy item
173159d59ecfSMatthias Ringwald             packet[offset++] = size + 1;
173259d59ecfSMatthias Ringwald             packet[offset++] = data_type;
173359d59ecfSMatthias Ringwald             memcpy(&packet[offset], data, size);
173459d59ecfSMatthias Ringwald             // update name item
173559d59ecfSMatthias Ringwald             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
173659d59ecfSMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
173759d59ecfSMatthias Ringwald             }
173859d59ecfSMatthias Ringwald             offset += size;
173959d59ecfSMatthias Ringwald         }
174059d59ecfSMatthias Ringwald     } else {
174159d59ecfSMatthias Ringwald         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
174259d59ecfSMatthias Ringwald         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
174359d59ecfSMatthias Ringwald         packet[offset++] = bytes_to_copy + 1;
174459d59ecfSMatthias Ringwald         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
174559d59ecfSMatthias Ringwald         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
174659d59ecfSMatthias Ringwald         // expand '00:00:00:00:00:00' in name with bd_addr
174759d59ecfSMatthias Ringwald         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
174859d59ecfSMatthias Ringwald     }
1749ca6804fdSMatthias Ringwald     hci_send_prepared_cmd_packet();
175059d59ecfSMatthias Ringwald }
1751ab4831a3SMatthias Ringwald 
1752ab4831a3SMatthias Ringwald static void hci_run_gap_tasks_classic(void){
1753baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1754baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1755ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1756ab4831a3SMatthias Ringwald         return;
1757ab4831a3SMatthias Ringwald     }
1758baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1759baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1760ab4831a3SMatthias Ringwald         gap_run_set_local_name();
1761ab4831a3SMatthias Ringwald         return;
1762ab4831a3SMatthias Ringwald     }
1763baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1764baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1765ab4831a3SMatthias Ringwald         gap_run_set_eir_data();
1766ab4831a3SMatthias Ringwald         return;
1767ab4831a3SMatthias Ringwald     }
1768baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1769baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1770ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1771ab4831a3SMatthias Ringwald         return;
1772ab4831a3SMatthias Ringwald     }
1773ab4831a3SMatthias Ringwald     // write page scan activity
1774baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1775baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1776ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1777ab4831a3SMatthias Ringwald         return;
1778ab4831a3SMatthias Ringwald     }
1779ab4831a3SMatthias Ringwald     // write page scan type
1780baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1781baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1782ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1783ab4831a3SMatthias Ringwald         return;
1784ab4831a3SMatthias Ringwald     }
178532a12730SMatthias Ringwald     // write page timeout
1786baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1787baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
178832a12730SMatthias Ringwald         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
178932a12730SMatthias Ringwald         return;
179032a12730SMatthias Ringwald     }
1791ab4831a3SMatthias Ringwald     // send scan enable
1792baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1793baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1794ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1795ab4831a3SMatthias Ringwald         return;
1796ab4831a3SMatthias Ringwald     }
1797c0c8a829SMatthias Ringwald     // send write scan activity
1798baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1799baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1800c0c8a829SMatthias Ringwald         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1801c0c8a829SMatthias Ringwald         return;
1802c0c8a829SMatthias Ringwald     }
1803f50ed5acSAndrey Fominykh     // send write inquiry transmit power level
1804f50ed5acSAndrey Fominykh     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL) != 0) {
1805f50ed5acSAndrey Fominykh         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
1806f50ed5acSAndrey Fominykh         hci_send_cmd(&hci_write_inquiry_transmit_power_level, hci_stack->inquiry_tx_power_level);
1807f50ed5acSAndrey Fominykh         return;
1808f50ed5acSAndrey Fominykh     }
1809ab4831a3SMatthias Ringwald }
181059d59ecfSMatthias Ringwald #endif
181159d59ecfSMatthias Ringwald 
18126fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
181306b9e820SMatthias Ringwald 
181496b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
181596b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
18169796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
181796b53536SMatthias Ringwald     return baud_rate;
181896b53536SMatthias Ringwald }
181996b53536SMatthias Ringwald 
1820ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
18219ec2630cSMatthias Ringwald     UNUSED(ds);
18229ec2630cSMatthias Ringwald 
18230305bdeaSMatthias Ringwald     switch (hci_stack->substate){
18240305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
18257b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
18260305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
18277b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
18280305bdeaSMatthias Ringwald             hci_run();
18290305bdeaSMatthias Ringwald             break;
18309f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
18319f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
18329f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
18339f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
18349f007422SMatthias Ringwald             }
1835cf373d3aSMatthias Ringwald 
1836cf373d3aSMatthias Ringwald             /* fall through */
1837cf373d3aSMatthias Ringwald 
1838e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1839e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1840e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1841e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1842e47e68c7SMatthias Ringwald             hci_run();
1843688c2635SMatthias Ringwald             break;
18447224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
18457224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
184696b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1847cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
18487dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18497224be7eSMatthias Ringwald             }
1850834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
185161f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1852834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1853834bce8cSMatthias Ringwald                     log_info("Link Reset");
1854834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1855834bce8cSMatthias Ringwald                 }
1856772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1857772a36d3SMatthias Ringwald                 hci_run();
1858772a36d3SMatthias Ringwald             }
18594696bddbSMatthias Ringwald             break;
1860559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1861559961d0SMatthias Ringwald             // otherwise continue
1862559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1863559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1864559961d0SMatthias Ringwald             break;
18650305bdeaSMatthias Ringwald         default:
18660305bdeaSMatthias Ringwald             break;
18670305bdeaSMatthias Ringwald     }
18680305bdeaSMatthias Ringwald }
186906b9e820SMatthias Ringwald #endif
18700305bdeaSMatthias Ringwald 
187171de195eSMatthias Ringwald static void hci_initializing_next_state(void){
187274b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
187374b323a9SMatthias Ringwald }
187474b323a9SMatthias Ringwald 
1875f795c86eSMatthias Ringwald static void hci_init_done(void){
1876f795c86eSMatthias Ringwald     // done. tell the app
1877f795c86eSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1878f795c86eSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1879f795c86eSMatthias Ringwald     hci_emit_state();
1880f795c86eSMatthias Ringwald }
1881f795c86eSMatthias Ringwald 
188274b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
188371de195eSMatthias Ringwald static void hci_initializing_run(void){
1884148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1885f4c579d4SMatthias Ringwald 
18860d37aff3SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
18870d37aff3SMatthias Ringwald 
1888f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1889f9fd20c2SMatthias Ringwald     bool need_baud_change = hci_stack->config
1890f4c579d4SMatthias Ringwald             && hci_stack->chipset
1891f4c579d4SMatthias Ringwald             && hci_stack->chipset->set_baudrate_command
1892f4c579d4SMatthias Ringwald             && hci_stack->hci_transport->set_baudrate
1893f4c579d4SMatthias Ringwald             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1894f4c579d4SMatthias Ringwald #endif
1895f4c579d4SMatthias Ringwald 
189674b323a9SMatthias Ringwald     switch (hci_stack->substate){
189774b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
189874b323a9SMatthias Ringwald             hci_state_reset();
1899a0cf2f3fSMatthias Ringwald 
19006fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
19010305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1902659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1903528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1904528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1905a0cf2f3fSMatthias Ringwald #endif
19060305bdeaSMatthias Ringwald             // send command
190774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
19080305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
190974b323a9SMatthias Ringwald             break;
191076fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
191176fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
191276fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
191376fcb19bSMatthias Ringwald             break;
1914e28e41c0SMatthias Ringwald 
1915e28e41c0SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1916e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1917e47e68c7SMatthias Ringwald             hci_state_reset();
1918e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1919659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1920528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1921528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1922e47e68c7SMatthias Ringwald             // send command
1923e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1924e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1925e47e68c7SMatthias Ringwald             break;
19268d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
19278d29070eSMatthias Ringwald             hci_state_reset();
19288d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
19298d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
19308d29070eSMatthias Ringwald             break;
1931f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1932a784d71bSMatthias Ringwald             hci_reserve_packet_buffer();
1933f4c579d4SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1934f4c579d4SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1935f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1936ca6804fdSMatthias Ringwald             hci_send_prepared_cmd_packet();
1937f4c579d4SMatthias Ringwald             break;
1938f4c579d4SMatthias Ringwald         }
1939c97af506SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
1940a784d71bSMatthias Ringwald             hci_reserve_packet_buffer();
1941c97af506SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1942c97af506SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1943c97af506SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1944ca6804fdSMatthias Ringwald             hci_send_prepared_cmd_packet();
1945c97af506SMatthias Ringwald             break;
19468250c242SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
19478250c242SMatthias Ringwald #ifdef ENABLE_CLASSIC
19488250c242SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
19498250c242SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
19508250c242SMatthias Ringwald             break;
19518250c242SMatthias Ringwald #endif
19528250c242SMatthias Ringwald             /* fall through */
19538250c242SMatthias Ringwald 
1954f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE:
1955f4c579d4SMatthias Ringwald             if (need_baud_change) {
1956a784d71bSMatthias Ringwald                 hci_reserve_packet_buffer();
195796b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
19583fb36a29SMatthias Ringwald                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
195974b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1960ca6804fdSMatthias Ringwald                 hci_send_prepared_cmd_packet();
19614696bddbSMatthias Ringwald                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
19624696bddbSMatthias Ringwald                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
196361f37892SMatthias Ringwald                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1964659d758cSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1965528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
19664696bddbSMatthias Ringwald                }
196774b323a9SMatthias Ringwald                break;
1968fab26ab3SMatthias Ringwald             }
19696fe16221SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1970f4c579d4SMatthias Ringwald 
1971f4c579d4SMatthias Ringwald             /* fall through */
1972f4c579d4SMatthias Ringwald 
197374b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
19746fe16221SMatthias Ringwald         case HCI_INIT_CUSTOM_PRE_INIT:
197574b323a9SMatthias Ringwald             // Custom initialization
19763fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1977ee418d0fSMatthias Ringwald                 hci_reserve_packet_buffer();
1978ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
19791979f09cSMatthias Ringwald                 bool send_cmd = false;
1980ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1981f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
19821979f09cSMatthias Ringwald                         send_cmd = true;
19836fe16221SMatthias Ringwald                         switch (hci_stack->substate){
19846fe16221SMatthias Ringwald                             case HCI_INIT_CUSTOM_INIT:
1985e47e68c7SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1986e47e68c7SMatthias Ringwald                                 break;
19876fe16221SMatthias Ringwald                             case HCI_INIT_CUSTOM_PRE_INIT:
19886fe16221SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_PRE_INIT;
19896fe16221SMatthias Ringwald                                 break;
19906fe16221SMatthias Ringwald                             default:
19916fe16221SMatthias Ringwald                                 btstack_assert(false);
19926fe16221SMatthias Ringwald                                 break;
19936fe16221SMatthias Ringwald                         }
19946fe16221SMatthias Ringwald                         break;
1995f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
19961979f09cSMatthias Ringwald                         send_cmd = true;
1997f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1998e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1999659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
2000528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2001528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
2002a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
2003772a36d3SMatthias Ringwald                             && hci_stack->config
20043fb36a29SMatthias Ringwald                             && hci_stack->chipset
20053fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
2006772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
20072caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
2008772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
2009772a36d3SMatthias Ringwald                         } else {
20109f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
2011772a36d3SMatthias Ringwald                         }
2012e47e68c7SMatthias Ringwald                         break;
2013f41911edSMatthias Ringwald                     default:
2014f41911edSMatthias Ringwald                         break;
2015e47e68c7SMatthias Ringwald                 }
2016ee720f3aSMatthias Ringwald 
2017ee720f3aSMatthias Ringwald                 if (send_cmd){
2018ca6804fdSMatthias Ringwald                     hci_send_prepared_cmd_packet();
201974b323a9SMatthias Ringwald                     break;
2020ee418d0fSMatthias Ringwald                 } else {
2021ee418d0fSMatthias Ringwald                     hci_release_packet_buffer();
202274b323a9SMatthias Ringwald                 }
2023148ca237SMatthias Ringwald                 log_info("Init script done");
202492a0d36dSMatthias Ringwald 
20256fe16221SMatthias Ringwald                 // Custom Pre-Init complete, start regular init with HCI Reset
20266fe16221SMatthias Ringwald                 if (hci_stack->substate == HCI_INIT_CUSTOM_PRE_INIT){
20276fe16221SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_SEND_RESET;
20286fe16221SMatthias Ringwald                     hci_send_cmd(&hci_reset);
20296fe16221SMatthias Ringwald                     break;
20306fe16221SMatthias Ringwald                 }
20316fe16221SMatthias Ringwald 
2032559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
2033ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2034a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
2035a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
2036e021ff1eSMatthias Ringwald 
2037559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
203892a0d36dSMatthias Ringwald                     if (need_baud_change) {
20399796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
2040cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
204192a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
204292a0d36dSMatthias Ringwald                     }
2043559961d0SMatthias Ringwald 
2044f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
2045f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
2046f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
2047f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
2048559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
2049f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
2050559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2051559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
2052559961d0SMatthias Ringwald                     break;
205392a0d36dSMatthias Ringwald                 }
205474b323a9SMatthias Ringwald             }
205506b9e820SMatthias Ringwald #endif
2056521bd5ffSMatthias Ringwald             /* fall through */
205706b9e820SMatthias Ringwald 
205806b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
205906b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
206006b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
206106b9e820SMatthias Ringwald             break;
206253860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
206353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
206453860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
206553860077SMatthias Ringwald             break;
206674b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
20675ffe9d0bSMatthias Ringwald             // only read buffer size if supported
20681ffa425cSMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
206974b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
20700305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_read_buffer_size);
207174b323a9SMatthias Ringwald                 break;
20725ffe9d0bSMatthias Ringwald             }
2073521bd5ffSMatthias Ringwald 
20745ffe9d0bSMatthias Ringwald             /* fall through */
20755ffe9d0bSMatthias Ringwald 
207653860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
207753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
20780305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
207974b323a9SMatthias Ringwald             break;
20802b838201SMatthias Ringwald 
20812b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
20822b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
20832b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
20842b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
20852b838201SMatthias Ringwald             break;
20862b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
20872b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
20882b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
20892b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
20902b838201SMatthias Ringwald             break;
20912b838201SMatthias Ringwald #endif
20922b838201SMatthias Ringwald 
209374b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
20940305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
209574b323a9SMatthias Ringwald             if (hci_le_supported()){
20965ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
209774b323a9SMatthias Ringwald             } else {
209874b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
20995ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
210074b323a9SMatthias Ringwald             }
210174b323a9SMatthias Ringwald             break;
21022b838201SMatthias Ringwald 
2103ff7d1758SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK_2:
2104a086dc35SMatthias Ringwald             // On Bluetooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
21058254e329SMatthias Ringwald             // setting Event Mask 2 causes Controller to drop Encryption Change events.
21068254e329SMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
21078254e329SMatthias Ringwald             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
2108ff7d1758SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
2109ff7d1758SMatthias Ringwald                 // Encryption Change Event v2 - bit 25
2110ff7d1758SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
2111ff7d1758SMatthias Ringwald                 break;
2112ff7d1758SMatthias Ringwald             }
2113ff7d1758SMatthias Ringwald 
211435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2115ff7d1758SMatthias Ringwald             /* fall through */
2116ff7d1758SMatthias Ringwald 
211774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
2118f795c86eSMatthias Ringwald             if (hci_classic_supported() && gap_ssp_supported()){
211974b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
21200305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
212174b323a9SMatthias Ringwald                 break;
2122e7c662faSMatthias Ringwald             }
2123521bd5ffSMatthias Ringwald 
2124e7c662faSMatthias Ringwald             /* fall through */
2125e7c662faSMatthias Ringwald 
2126f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
2127f795c86eSMatthias Ringwald             if (hci_classic_supported()){
2128f6858d14SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
21298a114470SMatthias Ringwald                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
2130f6858d14SMatthias Ringwald                 break;
2131f795c86eSMatthias Ringwald             }
2132521bd5ffSMatthias Ringwald 
2133f795c86eSMatthias Ringwald             /* fall through */
2134f795c86eSMatthias Ringwald 
21355d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
2136f3052906SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
21371ffa425cSMatthias Ringwald             if (hci_classic_supported() && hci_stack->secure_connections_enable
21381ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
2139c214d65bSMatthias Ringwald                 hci_stack->secure_connections_active = true;
21405d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
21411ffa425cSMatthias Ringwald                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
21425d23aae8SMatthias Ringwald                 break;
2143f3052906SMatthias Ringwald             }
2144521bd5ffSMatthias Ringwald 
2145a391128dSMatthias Ringwald             /* fall through */
2146a391128dSMatthias Ringwald 
2147a391128dSMatthias Ringwald         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
2148a391128dSMatthias Ringwald             // skip set min encryption key size
2149a391128dSMatthias Ringwald             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
2150a391128dSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
2151a391128dSMatthias Ringwald                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
2152a391128dSMatthias Ringwald                 break;
2153a391128dSMatthias Ringwald             }
2154a391128dSMatthias Ringwald 
2155e4c6114dSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2156521bd5ffSMatthias Ringwald             /* fall through */
2157521bd5ffSMatthias Ringwald 
2158483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
2159729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2160e4c6114dSMatthias Ringwald             // skip write synchronous flow control if not supported
21611ffa425cSMatthias Ringwald             if (hci_classic_supported()
21621ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2163729ed62eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2164729ed62eSMatthias Ringwald                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2165729ed62eSMatthias Ringwald                 break;
2166f795c86eSMatthias Ringwald             }
2167f795c86eSMatthias Ringwald             /* fall through */
2168f795c86eSMatthias Ringwald 
2169483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2170e4c6114dSMatthias Ringwald             // skip write default erroneous data reporting if not supported
21711ffa425cSMatthias Ringwald             if (hci_classic_supported()
21721ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2173483c5078SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2174483c5078SMatthias Ringwald                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2175483c5078SMatthias Ringwald                 break;
2176f795c86eSMatthias Ringwald             }
2177e4c6114dSMatthias Ringwald #endif
2178f795c86eSMatthias Ringwald 
2179f795c86eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2180521bd5ffSMatthias Ringwald             /* fall through */
2181521bd5ffSMatthias Ringwald 
21828051253fSMatthias Ringwald         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2183a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2184e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2185a42798c3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
21868051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2187a42798c3SMatthias Ringwald                 log_info("BCM: Route SCO data via HCI transport");
2188a42798c3SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
21898051253fSMatthias Ringwald #endif
21908051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
21918051253fSMatthias Ringwald                 log_info("BCM: Route SCO data via PCM interface");
21921d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
2193f795c86eSMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
21941d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
21951d2bbd54SMatthias Ringwald #else
21961d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
21971d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
21981d2bbd54SMatthias Ringwald #endif
21998051253fSMatthias Ringwald #endif
2200a42798c3SMatthias Ringwald                 break;
2201f795c86eSMatthias Ringwald             }
2202f795c86eSMatthias Ringwald #endif
2203f795c86eSMatthias Ringwald 
22044e821764SMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
2205521bd5ffSMatthias Ringwald             /* fall through */
2206521bd5ffSMatthias Ringwald 
22074e821764SMatthias Ringwald         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2208e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
22094e821764SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
22104e821764SMatthias Ringwald                 log_info("BCM: Config PCM interface for I2S");
22111d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
22121d2bbd54SMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
22131d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
22141d2bbd54SMatthias Ringwald #else
22151d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
22161d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
22171d2bbd54SMatthias Ringwald #endif
22184e821764SMatthias Ringwald                 break;
2219f795c86eSMatthias Ringwald             }
22201be678e9SMatthias Ringwald         case HCI_INIT_BCM_WRITE_PCM_DATA_FORMAT_PARAM:
22211be678e9SMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
22221be678e9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_PCM_DATA_FORMAT_PARAM;
22231be678e9SMatthias Ringwald                 log_info("BCM: Config PCM Data format");
22241be678e9SMatthias Ringwald                 // msb first, fill bits 0, left justified
22251be678e9SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_pcm_data_format_param, 0, 0, 3, 3, 0);
22261be678e9SMatthias Ringwald                 break;
22271be678e9SMatthias Ringwald             }
2228dd1f98b4SMatthias Ringwald #ifdef HAVE_BCM_PCM2
2229dd1f98b4SMatthias Ringwald         case HCI_INIT_BCM_PCM2_SETUP:
2230dd1f98b4SMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)) {
2231dd1f98b4SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_PCM2_SETUP;
2232dd1f98b4SMatthias Ringwald                 uint8_t  op_mode = 0;  // Op_Mode = 0 = PCM, 1 = I2S
2233dd1f98b4SMatthias Ringwald                 uint32_t pcm_clock_freq;
2234dd1f98b4SMatthias Ringwald                 uint8_t  ch_0_period;
2235dd1f98b4SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
2236dd1f98b4SMatthias Ringwald                 // 512 kHz, resample 8 kHz to 16 khz
2237dd1f98b4SMatthias Ringwald                 pcm_clock_freq = 512000;
2238dd1f98b4SMatthias Ringwald                 ch_0_period = 1;
2239dd1f98b4SMatthias Ringwald #else
2240dd1f98b4SMatthias Ringwald                 // 256 khz, 8 khz output
2241dd1f98b4SMatthias Ringwald                 pcm_clock_freq = 256000;
2242dd1f98b4SMatthias Ringwald                 ch_0_period = 0;
224335454696SMatthias Ringwald #endif
2244dd1f98b4SMatthias Ringwald                 log_info("BCM: Config PCM2 - op mode %u, pcm clock %" PRIu32 ", ch0_period %u", op_mode, pcm_clock_freq, ch_0_period);
2245dd1f98b4SMatthias Ringwald                 hci_send_cmd(&hci_bcm_pcm2_setup,
2246dd1f98b4SMatthias Ringwald                              0x00, // Action = Write
2247dd1f98b4SMatthias Ringwald                              0x00, // Test_Options = None
2248dd1f98b4SMatthias Ringwald                              op_mode, // Op_Mode
2249dd1f98b4SMatthias Ringwald                              0x1D, // Sync_and_Clock_Options Sync = Signal | Sync Output Enable | Generate PCM_CLK | Tristate When Idle
2250dd1f98b4SMatthias Ringwald                              pcm_clock_freq, // PCM_Clock_Freq
2251dd1f98b4SMatthias Ringwald                              0x01, // Sync_Signal_Width
2252dd1f98b4SMatthias Ringwald                              0x0F, // Slot_Width
2253dd1f98b4SMatthias Ringwald                              0x01, // NumberOfSlots
2254dd1f98b4SMatthias Ringwald                              0x00, // Bank_0_Fill_Mode = 0s
2255dd1f98b4SMatthias Ringwald                              0x00, // Bank_0_Number_of_Fill_Bits
2256dd1f98b4SMatthias Ringwald                              0x00, // Bank_0_Programmable_Fill_Data
2257dd1f98b4SMatthias Ringwald                              0x00, // Bank_1_Fill_Mode = 0s
2258dd1f98b4SMatthias Ringwald                              0x00, // Bank_1_Number_of_Fill_Bits
2259dd1f98b4SMatthias Ringwald                              0x00, // Bank_1_Programmable_Fill_Data
2260dd1f98b4SMatthias Ringwald                              0x00, // Data_Justify_And_Bit_Order_Options = Left Justify
2261dd1f98b4SMatthias Ringwald                              0x00, // Ch_0_Slot_Number
2262dd1f98b4SMatthias Ringwald                              0x01, // Ch_1_Slot_Number
2263dd1f98b4SMatthias Ringwald                              0x02, // Ch_2_Slot_Number
2264dd1f98b4SMatthias Ringwald                              0x03, // Ch_3_Slot_Number
2265dd1f98b4SMatthias Ringwald                              0x04, // Ch_4_Slot_Number
2266dd1f98b4SMatthias Ringwald                              ch_0_period, // Ch_0_Period
2267dd1f98b4SMatthias Ringwald                              0x00, // Ch_1_Period
2268dd1f98b4SMatthias Ringwald                              0x00  // Ch_2_Period
2269dd1f98b4SMatthias Ringwald                 );
2270dd1f98b4SMatthias Ringwald                 break;
2271dd1f98b4SMatthias Ringwald             }
22724e821764SMatthias Ringwald #endif
2273dd1f98b4SMatthias Ringwald #endif /* ENABLE_SCO_OVER_PCM */
2274dd1f98b4SMatthias Ringwald #endif /* ENABLE_CLASSIC */
22754e821764SMatthias Ringwald 
2276a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2277521bd5ffSMatthias Ringwald             /* fall through */
2278521bd5ffSMatthias Ringwald 
227974b323a9SMatthias Ringwald         // LE INIT
228074b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
2281f795c86eSMatthias Ringwald             if (hci_le_supported()){
228274b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
228379b7ea2dSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
228479b7ea2dSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size_v2);
228579b7ea2dSMatthias Ringwald                 } else {
22860305bdeaSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size);
228779b7ea2dSMatthias Ringwald                 }
228874b323a9SMatthias Ringwald                 break;
2289f795c86eSMatthias Ringwald             }
2290521bd5ffSMatthias Ringwald 
2291f795c86eSMatthias Ringwald             /* fall through */
2292f795c86eSMatthias Ringwald 
2293699a5fcaSMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2294699a5fcaSMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
22951ffa425cSMatthias Ringwald             if (hci_le_supported()
22961ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2297699a5fcaSMatthias Ringwald                 // LE Supported Host = 1, Simultaneous Host = 0
2298699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2299699a5fcaSMatthias Ringwald                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2300daabb8b8SMatthias Ringwald                 break;
2301f795c86eSMatthias Ringwald             }
2302521bd5ffSMatthias Ringwald 
2303f795c86eSMatthias Ringwald             /* fall through */
2304f795c86eSMatthias Ringwald 
2305699a5fcaSMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
2306f795c86eSMatthias Ringwald             if (hci_le_supported()){
2307699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
23085d6688b0SMatthias Ringwald #ifdef ENABLE_LE_ENHANCED_CONNECTION_COMPLETE_EVENT
2309920a6ac5SMatthias Ringwald                 hci_send_cmd(&hci_le_set_event_mask, 0xffffffff, 0x0107); // all events from core v5.3
23105d6688b0SMatthias Ringwald #else
2311920a6ac5SMatthias Ringwald                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x0007); // all events from core v5.3 without LE Enhanced Connection Complete
23125d6688b0SMatthias Ringwald #endif
231374b323a9SMatthias Ringwald                 break;
2314f795c86eSMatthias Ringwald             }
2315b435e062SMatthias Ringwald #endif
2316b435e062SMatthias Ringwald 
2317b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2318521bd5ffSMatthias Ringwald             /* fall through */
2319521bd5ffSMatthias Ringwald 
2320dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
23211ffa425cSMatthias Ringwald             if (hci_le_supported()
23221ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2323dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2324dcd678baSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_data_length);
2325dcd678baSMatthias Ringwald                 break;
2326f795c86eSMatthias Ringwald             }
2327521bd5ffSMatthias Ringwald 
2328f795c86eSMatthias Ringwald             /* fall through */
2329f795c86eSMatthias Ringwald 
2330dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
23311ffa425cSMatthias Ringwald             if (hci_le_supported()
23321ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2333dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2334b435e062SMatthias Ringwald                 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
2335dcd678baSMatthias Ringwald                 break;
2336f795c86eSMatthias Ringwald             }
2337b435e062SMatthias Ringwald #endif
2338b435e062SMatthias Ringwald 
2339b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2340521bd5ffSMatthias Ringwald             /* fall through */
2341521bd5ffSMatthias Ringwald 
23423b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
2343f795c86eSMatthias Ringwald             if (hci_le_supported()){
23443b6d4121SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
23453b6d4121SMatthias Ringwald                 hci_send_cmd(&hci_le_read_white_list_size);
23463b6d4121SMatthias Ringwald                 break;
2347f795c86eSMatthias Ringwald             }
2348521bd5ffSMatthias Ringwald 
234974b323a9SMatthias Ringwald #endif
23504f982f31SMatthias Ringwald 
23513a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23523a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
23533a74541eSMatthias Ringwald             /* fall through */
23543a74541eSMatthias Ringwald 
23553a74541eSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
235622f987e4SMatthias Ringwald             if (hci_le_extended_advertising_supported()){
23573a74541eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
23583a74541eSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
23593a74541eSMatthias Ringwald                 break;
23603a74541eSMatthias Ringwald             }
23613a74541eSMatthias Ringwald #endif
23623a74541eSMatthias Ringwald #endif
2363521bd5ffSMatthias Ringwald 
2364c63ee49aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
236536916f81SDirk Helbig             /* fall through */
236636916f81SDirk Helbig 
2367c63ee49aSMatthias Ringwald         case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2368e1f9b11fSMatthias Ringwald             if (hci_le_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_HOST_FEATURE_V1)) {
2369c63ee49aSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2370c63ee49aSMatthias Ringwald                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2371c63ee49aSMatthias Ringwald                 break;
2372c63ee49aSMatthias Ringwald             }
2373c63ee49aSMatthias Ringwald #endif
2374c63ee49aSMatthias Ringwald 
2375f266fcb1SMatthias Ringwald #ifdef ENABLE_BLE
2376f266fcb1SMatthias Ringwald             /* fall through */
2377f266fcb1SMatthias Ringwald         case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTION_SUBRATING:
2378e1f9b11fSMatthias Ringwald             if (hci_le_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_HOST_FEATURE_V1)) {
2379f266fcb1SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTION_SUBRATING;
2380f266fcb1SMatthias Ringwald                 hci_send_cmd(&hci_le_set_host_feature, 38, 1);
2381f266fcb1SMatthias Ringwald                 break;
2382f266fcb1SMatthias Ringwald             }
2383f266fcb1SMatthias Ringwald #endif
2384c63ee49aSMatthias Ringwald             /* fall through */
2385c63ee49aSMatthias Ringwald 
2386f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
23874f982f31SMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
238873799937SMatthias Ringwald             // main init sequence complete
23894f982f31SMatthias Ringwald #ifdef ENABLE_CLASSIC
239073799937SMatthias Ringwald             // check if initial Classic GAP Tasks are completed
2391baa4881eSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
23924f982f31SMatthias Ringwald                 hci_run_gap_tasks_classic();
23934f982f31SMatthias Ringwald                 break;
23944f982f31SMatthias Ringwald             }
23954f982f31SMatthias Ringwald #endif
239673799937SMatthias Ringwald #ifdef ENABLE_BLE
239773799937SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
239873799937SMatthias Ringwald             // check if initial LE GAP Tasks are completed
239973799937SMatthias Ringwald             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
240073799937SMatthias Ringwald                 hci_run_general_gap_le();
240173799937SMatthias Ringwald                 break;
240273799937SMatthias Ringwald             }
240373799937SMatthias Ringwald #endif
240473799937SMatthias Ringwald #endif
2405f795c86eSMatthias Ringwald             hci_init_done();
2406f795c86eSMatthias Ringwald             break;
2407f795c86eSMatthias Ringwald 
240874b323a9SMatthias Ringwald         default:
240974b323a9SMatthias Ringwald             return;
241074b323a9SMatthias Ringwald     }
241155975f88SMatthias Ringwald }
241255975f88SMatthias Ringwald 
241307fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
241407fd2f31SMatthias Ringwald     bool command_completed = false;
24150e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2416f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
24176155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
241807fd2f31SMatthias Ringwald             command_completed = true;
2419148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
24206155b3d3S[email protected]         } else {
2421d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
24226155b3d3S[email protected]         }
24236155b3d3S[email protected]     }
24240f97eae7SMatthias Ringwald 
24250e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
24266155b3d3S[email protected]         uint8_t  status = packet[2];
2427f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
24286155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
24296155b3d3S[email protected]             if (status){
243007fd2f31SMatthias Ringwald                 command_completed = true;
2431148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
24326155b3d3S[email protected]             } else {
24336155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
24346155b3d3S[email protected]             }
24356155b3d3S[email protected]         } else {
2436148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
24376155b3d3S[email protected]         }
24386155b3d3S[email protected]     }
24396fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2440e47e68c7SMatthias Ringwald     // Vendor == CSR
24410e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2442e47e68c7SMatthias Ringwald         // TODO: track actual command
244307fd2f31SMatthias Ringwald         command_completed = true;
2444e47e68c7SMatthias Ringwald     }
2445a2481739S[email protected] 
24464e9daa6fSMatthias Ringwald     // Vendor == Toshiba
24470e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
24484e9daa6fSMatthias Ringwald         // TODO: track actual command
244907fd2f31SMatthias Ringwald         command_completed = true;
2450004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2451004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
24524e9daa6fSMatthias Ringwald     }
245307fd2f31SMatthias Ringwald #endif
245407fd2f31SMatthias Ringwald 
245507fd2f31SMatthias Ringwald     return command_completed;
245607fd2f31SMatthias Ringwald }
245707fd2f31SMatthias Ringwald 
245807fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
245907fd2f31SMatthias Ringwald 
246007fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
246107fd2f31SMatthias Ringwald 
246207fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
246307fd2f31SMatthias Ringwald 
24646fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
24654e9daa6fSMatthias Ringwald 
24660f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
24670f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
24680f97eae7SMatthias Ringwald     //
24690f97eae7SMatthias Ringwald     // HCI Reset
24700f97eae7SMatthias Ringwald     // Timeout 100 ms
24710f97eae7SMatthias Ringwald     // HCI Reset
24720f97eae7SMatthias Ringwald     // Command Complete Reset
24730f97eae7SMatthias Ringwald     // HCI Read Local Version Information
24740f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
24750f97eae7SMatthias Ringwald     // hang...
24760f97eae7SMatthias Ringwald     //
24770f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
24780f97eae7SMatthias Ringwald     if (!command_completed
2479a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
24800e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
24810f97eae7SMatthias Ringwald 
2482f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
24830f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
24840f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
24850f97eae7SMatthias Ringwald             return;
24860f97eae7SMatthias Ringwald         }
24870f97eae7SMatthias Ringwald     }
24880f97eae7SMatthias Ringwald 
24899f007422SMatthias Ringwald     // CSR & H5
24909f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
24919f007422SMatthias Ringwald     if (!command_completed
2492a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
24930e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
24949f007422SMatthias Ringwald 
24959f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
24969f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
24979f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
24989f007422SMatthias Ringwald             return;
24999f007422SMatthias Ringwald         }
25009f007422SMatthias Ringwald     }
25019f007422SMatthias Ringwald 
25029f007422SMatthias Ringwald     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
25039f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
25049f007422SMatthias Ringwald     if (command_completed){
25059f007422SMatthias Ringwald         switch (hci_stack->substate){
25069f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
25079f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
25089f007422SMatthias Ringwald                 break;
25099f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
25109f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
25119f007422SMatthias Ringwald                 break;
25129f007422SMatthias Ringwald             default:
25139f007422SMatthias Ringwald                 break;
25149f007422SMatthias Ringwald         }
25159f007422SMatthias Ringwald     }
25160f97eae7SMatthias Ringwald 
251706b9e820SMatthias Ringwald #endif
25180f97eae7SMatthias Ringwald 
2519a2481739S[email protected]     if (!command_completed) return;
2520a2481739S[email protected] 
252107fd2f31SMatthias Ringwald     bool need_baud_change = false;
252207fd2f31SMatthias Ringwald     bool need_addr_change = false;
252306b9e820SMatthias Ringwald 
25246fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
252506b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
25263fb36a29SMatthias Ringwald                         && hci_stack->chipset
25273fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
2528db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
25299796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2530db8bc6ffSMatthias Ringwald 
253106b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
25323fb36a29SMatthias Ringwald                         && hci_stack->chipset
25333fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
253406b9e820SMatthias Ringwald #endif
2535a80162e9SMatthias Ringwald 
25365c363727SMatthias Ringwald     switch(hci_stack->substate){
253706b9e820SMatthias Ringwald 
25386fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
25399f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
2540d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
25419f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
2542f4c579d4SMatthias Ringwald 
2543f4c579d4SMatthias Ringwald             /* fall through */
2544f4c579d4SMatthias Ringwald #endif
2545f4c579d4SMatthias Ringwald 
254674b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
2547528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2548f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
25492f48d920SMatthias Ringwald             return;
2550f4c579d4SMatthias Ringwald 
2551f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2552a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
25534696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
2554fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
255561f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
255696b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2557cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2558fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
25594696bddbSMatthias Ringwald             }
256074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
256174b323a9SMatthias Ringwald             return;
2562a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2563528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2564a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2565a80162e9SMatthias Ringwald             return;
256674b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
256774b323a9SMatthias Ringwald             // repeat custom init
256874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
256974b323a9SMatthias Ringwald             return;
25706fe16221SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_PRE_INIT:
25716fe16221SMatthias Ringwald             // repeat custom init
25726fe16221SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
25736fe16221SMatthias Ringwald             return;
257406b9e820SMatthias Ringwald #endif
257506b9e820SMatthias Ringwald 
2576a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
25770e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2578efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2579efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2580eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2581eb3a5314SMatthias Ringwald                 return;
2582eb3a5314SMatthias Ringwald             }
258353860077SMatthias Ringwald             if (need_addr_change){
258453860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
258553860077SMatthias Ringwald                 return;
258653860077SMatthias Ringwald             }
258753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
258853860077SMatthias Ringwald             return;
25896fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
25907224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
25917224be7eSMatthias Ringwald             if (need_baud_change){
259296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2593cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2594fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
25957224be7eSMatthias Ringwald             }
2596eb3a5314SMatthias Ringwald             if (need_addr_change){
2597eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2598eb3a5314SMatthias Ringwald                 return;
2599eb3a5314SMatthias Ringwald             }
2600eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2601eb3a5314SMatthias Ringwald             return;
260253860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
26036ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
26046ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
26056ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
260653860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
260753860077SMatthias Ringwald                 return;
260853860077SMatthias Ringwald             }
260953860077SMatthias Ringwald             // skipping st warm boot
261053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
261153860077SMatthias Ringwald             return;
261253860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
261353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
261453860077SMatthias Ringwald             return;
261506b9e820SMatthias Ringwald #endif
2616e7c662faSMatthias Ringwald 
2617f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
2618eb8d95caSMatthias Ringwald             // set state if we came here by fall through
2619eb8d95caSMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
2620f795c86eSMatthias Ringwald             return;
2621a650ba4dSMatthias Ringwald 
26226155b3d3S[email protected]         default:
262374b323a9SMatthias Ringwald             break;
26246155b3d3S[email protected]     }
262555975f88SMatthias Ringwald     hci_initializing_next_state();
26266155b3d3S[email protected] }
26276155b3d3S[email protected] 
2628f0f95544SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
26290bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
26303bb5ff27SMatthias Ringwald     // CC2564C might emit Connection Complete for rejected incoming SCO connection
2631a086dc35SMatthias Ringwald     // To prevent accidentally freeing the HCI connection for the ACL connection,
26321a4fdac4SMatthias Ringwald     // check if we have been aware of the HCI connection
26331f34df2cSMatthias Ringwald     switch (conn->state){
26341a4fdac4SMatthias Ringwald         case SENT_CREATE_CONNECTION:
26351f34df2cSMatthias Ringwald         case RECEIVED_CONNECTION_REQUEST:
26369071873aSMatthias Ringwald         case ACCEPTED_CONNECTION_REQUEST:
26371f34df2cSMatthias Ringwald             break;
26381f34df2cSMatthias Ringwald         default:
26391f34df2cSMatthias Ringwald             return;
26401f34df2cSMatthias Ringwald     }
26413bb5ff27SMatthias Ringwald 
2642229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
26430bbba85bSMatthias Ringwald     bd_addr_t bd_address;
26446535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
26450bbba85bSMatthias Ringwald 
26466bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
26476bc9fa5eSMatthias Ringwald     // cache needed data
26486bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
26496bc9fa5eSMatthias Ringwald #endif
26506bc9fa5eSMatthias Ringwald 
26510bbba85bSMatthias Ringwald     // connection failed, remove entry
26520bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
26530bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
26540bbba85bSMatthias Ringwald 
26556bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
26560bbba85bSMatthias Ringwald     // notify client if dedicated bonding
26570bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
26580bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
26590bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
26600bbba85bSMatthias Ringwald     }
26610bbba85bSMatthias Ringwald 
26620bbba85bSMatthias Ringwald     // if authentication error, also delete link key
26630bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
26640bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
26650bbba85bSMatthias Ringwald     }
26661c79b5e3SMatthias Ringwald #else
26671c79b5e3SMatthias Ringwald     UNUSED(status);
26686bc9fa5eSMatthias Ringwald #endif
26690bbba85bSMatthias Ringwald }
2670f0f95544SMatthias Ringwald #endif
2671f0f95544SMatthias Ringwald 
26720bbba85bSMatthias Ringwald 
2673be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
26742f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
26752f5c44baSMatthias Ringwald     // SSP Controller
26762f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
26772f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
26782f5c44baSMatthias Ringwald     }
26792f5c44baSMatthias Ringwald     // eSCO
26802f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
26812f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
26822f5c44baSMatthias Ringwald     }
26832f5c44baSMatthias Ringwald     // Extended features
26842f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
26852f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
26862f5c44baSMatthias Ringwald     }
26870b78a447SMatthias Ringwald     // SCO packet types
26880b78a447SMatthias Ringwald     conn->remote_supported_sco_packets = hci_sco_packet_types_for_features(features);
26892f5c44baSMatthias Ringwald }
26902f5c44baSMatthias Ringwald 
26912f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
26922f5c44baSMatthias Ringwald     // SSP Host
26932f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
26942f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
26952f5c44baSMatthias Ringwald     }
269650c51a77SMatthias Ringwald     // SC Host
269750c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
269850c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
269950c51a77SMatthias Ringwald     }
270050c51a77SMatthias Ringwald }
270150c51a77SMatthias Ringwald 
270250c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
270350c51a77SMatthias Ringwald     // SC Controller
270450c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
270550c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
270650c51a77SMatthias Ringwald     }
27072f5c44baSMatthias Ringwald }
27082f5c44baSMatthias Ringwald 
2709de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
2710461a2bc4SMatthias Ringwald     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2711de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2712cb7b3e6fSMatthias Ringwald     log_info("Remote features %02x, bonding flags %" PRIx32, conn->remote_supported_features[0], conn->bonding_flags);
2713de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
2714de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2715de0df013SMatthias Ringwald     }
2716de0df013SMatthias Ringwald }
2717128825c3SMatthias Ringwald static bool hci_remote_sc_enabled(hci_connection_t * connection){
2718128825c3SMatthias Ringwald     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2719128825c3SMatthias Ringwald     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2720128825c3SMatthias Ringwald }
2721128825c3SMatthias Ringwald 
2722be500194SMatthias Ringwald #endif
2723de0df013SMatthias Ringwald 
272467c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
272567c6c9dcSMatthias Ringwald     // handle BT initialization
272667c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
272767c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
272867c6c9dcSMatthias Ringwald     }
272967c6c9dcSMatthias Ringwald 
273067c6c9dcSMatthias Ringwald     // help with BT sleep
273167c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
273267c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
273372a2585aSMatthias Ringwald         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
273472a2585aSMatthias Ringwald         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
273567c6c9dcSMatthias Ringwald         hci_initializing_next_state();
273667c6c9dcSMatthias Ringwald     }
273767c6c9dcSMatthias Ringwald }
273867c6c9dcSMatthias Ringwald 
27399866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
27404aa2f135SMatthias Ringwald static void hci_handle_mutual_authentication_completed(hci_connection_t * conn){
27414aa2f135SMatthias Ringwald     // bonding complete if connection is authenticated (either initiated or BR/EDR SC)
27424aa2f135SMatthias Ringwald     conn->requested_security_level = LEVEL_0;
27434aa2f135SMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_connection(conn);
27444aa2f135SMatthias Ringwald     hci_emit_security_level(conn->con_handle, security_level);
27454aa2f135SMatthias Ringwald 
274667718330SMatthias Ringwald     // dedicated bonding
2747de9f0299SMatthias Ringwald     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2748de9f0299SMatthias Ringwald         conn->bonding_flags &= ~BONDING_DEDICATED;
2749de9f0299SMatthias Ringwald         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2750db3c1f89SMatthias Ringwald #ifdef ENABLE_EXPLICIT_DEDICATED_BONDING_DISCONNECT
2751db3c1f89SMatthias Ringwald         // emit dedicated bonding complete, don't disconnect
2752db3c1f89SMatthias Ringwald         hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2753db3c1f89SMatthias Ringwald #else
2754db3c1f89SMatthias Ringwald         // request disconnect, event is emitted after disconnect
2755db3c1f89SMatthias Ringwald         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2756db3c1f89SMatthias Ringwald #endif
2757de9f0299SMatthias Ringwald     }
275867718330SMatthias Ringwald }
2759abdad579SMatthias Ringwald 
276067718330SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
276167718330SMatthias Ringwald     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
276267718330SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
276367718330SMatthias Ringwald 
276467718330SMatthias Ringwald     // mutual authentication complete if authenticated and we have retrieved the encryption key size
27658daf94bcSMatthias Ringwald     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
27664aa2f135SMatthias Ringwald         hci_handle_mutual_authentication_completed(conn);
27674cd03f8aSMatthias Ringwald     } else {
27684cd03f8aSMatthias Ringwald         // otherwise trigger remote feature request and send authentication request
2769dbe0d85cSMatthias Ringwald         hci_trigger_remote_features_for_connection(conn);
27704cd03f8aSMatthias Ringwald         if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) {
2771abdad579SMatthias Ringwald             conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
27729866fdc7SMatthias Ringwald         }
27734cd03f8aSMatthias Ringwald     }
27744cd03f8aSMatthias Ringwald }
27759866fdc7SMatthias Ringwald #endif
27769866fdc7SMatthias Ringwald 
27773b631737SMatthias Ringwald static void hci_store_local_supported_commands(const uint8_t * packet){
277825e46151SMatthias Ringwald     // create mapping table
277925e46151SMatthias Ringwald #define X(name, offset, bit) { offset, bit },
278025e46151SMatthias Ringwald     static struct {
278125e46151SMatthias Ringwald         uint8_t byte_offset;
278225e46151SMatthias Ringwald         uint8_t bit_position;
278325e46151SMatthias Ringwald     } supported_hci_commands_map [] = {
278425e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
278525e46151SMatthias Ringwald     };
278625e46151SMatthias Ringwald #undef X
278725e46151SMatthias Ringwald 
278825e46151SMatthias Ringwald     // create names for debug purposes
278925e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
279025e46151SMatthias Ringwald #define X(name, offset, bit) #name,
279125e46151SMatthias Ringwald     static const char * command_names[] = {
279225e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
279325e46151SMatthias Ringwald     };
279425e46151SMatthias Ringwald #undef X
279525e46151SMatthias Ringwald #endif
279625e46151SMatthias Ringwald 
27971ffa425cSMatthias Ringwald     hci_stack->local_supported_commands = 0;
279825e46151SMatthias Ringwald     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
279925e46151SMatthias Ringwald     uint16_t i;
280025e46151SMatthias Ringwald     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
280125e46151SMatthias Ringwald         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
280225e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
2803345352acSMatthias Ringwald             log_debug("Command %s (%u) supported %u/%u", command_names[i], i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
280425e46151SMatthias Ringwald #else
28051ffa425cSMatthias Ringwald             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
280625e46151SMatthias Ringwald #endif
28071ffa425cSMatthias Ringwald             hci_stack->local_supported_commands |= (1LU << i);
280825e46151SMatthias Ringwald         }
280925e46151SMatthias Ringwald     }
2810cb7b3e6fSMatthias Ringwald     log_info("Local supported commands summary %08" PRIx32, hci_stack->local_supported_commands);
28113b631737SMatthias Ringwald }
28123b631737SMatthias Ringwald 
28134f781026SMatthias Ringwald static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2814b08371a9SMilanka Ringwald     UNUSED(size);
2815e76a89eeS[email protected] 
28164781fa78SDirk Helbig     uint8_t status = 0;
28174781fa78SDirk Helbig     if( size > OFFSET_OF_DATA_IN_COMMAND_COMPLETE ) {
28184781fa78SDirk Helbig         status = hci_event_command_complete_get_return_parameters(packet)[0];
28194781fa78SDirk Helbig     }
28209cbd2215SMatthias Ringwald     uint16_t manufacturer;
28219cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
28221f7b95a1Smatthias.ringwald     hci_connection_t * conn;
2823c7a108afSMatthias Ringwald #endif
282436916f81SDirk Helbig #if defined(ENABLE_CLASSIC)
28254781fa78SDirk Helbig     hci_con_handle_t handle;
28269cbd2215SMatthias Ringwald #endif
2827d3a89d91SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2828d3a89d91SMatthias Ringwald     le_audio_cig_t * cig;
2829d3a89d91SMatthias Ringwald #endif
283091036612SMatthias Ringwald #if defined(ENABLE_BLE) && defined(ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
2831f48a5586SMatthias Ringwald     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
2832f48a5586SMatthias Ringwald #endif
2833d3a89d91SMatthias Ringwald 
28346bef4003SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
28356bef4003SMatthias Ringwald     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
28367ec5eeaaSmatthias.ringwald 
2837645b7c25SMatthias Ringwald     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2838645b7c25SMatthias Ringwald     switch (opcode){
2839645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
28404781fa78SDirk Helbig             if (status) break;
28419e263bd7SMatthias Ringwald             // terminate, name 248 chars
28429e263bd7SMatthias Ringwald             packet[6+248] = 0;
28439e263bd7SMatthias Ringwald             log_info("local name: %s", &packet[6]);
2844645b7c25SMatthias Ringwald             break;
2845645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
28461d279b20Smatthias.ringwald             // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
2847c3b46f5aSMatthias Ringwald             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2848429122ccSMatthias Ringwald                 uint16_t acl_len = little_endian_read_16(packet, 6);
2849429122ccSMatthias Ringwald                 uint16_t sco_len = packet[8];
2850429122ccSMatthias Ringwald 
2851429122ccSMatthias Ringwald                 // determine usable ACL/SCO payload size
2852429122ccSMatthias Ringwald                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2853429122ccSMatthias Ringwald                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2854429122ccSMatthias Ringwald 
2855616cfd90SMatthias Ringwald                 hci_stack->acl_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet,  9), MAX_NR_CONTROLLER_ACL_BUFFERS);
2856616cfd90SMatthias Ringwald                 hci_stack->sco_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet, 11), MAX_NR_CONTROLLER_SCO_PACKETS);
2857a8b12447S[email protected] 
2858429122ccSMatthias Ringwald                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2859429122ccSMatthias Ringwald                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
28601a06f663S[email protected]                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2861c3b46f5aSMatthias Ringwald             }
2862645b7c25SMatthias Ringwald             break;
2863645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_RSSI:
28644781fa78SDirk Helbig             if (status == ERROR_CODE_SUCCESS){
2865891b9fc2SMatthias Ringwald                 uint8_t event[5];
2866891b9fc2SMatthias Ringwald                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2867891b9fc2SMatthias Ringwald                 event[1] = 3;
28686535961aSMatthias Ringwald                 (void)memcpy(&event[2], &packet[6], 3);
28699da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
2870891b9fc2SMatthias Ringwald             }
2871645b7c25SMatthias Ringwald             break;
2872a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
287379b7ea2dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
287479b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
287579b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_total_num = packet[11];
287679b7ea2dSMatthias Ringwald             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
287779b7ea2dSMatthias Ringwald                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
287879b7ea2dSMatthias Ringwald 
287979b7ea2dSMatthias Ringwald             /* fall through */
288079b7ea2dSMatthias Ringwald 
2881645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2882f8fbdce0SMatthias Ringwald             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2883ee303eddS[email protected]             hci_stack->le_acl_packets_total_num = packet[8];
28846c26b087S[email protected]             // determine usable ACL payload size
28856c26b087S[email protected]             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
28866c26b087S[email protected]                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
28876c26b087S[email protected]             }
288879b7ea2dSMatthias Ringwald             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);
2889645b7c25SMatthias Ringwald             break;
2890b435e062SMatthias Ringwald #endif
2891b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2892645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2893dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2894dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2895dcd678baSMatthias Ringwald             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);
2896645b7c25SMatthias Ringwald             break;
2897b435e062SMatthias Ringwald #endif
2898d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2899645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2900e691bb38SMatthias Ringwald             hci_stack->le_whitelist_capacity = packet[6];
290115d0a15bSMatthias Ringwald             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2902645b7c25SMatthias Ringwald             break;
290365a46ef3S[email protected] #endif
29043a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
29053a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
29063a74541eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
29073a74541eSMatthias Ringwald             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
29083a74541eSMatthias Ringwald             break;
290925df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
291025df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
291125df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
291225df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
291325df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
291425df6c61SMatthias Ringwald                 uint8_t adv_status = packet[6];
291525df6c61SMatthias Ringwald                 uint8_t tx_power   = packet[7];
291625df6c61SMatthias Ringwald                 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 };
291725df6c61SMatthias Ringwald                 if (adv_status == 0){
291825df6c61SMatthias Ringwald                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
291925df6c61SMatthias Ringwald                 }
29209da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
292125df6c61SMatthias Ringwald             }
292225df6c61SMatthias Ringwald             break;
292325df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
292425df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
292525df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
292625df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
292725df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
29284781fa78SDirk Helbig                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, status };
29294781fa78SDirk Helbig                 if (status == 0){
293025df6c61SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
293125df6c61SMatthias Ringwald                 }
29329da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
293325df6c61SMatthias Ringwald             }
293425df6c61SMatthias Ringwald             break;
29353a74541eSMatthias Ringwald #endif
29363a74541eSMatthias Ringwald #endif
2937645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BD_ADDR:
2938645b7c25SMatthias Ringwald             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
29394781fa78SDirk Helbig             log_info("Local Address, Status: 0x%02x: Addr: %s", status, bd_addr_to_str(hci_stack->local_bd_addr));
294033373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
29411624665aSMatthias Ringwald             if (hci_stack->link_key_db){
29421624665aSMatthias Ringwald                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
29431624665aSMatthias Ringwald             }
294433373e40SMatthias Ringwald #endif
2945645b7c25SMatthias Ringwald             break;
294635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2947645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
294871fd255dSMatthias Ringwald             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2949645b7c25SMatthias Ringwald             break;
29503d1f2d24SMatthias Ringwald         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
29513d1f2d24SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
29523d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
29533d1f2d24SMatthias Ringwald             } else {
29543d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
29553d1f2d24SMatthias Ringwald             }
29563d1f2d24SMatthias Ringwald             break;
2957645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
295830199e24SMatthias Ringwald         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2959f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2960f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2961f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
29629da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
2963f5875de5SMatthias Ringwald             }
2964645b7c25SMatthias Ringwald             break;
296535454696SMatthias Ringwald #endif
2966645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
29674f781026SMatthias Ringwald             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
296865389bfcS[email protected] 
296935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2970a5a23fc2S[email protected]             // determine usable ACL packet types based on host buffer size and supported features
297129e39de4SMatthias Ringwald             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]);
2972c92ca2c8SMatthias Ringwald             log_info("ACL Packet types %04x", hci_stack->usable_packet_types_acl);
2973c92ca2c8SMatthias Ringwald             // determine usable SCO packet types based on supported features
2974c92ca2c8SMatthias Ringwald             hci_stack->usable_packet_types_sco = hci_sco_packet_types_for_features(
2975c92ca2c8SMatthias Ringwald                     &hci_stack->local_supported_features[0]);
2976c92ca2c8SMatthias Ringwald             log_info("SCO Packet types %04x - eSCO %u", hci_stack->usable_packet_types_sco, hci_extended_sco_link_supported());
297735454696SMatthias Ringwald #endif
2978f5d8d141S[email protected]             // Classic/LE
2979f5d8d141S[email protected]             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2980645b7c25SMatthias Ringwald             break;
2981645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2982645b7c25SMatthias Ringwald             manufacturer = little_endian_read_16(packet, 10);
2983547a29a6SMatthias Ringwald             // map Cypress & Infineon to Broadcom
2984547a29a6SMatthias Ringwald             switch (manufacturer){
2985547a29a6SMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR:
2986547a29a6SMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_INFINEON_TECHNOLOGIES_AG:
2987547a29a6SMatthias Ringwald                     log_info("Treat Cypress/Infineon as Broadcom");
2988c21d89f3SMatthias Ringwald                     manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2989c21d89f3SMatthias Ringwald                     little_endian_store_16(packet, 10, manufacturer);
2990547a29a6SMatthias Ringwald                     break;
2991547a29a6SMatthias Ringwald                 default:
2992547a29a6SMatthias Ringwald                     break;
2993c21d89f3SMatthias Ringwald             }
2994c21d89f3SMatthias Ringwald             hci_stack->manufacturer = manufacturer;
29954696bddbSMatthias Ringwald             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2996645b7c25SMatthias Ringwald             break;
2997645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
29983b631737SMatthias Ringwald             hci_store_local_supported_commands(packet);
2999645b7c25SMatthias Ringwald             break;
3000e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
3001645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
30024781fa78SDirk Helbig             if (status) return;
30035b9b590fSMatthias Ringwald             hci_stack->synchronous_flow_control_enabled = 1;
3004645b7c25SMatthias Ringwald             break;
3005645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
3006573897a0SMatthias Ringwald             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
3007573897a0SMatthias Ringwald             conn   = hci_connection_for_handle(handle);
3008c3b46f5aSMatthias Ringwald             if (conn != NULL) {
30099866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
3010573897a0SMatthias Ringwald                 if (status == 0){
30119866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
30124a659b0eSMatthias Ringwald                     log_info("Handle %04x key Size: %u", handle, key_size);
3013170fafaeSMatthias Ringwald                 } else {
3014e9f98c4aSMatthias Ringwald                     key_size = 1;
30159866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
3016573897a0SMatthias Ringwald                 }
30179866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
3018c3b46f5aSMatthias Ringwald             }
3019645b7c25SMatthias Ringwald             break;
3020cc15bb2cSMatthias Ringwald         // assert pairing complete event is emitted.
3021cc15bb2cSMatthias Ringwald         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
3022cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
3023cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
3024cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
30258cc1507eSMatthias Ringwald             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3026cc15bb2cSMatthias Ringwald             // lookup connection by gap pairing addr
3027cc15bb2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
3028cc15bb2cSMatthias Ringwald             if (conn == NULL) break;
3029cc15bb2cSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
3030cc15bb2cSMatthias Ringwald             break;
3031cc15bb2cSMatthias Ringwald 
303275a8e4faSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
303375a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
303475a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
303575a8e4faSMatthias Ringwald             uint8_t event[67];
303675a8e4faSMatthias Ringwald             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
303775a8e4faSMatthias Ringwald             event[1] = 65;
303875a8e4faSMatthias Ringwald             (void)memset(&event[2], 0, 65);
30394781fa78SDirk Helbig             if (status == ERROR_CODE_SUCCESS){
304075a8e4faSMatthias Ringwald                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
304175a8e4faSMatthias Ringwald                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
304275a8e4faSMatthias Ringwald                     event[2] = 3;
304375a8e4faSMatthias Ringwald                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
304475a8e4faSMatthias Ringwald                 } else {
304575a8e4faSMatthias Ringwald                     event[2] = 1;
304675a8e4faSMatthias Ringwald                 }
304775a8e4faSMatthias Ringwald             }
30489da9850bSMatthias Ringwald             hci_emit_btstack_event(event, sizeof(event), 0);
304975a8e4faSMatthias Ringwald             break;
305075a8e4faSMatthias Ringwald         }
30511ae74bf3SMatthias Ringwald 
30521ae74bf3SMatthias Ringwald         // note: only needed if user does not provide OOB data
30531ae74bf3SMatthias Ringwald         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
30541ae74bf3SMatthias Ringwald             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
30551ae74bf3SMatthias Ringwald             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
30561ae74bf3SMatthias Ringwald             if (conn == NULL) break;
30571ae74bf3SMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
30581ae74bf3SMatthias Ringwald             break;
3059e8c8828eSMatthias Ringwald #endif
306075a8e4faSMatthias Ringwald #endif
30614ae8623eSMatthias Ringwald #ifdef ENABLE_BLE
30624ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3063d3a89d91SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_CIG_PARAMETERS:
3064d3a89d91SMatthias Ringwald             // lookup CIG
3065d3a89d91SMatthias Ringwald             cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3066d3a89d91SMatthias Ringwald             if (cig != NULL){
3067d3a89d91SMatthias Ringwald                 if (status == ERROR_CODE_SUCCESS){
30685a723302SMatthias Ringwald                     uint8_t i;
30695a723302SMatthias Ringwald                     for (i=0;i<cig->num_cis;i++) {
3070d3a89d91SMatthias Ringwald                         // assign CIS handles to pre-allocated CIS
30715a723302SMatthias Ringwald                         uint8_t cis_id = cig->params->cis_params[i].cis_id;
3072d3a89d91SMatthias Ringwald                         btstack_linked_list_iterator_t it;
3073d3a89d91SMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3074d3a89d91SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) {
3075d3a89d91SMatthias Ringwald                             hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3076d3a89d91SMatthias Ringwald                             if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) &&
30775a723302SMatthias Ringwald                                 (iso_stream->iso_type == HCI_ISO_TYPE_CIS) &&
30785a723302SMatthias Ringwald                                 (iso_stream->stream_id == cis_id)){
3079d3a89d91SMatthias Ringwald                                 hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i));
3080969d876aSMatthias Ringwald                                 iso_stream->cis_handle  = cis_handle;
3081d3a89d91SMatthias Ringwald                                 cig->cis_con_handles[i] = cis_handle;
30825a723302SMatthias Ringwald                                 break;
30835a723302SMatthias Ringwald                             }
3084d3a89d91SMatthias Ringwald                         }
3085d3a89d91SMatthias Ringwald                     }
3086444e371eSMatthias Ringwald                     cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST;
3087d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
3088d3a89d91SMatthias Ringwald                 } else {
3089d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
3090d3a89d91SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
3091d3a89d91SMatthias Ringwald                 }
3092d3a89d91SMatthias Ringwald             }
309326b93350SMatthias Ringwald             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3094d3a89d91SMatthias Ringwald             break;
30954ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
30964ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3097d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
30984ae8623eSMatthias Ringwald             }
30994ae8623eSMatthias Ringwald             break;
310042529435SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
310142529435SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3102d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
310342529435SMatthias Ringwald             }
310442529435SMatthias Ringwald             break;
31057aa35f6aSMatthias Ringwald         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
31067aa35f6aSMatthias Ringwald             // lookup BIG by state
31077aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_t it;
31087aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
31097aa35f6aSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
31107aa35f6aSMatthias Ringwald                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
31117aa35f6aSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
31127aa35f6aSMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
31137aa35f6aSMatthias Ringwald                         big->state_vars.next_bis++;
31147aa35f6aSMatthias Ringwald                         if (big->state_vars.next_bis == big->num_bis){
31157aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
31167aa35f6aSMatthias Ringwald                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
31177aa35f6aSMatthias Ringwald                         } else {
31187aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
31197aa35f6aSMatthias Ringwald                         }
31207aa35f6aSMatthias Ringwald                     } else {
31217aa35f6aSMatthias Ringwald                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
31227aa35f6aSMatthias Ringwald                         big->state_vars.status = status;
31232a6c0f82SMatthias Ringwald                     }
31242a6c0f82SMatthias Ringwald                     return;
31252a6c0f82SMatthias Ringwald                 }
31262a6c0f82SMatthias Ringwald             }
31272a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
31282a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
31292a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
31302a6c0f82SMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
31312a6c0f82SMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
31322a6c0f82SMatthias Ringwald                         big_sync->state_vars.next_bis++;
31332a6c0f82SMatthias Ringwald                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
31342a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
31352a6c0f82SMatthias Ringwald                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
31362a6c0f82SMatthias Ringwald                         } else {
31372a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
31382a6c0f82SMatthias Ringwald                         }
31392a6c0f82SMatthias Ringwald                     } else {
31402a6c0f82SMatthias Ringwald                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
31412a6c0f82SMatthias Ringwald                         big_sync->state_vars.status = status;
31422a6c0f82SMatthias Ringwald                     }
31432a6c0f82SMatthias Ringwald                     return;
31442a6c0f82SMatthias Ringwald                 }
31452a6c0f82SMatthias Ringwald             }
3146f9306a1aSMatthias Ringwald             // Lookup CIS via active group operation
3147f9306a1aSMatthias Ringwald             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
314826b93350SMatthias Ringwald                 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
314926b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
315026b93350SMatthias Ringwald 
315126b93350SMatthias Ringwald                     // lookup CIS by state
315226b93350SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
315326b93350SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it)){
315426b93350SMatthias Ringwald                         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3155532211feSMatthias Ringwald                         bool emit_cis_created = false;
315626b93350SMatthias Ringwald                         switch (iso_stream->state){
315726b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT:
315826b93350SMatthias Ringwald                                 if (status != ERROR_CODE_SUCCESS){
3159532211feSMatthias Ringwald                                     emit_cis_created = true;
316026b93350SMatthias Ringwald                                     break;
316126b93350SMatthias Ringwald                                 }
316226b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_c_to_p > 0){
31631418332dSMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
316426b93350SMatthias Ringwald                                 } else {
3165532211feSMatthias Ringwald                                     emit_cis_created = true;
316626b93350SMatthias Ringwald                                 }
316726b93350SMatthias Ringwald                                 break;
316826b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT:
316900220a2bSMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_ACTIVE;
3170532211feSMatthias Ringwald                                 emit_cis_created = true;
317126b93350SMatthias Ringwald                                 break;
317226b93350SMatthias Ringwald                             default:
317326b93350SMatthias Ringwald                                 break;
317426b93350SMatthias Ringwald                         }
3175532211feSMatthias Ringwald                         if (emit_cis_created){
317614045fdbSMatthias Ringwald                             hci_cis_handle_created(iso_stream, status);
3177532211feSMatthias Ringwald                         }
317826b93350SMatthias Ringwald                     }
317926b93350SMatthias Ringwald                 } else {
3180f9306a1aSMatthias Ringwald                     cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3181532211feSMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3182f9306a1aSMatthias Ringwald                     if (cig != NULL) {
3183f9306a1aSMatthias Ringwald                         // emit cis created if all ISO Paths have been created
3184f9306a1aSMatthias Ringwald                         // assume we are central
3185f9306a1aSMatthias Ringwald                         uint8_t cis_index     = cig->state_vars.next_cis >> 1;
3186f9306a1aSMatthias Ringwald                         uint8_t cis_direction = cig->state_vars.next_cis & 1;
31875a723302SMatthias Ringwald                         uint8_t cis_id        = cig->params->cis_params[cis_index].cis_id;
3188f9306a1aSMatthias Ringwald                         bool outgoing_needed  = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
3189f9306a1aSMatthias Ringwald                         // if outgoing has been setup, or incoming was setup but outgoing not required
3190f9306a1aSMatthias Ringwald                         if ((cis_direction == 1) || (outgoing_needed == false)){
3191532211feSMatthias Ringwald                             // lookup iso stream by cig/cis
3192b5ecaedbSMatthias Ringwald                             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3193532211feSMatthias Ringwald                             while (btstack_linked_list_iterator_has_next(&it)) {
3194532211feSMatthias Ringwald                                 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
31955a723302SMatthias Ringwald                                 if ((iso_stream->group_id == cig->cig_id) && (iso_stream->stream_id == cis_id)){
319614045fdbSMatthias Ringwald                                     hci_cis_handle_created(iso_stream, status);
3197532211feSMatthias Ringwald                                 }
3198532211feSMatthias Ringwald                             }
3199f9306a1aSMatthias Ringwald                         }
3200f9306a1aSMatthias Ringwald                         // next state
3201f9306a1aSMatthias Ringwald                         cig->state_vars.next_cis++;
3202f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
3203f9306a1aSMatthias Ringwald                     }
3204f9306a1aSMatthias Ringwald                 }
320526b93350SMatthias Ringwald             }
32062a6c0f82SMatthias Ringwald             break;
32072a6c0f82SMatthias Ringwald         }
32082a6c0f82SMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
32092a6c0f82SMatthias Ringwald             // lookup BIG by state
32102a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_t it;
32112a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
32122a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
32132a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3214d04a9afcSMatthias Ringwald                 uint8_t big_handle = big_sync->big_handle;
32152a6c0f82SMatthias Ringwald                 switch (big_sync->state){
32162a6c0f82SMatthias Ringwald                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3217d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
32182a6c0f82SMatthias Ringwald                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
3219d04a9afcSMatthias Ringwald                         return;
32202a6c0f82SMatthias Ringwald                     default:
3221d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
3222d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
32237aa35f6aSMatthias Ringwald                         return;
32247aa35f6aSMatthias Ringwald                 }
32257aa35f6aSMatthias Ringwald             }
32267aa35f6aSMatthias Ringwald             break;
32277aa35f6aSMatthias Ringwald         }
32284ae8623eSMatthias Ringwald #endif
32294ae8623eSMatthias Ringwald #endif
32306f35bb46SMatthias Ringwald         default:
32316f35bb46SMatthias Ringwald             break;
32324f781026SMatthias Ringwald     }
3233645b7c25SMatthias Ringwald }
32344f781026SMatthias Ringwald 
3235d8905293SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3236d8905293SMatthias Ringwald static void
3237d8905293SMatthias Ringwald hci_iso_create_big_failed(const le_audio_big_t *big, uint8_t status) {
3238d8905293SMatthias Ringwald     hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
3239d8905293SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3240d8905293SMatthias Ringwald     if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
3241d8905293SMatthias Ringwald         hci_emit_big_created(big, status);
3242d8905293SMatthias Ringwald     } else {
3243d8905293SMatthias Ringwald         hci_emit_big_terminated(big);
3244d8905293SMatthias Ringwald     }
3245d8905293SMatthias Ringwald }
3246d8905293SMatthias Ringwald 
3247d8905293SMatthias Ringwald static void hci_iso_big_sync_failed(const le_audio_big_sync_t *big_sync, uint8_t status) {
3248d8905293SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
3249d8905293SMatthias Ringwald     if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3250d8905293SMatthias Ringwald         hci_emit_big_sync_created(big_sync, status);
3251d8905293SMatthias Ringwald     } else {
3252d8905293SMatthias Ringwald         hci_emit_big_sync_stopped(big_sync->big_handle);
3253d8905293SMatthias Ringwald     }
3254d8905293SMatthias Ringwald }
3255d8905293SMatthias Ringwald #endif
3256d8905293SMatthias Ringwald 
3257afbf1cd7SMatthias Ringwald static void handle_command_status_event(uint8_t * packet, uint16_t size) {
3258afbf1cd7SMatthias Ringwald     UNUSED(size);
3259afbf1cd7SMatthias Ringwald 
3260afbf1cd7SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
3261afbf1cd7SMatthias Ringwald     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
3262afbf1cd7SMatthias Ringwald 
3263c70df5f8SMatthias Ringwald     // get opcode and command status
3264c70df5f8SMatthias Ringwald     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
3265c70df5f8SMatthias Ringwald 
3266c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
3267c70df5f8SMatthias Ringwald     uint8_t status = hci_event_command_status_get_status(packet);
3268c70df5f8SMatthias Ringwald #endif
3269c70df5f8SMatthias Ringwald 
3270c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3271c70df5f8SMatthias Ringwald     bd_addr_type_t addr_type;
327273bccf35Slouislee91     bd_addr_t addr;
3273c70df5f8SMatthias Ringwald #endif
3274c70df5f8SMatthias Ringwald 
327591036612SMatthias Ringwald #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
3276f48a5586SMatthias Ringwald     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
3277f48a5586SMatthias Ringwald #endif
3278f48a5586SMatthias Ringwald 
3279c70df5f8SMatthias Ringwald     switch (opcode){
3280afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3281c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
32829071873aSMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
3283c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
3284afbf1cd7SMatthias Ringwald #endif
3285afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3286c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
3287afbf1cd7SMatthias Ringwald #endif
3288c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3289afbf1cd7SMatthias Ringwald             addr_type = hci_stack->outgoing_addr_type;
329073bccf35Slouislee91             memcpy(addr, hci_stack->outgoing_addr, 6);
3291afbf1cd7SMatthias Ringwald 
3292afbf1cd7SMatthias Ringwald             // reset outgoing address info
3293afbf1cd7SMatthias Ringwald             memset(hci_stack->outgoing_addr, 0, 6);
3294afbf1cd7SMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
3295afbf1cd7SMatthias Ringwald 
3296afbf1cd7SMatthias Ringwald             // on error
3297afbf1cd7SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3298afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3299afbf1cd7SMatthias Ringwald                 if (hci_is_le_connection_type(addr_type)){
3300afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3301afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3302afbf1cd7SMatthias Ringwald                 }
3303afbf1cd7SMatthias Ringwald #endif
3304afbf1cd7SMatthias Ringwald                 // error => outgoing connection failed
330573bccf35Slouislee91                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3306afbf1cd7SMatthias Ringwald                 if (conn != NULL){
3307afbf1cd7SMatthias Ringwald                     hci_handle_connection_failed(conn, status);
3308afbf1cd7SMatthias Ringwald                 }
3309afbf1cd7SMatthias Ringwald             }
3310c70df5f8SMatthias Ringwald             break;
3311c70df5f8SMatthias Ringwald #endif
3312afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3313c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY:
3314afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
3315afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3316afbf1cd7SMatthias Ringwald             } else {
3317afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3318afbf1cd7SMatthias Ringwald             }
3319c70df5f8SMatthias Ringwald             break;
3320c70df5f8SMatthias Ringwald #endif
3321afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3322c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3323c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3324afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS){
3325d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID);
3326afbf1cd7SMatthias Ringwald             } else {
3327d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3328afbf1cd7SMatthias Ringwald             }
3329c70df5f8SMatthias Ringwald             break;
333015f9bb6dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_BIG:
333115f9bb6dSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
333215f9bb6dSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3333d8905293SMatthias Ringwald                 // get current big
3334d8905293SMatthias Ringwald                 le_audio_big_t * big = hci_big_for_handle(hci_stack->iso_active_operation_group_id);
3335d8905293SMatthias Ringwald                 if (big != NULL){
3336d8905293SMatthias Ringwald                     hci_iso_create_big_failed(big, status);
3337d8905293SMatthias Ringwald                 }
333815f9bb6dSMatthias Ringwald             }
333915f9bb6dSMatthias Ringwald             break;
334015f9bb6dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_CREATE_SYNC:
334115f9bb6dSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
334215f9bb6dSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3343d8905293SMatthias Ringwald                 // get current big sync
3344d8905293SMatthias Ringwald                 le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(hci_stack->iso_active_operation_group_id);
3345d8905293SMatthias Ringwald                 if (big_sync != NULL){
3346d8905293SMatthias Ringwald                     hci_iso_big_sync_failed(big_sync, status);
3347d8905293SMatthias Ringwald                 }
334815f9bb6dSMatthias Ringwald             }
334915f9bb6dSMatthias Ringwald             break;
3350afbf1cd7SMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3351c70df5f8SMatthias Ringwald         default:
3352c70df5f8SMatthias Ringwald             break;
3353c70df5f8SMatthias Ringwald     }
3354afbf1cd7SMatthias Ringwald }
3355afbf1cd7SMatthias Ringwald 
33560ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
3357e4def797SMatthias Ringwald static void hci_create_gap_connection_complete_event(const uint8_t * hci_event, uint8_t * gap_event) {
3358e4def797SMatthias Ringwald     gap_event[0] = HCI_EVENT_META_GAP;
3359e4def797SMatthias Ringwald     gap_event[1] = 36 - 2;
3360e4def797SMatthias Ringwald     gap_event[2] = GAP_SUBEVENT_LE_CONNECTION_COMPLETE;
3361bede2a55SMatthias Ringwald     switch (hci_event_le_meta_get_subevent_code(hci_event)){
3362a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3363e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 11);
3364e4def797SMatthias Ringwald             memset(&gap_event[14], 0, 12);
3365e4def797SMatthias Ringwald             memcpy(&gap_event[26], &hci_event[14], 7);
3366e4def797SMatthias Ringwald             memset(&gap_event[33], 0xff, 3);
33677efb077fSMatthias Ringwald             // Some Controllers incorrectly report a resolved identity address in HCI_SUBEVENT_LE_CONNECTION_COMPLETE.
33687efb077fSMatthias Ringwald             // If an address is resolved, we're working with it, but this event does not provide it.
33697efb077fSMatthias Ringwald             // As a workaround, we map identity addresses to regular addresses.
33707efb077fSMatthias Ringwald             gap_event[7] = gap_event[7] & 1;
3371a9212437SMatthias Ringwald             break;
3372a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
3373e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 30);
3374e4def797SMatthias Ringwald             memset(&gap_event[33], 0xff, 3);
3375a9212437SMatthias Ringwald             break;
3376a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
3377e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 33);
3378a9212437SMatthias Ringwald             break;
3379a9212437SMatthias Ringwald         default:
3380a9212437SMatthias Ringwald             btstack_unreachable();
3381a9212437SMatthias Ringwald             break;
3382a9212437SMatthias Ringwald     }
3383a9212437SMatthias Ringwald }
3384a9212437SMatthias Ringwald 
3385688bcdb4SMatthias Ringwald static void hci_handle_le_connection_complete_event(const uint8_t * hci_event){
338698e0165dSMatthias Ringwald     // create GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3387a9212437SMatthias Ringwald     uint8_t gap_event[36];
3388a9212437SMatthias Ringwald     hci_create_gap_connection_complete_event(hci_event, gap_event);
338960fb273dSMatthias Ringwald 
339098e0165dSMatthias Ringwald     // read fields
3391a9212437SMatthias Ringwald     uint8_t status = gap_subevent_le_connection_complete_get_status(gap_event);
3392a9212437SMatthias Ringwald     hci_role_t role = (hci_role_t) gap_subevent_le_connection_complete_get_role(gap_event);
3393a9212437SMatthias Ringwald     uint16_t conn_interval = gap_subevent_le_connection_complete_get_conn_interval(gap_event);
339498e0165dSMatthias Ringwald 
33950ce3f217SMatthias Ringwald 	// Connection management
3396138e942eSMatthias Ringwald     bd_addr_t addr;
3397a9212437SMatthias Ringwald     gap_subevent_le_connection_complete_get_peer_address(gap_event, addr);
3398138e942eSMatthias Ringwald     bd_addr_type_t addr_type = (bd_addr_type_t) gap_subevent_le_connection_complete_get_peer_address_type(gap_event);
3399138e942eSMatthias Ringwald     hci_con_handle_t con_handle = gap_subevent_le_connection_complete_get_connection_handle(gap_event);
340060fb273dSMatthias Ringwald     log_info("LE Connection_complete (status=%u) type %u, %s", status, addr_type, bd_addr_to_str(addr));
3401138e942eSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
34020ce3f217SMatthias Ringwald 
34030ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
34040ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
340560fb273dSMatthias Ringwald 	if (status){
34060ce3f217SMatthias Ringwald 
34070ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
34080ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
34090ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
34100ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
3411f24eac89SMatthias Ringwald         bool connection_was_cancelled = false;
341260fb273dSMatthias Ringwald 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3413f24eac89SMatthias Ringwald             connection_was_cancelled = true;
34141f468175SMatthias Ringwald 		    // reset state
34150ce3f217SMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
34160ce3f217SMatthias Ringwald             // get outgoing connection conn struct for direct connect
3417ca0d6e5aSMatthias Ringwald             conn = gap_get_outgoing_le_connection();
34181f4510f5SMatthias Ringwald             // prepare restart if still active
34191f4510f5SMatthias Ringwald             if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
34209fd274a1SMatthias Ringwald                 conn->state = SEND_CREATE_CONNECTION;
34219fd274a1SMatthias Ringwald             }
34220ce3f217SMatthias Ringwald 		}
34230ce3f217SMatthias Ringwald 
3424c1281a25SMatthias Ringwald 		// free connection if cancelled by user (request == IDLE)
3425f24eac89SMatthias Ringwald         bool cancelled_by_user = hci_stack->le_connecting_request == LE_CONNECTING_IDLE;
3426f24eac89SMatthias Ringwald 		if ((conn != NULL) && cancelled_by_user){
34270ce3f217SMatthias Ringwald 			// remove entry
34280ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
34290ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
34300ce3f217SMatthias Ringwald 		}
34314dbe0476SMatthias Ringwald 
3432f24eac89SMatthias Ringwald         // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE for:
3433f24eac89SMatthias Ringwald         // - outgoing error not caused by connection cancel
3434f24eac89SMatthias Ringwald         // - connection cancelled by user
3435f24eac89SMatthias Ringwald         // by this, no event is emitted for intermediate connection cancel required filterlist modification
3436f24eac89SMatthias Ringwald         if ((connection_was_cancelled == false) || cancelled_by_user){
34371f4510f5SMatthias Ringwald             hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
3438f24eac89SMatthias Ringwald         }
34390ce3f217SMatthias Ringwald         return;
34400ce3f217SMatthias Ringwald 	}
34410ce3f217SMatthias Ringwald #endif
34420ce3f217SMatthias Ringwald 
34430ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
344460fb273dSMatthias Ringwald     if (role == HCI_ROLE_MASTER){
34450ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
34465bb205a5SMatthias Ringwald 		// if we're master, it was an outgoing connection
34470ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
34485bb205a5SMatthias Ringwald 
3449a086dc35SMatthias Ringwald         // if an identity addresses was used without enhanced connection complete event,
345058babb64SMatthias Ringwald         // the connection complete event contains the current random address of the peer device.
345158babb64SMatthias Ringwald         // This random address is needed in the case of a re-pairing
345258babb64SMatthias Ringwald         if (hci_event_le_meta_get_subevent_code(hci_event) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE){
34535bb205a5SMatthias Ringwald             conn = gap_get_outgoing_le_connection();
345458babb64SMatthias Ringwald             // if outgoing connection object is available, check if identity address was used.
345558babb64SMatthias Ringwald             // if yes, track resolved random address and provide rpa
34565bb205a5SMatthias Ringwald             // note: we don't update hci le subevent connection complete
34575bb205a5SMatthias Ringwald             if (conn != NULL){
345858babb64SMatthias Ringwald                 if (hci_is_le_identity_address_type(conn->address_type)){
345958babb64SMatthias Ringwald                     memcpy(&gap_event[20], &gap_event[8], 6);
34605bb205a5SMatthias Ringwald                     gap_event[7] = conn->address_type;
34615bb205a5SMatthias Ringwald                     reverse_bd_addr(conn->address, &gap_event[8]);
34625bb205a5SMatthias Ringwald                 }
346358babb64SMatthias Ringwald             }
346458babb64SMatthias Ringwald         }
34655bb205a5SMatthias Ringwald 
34665bb205a5SMatthias Ringwald         // we're done with it
34670ce3f217SMatthias Ringwald         hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
34680ce3f217SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
34690ce3f217SMatthias Ringwald #endif
34700ce3f217SMatthias Ringwald 	} else {
34710ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
34722775f8e2SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
34732775f8e2SMatthias Ringwald         if (hci_le_extended_advertising_supported()) {
3474f7043595SMatthias Ringwald             // advertisement state managed with HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED
3475f7043595SMatthias Ringwald 
3476f7043595SMatthias Ringwald             // if advertisement set terminated event arrives before connection complete, connection struct has been prepared
3477f7043595SMatthias Ringwald             // set missing peer address + address type
3478f7043595SMatthias Ringwald             conn = hci_connection_for_handle(con_handle);
3479f7043595SMatthias Ringwald             if (conn != NULL){
3480f7043595SMatthias Ringwald                 memcpy(conn->address, addr, 6);
3481f7043595SMatthias Ringwald                 conn->address_type = addr_type;
3482f7043595SMatthias Ringwald             }
34832775f8e2SMatthias Ringwald         }
34842775f8e2SMatthias Ringwald         else
34852775f8e2SMatthias Ringwald #endif
34862775f8e2SMatthias Ringwald         {
34872775f8e2SMatthias Ringwald             // if we're slave, it was an incoming connection and advertisements have stopped
3488935aa76eSMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
34892775f8e2SMatthias Ringwald         }
34900ce3f217SMatthias Ringwald #endif
34910ce3f217SMatthias Ringwald 	}
34920ce3f217SMatthias Ringwald 
34930ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
34940ce3f217SMatthias Ringwald 	if (!conn){
349588f925b1SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
34960ce3f217SMatthias Ringwald 	}
34970ce3f217SMatthias Ringwald 
34980ce3f217SMatthias Ringwald 	// no memory, sorry.
34990ce3f217SMatthias Ringwald 	if (!conn){
35000ce3f217SMatthias Ringwald 		return;
35010ce3f217SMatthias Ringwald 	}
35020ce3f217SMatthias Ringwald 
35030ce3f217SMatthias Ringwald 	conn->state = OPEN;
3504138e942eSMatthias Ringwald 	conn->con_handle             = con_handle;
350560fb273dSMatthias Ringwald     conn->le_connection_interval = conn_interval;
35060ce3f217SMatthias Ringwald 
35074639b1e4SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3508ac0f6b83SMatthias Ringwald     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
35094639b1e4SMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_REMOTE_FEATURES)){
3510ac0f6b83SMatthias Ringwald         conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
35114639b1e4SMatthias Ringwald     }
35124639b1e4SMatthias Ringwald #endif
3513ac0f6b83SMatthias Ringwald 
35140ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
351560fb273dSMatthias Ringwald     if (role == HCI_ROLE_SLAVE){
35160ce3f217SMatthias Ringwald         hci_update_advertisements_enabled_for_current_roles();
35170ce3f217SMatthias Ringwald     }
35180ce3f217SMatthias Ringwald #endif
35190ce3f217SMatthias Ringwald 
3520dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
3521dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3522dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
3523dde9ff1eSMatthias Ringwald 
35240ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
35250ce3f217SMatthias Ringwald 
35260ce3f217SMatthias Ringwald 	// restart timer
35270ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
35280ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
35290ce3f217SMatthias Ringwald 
35300ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
35310ce3f217SMatthias Ringwald 
353298e0165dSMatthias Ringwald     // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE
35339da9850bSMatthias Ringwald     hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
353498e0165dSMatthias Ringwald 
353598e0165dSMatthias Ringwald     // emit BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
35360ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
35370ce3f217SMatthias Ringwald }
35380ce3f217SMatthias Ringwald #endif
35390ce3f217SMatthias Ringwald 
354017c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
354117c6fe5cSMatthias Ringwald 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){
354217c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
354317c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
35449a8f78c1SMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
35459a8f78c1SMatthias Ringwald     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
354617c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
35479a8f78c1SMatthias Ringwald         // MITM not possible without keyboard or display
354817c6fe5cSMatthias Ringwald         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
354917c6fe5cSMatthias Ringwald         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
35509a8f78c1SMatthias Ringwald 
35519a8f78c1SMatthias Ringwald         // MITM possible if one side has keyboard and the other has keyboard or display
35529a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
35539a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
35549a8f78c1SMatthias Ringwald 
35559a8f78c1SMatthias Ringwald         // MITM not possible if one side has only display and other side has no keyboard
35569a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
35579a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
355817c6fe5cSMatthias Ringwald     }
355917c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
356017c6fe5cSMatthias Ringwald     return true;
356117c6fe5cSMatthias Ringwald }
35623817f9dfSMatthias Ringwald 
3563b3c4163bSMatthias Ringwald static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
35642dd8985bSMatthias Ringwald     // get requested security level
35652dd8985bSMatthias Ringwald     gap_security_level_t requested_security_level = conn->requested_security_level;
35662dd8985bSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
35672dd8985bSMatthias Ringwald         requested_security_level = LEVEL_4;
35682dd8985bSMatthias Ringwald     }
35692dd8985bSMatthias Ringwald 
3570b3c4163bSMatthias Ringwald     // assess security: LEVEL 4 requires SC
35712dd8985bSMatthias Ringwald     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
35722dd8985bSMatthias Ringwald     if ((requested_security_level == LEVEL_4) &&
35732dd8985bSMatthias Ringwald         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
35742dd8985bSMatthias Ringwald         !hci_remote_sc_enabled(conn)){
3575b3c4163bSMatthias Ringwald         log_info("Level 4 required, but SC not supported -> abort");
3576b3c4163bSMatthias Ringwald         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3577b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3578b3c4163bSMatthias Ringwald         return;
3579b3c4163bSMatthias Ringwald     }
3580b3c4163bSMatthias Ringwald 
3581c2414c00SMatthias Ringwald     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3582c2414c00SMatthias Ringwald     // - GAP/MOD/NBON/BV-02-C
3583c2414c00SMatthias Ringwald     // - GAP/DM/NBON/BV-01-C
3584c2414c00SMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3585c2414c00SMatthias Ringwald         switch (conn->io_cap_response_auth_req){
3586c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3587c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3588c2414c00SMatthias Ringwald                 if (hci_stack->bondable == false){
3589c2414c00SMatthias Ringwald                     log_info("Dedicated vs. non-bondable -> abort");
3590c2414c00SMatthias Ringwald                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3591c2414c00SMatthias Ringwald                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3592c2414c00SMatthias Ringwald                     return;
3593c2414c00SMatthias Ringwald                 }
3594c2414c00SMatthias Ringwald             default:
3595c2414c00SMatthias Ringwald                 break;
3596c2414c00SMatthias Ringwald         }
3597c2414c00SMatthias Ringwald     }
3598c2414c00SMatthias Ringwald 
3599b3c4163bSMatthias Ringwald     // assess security based on io capabilities
3600b3c4163bSMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3601b3c4163bSMatthias Ringwald         // responder: fully validate io caps of both sides as well as OOB data
3602b3c4163bSMatthias Ringwald         bool security_possible = false;
3603b3c4163bSMatthias Ringwald         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3604b3c4163bSMatthias Ringwald 
3605b3c4163bSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3606b3c4163bSMatthias Ringwald         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3607b3c4163bSMatthias Ringwald         // so we merge the OOB data availability
3608b3c4163bSMatthias Ringwald         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3609b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_192 != NULL){
3610b3c4163bSMatthias Ringwald             have_oob_data |= 1;
3611b3c4163bSMatthias Ringwald         }
3612b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_256 != NULL){
3613b3c4163bSMatthias Ringwald             have_oob_data |= 2;
3614b3c4163bSMatthias Ringwald         }
3615b3c4163bSMatthias Ringwald         // for up to Level 3, either P-192 as well as P-256 will do
3616b3c4163bSMatthias Ringwald         // 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
3617b3c4163bSMatthias Ringwald         // if remote does not SC, we should not receive P-256 data either
3618b3c4163bSMatthias Ringwald         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3619b3c4163bSMatthias Ringwald             security_possible = true;
3620b3c4163bSMatthias Ringwald         }
3621b3c4163bSMatthias Ringwald         // for Level 4, P-256 is needed
3622b3c4163bSMatthias Ringwald         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3623b3c4163bSMatthias Ringwald             security_possible = true;
3624b3c4163bSMatthias Ringwald         }
3625b3c4163bSMatthias Ringwald #endif
3626b3c4163bSMatthias Ringwald 
3627b3c4163bSMatthias Ringwald         if (security_possible == false){
36282dd8985bSMatthias Ringwald             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3629b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3630b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3631b3c4163bSMatthias Ringwald             return;
3632b3c4163bSMatthias Ringwald         }
3633b3c4163bSMatthias Ringwald     } else {
3634b3c4163bSMatthias Ringwald         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
36351fe968f5SMatthias Ringwald #ifndef ENABLE_CLASSIC_PAIRING_OOB
36361fe968f5SMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3637b3c4163bSMatthias Ringwald         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3638b3c4163bSMatthias Ringwald             log_info("Level 3+ required, but no input/output -> abort");
3639b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3640b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3641b3c4163bSMatthias Ringwald             return;
3642b3c4163bSMatthias Ringwald         }
3643b3c4163bSMatthias Ringwald #endif
36441fe968f5SMatthias Ringwald #endif
3645b3c4163bSMatthias Ringwald     }
3646b3c4163bSMatthias Ringwald 
3647b3c4163bSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3648b3c4163bSMatthias Ringwald     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3649b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3650b3c4163bSMatthias Ringwald     } else {
3651b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3652b3c4163bSMatthias Ringwald     }
3653b3c4163bSMatthias Ringwald #endif
3654b3c4163bSMatthias Ringwald }
3655b3c4163bSMatthias Ringwald 
365617c6fe5cSMatthias Ringwald #endif
365717c6fe5cSMatthias Ringwald 
3658c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
36594f781026SMatthias Ringwald 
36604f781026SMatthias Ringwald     uint16_t event_length = packet[1];
36614f781026SMatthias Ringwald 
36624f781026SMatthias Ringwald     // assert packet is complete
36634ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
36644f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
36654f781026SMatthias Ringwald         return;
36664f781026SMatthias Ringwald     }
36674f781026SMatthias Ringwald 
36684f781026SMatthias Ringwald     hci_con_handle_t handle;
36694f781026SMatthias Ringwald     hci_connection_t * conn;
36704f781026SMatthias Ringwald     int i;
36714f781026SMatthias Ringwald 
36724f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
36735e91d96cSMatthias Ringwald     hci_link_type_t link_type;
367448f33f37SMatthias Ringwald     bd_addr_t addr;
3675cef94710SMatthias Ringwald     bd_addr_type_t addr_type;
36764f781026SMatthias Ringwald #endif
36774ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
36784ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream;
36797aa35f6aSMatthias Ringwald     le_audio_big_t   * big;
36802a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync;
36814ae8623eSMatthias Ringwald #endif
368289254d99SMatthias Ringwald #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
368389254d99SMatthias Ringwald     btstack_linked_list_iterator_t it;
368489254d99SMatthias Ringwald #endif
3685759e0a0dSMatthias Ringwald #if defined(ENABLE_LE_EXTENDED_ADVERTISING) && defined(ENABLE_LE_CENTRAL)
368689254d99SMatthias Ringwald     uint8_t advertising_handle;
368789254d99SMatthias Ringwald #endif
36884f781026SMatthias Ringwald 
36894f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
36904f781026SMatthias Ringwald 
36914f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
36924f781026SMatthias Ringwald 
36934f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
36944f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
369556cf178bSmatthias.ringwald             break;
369656cf178bSmatthias.ringwald 
36977ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
3698afbf1cd7SMatthias Ringwald             handle_command_status_event(packet, size);
36997ec5eeaaSmatthias.ringwald             break;
37007ec5eeaaSmatthias.ringwald 
37012e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
37029784dac1SMatthias Ringwald             if (size < 3) return;
37039784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
37044ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
3705d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3706d9a1d8edSMatthias Ringwald             bool notify_sco = false;
3707d9a1d8edSMatthias Ringwald #endif
3708d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3709d9a1d8edSMatthias Ringwald             bool notify_iso = false;
3710d9a1d8edSMatthias Ringwald #endif
37119784dac1SMatthias Ringwald             uint16_t offset = 3;
37129784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
37134ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
37144ea43905SMatthias Ringwald                 offset += 2u;
3715f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
37164ea43905SMatthias Ringwald                 offset += 2u;
37172e440c8aS[email protected] 
37185061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
3719e5413aa0SMatthias Ringwald                 if (conn != NULL) {
372023bed257S[email protected] 
3721ce41473eSMatthias Ringwald                     if (conn->num_packets_sent >= num_packets) {
3722ce41473eSMatthias Ringwald                         conn->num_packets_sent -= num_packets;
3723e35edcc1S[email protected]                     } else {
3724ce41473eSMatthias Ringwald                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3725ce41473eSMatthias Ringwald                         conn->num_packets_sent = 0;
3726e35edcc1S[email protected]                     }
3727ce41473eSMatthias Ringwald                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3728d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3729d9a1d8edSMatthias Ringwald                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3730d9a1d8edSMatthias Ringwald                         notify_sco = true;
3731d9a1d8edSMatthias Ringwald                     }
3732d9a1d8edSMatthias Ringwald #endif
3733e5413aa0SMatthias Ringwald                 }
3734e5413aa0SMatthias Ringwald 
37358ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
37368ad9cf99SMatthias Ringwald                 hci_controller_dump_packets();
37378ad9cf99SMatthias Ringwald #endif
37388ad9cf99SMatthias Ringwald 
3739e5413aa0SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3740e5413aa0SMatthias Ringwald                 if (conn == NULL){
3741c30bd0a5SMatthias Ringwald                     iso_stream = hci_iso_stream_for_con_handle(handle);
3742e5413aa0SMatthias Ringwald                     if (iso_stream != NULL){
3743e5413aa0SMatthias Ringwald                         if (iso_stream->num_packets_sent >= num_packets) {
3744e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent -= num_packets;
3745e5413aa0SMatthias Ringwald                         } else {
3746e5413aa0SMatthias Ringwald                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3747e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent = 0;
3748e5413aa0SMatthias Ringwald                         }
37498d72db10SMatthias Ringwald                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3750c30bd0a5SMatthias Ringwald                             big = hci_big_for_handle(iso_stream->group_id);
3751fe977b37SMatthias Ringwald                             if (big != NULL){
3752fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_valid = true;
3753fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3754fe977b37SMatthias Ringwald                             }
3755fe977b37SMatthias Ringwald                         }
3756e5413aa0SMatthias Ringwald                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3757e5413aa0SMatthias Ringwald                                  num_packets, handle, iso_stream->num_packets_sent);
3758d9a1d8edSMatthias Ringwald                         notify_iso = true;
3759e5413aa0SMatthias Ringwald                     }
3760d9a1d8edSMatthias Ringwald                 }
3761d9a1d8edSMatthias Ringwald #endif
3762d9a1d8edSMatthias Ringwald             }
3763d9a1d8edSMatthias Ringwald 
3764d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3765d9a1d8edSMatthias Ringwald             if (notify_sco){
3766d9a1d8edSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
3767d9a1d8edSMatthias Ringwald             }
3768d9a1d8edSMatthias Ringwald #endif
3769d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3770d9a1d8edSMatthias Ringwald             if (notify_iso){
37715ade6657SMatthias Ringwald                 hci_iso_notify_can_send_now();
3772e5413aa0SMatthias Ringwald             }
3773e5413aa0SMatthias Ringwald #endif
37746772a24cSmatthias.ringwald             break;
37752e440c8aS[email protected]         }
377635454696SMatthias Ringwald 
377735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
37789afaa4d4SMatthias Ringwald         case HCI_EVENT_FLUSH_OCCURRED:
37799afaa4d4SMatthias Ringwald             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
37809afaa4d4SMatthias Ringwald             handle = hci_event_flush_occurred_get_handle(packet);
37819afaa4d4SMatthias Ringwald             conn = hci_connection_for_handle(handle);
37829afaa4d4SMatthias Ringwald             if (conn) {
37839afaa4d4SMatthias Ringwald                 log_info("Flush occurred, disconnect 0x%04x", handle);
37849afaa4d4SMatthias Ringwald                 conn->state = SEND_DISCONNECT;
37859afaa4d4SMatthias Ringwald             }
37869afaa4d4SMatthias Ringwald             break;
37879afaa4d4SMatthias Ringwald 
3788f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
3789f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3790f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3791f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
37929da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
3793f5875de5SMatthias Ringwald             }
3794f5875de5SMatthias Ringwald             break;
3795b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3796b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3797b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3798b7f1ee76SMatthias Ringwald             }
3799b7f1ee76SMatthias Ringwald             break;
38001f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
3801724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
38025e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
380372cf8859SMatthias Ringwald 
380472cf8859SMatthias Ringwald             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
380572cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
380672cf8859SMatthias Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
380772cf8859SMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
380872cf8859SMatthias Ringwald                 break;
380972cf8859SMatthias Ringwald             }
381072cf8859SMatthias Ringwald 
381107e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
38125e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3813d152b6c6SMatthias Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
381407e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
381507e010b6SMilanka Ringwald                     break;
381607e010b6SMilanka Ringwald                 }
381707e010b6SMilanka Ringwald             }
381807e010b6SMilanka Ringwald 
381937eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
38205e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
38215e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
38222e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
38231f7b95a1Smatthias.ringwald             if (!conn) {
382488f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
38251f7b95a1Smatthias.ringwald             }
3826ce4c8fabSmatthias.ringwald             if (!conn) {
3827ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
38284536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3829058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
3830f23819bcSMatthias Ringwald                 hci_run();
3831f23819bcSMatthias Ringwald                 // avoid event to higher layer
3832f23819bcSMatthias Ringwald                 return;
3833ce4c8fabSmatthias.ringwald             }
383432ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
3835f3a16b9aSMatthias Ringwald             // store info about eSCO
38365e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
383776ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
3838f3a16b9aSMatthias Ringwald             }
3839d7891039SMatthias Ringwald             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3840d7891039SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_SCO){
3841182d886dSMatthias Ringwald                 const hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3842182d886dSMatthias Ringwald                 // ACL exists unless fuzzing
3843182d886dSMatthias Ringwald                 if (acl_conn != NULL) {
3844d7891039SMatthias Ringwald                     conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3845d7891039SMatthias Ringwald                 }
3846182d886dSMatthias Ringwald             }
384732ab9390Smatthias.ringwald             hci_run();
38481f7b95a1Smatthias.ringwald             break;
38491f7b95a1Smatthias.ringwald 
38506772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
3851fe1ed1b8Smatthias.ringwald             // Connection management
3852724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
38539da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3854f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
38552e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3856fe1ed1b8Smatthias.ringwald             if (conn) {
3857893b4ccdSMatthias Ringwald                 switch (conn->state){
3858893b4ccdSMatthias Ringwald                     // expected states
3859893b4ccdSMatthias Ringwald                     case ACCEPTED_CONNECTION_REQUEST:
3860893b4ccdSMatthias Ringwald                     case SENT_CREATE_CONNECTION:
3861893b4ccdSMatthias Ringwald                         break;
3862893b4ccdSMatthias Ringwald                     // unexpected state -> ignore
3863893b4ccdSMatthias Ringwald                     default:
3864893b4ccdSMatthias Ringwald                         // don't forward event to app
3865893b4ccdSMatthias Ringwald                         return;
3866893b4ccdSMatthias Ringwald                 }
3867b448a0e7Smatthias.ringwald                 if (!packet[2]){
3868c8e4258aSmatthias.ringwald                     conn->state = OPEN;
3869f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
38706909f064SMatthias Ringwald 
387122df2fe2SMatthias Ringwald                     // trigger write supervision timeout if we're master
3872d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
387322df2fe2SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
38746909f064SMatthias Ringwald                     }
38756909f064SMatthias Ringwald 
387622df2fe2SMatthias Ringwald                     // trigger write automatic flush timeout
38779afaa4d4SMatthias Ringwald                     if (hci_stack->automatic_flush_timeout != 0){
38789afaa4d4SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
38799afaa4d4SMatthias Ringwald                     }
38809afaa4d4SMatthias Ringwald 
3881c785ef68Smatthias.ringwald                     // restart timer
3882528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3883528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
3884c785ef68Smatthias.ringwald 
388518c4a0a3SMatthias Ringwald                     // trigger remote features for dedicated bonding
388618c4a0a3SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
388718c4a0a3SMatthias Ringwald                         hci_trigger_remote_features_for_connection(conn);
388818c4a0a3SMatthias Ringwald                     }
388918c4a0a3SMatthias Ringwald 
38909da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
389143bfb1bdSmatthias.ringwald 
389243bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
3893b448a0e7Smatthias.ringwald                 } else {
38940bbba85bSMatthias Ringwald                     // connection failed
38950bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
3896fe1ed1b8Smatthias.ringwald                 }
3897fe1ed1b8Smatthias.ringwald             }
38986772a24cSmatthias.ringwald             break;
3899fe1ed1b8Smatthias.ringwald 
390044d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3901724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
39021f34df2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
39031f34df2cSMatthias Ringwald             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3904182d886dSMatthias Ringwald 
3905182d886dSMatthias Ringwald             // SCO exists unless fuzzer
3906182d886dSMatthias Ringwald             if (conn == NULL) break;
39079071873aSMatthias Ringwald 
39089071873aSMatthias Ringwald             if (packet[2] != ERROR_CODE_SUCCESS){
39099071873aSMatthias Ringwald                 // connection failed, remove entry
39101f34df2cSMatthias Ringwald                 hci_handle_connection_failed(conn, packet[2]);
391144d0e3d5S[email protected]                 break;
391244d0e3d5S[email protected]             }
39139071873aSMatthias Ringwald 
39141a06f663S[email protected]             conn->state = OPEN;
3915f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
3916ee752bb8SMatthias Ringwald 
3917d7891039SMatthias Ringwald             // update sco payload length for eSCO connections
3918d7891039SMatthias Ringwald             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3919d7891039SMatthias Ringwald                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3920d7891039SMatthias Ringwald                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3921d7891039SMatthias Ringwald             }
3922d7891039SMatthias Ringwald 
3923ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3924ee752bb8SMatthias Ringwald             // update SCO
3925ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3926ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3927ee752bb8SMatthias Ringwald             }
3928f234b250SMatthias Ringwald             // trigger can send now
3929f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
39301972f31fSMatthias Ringwald                 hci_stack->sco_can_send_now = true;
3931f234b250SMatthias Ringwald             }
3932fa7f2dfdSMatthias Ringwald 
3933a086dc35SMatthias Ringwald             // setup implicit sco flow control
3934fa7f2dfdSMatthias Ringwald             conn->sco_tx_ready = 0;
3935fa7f2dfdSMatthias Ringwald             conn->sco_tx_active  = 0;
3936fa7f2dfdSMatthias Ringwald             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3937fa7f2dfdSMatthias Ringwald 
3938ee752bb8SMatthias Ringwald #endif
3939cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3940cb70c5abSMatthias Ringwald             // configure sco transport
3941cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
3942cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3943cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3944cb70c5abSMatthias Ringwald             }
3945cb70c5abSMatthias Ringwald #endif
394644d0e3d5S[email protected]             break;
394744d0e3d5S[email protected] 
3948afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3949f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
3950afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
3951afd4e962S[email protected]             if (!conn) break;
3952afd4e962S[email protected]             if (!packet[2]){
39532f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
39542f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
39552f5c44baSMatthias Ringwald 
39565ccef624SMatthias Ringwald                 // read extended features if possible
39571ffa425cSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
39581ffa425cSMatthias Ringwald                 && ((conn->remote_supported_features[0] & 2) != 0)) {
39595ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
39605ccef624SMatthias Ringwald                     break;
39615ccef624SMatthias Ringwald                 }
39625ccef624SMatthias Ringwald             }
39635ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
39645ccef624SMatthias Ringwald             break;
39655ccef624SMatthias Ringwald 
39665ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
39675ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
39685ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
39695ccef624SMatthias Ringwald             if (!conn) break;
39705ccef624SMatthias Ringwald             // status = ok, page = 1
397150c51a77SMatthias Ringwald             if (!packet[2]) {
397250c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
397350c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
39745ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
397550c51a77SMatthias Ringwald                 bool done = false;
397650c51a77SMatthias Ringwald                 switch (page_number){
397750c51a77SMatthias Ringwald                     case 1:
39782f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
397950c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
398050c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
398150c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
398250c51a77SMatthias Ringwald                         } else {
398350c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
398450c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
398550c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
398650c51a77SMatthias Ringwald                             }
398750c51a77SMatthias Ringwald                             done = true;
398850c51a77SMatthias Ringwald                         }
398950c51a77SMatthias Ringwald                         break;
399050c51a77SMatthias Ringwald                     case 2:
399150c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
399250c51a77SMatthias Ringwald                         done = true;
399350c51a77SMatthias Ringwald                         break;
399450c51a77SMatthias Ringwald                     default:
399550c51a77SMatthias Ringwald                         break;
399650c51a77SMatthias Ringwald                 }
399750c51a77SMatthias Ringwald                 if (!done) break;
3998afd4e962S[email protected]             }
3999de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
4000afd4e962S[email protected]             break;
4001afd4e962S[email protected] 
40027fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
4003308eeaffSMatthias Ringwald #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
400463c0b2fdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
400563c0b2fdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
400663c0b2fdSMatthias Ringwald             if (!conn) break;
400763c0b2fdSMatthias Ringwald 
400863c0b2fdSMatthias Ringwald             // lookup link key in db if not cached
400963c0b2fdSMatthias Ringwald             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
401063c0b2fdSMatthias Ringwald                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
401163c0b2fdSMatthias Ringwald             }
401263c0b2fdSMatthias Ringwald 
401363c0b2fdSMatthias Ringwald             // response sent by hci_run()
401463c0b2fdSMatthias Ringwald             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
401563c0b2fdSMatthias Ringwald #endif
4016608f51bbSMatthias Ringwald             break;
40177fde4af9Smatthias.ringwald 
40189ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
40191714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
4020f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40219ab95c90S[email protected]             if (!conn) break;
40221714cbbdSMatthias Ringwald 
40231714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
40241714cbbdSMatthias Ringwald 
40253817f9dfSMatthias Ringwald             // CVE-2020-26555: ignore NULL link key
40263817f9dfSMatthias Ringwald             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
40273817f9dfSMatthias Ringwald             if (btstack_is_null(&packet[8], 16)) break;
40283817f9dfSMatthias Ringwald 
40297bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
40309ab95c90S[email protected]             // Change Connection Encryption keeps link key type
40319ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
40329ab95c90S[email protected]                 conn->link_key_type = link_key_type;
40339ab95c90S[email protected]             }
40343817f9dfSMatthias Ringwald 
4035e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
4036e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
4037e9f98c4aSMatthias Ringwald 
4038bec5f683SMatthias Ringwald             // only store link key:
4039bec5f683SMatthias Ringwald             // - if bondable enabled
4040bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
4041af411b3fSMatthias Ringwald             // - if at least one side requests bonding during the IO Capabilities exchange.
4042af411b3fSMatthias Ringwald             // Note: we drop bonding flag in acceptor role if remote doesn't request it
4043af411b3fSMatthias Ringwald             bool bonding_local  = conn->io_cap_request_auth_req  >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4044af411b3fSMatthias Ringwald             bool bonding_remote = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4045af411b3fSMatthias Ringwald             if ((bonding_local == false) && (bonding_remote == false)) break;
40466edaed7fSMatthias Ringwald             // - if security level sufficient
40476edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
404855597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
40497fde4af9Smatthias.ringwald             break;
40509ab95c90S[email protected]         }
40517fde4af9Smatthias.ringwald 
40527fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
40531714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
40541714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40551714cbbdSMatthias Ringwald             if (!conn) break;
40561714cbbdSMatthias Ringwald 
40571714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
4058a800d95eSMatthias Ringwald             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
40593a9fb326S[email protected]             if (!hci_stack->bondable ){
40608daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
40611714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
4062f8fb5f6eS[email protected]                 hci_run();
4063f8fb5f6eS[email protected]                 return;
40644c57c146S[email protected]             }
4065a800d95eSMatthias Ringwald             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
4066a800d95eSMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
4067a800d95eSMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
406850dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
406950dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
407050dcc63cSMatthias Ringwald                 hci_run();
407150dcc63cSMatthias Ringwald                 return;
407250dcc63cSMatthias Ringwald             }
40737fde4af9Smatthias.ringwald             break;
40747fde4af9Smatthias.ringwald 
407550d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
407650d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
407750d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
407850d7398cSMatthias Ringwald             if (!conn) break;
40791714cbbdSMatthias Ringwald 
40808daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
40811714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
408250d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
4083e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
4084d22b82d6SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
4085d22b82d6SMatthias Ringwald             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
4086d22b82d6SMatthias Ringwald #endif
408750d7398cSMatthias Ringwald             break;
408850d7398cSMatthias Ringwald 
40891d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
40901714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
40911714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40921714cbbdSMatthias Ringwald             if (!conn) break;
40931714cbbdSMatthias Ringwald 
4094c950c316SMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
40959671e615SMatthias Ringwald             hci_connection_timestamp(conn);
40961714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
4097dbe1a790S[email protected]             break;
4098dbe1a790S[email protected] 
40991849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
41001849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
41017ca4a7edSMatthias Ringwald             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
41027ca4a7edSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
41037ca4a7edSMatthias Ringwald             if (!conn) break;
41047ca4a7edSMatthias Ringwald 
41057ca4a7edSMatthias Ringwald             hci_connection_timestamp(conn);
41067ca4a7edSMatthias Ringwald 
41077ca4a7edSMatthias Ringwald             hci_pairing_started(conn, true);
41087ca4a7edSMatthias Ringwald 
41097ca4a7edSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
41101849becdSMatthias Ringwald             break;
41111849becdSMatthias Ringwald #endif
41121849becdSMatthias Ringwald 
4113dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
411417c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
4115367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4116367aedc0SMatthias Ringwald             if (!conn) break;
4117367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
4118367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
41198daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4120367aedc0SMatthias Ringwald                 };
4121367aedc0SMatthias Ringwald             } else {
4122367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
4123367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4124367aedc0SMatthias Ringwald                 // don't forward event to app
4125367aedc0SMatthias Ringwald                 hci_run();
4126367aedc0SMatthias Ringwald                 return;
4127367aedc0SMatthias Ringwald             }
4128dbe1a790S[email protected]             break;
4129dbe1a790S[email protected] 
4130dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
4131367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
4132367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
41338daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4134367aedc0SMatthias Ringwald             };
41351d6b20aeS[email protected]             break;
41361849becdSMatthias Ringwald 
41373dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
41383dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
41393dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
41403dce6128SMatthias Ringwald             if (!conn) break;
41413dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
41423dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
41433dce6128SMatthias Ringwald             break;
414435454696SMatthias Ringwald #endif
41451d6b20aeS[email protected] 
4146f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
4147a355334eSMatthias Ringwald         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4148254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
4149f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
4150f0944df2S[email protected]             if (!conn) break;
4151db3c1f89SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
4152254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
4153254b78eeSMatthias Ringwald                 if (encryption_enabled){
4154573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
4155573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
41568daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
4157573897a0SMatthias Ringwald                     }
4158573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
4159573897a0SMatthias Ringwald                     else {
4160fcaf38b9SMatthias Ringwald 
4161254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
416236c3546bSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
4163254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
4164edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
4165813a09c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4166813a09c6SMatthias Ringwald                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
4167813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-31-C
4168813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-32-C
4169813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-33-C
4170813a09c6SMatthias Ringwald 
4171813a09c6SMatthias Ringwald                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
4172813a09c6SMatthias Ringwald                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
417329d4766dSMatthias Ringwald                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
417429d4766dSMatthias Ringwald                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
4175813a09c6SMatthias Ringwald                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4176813a09c6SMatthias Ringwald                             }
4177813a09c6SMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
4178813a09c6SMatthias Ringwald                                      conn->link_key_type, new_link_key_type);
4179813a09c6SMatthias Ringwald                             conn->link_key_type = new_link_key_type;
4180813a09c6SMatthias Ringwald #else
4181254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
41829ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4183254b78eeSMatthias Ringwald                             break;
4184813a09c6SMatthias Ringwald #endif
4185254b78eeSMatthias Ringwald                         }
4186254b78eeSMatthias Ringwald 
418762daa441SMatthias Ringwald #ifdef ENABLE_MUTUAL_AUTHENTICATION_FOR_LEGACY_SECURE_CONNECTIONS
4188aa2fe986SMatthias Ringwald                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
4189aa2fe986SMatthias Ringwald                         if (connected_uses_aes_ccm){
4190aa2fe986SMatthias Ringwald                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4191aa2fe986SMatthias Ringwald                         }
419262daa441SMatthias Ringwald #else
419362daa441SMatthias Ringwald                         // We consider even Legacy Secure Connections as authenticated as BTstack mandates encryption
4194a086dc35SMatthias Ringwald                         // with encryption key size > hci_stack->gap_required_encryption_key_size
419562daa441SMatthias Ringwald                         // for all operations that require any security. See BIAS attacks.
4196aa2fe986SMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4197aa2fe986SMatthias Ringwald #endif
4198a355334eSMatthias Ringwald                         // validate encryption key size
4199a355334eSMatthias Ringwald                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
4200a355334eSMatthias Ringwald                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
4201a355334eSMatthias Ringwald                             // already got encryption key size
4202a355334eSMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
4203a355334eSMatthias Ringwald                         } else {
42041ffa425cSMatthias Ringwald                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
42056e058d3fSMatthias Ringwald                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
4206573897a0SMatthias Ringwald                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
42076e058d3fSMatthias Ringwald                             } else {
42086e058d3fSMatthias Ringwald                                 // if not, pretend everything is perfect
42099866fdc7SMatthias Ringwald                                 hci_handle_read_encryption_key_size_complete(conn, 16);
42106e058d3fSMatthias Ringwald                             }
4211573897a0SMatthias Ringwald                         }
4212a355334eSMatthias Ringwald                     }
4213573897a0SMatthias Ringwald #endif
4214f0944df2S[email protected]                 } else {
42158daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
4216f0944df2S[email protected]                 }
42175999ee11SMatthias Ringwald             } else {
42188eae094cSMatthias Ringwald #ifdef ENABLE_CLASSIC
42198eae094cSMatthias Ringwald                 if (!hci_is_le_connection(conn)){
42205999ee11SMatthias Ringwald                     uint8_t status = hci_event_encryption_change_get_status(packet);
42215999ee11SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
42225999ee11SMatthias Ringwald                         conn->bonding_flags &= ~BONDING_DEDICATED;
42235999ee11SMatthias Ringwald                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
42245999ee11SMatthias Ringwald                         conn->bonding_status = status;
42255999ee11SMatthias Ringwald                     }
422627b992efSMatthias Ringwald                     // trigger security update -> level 0
422727b992efSMatthias Ringwald                     hci_handle_mutual_authentication_completed(conn);
4228ad83dc6aS[email protected]                 }
42298eae094cSMatthias Ringwald #endif
42308eae094cSMatthias Ringwald             }
4231573897a0SMatthias Ringwald 
4232f0944df2S[email protected]             break;
4233f0944df2S[email protected] 
423435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
42351eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4236abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
42371eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
42381eb2563eS[email protected]             if (!conn) break;
4239ad83dc6aS[email protected] 
4240dbd5dcc3SMatthias Ringwald             // clear authentication active flag
4241dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
42421714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4243dbd5dcc3SMatthias Ringwald 
4244abdad579SMatthias Ringwald             // authenticated only if auth status == 0
4245abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
4246abdad579SMatthias Ringwald                 // authenticated
42478daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4248abdad579SMatthias Ringwald 
4249131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
42508daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
42511eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4252ad83dc6aS[email protected]                     break;
4253ad83dc6aS[email protected]                 }
4254abdad579SMatthias Ringwald             }
4255abdad579SMatthias Ringwald 
42564aa2f135SMatthias Ringwald             // emit updated security level (will be 0 if not authenticated)
42574aa2f135SMatthias Ringwald             hci_handle_mutual_authentication_completed(conn);
42581eb2563eS[email protected]             break;
42591714cbbdSMatthias Ringwald 
42601714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
42611714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
42621714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
42631714cbbdSMatthias Ringwald             if (!conn) break;
42641714cbbdSMatthias Ringwald 
4265aa2fe986SMatthias Ringwald             // treat successfully paired connection as authenticated
4266aa2fe986SMatthias Ringwald             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4267f3aafff1SMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4268aa2fe986SMatthias Ringwald             }
4269aa2fe986SMatthias Ringwald 
42701714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
42711714cbbdSMatthias Ringwald             break;
427235454696SMatthias Ringwald #endif
427334d2123cS[email protected] 
427486805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
4275ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
4276ccda6e14S[email protected]         // see end of function, too.
4277a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
4278a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
4279f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
428081d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
42814ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
4282c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
42834ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
428481d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4285c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
4286c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
428781d2bdb2SMatthias Ringwald                     if (release_buffer){
428881d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
428981d2bdb2SMatthias Ringwald                     }
4290c6a37cfdSMatthias Ringwald                 }
4291c6a37cfdSMatthias Ringwald             }
429235454696SMatthias Ringwald 
42934ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4294098c2716SMatthias Ringwald             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4295098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size > 0u) {
4296098c2716SMatthias Ringwald                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4297098c2716SMatthias Ringwald                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4298098c2716SMatthias Ringwald                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4299098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_total_size = 0;
4300098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_pos = 0;
4301098c2716SMatthias Ringwald                     if (release_buffer){
4302098c2716SMatthias Ringwald                         hci_release_packet_buffer();
4303098c2716SMatthias Ringwald                     }
4304098c2716SMatthias Ringwald                 }
4305098c2716SMatthias Ringwald             }
4306098c2716SMatthias Ringwald 
43076fd1d2c8SMatthias Ringwald             // finalize iso stream for CIS handle
430815a15be3SMatthias Ringwald             iso_stream = hci_iso_stream_for_con_handle(handle);
43094ae8623eSMatthias Ringwald             if (iso_stream != NULL){
43104ae8623eSMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
43114ae8623eSMatthias Ringwald                 break;
43124ae8623eSMatthias Ringwald             }
43134ae8623eSMatthias Ringwald #endif
43144ae8623eSMatthias Ringwald 
431591036612SMatthias Ringwald #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4316f48a5586SMatthias Ringwald             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4317f48a5586SMatthias Ringwald                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4318f48a5586SMatthias Ringwald                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4319f48a5586SMatthias Ringwald                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
432005acf48bSMatthias Ringwald                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
432105acf48bSMatthias Ringwald                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4322f48a5586SMatthias Ringwald                 hci_stack->num_cmd_packets = 1;
4323f48a5586SMatthias Ringwald             }
4324f48a5586SMatthias Ringwald #endif
4325f48a5586SMatthias Ringwald 
4326c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
4327c6a37cfdSMatthias Ringwald             if (!conn) break;
43281714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
43291714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
43301714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
43311714cbbdSMatthias Ringwald #endif
4332046ec007SMatthias Ringwald 
4333a086dc35SMatthias Ringwald             // emit dedicated bonding event
4334046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4335046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4336046ec007SMatthias Ringwald             }
4337046ec007SMatthias Ringwald 
4338459d27b9SMatthias Ringwald             // mark connection for shutdown, stop timers, reset state
4339459d27b9SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4340459d27b9SMatthias Ringwald             hci_connection_stop_timer(conn);
4341459d27b9SMatthias Ringwald             hci_connection_init(conn);
4342459d27b9SMatthias Ringwald 
434335454696SMatthias Ringwald #ifdef ENABLE_BLE
4344d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4345046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
43462b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
4347bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
43489a2e4658SMatthias Ringwald             }
434935454696SMatthias Ringwald #endif
4350d70217a2SMatthias Ringwald #endif
4351ccda6e14S[email protected]             break;
43526772a24cSmatthias.ringwald 
4353c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
4354313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
4355d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
4356c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
43577586ee35S[email protected]             } else {
43587586ee35S[email protected]                 // if no special requests, just reboot stack
43597586ee35S[email protected]                 hci_power_control_off();
43607586ee35S[email protected]                 hci_power_control_on();
4361c68bdf90Smatthias.ringwald             }
4362c68bdf90Smatthias.ringwald             break;
4363c68bdf90Smatthias.ringwald 
43640e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
43655cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
43665cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
4367c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
4368f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
4369c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4370c4c88f1bSJakob Krantz             if (!conn) break;
437188f925b1SMatthias Ringwald             conn->role = (hci_role_t) packet[9];
43725cf766e8SMatthias Ringwald             break;
43730e6f3837SMatthias Ringwald #endif
43745cf766e8SMatthias Ringwald 
437563fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4376098c2716SMatthias Ringwald             // release packet buffer only for asynchronous transport and if there are not further fragments
43774fa24b5fS[email protected]             if (hci_transport_synchronous()) {
437863fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
43794fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
43804fa24b5fS[email protected]             }
438181d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
4382098c2716SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4383098c2716SMatthias Ringwald             hci_stack->iso_fragmentation_tx_active = 0;
4384098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size) break;
4385098c2716SMatthias Ringwald #endif
4386d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
43875daaa52eSMatthias Ringwald 
43885daaa52eSMatthias Ringwald             // release packet buffer without HCI_EVENT_TRANSPORT_PACKET_SENT (as it will be later)
43895daaa52eSMatthias Ringwald             hci_stack->hci_packet_buffer_reserved = false;
4390701e3307SMatthias Ringwald 
43915ade6657SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
43925ade6657SMatthias Ringwald             hci_iso_notify_can_send_now();
43935ade6657SMatthias Ringwald #endif
439463fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
439563fa3374SMatthias Ringwald 
439635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
439763fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
4398701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
439935454696SMatthias Ringwald #endif
44006b4af23dS[email protected]             break;
44016b4af23dS[email protected] 
440235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
440363fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
440463fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
44051972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = true;
440663fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
440763fa3374SMatthias Ringwald             return;
44081cfb383eSMatthias Ringwald 
4409a086dc35SMatthias Ringwald         // explode inquiry results for easier consumption
44101cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
44111cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
44121cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
44139784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
44141cfb383eSMatthias Ringwald             break;
441535454696SMatthias Ringwald #endif
441663fa3374SMatthias Ringwald 
4417a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
44185909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
44195909f7f2Smatthias.ringwald             switch (packet[2]){
4420d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
442157c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
44226fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
442357c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
44247bdc6798S[email protected]                     break;
4425a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4426a0698cb4SMatthias Ringwald                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4427a0698cb4SMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
4428a0698cb4SMatthias Ringwald                     le_handle_extended_advertisement_report(packet, size);
4429a0698cb4SMatthias Ringwald                     break;
4430ce56b945SMatthias Ringwald                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4431ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4432ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4433ce56b945SMatthias Ringwald                     break;
443489254d99SMatthias Ringwald                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
443589254d99SMatthias Ringwald                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
44362daa339aSMatthias Ringwald                     if (advertising_handle == LE_EXTENDED_ADVERTISING_LEGACY_HANDLE){
44372daa339aSMatthias Ringwald                         // legacy advertisements
44382daa339aSMatthias Ringwald                         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
44392daa339aSMatthias Ringwald                         hci_update_advertisements_enabled_for_current_roles();
44402daa339aSMatthias Ringwald                     } else {
444189254d99SMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
444289254d99SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)) {
444389254d99SMatthias Ringwald                             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
444489254d99SMatthias Ringwald                             if (advertising_set->advertising_handle == advertising_handle){
444589254d99SMatthias Ringwald                                 advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
444689254d99SMatthias Ringwald                             }
444789254d99SMatthias Ringwald                         }
44482775f8e2SMatthias Ringwald                     }
4449f7043595SMatthias Ringwald                     // event may come before le connection complete and announces new connection
4450f7043595SMatthias Ringwald                     if (hci_subevent_le_advertising_set_terminated_get_status(packet) == ERROR_CODE_SUCCESS){
4451f7043595SMatthias Ringwald                         handle = hci_subevent_le_advertising_set_terminated_get_connection_handle(packet);
4452f7043595SMatthias Ringwald                         conn = hci_connection_for_handle(handle);
4453f7043595SMatthias Ringwald                         if (conn == NULL){
445494791381SMatthias Ringwald                             // use placeholder address for peer, will be overwritten in hci_handle_le_connection_complete_event()
445594791381SMatthias Ringwald                             bd_addr_t addr;
445694791381SMatthias Ringwald                             memset(addr, 0, 6);
445794791381SMatthias Ringwald                             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_UNKNOWN, HCI_ROLE_SLAVE);
4458f7043595SMatthias Ringwald                             if (conn != NULL){
4459f7043595SMatthias Ringwald                                 conn->state = ANNOUNCED;
4460f7043595SMatthias Ringwald                                 conn->con_handle = handle;
4461f7043595SMatthias Ringwald                             }
4462f7043595SMatthias Ringwald                         }
4463f7043595SMatthias Ringwald                     }
446489254d99SMatthias Ringwald                     break;
4465a0698cb4SMatthias Ringwald #endif
4466d70217a2SMatthias Ringwald #endif
44675909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
446860fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
446960fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4470688bcdb4SMatthias Ringwald                     hci_handle_le_connection_complete_event(packet);
44715909f7f2Smatthias.ringwald                     break;
44725909f7f2Smatthias.ringwald 
4473f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4474c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4475c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4476c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
4477c9db5c21SMilanka Ringwald                     if (!conn) break;
4478c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4479c9db5c21SMilanka Ringwald                     break;
448065a46ef3S[email protected] 
448173cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
448273cd8a2aSMatthias Ringwald                     // connection
448373cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
448473cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
448573cd8a2aSMatthias Ringwald                     if (conn) {
448673cd8a2aSMatthias Ringwald                         // read arguments
448773cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
448873cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
448973cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
449073cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
449173cd8a2aSMatthias Ringwald 
449273cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
449373cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
449473cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
449573cd8a2aSMatthias Ringwald                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
449673cd8a2aSMatthias Ringwald                         if (update_parameter){
449773cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
449873cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
449973cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
450073cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
450173cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
450273cd8a2aSMatthias Ringwald                         } else {
4503c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
450473cd8a2aSMatthias Ringwald                         }
450573cd8a2aSMatthias Ringwald                     }
450673cd8a2aSMatthias Ringwald                     break;
45070f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
45080f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
45090f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
45100f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
45110f3b27c5SMatthias Ringwald                     if (conn) {
45120f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
45130f3b27c5SMatthias Ringwald                     }
45140f3b27c5SMatthias Ringwald                     break;
45150f3b27c5SMatthias Ringwald #endif
45164ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
45176fd1d2c8SMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_REQUEST:
45186fd1d2c8SMatthias Ringwald                     // incoming CIS request, allocate iso stream object and cache metadata
45196fd1d2c8SMatthias Ringwald                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
45206fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cig_id(packet),
45216fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cis_id(packet));
45226fd1d2c8SMatthias Ringwald                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
45236fd1d2c8SMatthias Ringwald                     if (iso_stream != NULL){
45246fd1d2c8SMatthias Ringwald                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
45256fd1d2c8SMatthias Ringwald                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
45266fd1d2c8SMatthias Ringwald                     }
45276fd1d2c8SMatthias Ringwald                     break;
45284ae8623eSMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
45298e58e4f7SMatthias Ringwald                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
45304ae8623eSMatthias Ringwald                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
45314ae8623eSMatthias Ringwald                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
45328e58e4f7SMatthias Ringwald                         iso_stream = hci_iso_stream_for_con_handle(handle);
45338e58e4f7SMatthias Ringwald                         btstack_assert(iso_stream != NULL);
45347dd97f73SMatthias Ringwald                         // track connection info
45357dd97f73SMatthias Ringwald                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
45367dd97f73SMatthias Ringwald                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
45377dd97f73SMatthias Ringwald                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
45387dd97f73SMatthias Ringwald                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
45397dd97f73SMatthias Ringwald                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
454026b93350SMatthias Ringwald                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
454126b93350SMatthias Ringwald                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
45427dd97f73SMatthias Ringwald                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
454326b93350SMatthias Ringwald                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
454426b93350SMatthias Ringwald                             // CIS Accept by Peripheral
454526b93350SMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
454626b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_p_to_c > 0){
454726b93350SMatthias Ringwald                                     // we're peripheral and we will send data
454826b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
454926b93350SMatthias Ringwald                                 } else {
455026b93350SMatthias Ringwald                                     // we're peripheral and we will only receive data
455126b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
455226b93350SMatthias Ringwald                                 }
455326b93350SMatthias Ringwald                             } else {
455414045fdbSMatthias Ringwald                                 hci_cis_handle_created(iso_stream, status);
455526b93350SMatthias Ringwald                             }
455626b93350SMatthias Ringwald                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
455726b93350SMatthias Ringwald                         } else {
455826b93350SMatthias Ringwald                             // CIG Setup by Central
455926b93350SMatthias Ringwald                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
456026b93350SMatthias Ringwald                             btstack_assert(cig != NULL);
456126b93350SMatthias Ringwald                             // update iso stream state
45624ae8623eSMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
45634ae8623eSMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
45644ae8623eSMatthias Ringwald                             } else {
45658e58e4f7SMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
45664ae8623eSMatthias Ringwald                             }
45678e58e4f7SMatthias Ringwald                             // update cig state
4568f06bb90fSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
4569f06bb90fSMatthias Ringwald                                 if (cig->cis_con_handles[i] == handle){
45703abcd16cSMatthias Ringwald                                     cig->cis_setup_active[i] = false;
4571f9306a1aSMatthias Ringwald                                     if (status == ERROR_CODE_SUCCESS){
4572f9306a1aSMatthias Ringwald                                         cig->cis_established[i] = true;
4573f9306a1aSMatthias Ringwald                                     } else {
457414045fdbSMatthias Ringwald                                         hci_cis_handle_created(iso_stream, status);
4575f06bb90fSMatthias Ringwald                                     }
4576f06bb90fSMatthias Ringwald                                 }
4577f06bb90fSMatthias Ringwald                             }
45788e58e4f7SMatthias Ringwald 
45798e58e4f7SMatthias Ringwald                             // trigger iso path setup if complete
45800f0ba168SMatthias Ringwald                             bool cis_setup_active = false;
4581f9306a1aSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
45820f0ba168SMatthias Ringwald                                 cis_setup_active |= cig->cis_setup_active[i];
4583f9306a1aSMatthias Ringwald                             }
45840f0ba168SMatthias Ringwald                             if (cis_setup_active == false){
4585f9306a1aSMatthias Ringwald                                 cig->state_vars.next_cis = 0;
4586f9306a1aSMatthias Ringwald                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
458726b93350SMatthias Ringwald                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
458826b93350SMatthias Ringwald                             }
4589f06bb90fSMatthias Ringwald                         }
45904ae8623eSMatthias Ringwald                     }
45917aa35f6aSMatthias Ringwald                     break;
45927aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
459326b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
45947aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(packet[4]);
45957aa35f6aSMatthias Ringwald                     if (big != NULL){
45967aa35f6aSMatthias Ringwald                         uint8_t status = packet[3];
45977aa35f6aSMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
45987aa35f6aSMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
45995fd415a6SMatthias Ringwald                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4600c30bd0a5SMatthias Ringwald 
46017aa35f6aSMatthias Ringwald                             for (i=0;i<num_bis;i++){
4602fb16346aSMatthias Ringwald                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4603fb16346aSMatthias Ringwald                                 big->bis_con_handles[i] = bis_handle;
4604fb16346aSMatthias Ringwald                                 // assign bis handle
4605fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4606fb16346aSMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
4607c30bd0a5SMatthias Ringwald                                     iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4608fb16346aSMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
46098d72db10SMatthias Ringwald                                         (iso_stream->group_id == big->big_handle)){
4610969d876aSMatthias Ringwald                                         iso_stream->cis_handle = bis_handle;
4611fb16346aSMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4612cd1139aaSMatthias Ringwald                                         break;
4613fb16346aSMatthias Ringwald                                     }
4614fb16346aSMatthias Ringwald                                 }
46157aa35f6aSMatthias Ringwald                             }
46162a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
46177aa35f6aSMatthias Ringwald                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
46187aa35f6aSMatthias Ringwald                                 big->state_vars.next_bis = 0;
46192a6c0f82SMatthias Ringwald                             }
46207aa35f6aSMatthias Ringwald                         } else {
46212a6c0f82SMatthias Ringwald                             // create BIG failed or has been stopped by us
4622d8905293SMatthias Ringwald                             hci_iso_create_big_failed(big, status);
46237aa35f6aSMatthias Ringwald                         }
46247aa35f6aSMatthias Ringwald                     }
46257aa35f6aSMatthias Ringwald                     break;
46267aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4627c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46287aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
46297aa35f6aSMatthias Ringwald                     if (big != NULL){
4630fb16346aSMatthias Ringwald                         // finalize associated ISO streams
4631c30bd0a5SMatthias Ringwald 
4632fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4633fb16346aSMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)){
4634c30bd0a5SMatthias Ringwald                             iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
46358d72db10SMatthias Ringwald                             if (iso_stream->group_id == big->big_handle){
4636969d876aSMatthias Ringwald                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4637fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_remove(&it);
4638fb16346aSMatthias Ringwald                                 btstack_memory_hci_iso_stream_free(iso_stream);
4639fb16346aSMatthias Ringwald                             }
4640fb16346aSMatthias Ringwald                         }
46417aa35f6aSMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
46427aa35f6aSMatthias Ringwald                         switch (big->state){
46437aa35f6aSMatthias Ringwald                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
46447aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, big->state_vars.status);
46457aa35f6aSMatthias Ringwald                                 break;
46467aa35f6aSMatthias Ringwald                             default:
46477aa35f6aSMatthias Ringwald                                 hci_emit_big_terminated(big);
46487aa35f6aSMatthias Ringwald                                 break;
46497aa35f6aSMatthias Ringwald                         }
46507aa35f6aSMatthias Ringwald                     }
46517aa35f6aSMatthias Ringwald                     break;
46522a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4653c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46542a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
46552a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
46562a6c0f82SMatthias Ringwald                         uint8_t status = packet[3];
46572a6c0f82SMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
46582a6c0f82SMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
46595fd415a6SMatthias Ringwald                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
46602a6c0f82SMatthias Ringwald                             for (i=0;i<num_bis;i++){
466102e19895SMatthias Ringwald                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
466202e19895SMatthias Ringwald                                 big_sync->bis_con_handles[i] = bis_handle;
466302e19895SMatthias Ringwald                                 // setup iso_stream_t
466402e19895SMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
466502e19895SMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
4666c30bd0a5SMatthias Ringwald                                     iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
466702e19895SMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
466802e19895SMatthias Ringwald                                         (iso_stream->group_id == big_sync->big_handle)){
466902e19895SMatthias Ringwald                                         iso_stream->cis_handle = bis_handle;
467002e19895SMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
467102e19895SMatthias Ringwald                                         break;
467202e19895SMatthias Ringwald                                     }
467302e19895SMatthias Ringwald                                 }
46742a6c0f82SMatthias Ringwald                             }
46752a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
46762a6c0f82SMatthias Ringwald                                 // trigger iso path setup
46772a6c0f82SMatthias Ringwald                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
46782a6c0f82SMatthias Ringwald                                 big_sync->state_vars.next_bis = 0;
46792a6c0f82SMatthias Ringwald                             }
46802a6c0f82SMatthias Ringwald                         } else {
46812a6c0f82SMatthias Ringwald                             // create BIG Sync failed or has been stopped by us
4682d8905293SMatthias Ringwald                             hci_iso_big_sync_failed(big_sync, status);
46832a6c0f82SMatthias Ringwald                         }
46842a6c0f82SMatthias Ringwald                     }
46852a6c0f82SMatthias Ringwald                     break;
46862a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4687c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46882a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
46892a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
4690d04a9afcSMatthias Ringwald                         uint8_t big_handle = packet[4];
46912a6c0f82SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4692d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
46932a6c0f82SMatthias Ringwald                     }
46942a6c0f82SMatthias Ringwald                     break;
46954ae8623eSMatthias Ringwald #endif
46965909f7f2Smatthias.ringwald                 default:
46975909f7f2Smatthias.ringwald                     break;
46985909f7f2Smatthias.ringwald             }
46995909f7f2Smatthias.ringwald             break;
47005909f7f2Smatthias.ringwald #endif
47010b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
47020b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
47030b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
47040b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
47050b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
47060b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
47070b36101dSMatthias Ringwald                     break;
47080b36101dSMatthias Ringwald                 default:
47090b36101dSMatthias Ringwald                     break;
47100b36101dSMatthias Ringwald             }
47110b36101dSMatthias Ringwald             break;
47126772a24cSmatthias.ringwald         default:
47136772a24cSmatthias.ringwald             break;
4714fe1ed1b8Smatthias.ringwald     }
4715fe1ed1b8Smatthias.ringwald 
471667c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
471789db417bSmatthias.ringwald 
471886805605S[email protected]     // notify upper stack
4719d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
472094ab26f8Smatthias.ringwald 
472186805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4722797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4723f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
472405ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4725046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
4726797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
472705ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
4728b0136355SMatthias Ringwald 		}
47298ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
47308ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
47318ad9cf99SMatthias Ringwald #endif
473286805605S[email protected]     }
473386805605S[email protected] 
473494ab26f8Smatthias.ringwald 	// execute main loop
473594ab26f8Smatthias.ringwald 	hci_run();
473616833f0aSmatthias.ringwald }
473716833f0aSmatthias.ringwald 
473835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
47396f28d2eeSMatthias Ringwald 
4740c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
47410b3f95dfSMatthias Ringwald     // lookup connection struct
47422b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
47432b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
47440b3f95dfSMatthias Ringwald     if (!conn) return;
47450b3f95dfSMatthias Ringwald 
47466be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
4747760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4748760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4749a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4750760b20efSMatthias Ringwald             packet[2] = 0x3c;
4751760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
4752760b20efSMatthias Ringwald             size = 63;
47530b3f95dfSMatthias Ringwald         }
47540b3f95dfSMatthias Ringwald     }
4755760b20efSMatthias Ringwald 
4756f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
4757f234b250SMatthias Ringwald         // Nothing to do
4758f234b250SMatthias Ringwald     } else {
475949205f5dSMatthias Ringwald         // 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);
4760760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
4761fa7f2dfdSMatthias Ringwald             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4762b1202089SMatthias Ringwald             uint8_t max_sco_packets = (uint8_t) btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4763fa7f2dfdSMatthias Ringwald             if (conn->sco_tx_active == 0){
4764fa7f2dfdSMatthias Ringwald                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4765fa7f2dfdSMatthias Ringwald                     conn->sco_tx_active = 1;
4766fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready = max_sco_packets;
4767fa7f2dfdSMatthias Ringwald                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4768fa7f2dfdSMatthias Ringwald                     hci_notify_if_sco_can_send_now();
476959c33575SMatthias Ringwald                 }
477059c33575SMatthias Ringwald             } else {
4771fa7f2dfdSMatthias Ringwald                 if (conn->sco_tx_ready < max_sco_packets){
4772fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready++;
477359c33575SMatthias Ringwald                 }
4774fa7f2dfdSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
47756f28d2eeSMatthias Ringwald             }
4776760b20efSMatthias Ringwald         }
4777f234b250SMatthias Ringwald     }
47786be3cf7fSMatthias Ringwald #endif
47796be3cf7fSMatthias Ringwald 
47800b3f95dfSMatthias Ringwald     // deliver to app
47810b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
47820b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
47830b3f95dfSMatthias Ringwald     }
47840b3f95dfSMatthias Ringwald 
4785ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4786ed325439SMatthias Ringwald     // We can send one packet for each received packet
4787ed325439SMatthias Ringwald     conn->sco_tx_ready++;
4788ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
4789ed325439SMatthias Ringwald #endif
4790ed325439SMatthias Ringwald 
47910b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
47922b838201SMatthias Ringwald     conn->num_packets_completed++;
47932b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
47942b838201SMatthias Ringwald     hci_run();
47952b838201SMatthias Ringwald #endif
4796c91d150bS[email protected] }
479735454696SMatthias Ringwald #endif
4798c91d150bS[email protected] 
47990a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
48004248f37eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
48014248f37eSMatthias Ringwald     // propagate ISO packets received as ACL
4802062276f9SMatthias Ringwald     hci_iso_stream_t * iso_stream = NULL;
48034248f37eSMatthias Ringwald     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
48044248f37eSMatthias Ringwald         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
48054248f37eSMatthias Ringwald         iso_stream = hci_iso_stream_for_con_handle(con_handle);
48064248f37eSMatthias Ringwald         if (iso_stream != NULL){
48074248f37eSMatthias Ringwald             packet_type = HCI_ISO_DATA_PACKET;
48084248f37eSMatthias Ringwald         }
48094248f37eSMatthias Ringwald     }
48104248f37eSMatthias Ringwald #endif
48114248f37eSMatthias Ringwald 
4812b09f7410SMatthias Ringwald     // don't log internal events unless requested
4813b09f7410SMatthias Ringwald     bool internal_event = (packet_type == HCI_EVENT_PACKET) && (hci_event_packet_get_type(packet) >= BTSTACK_EVENT_FIRST);
4814b09f7410SMatthias Ringwald     bool log_packet = internal_event == false;
4815b09f7410SMatthias Ringwald #ifdef ENABLE_LOG_BTSTACK_EVENTS
4816b09f7410SMatthias Ringwald     log_packet = true;
4817b09f7410SMatthias Ringwald #endif
4818b09f7410SMatthias Ringwald     if (log_packet){
48195bb5bc3eS[email protected]         hci_dump_packet(packet_type, 1, packet, size);
4820b09f7410SMatthias Ringwald     }
4821b09f7410SMatthias Ringwald 
482210e830c9Smatthias.ringwald     switch (packet_type) {
482310e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
482410e830c9Smatthias.ringwald             event_handler(packet, size);
482510e830c9Smatthias.ringwald             break;
482610e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
482710e830c9Smatthias.ringwald             acl_handler(packet, size);
482810e830c9Smatthias.ringwald             break;
482935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4830c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
4831c91d150bS[email protected]             sco_handler(packet, size);
4832202c8a4cSMatthias Ringwald             break;
483335454696SMatthias Ringwald #endif
48340a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
48355027c498SMatthias Ringwald         case HCI_ISO_DATA_PACKET:
4836750818acSMatthias Ringwald             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4837750818acSMatthias Ringwald                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4838750818acSMatthias Ringwald                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4839750818acSMatthias Ringwald             }
4840750818acSMatthias Ringwald             hci_iso_packet_handler(iso_stream, packet, size);
48415027c498SMatthias Ringwald             break;
48425027c498SMatthias Ringwald #endif
484310e830c9Smatthias.ringwald         default:
484410e830c9Smatthias.ringwald             break;
484510e830c9Smatthias.ringwald     }
484610e830c9Smatthias.ringwald }
484710e830c9Smatthias.ringwald 
4848d6b06661SMatthias Ringwald /**
4849d6b06661SMatthias Ringwald  * @brief Add event packet handler.
4850d6b06661SMatthias Ringwald  */
4851d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4852d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4853d6b06661SMatthias Ringwald }
4854d6b06661SMatthias Ringwald 
485567f708e0SMatthias Ringwald /**
485667f708e0SMatthias Ringwald  * @brief Remove event packet handler.
485767f708e0SMatthias Ringwald  */
485867f708e0SMatthias Ringwald void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
485967f708e0SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
486067f708e0SMatthias Ringwald }
4861d6b06661SMatthias Ringwald 
4862fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
48633d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4864fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
486516833f0aSmatthias.ringwald }
486616833f0aSmatthias.ringwald 
486735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
48688abbe8b5SMatthias Ringwald /**
48698abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
48708abbe8b5SMatthias Ringwald  */
48713d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
48728abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
48738abbe8b5SMatthias Ringwald }
487435454696SMatthias Ringwald #endif
48758abbe8b5SMatthias Ringwald 
48760a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
48775027c498SMatthias Ringwald void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
48785027c498SMatthias Ringwald     hci_stack->iso_packet_handler = handler;
48795027c498SMatthias Ringwald }
48805027c498SMatthias Ringwald #endif
48815027c498SMatthias Ringwald 
488271de195eSMatthias Ringwald static void hci_state_reset(void){
4883595bdbfbS[email protected]     // no connections yet
4884595bdbfbS[email protected]     hci_stack->connections = NULL;
488574308b23Smatthias.ringwald 
488674308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
488774308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
488874308b23Smatthias.ringwald     // hci_stack->connectable = 0;
488974308b23Smatthias.ringwald     // hci_stack->bondable = 1;
4890b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
4891595bdbfbS[email protected] 
489244935e40S[email protected]     // buffer is free
489302c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
489444935e40S[email protected] 
4895595bdbfbS[email protected]     // no pending cmds
4896595bdbfbS[email protected]     hci_stack->decline_reason = 0;
4897595bdbfbS[email protected] 
4898c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
4899c214d65bSMatthias Ringwald 
4900bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
4901496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
490232a12730SMatthias Ringwald 
4903baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic =
490459d59ecfSMatthias Ringwald             GAP_TASK_SET_DEFAULT_LINK_POLICY |
490559d59ecfSMatthias Ringwald             GAP_TASK_SET_CLASS_OF_DEVICE |
490659d59ecfSMatthias Ringwald             GAP_TASK_SET_LOCAL_NAME |
4907bc2dcc03SMatthias Ringwald             GAP_TASK_SET_EIR_DATA |
490832a12730SMatthias Ringwald             GAP_TASK_WRITE_SCAN_ENABLE |
490932a12730SMatthias Ringwald             GAP_TASK_WRITE_PAGE_TIMEOUT;
4910bea424a5SMatthias Ringwald #endif
4911bea424a5SMatthias Ringwald 
4912cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
49138d5f0979SMatthias Ringwald     hci_stack->classic_read_local_oob_data = false;
49141ae74bf3SMatthias Ringwald     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4915cf01e888SMatthias Ringwald #endif
4916cf01e888SMatthias Ringwald 
4917595bdbfbS[email protected]     // LE
4918b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
4919b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
4920b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
4921d70217a2SMatthias Ringwald #endif
4922d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4923a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
492473799937SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
4925b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4926d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4927e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
49284bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
49294bafedd5SMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
49304bafedd5SMatthias Ringwald #endif
4931d70217a2SMatthias Ringwald #endif
4932a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4933935aa76eSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
49346bf435a6SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4935a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4936a61834b6SMatthias Ringwald     }
4937a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
4938a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4939a61834b6SMatthias Ringwald     }
4940a61834b6SMatthias Ringwald #endif
4941d320e123SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4942d320e123SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4943d320e123SMatthias Ringwald #endif
494440f86dfdSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
494526b93350SMatthias Ringwald     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4946d75a6bbfSMatthias Ringwald     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
494740f86dfdSMatthias Ringwald #endif
494891036612SMatthias Ringwald #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4949f48a5586SMatthias Ringwald     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4950f48a5586SMatthias Ringwald #endif
4951595bdbfbS[email protected] }
4952595bdbfbS[email protected] 
495335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
49542d5e09d6SMatthias Ringwald /**
49552d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
49562d5e09d6SMatthias Ringwald  */
49572d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
49582d5e09d6SMatthias Ringwald     // store and open remote device db
49592d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
49602d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
49612d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
49622d5e09d6SMatthias Ringwald     }
49632d5e09d6SMatthias Ringwald }
496435454696SMatthias Ringwald #endif
49652d5e09d6SMatthias Ringwald 
49662d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
4967475c8125Smatthias.ringwald 
49683a9fb326S[email protected] #ifdef HAVE_MALLOC
49693a9fb326S[email protected]     if (!hci_stack) {
49703a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
49713a9fb326S[email protected]     }
4972b1202089SMatthias Ringwald     btstack_assert(hci_stack != NULL);
49733a9fb326S[email protected] #else
49743a9fb326S[email protected]     hci_stack = &hci_stack_static;
49753a9fb326S[email protected] #endif
497666fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
49773a9fb326S[email protected] 
4978475c8125Smatthias.ringwald     // reference to use transport layer implementation
49793a9fb326S[email protected]     hci_stack->hci_transport = transport;
4980475c8125Smatthias.ringwald 
498111e23e5fSmatthias.ringwald     // reference to used config
49823a9fb326S[email protected]     hci_stack->config = config;
498311e23e5fSmatthias.ringwald 
498426a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
498526a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
498626a9b6daSMatthias Ringwald 
49878fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
49883a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
49898fcba05dSmatthias.ringwald 
499016833f0aSmatthias.ringwald     // register packet handlers with transport
499110e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
4992f5454fc6Smatthias.ringwald 
49933a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
4994e2386ba1S[email protected] 
4995e2386ba1S[email protected]     // class of device
49963a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
4997a45d6b9fS[email protected] 
4998f20168b8Smatthias.ringwald     // bondable by default
4999f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
5000f20168b8Smatthias.ringwald 
5001e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
500263168530SMatthias Ringwald     // classic name
500363168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
5004c4c88f1bSJakob Krantz 
5005c4c88f1bSJakob Krantz     // Master slave policy
5006c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
5007170fafaeSMatthias Ringwald 
5008b4eb4420SMatthias Ringwald     // Allow Role Switch
5009b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
5010b4eb4420SMatthias Ringwald 
501178315a58SMatthias Ringwald     // Default / minimum security level = 2
501278315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
501378315a58SMatthias Ringwald 
50145dbec6b3SMatthias Ringwald     // Default Security Mode 4
50155dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
50165dbec6b3SMatthias Ringwald 
5017cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
5018cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
5019d821984bSMatthias Ringwald 
5020d821984bSMatthias Ringwald     // Link Supervision Timeout
5021d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
5022d821984bSMatthias Ringwald 
5023c874aa46SMatthias Ringwald     // Page Timeout
5024c874aa46SMatthias Ringwald     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
5025c874aa46SMatthias Ringwald 
5026a086dc35SMatthias Ringwald     // All ACL packet types are enabled
5027028ead5eSMatthias Ringwald     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
5028e9f343c8SMatthias Ringwald #endif
502963168530SMatthias Ringwald 
503063048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
50313a9fb326S[email protected]     hci_stack->ssp_enable = 1;
50323a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
50333a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
50343a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
503569a97523S[email protected] 
50365d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
50375d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
50385d23aae8SMatthias Ringwald 
5039fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
5040fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
5041d950d659SMatthias Ringwald 
50420c2c5f79SMatthias Ringwald #ifdef ENABLE_BLE
5043cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
5044cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
5045831711daSMatthias Ringwald     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
5046831711daSMatthias Ringwald     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
5047831711daSMatthias Ringwald     hci_stack->le_connection_latency       =      4;    //    4
5048831711daSMatthias Ringwald     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
504924d14ae3SMatthias Ringwald     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
505024d14ae3SMatthias Ringwald     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
50510c2c5f79SMatthias Ringwald #endif
50520c2c5f79SMatthias Ringwald 
50530c2c5f79SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
50547eb5b27eSMatthias Ringwald     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
50557261e5d8SMatthias Ringwald 
50567261e5d8SMatthias Ringwald     // default LE Scanning
50577eb5b27eSMatthias Ringwald     hci_stack->le_scan_type     =  0x01; // active
50588b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
50598b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
50607eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
5061831711daSMatthias Ringwald #endif
5062831711daSMatthias Ringwald 
50632b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
50642b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
5065ee605458SMatthias Ringwald 
5066ee605458SMatthias Ringwald     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
5067ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_min =                         0x0800;
5068ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_max =                         0x0800;
5069ee605458SMatthias Ringwald     hci_stack->le_advertisements_type =                                      0;
5070ee605458SMatthias Ringwald     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
5071ee605458SMatthias Ringwald     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
5072ee605458SMatthias Ringwald     hci_stack->le_advertisements_channel_map =                            0x07;
5073ee605458SMatthias Ringwald     hci_stack->le_advertisements_filter_policy =                             0;
50742b6ab3e6SMatthias Ringwald #endif
50752b6ab3e6SMatthias Ringwald 
5076831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
5077831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
5078831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
5079831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
5080831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
5081831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
5082831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
5083831711daSMatthias Ringwald 
508401d4f05fSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
508501d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = 1;
508601d4f05fSMatthias Ringwald #endif
508701d4f05fSMatthias Ringwald 
5088c3d19a30SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5089c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
5090c3d19a30SMatthias Ringwald #endif
5091c3d19a30SMatthias Ringwald 
5092595bdbfbS[email protected]     hci_state_reset();
5093475c8125Smatthias.ringwald }
5094475c8125Smatthias.ringwald 
50954688f216SMatthias Ringwald void hci_deinit(void){
5096b02cfc15SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
50974688f216SMatthias Ringwald #ifdef HAVE_MALLOC
50984688f216SMatthias Ringwald     if (hci_stack) {
50994688f216SMatthias Ringwald         free(hci_stack);
51004688f216SMatthias Ringwald     }
51014688f216SMatthias Ringwald #endif
51024688f216SMatthias Ringwald     hci_stack = NULL;
5103b5bbcbf4SMatthias Ringwald 
5104b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
51054688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
5106b5bbcbf4SMatthias Ringwald #endif
51074688f216SMatthias Ringwald }
51084688f216SMatthias Ringwald 
51093fb36a29SMatthias Ringwald /**
51103fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
51113fb36a29SMatthias Ringwald  */
51123fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
51133fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
51143fb36a29SMatthias Ringwald 
51153fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
51163fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
51173fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
51183fb36a29SMatthias Ringwald     }
51193fb36a29SMatthias Ringwald }
51203fb36a29SMatthias Ringwald 
51216fe16221SMatthias Ringwald void hci_enable_custom_pre_init(void){
51226fe16221SMatthias Ringwald     hci_stack->chipset_pre_init = true;
51236fe16221SMatthias Ringwald }
51246fe16221SMatthias Ringwald 
5125fb55bd0aSMatthias Ringwald /**
5126d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5127fb55bd0aSMatthias Ringwald  */
5128fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
5129fb55bd0aSMatthias Ringwald     // references to used control implementation
5130fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
5131d0b87befSMatthias Ringwald     // init with transport config
5132d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
5133fb55bd0aSMatthias Ringwald }
5134fb55bd0aSMatthias Ringwald 
51351f9eb2ccSMatthias Ringwald static void hci_discard_connections(void){
5136346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_t it;
5137346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5138346f8c2cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5139a086dc35SMatthias Ringwald         // cancel all l2cap connections by emitting disconnection complete before shutdown (free) connection
5140346f8c2cSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
51411f9eb2ccSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
51421f9eb2ccSMatthias Ringwald         hci_shutdown_connection(connection);
51431f9eb2ccSMatthias Ringwald     }
5144346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5145346f8c2cSMatthias Ringwald     while (hci_stack->iso_streams != NULL){
5146346f8c2cSMatthias Ringwald         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5147346f8c2cSMatthias Ringwald     }
5148346f8c2cSMatthias Ringwald #endif
51491f9eb2ccSMatthias Ringwald }
51501f9eb2ccSMatthias Ringwald 
515171de195eSMatthias Ringwald void hci_close(void){
5152e6d6524dSMatthias Ringwald 
5153e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
5154404843c1Smatthias.ringwald     // close remote device db
5155a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
5156a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
5157404843c1Smatthias.ringwald     }
5158e6d6524dSMatthias Ringwald #endif
51597224be7eSMatthias Ringwald 
51601f9eb2ccSMatthias Ringwald     hci_discard_connections();
51617224be7eSMatthias Ringwald 
5162f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
51633a9fb326S[email protected] 
51643a9fb326S[email protected] #ifdef HAVE_MALLOC
51653a9fb326S[email protected]     free(hci_stack);
51663a9fb326S[email protected] #endif
51673a9fb326S[email protected]     hci_stack = NULL;
5168404843c1Smatthias.ringwald }
5169404843c1Smatthias.ringwald 
5170cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
5171cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5172cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
5173cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
5174cb70c5abSMatthias Ringwald }
5175cb70c5abSMatthias Ringwald #endif
5176cb70c5abSMatthias Ringwald 
517735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5178170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5179a086dc35SMatthias Ringwald     // validate range and set
5180170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
5181170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
5182170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5183170fafaeSMatthias Ringwald }
518478315a58SMatthias Ringwald 
5185137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5186137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
51875dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
5188137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
5189137715ebSMatthias Ringwald     } else {
5190137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5191137715ebSMatthias Ringwald     }
51925dbec6b3SMatthias Ringwald }
51935dbec6b3SMatthias Ringwald 
51945dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
51955dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
51965dbec6b3SMatthias Ringwald }
51975dbec6b3SMatthias Ringwald 
519878315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
519978315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
520078315a58SMatthias Ringwald }
520178315a58SMatthias Ringwald 
520278315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
5203d7387af3SMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
5204d7387af3SMatthias Ringwald         return LEVEL_4;
5205d7387af3SMatthias Ringwald     }
520678315a58SMatthias Ringwald     return hci_stack->gap_security_level;
520778315a58SMatthias Ringwald }
520830cdf3c6SMatthias Ringwald 
52098ad4dfffSMatthias Ringwald void gap_set_minimal_service_security_level(gap_security_level_t security_level){
52108ad4dfffSMatthias Ringwald     hci_stack->gap_minimal_service_security_level = security_level;
52118ad4dfffSMatthias Ringwald }
52128ad4dfffSMatthias Ringwald 
521330cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
521430cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
521530cdf3c6SMatthias Ringwald }
521630cdf3c6SMatthias Ringwald 
521730cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
521830cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
521930cdf3c6SMatthias Ringwald }
5220170fafaeSMatthias Ringwald #endif
5221170fafaeSMatthias Ringwald 
5222170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
522360b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
52249e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
5225baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
522659d59ecfSMatthias Ringwald     hci_run();
52279e61646fS[email protected] }
522876f27cffSMatthias Ringwald 
5229c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5230c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
5231baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
523259d59ecfSMatthias Ringwald     hci_run();
5233c33e56d3SMatthias Ringwald }
5234c33e56d3SMatthias Ringwald 
5235b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
5236b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5237b4eb4420SMatthias Ringwald }
5238b4eb4420SMatthias Ringwald 
5239b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
5240b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
5241b4eb4420SMatthias Ringwald }
5242b4eb4420SMatthias Ringwald 
52430c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
52440c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
52450c3eb48dSMatthias Ringwald }
52460c3eb48dSMatthias Ringwald 
52479afaa4d4SMatthias Ringwald void gap_enable_link_watchdog(uint16_t timeout_ms){
52489afaa4d4SMatthias Ringwald     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
52499afaa4d4SMatthias Ringwald }
52509afaa4d4SMatthias Ringwald 
52519afaa4d4SMatthias Ringwald uint16_t hci_automatic_flush_timeout(void){
52529afaa4d4SMatthias Ringwald     return hci_stack->automatic_flush_timeout;
52539afaa4d4SMatthias Ringwald }
52549afaa4d4SMatthias Ringwald 
525576f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
525676f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
525776f27cffSMatthias Ringwald }
525835454696SMatthias Ringwald #endif
52599e61646fS[email protected] 
52606fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
5261f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5262f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
52636535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5264f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
5265f456b2d0S[email protected] }
526676f27cffSMatthias Ringwald #endif
5267f456b2d0S[email protected] 
52688d213e1aSmatthias.ringwald // State-Module-Driver overview
52698d213e1aSmatthias.ringwald // state                    module  low-level
52708d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
52718d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
52728d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
52738d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
5274d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
5275d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
5276c7e0c5f6Smatthias.ringwald 
527740d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
52787301ad89Smatthias.ringwald 
5279038bc64cSmatthias.ringwald     // power on
5280f9a30166Smatthias.ringwald     int err = 0;
52813a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
5282d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
5283f9a30166Smatthias.ringwald     }
5284038bc64cSmatthias.ringwald     if (err){
52859da54300S[email protected]         log_error( "POWER_ON failed");
5286038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
5287038bc64cSmatthias.ringwald         return err;
5288038bc64cSmatthias.ringwald     }
5289038bc64cSmatthias.ringwald 
529024b3c629SMatthias Ringwald     // int chipset driver
52913fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
52923fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
52933fb36a29SMatthias Ringwald     }
52943fb36a29SMatthias Ringwald 
529524b3c629SMatthias Ringwald     // init transport
529624b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
529724b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
529824b3c629SMatthias Ringwald     }
529924b3c629SMatthias Ringwald 
530024b3c629SMatthias Ringwald     // open transport
530124b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
5302038bc64cSmatthias.ringwald     if (err){
53039da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
53043a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5305d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5306f9a30166Smatthias.ringwald         }
5307038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
5308038bc64cSmatthias.ringwald         return err;
5309038bc64cSmatthias.ringwald     }
53108d213e1aSmatthias.ringwald     return 0;
53118d213e1aSmatthias.ringwald }
5312038bc64cSmatthias.ringwald 
531340d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
53148d213e1aSmatthias.ringwald 
53159da54300S[email protected]     log_info("hci_power_control_off");
53169418f9c9Smatthias.ringwald 
53178d213e1aSmatthias.ringwald     // close low-level device
531824b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
53198d213e1aSmatthias.ringwald 
53209da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
53219418f9c9Smatthias.ringwald 
53228d213e1aSmatthias.ringwald     // power off
53233a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
5324d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
53258d213e1aSmatthias.ringwald     }
53269418f9c9Smatthias.ringwald 
53279da54300S[email protected]     log_info("hci_power_control_off - control closed");
53289418f9c9Smatthias.ringwald 
53293a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
533072ea5239Smatthias.ringwald }
533172ea5239Smatthias.ringwald 
533240d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
533372ea5239Smatthias.ringwald 
53349da54300S[email protected]     log_info("hci_power_control_sleep");
53353144bce4Smatthias.ringwald 
5336b429b9b7Smatthias.ringwald #if 0
5337b429b9b7Smatthias.ringwald     // don't close serial port during sleep
5338b429b9b7Smatthias.ringwald 
533972ea5239Smatthias.ringwald     // close low-level device
53403a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
5341b429b9b7Smatthias.ringwald #endif
534272ea5239Smatthias.ringwald 
534372ea5239Smatthias.ringwald     // sleep mode
53443a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
5345d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
534672ea5239Smatthias.ringwald     }
5347b429b9b7Smatthias.ringwald 
53483a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
53498d213e1aSmatthias.ringwald }
53508d213e1aSmatthias.ringwald 
535140d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
5352b429b9b7Smatthias.ringwald 
53539da54300S[email protected]     log_info("hci_power_control_wake");
5354b429b9b7Smatthias.ringwald 
5355b429b9b7Smatthias.ringwald     // wake on
53563a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
5357d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
5358b429b9b7Smatthias.ringwald     }
5359b429b9b7Smatthias.ringwald 
5360b429b9b7Smatthias.ringwald #if 0
5361b429b9b7Smatthias.ringwald     // open low-level device
53623a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
5363b429b9b7Smatthias.ringwald     if (err){
53649da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
53653a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5366d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5367b429b9b7Smatthias.ringwald         }
5368b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
5369b429b9b7Smatthias.ringwald         return err;
5370b429b9b7Smatthias.ringwald     }
5371b429b9b7Smatthias.ringwald #endif
5372b429b9b7Smatthias.ringwald 
5373b429b9b7Smatthias.ringwald     return 0;
5374b429b9b7Smatthias.ringwald }
5375b429b9b7Smatthias.ringwald 
53760c88d5efSMatthias Ringwald static void hci_power_enter_initializing_state(void){
537744935e40S[email protected]     // set up state machine
537844935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
537902c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
538044935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
53816fe16221SMatthias Ringwald 
53820535e08cSMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
53836fe16221SMatthias Ringwald     if (hci_stack->chipset_pre_init) {
53846fe16221SMatthias Ringwald         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
53850535e08cSMatthias Ringwald     } else
53860535e08cSMatthias Ringwald #endif
53870535e08cSMatthias Ringwald     {
53885c363727SMatthias Ringwald         hci_stack->substate = HCI_INIT_SEND_RESET;
538944935e40S[email protected]     }
53906fe16221SMatthias Ringwald }
5391b429b9b7Smatthias.ringwald 
53920c88d5efSMatthias Ringwald static void hci_power_enter_halting_state(void){
53930c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
53941e907691SMatthias Ringwald     // drop entries scheduled for removal, mark others for re-adding
53951e907691SMatthias Ringwald     btstack_linked_list_iterator_t it;
53961e907691SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
53971e907691SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
53981e907691SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
53991e907691SMatthias Ringwald         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
54001e907691SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
54011e907691SMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
54021e907691SMatthias Ringwald         } else {
54031e907691SMatthias Ringwald             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
54041e907691SMatthias Ringwald         }
54051e907691SMatthias Ringwald     }
54064718c38dSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5407a2c9d908SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5408e8d160b3SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5409e8d160b3SMatthias Ringwald     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5410e8d160b3SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5411e8d160b3SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5412e8d160b3SMatthias Ringwald         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5413e8d160b3SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
5414e8d160b3SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
5415e8d160b3SMatthias Ringwald         } else {
5416e8d160b3SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5417e8d160b3SMatthias Ringwald             continue;
5418e8d160b3SMatthias Ringwald         }
5419e8d160b3SMatthias Ringwald     }
5420a2c9d908SMatthias Ringwald #endif
54210c88d5efSMatthias Ringwald #endif
54224718c38dSMatthias Ringwald #endif
5423184dbe2fSMatthias Ringwald     // see hci_run
5424184dbe2fSMatthias Ringwald     hci_stack->state = HCI_STATE_HALTING;
54250c88d5efSMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5426184dbe2fSMatthias Ringwald     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5427184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5428184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5429184dbe2fSMatthias Ringwald     btstack_run_loop_add_timer(&hci_stack->timeout);
5430184dbe2fSMatthias Ringwald }
5431184dbe2fSMatthias Ringwald 
543242bd3d77SMatthias Ringwald // returns error
543342bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
543442bd3d77SMatthias Ringwald     int err;
54358d213e1aSmatthias.ringwald     switch (power_mode){
54368d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54378d213e1aSmatthias.ringwald             err = hci_power_control_on();
543842bd3d77SMatthias Ringwald             if (err != 0) {
5439f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
544097b61c7bS[email protected]                 return err;
544197b61c7bS[email protected]             }
54420c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
54438d213e1aSmatthias.ringwald             break;
54448d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54458d213e1aSmatthias.ringwald             // do nothing
54468d213e1aSmatthias.ringwald             break;
54478d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5448b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
54498d213e1aSmatthias.ringwald             break;
54507bbeb3adSMilanka Ringwald         default:
54517bbeb3adSMilanka Ringwald             btstack_assert(false);
54527bbeb3adSMilanka Ringwald             break;
54538d213e1aSmatthias.ringwald     }
545442bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
545542bd3d77SMatthias Ringwald }
54567301ad89Smatthias.ringwald 
545742bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
54588d213e1aSmatthias.ringwald     switch (power_mode){
54598d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54608d213e1aSmatthias.ringwald             // do nothing
54618d213e1aSmatthias.ringwald             break;
54628d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54638d213e1aSmatthias.ringwald             // no connections yet, just turn it off
54648d213e1aSmatthias.ringwald             hci_power_control_off();
54658d213e1aSmatthias.ringwald             break;
54668d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5467b546ac54Smatthias.ringwald             // no connections yet, just turn it off
546872ea5239Smatthias.ringwald             hci_power_control_sleep();
54698d213e1aSmatthias.ringwald             break;
54707bbeb3adSMilanka Ringwald         default:
54717bbeb3adSMilanka Ringwald             btstack_assert(false);
54727bbeb3adSMilanka Ringwald             break;
54738d213e1aSmatthias.ringwald     }
547442bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
547542bd3d77SMatthias Ringwald }
54767301ad89Smatthias.ringwald 
547742bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
54788d213e1aSmatthias.ringwald     switch (power_mode){
54798d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54808d213e1aSmatthias.ringwald             // do nothing
54818d213e1aSmatthias.ringwald             break;
54828d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54830c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
54848d213e1aSmatthias.ringwald             break;
54858d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5486b546ac54Smatthias.ringwald             // see hci_run
54873a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
548874b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
54898d213e1aSmatthias.ringwald             break;
54907bbeb3adSMilanka Ringwald         default:
54917bbeb3adSMilanka Ringwald             btstack_assert(false);
54927bbeb3adSMilanka Ringwald             break;
54938d213e1aSmatthias.ringwald     }
549442bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
549542bd3d77SMatthias Ringwald }
54967301ad89Smatthias.ringwald 
549742bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
54988d213e1aSmatthias.ringwald     switch (power_mode){
54998d213e1aSmatthias.ringwald         case HCI_POWER_ON:
55000c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
55018d213e1aSmatthias.ringwald             break;
55028d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
55038d213e1aSmatthias.ringwald             // do nothing
55048d213e1aSmatthias.ringwald             break;
55058d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5506b546ac54Smatthias.ringwald             // see hci_run
55073a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
550874b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
55098d213e1aSmatthias.ringwald             break;
55107bbeb3adSMilanka Ringwald         default:
55117bbeb3adSMilanka Ringwald             btstack_assert(false);
55127bbeb3adSMilanka Ringwald             break;
55138d213e1aSmatthias.ringwald     }
551400278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
551542bd3d77SMatthias Ringwald }
55168d213e1aSmatthias.ringwald 
551742bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
55188d213e1aSmatthias.ringwald     switch (power_mode){
55198d213e1aSmatthias.ringwald         case HCI_POWER_ON:
55200c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
55218d213e1aSmatthias.ringwald             break;
55228d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
55230c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
55248d213e1aSmatthias.ringwald             break;
55258d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5526b546ac54Smatthias.ringwald             // do nothing
55278d213e1aSmatthias.ringwald             break;
55287bbeb3adSMilanka Ringwald         default:
55297bbeb3adSMilanka Ringwald             btstack_assert(false);
55307bbeb3adSMilanka Ringwald             break;
55318d213e1aSmatthias.ringwald     }
553242bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
553342bd3d77SMatthias Ringwald }
55348d213e1aSmatthias.ringwald 
553542bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
553642bd3d77SMatthias Ringwald     int err;
55378d213e1aSmatthias.ringwald     switch (power_mode){
55388d213e1aSmatthias.ringwald         case HCI_POWER_ON:
55393144bce4Smatthias.ringwald             err = hci_power_control_wake();
55403144bce4Smatthias.ringwald             if (err) return err;
55410c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
55428d213e1aSmatthias.ringwald             break;
55438d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
55440c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
55458d213e1aSmatthias.ringwald             break;
55468d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5547b546ac54Smatthias.ringwald             // do nothing
55488d213e1aSmatthias.ringwald             break;
55497bbeb3adSMilanka Ringwald         default:
55507bbeb3adSMilanka Ringwald             btstack_assert(false);
55517bbeb3adSMilanka Ringwald             break;
55528d213e1aSmatthias.ringwald     }
555342bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
555442bd3d77SMatthias Ringwald }
55557bbeb3adSMilanka Ringwald 
555642bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
555742bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5558bef627f1SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
555924f87726SMatthias Ringwald     int err = 0;
556042bd3d77SMatthias Ringwald     switch (hci_stack->state){
556142bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
556242bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
556342bd3d77SMatthias Ringwald             break;
556442bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
556542bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
556642bd3d77SMatthias Ringwald             break;
556742bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
556842bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
556942bd3d77SMatthias Ringwald             break;
557042bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
557142bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
557242bd3d77SMatthias Ringwald             break;
557342bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
557442bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
557542bd3d77SMatthias Ringwald             break;
557642bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
557742bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
557842bd3d77SMatthias Ringwald             break;
55797bbeb3adSMilanka Ringwald         default:
55807bbeb3adSMilanka Ringwald             btstack_assert(false);
55817bbeb3adSMilanka Ringwald             break;
558211e23e5fSmatthias.ringwald     }
558324f87726SMatthias Ringwald     if (err != 0){
558442bd3d77SMatthias Ringwald         return err;
558542bd3d77SMatthias Ringwald     }
558668d92d03Smatthias.ringwald 
5587038bc64cSmatthias.ringwald     // create internal event
5588ee8bf225Smatthias.ringwald 	hci_emit_state();
5589ee8bf225Smatthias.ringwald 
559068d92d03Smatthias.ringwald 	// trigger next/first action
559168d92d03Smatthias.ringwald 	hci_run();
559268d92d03Smatthias.ringwald 
5593475c8125Smatthias.ringwald     return 0;
5594475c8125Smatthias.ringwald }
5595475c8125Smatthias.ringwald 
559635454696SMatthias Ringwald 
5597091e35e3SMatthias Ringwald static void hci_halting_run(void) {
5598091e35e3SMatthias Ringwald 
5599091e35e3SMatthias Ringwald     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5600091e35e3SMatthias Ringwald 
5601091e35e3SMatthias Ringwald     hci_connection_t *connection;
5602d5f71a7eSMatthias Ringwald #ifdef ENABLE_BLE
5603d5f71a7eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5604a086dc35SMatthias Ringwald     bool stop_advertisements;
5605d5f71a7eSMatthias Ringwald #endif
5606d5f71a7eSMatthias Ringwald #endif
5607091e35e3SMatthias Ringwald 
5608091e35e3SMatthias Ringwald     switch (hci_stack->substate) {
56090c88d5efSMatthias Ringwald         case HCI_HALTING_CLASSIC_STOP:
56100c88d5efSMatthias Ringwald #ifdef ENABLE_CLASSIC
5611911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5612911801caSMatthias Ringwald 
56130c88d5efSMatthias Ringwald             if (hci_stack->connectable || hci_stack->discoverable){
56140c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
56150c88d5efSMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, 0);
56160c88d5efSMatthias Ringwald                 return;
56170c88d5efSMatthias Ringwald             }
56180c88d5efSMatthias Ringwald #endif
56190c88d5efSMatthias Ringwald             /* fall through */
56200c88d5efSMatthias Ringwald 
56210c88d5efSMatthias Ringwald         case HCI_HALTING_LE_ADV_STOP:
56220c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
56230c88d5efSMatthias Ringwald 
56240c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
56250c88d5efSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5626911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5627911801caSMatthias Ringwald 
5628a086dc35SMatthias Ringwald             stop_advertisements = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5629911801caSMatthias Ringwald 
5630911801caSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
563122f987e4SMatthias Ringwald             if (hci_le_extended_advertising_supported()){
5632c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5633911801caSMatthias Ringwald                 btstack_linked_list_iterator_t it;
5634911801caSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5635911801caSMatthias Ringwald                 // stop all periodic advertisements and check if an extended set is active
5636911801caSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
5637911801caSMatthias Ringwald                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5638911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5639911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5640911801caSMatthias Ringwald                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
56410c88d5efSMatthias Ringwald                         return;
56420c88d5efSMatthias Ringwald                     }
5643911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
56440aeb0b24SMatthias Ringwald                         stop_advertisements = true;
5645911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5646911801caSMatthias Ringwald                     }
5647911801caSMatthias Ringwald                 }
5648c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
56490aeb0b24SMatthias Ringwald                 if (stop_advertisements){
5650911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5651911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5652911801caSMatthias Ringwald                     return;
5653911801caSMatthias Ringwald                 }
5654d935373dSMatthias Ringwald             } else
5655a2c9d908SMatthias Ringwald #else /* ENABLE_LE_PERIPHERAL */
5656911801caSMatthias Ringwald             {
5657a086dc35SMatthias Ringwald                 if (stop_advertisements) {
5658911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5659911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5660911801caSMatthias Ringwald                     return;
5661911801caSMatthias Ringwald                 }
5662911801caSMatthias Ringwald             }
5663911801caSMatthias Ringwald #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5664911801caSMatthias Ringwald #endif  /* ENABLE_LE_PERIPHERAL */
5665911801caSMatthias Ringwald #endif  /* ENABLE_BLE */
5666911801caSMatthias Ringwald 
56670c88d5efSMatthias Ringwald             /* fall through */
56680c88d5efSMatthias Ringwald 
56690c88d5efSMatthias Ringwald         case HCI_HALTING_LE_SCAN_STOP:
56700c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5671911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5672091e35e3SMatthias Ringwald 
5673091e35e3SMatthias Ringwald #ifdef ENABLE_BLE
5674091e35e3SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
56750c88d5efSMatthias Ringwald             if (hci_stack->le_scanning_active){
5676c42da3bcSMatthias Ringwald                 hci_le_scan_stop();
56770c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
56780c88d5efSMatthias Ringwald                 return;
56790c88d5efSMatthias Ringwald             }
5680091e35e3SMatthias Ringwald #endif
5681091e35e3SMatthias Ringwald #endif
56820c88d5efSMatthias Ringwald 
56830c88d5efSMatthias Ringwald             /* fall through */
56840c88d5efSMatthias Ringwald 
56850c88d5efSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL:
56860c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5687911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
56880c88d5efSMatthias Ringwald 
5689091e35e3SMatthias Ringwald             // close all open connections
5690091e35e3SMatthias Ringwald             connection = (hci_connection_t *) hci_stack->connections;
5691091e35e3SMatthias Ringwald             if (connection) {
5692091e35e3SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5693091e35e3SMatthias Ringwald 
569447bf68a7SDirk Helbig                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", (void*)connection, con_handle, connection->state);
5695091e35e3SMatthias Ringwald 
569603270f05SMatthias Ringwald                 // check state
569703270f05SMatthias Ringwald                 switch(connection->state) {
569803270f05SMatthias Ringwald                     case SENT_DISCONNECT:
569903270f05SMatthias Ringwald                     case RECEIVED_DISCONNECTION_COMPLETE:
570003270f05SMatthias Ringwald                         // wait until connection is gone
570103270f05SMatthias Ringwald                         return;
570203270f05SMatthias Ringwald                     default:
570303270f05SMatthias Ringwald                         break;
570403270f05SMatthias Ringwald                 }
5705091e35e3SMatthias Ringwald 
5706091e35e3SMatthias Ringwald                 // finally, send the disconnect command
570703270f05SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
5708091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5709091e35e3SMatthias Ringwald                 return;
5710091e35e3SMatthias Ringwald             }
5711091e35e3SMatthias Ringwald 
5712346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5713346f8c2cSMatthias Ringwald             // stop BIGs and BIG Syncs
5714346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_bigs != NULL){
5715346f8c2cSMatthias Ringwald                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5716346f8c2cSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5717346f8c2cSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5718346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5719346f8c2cSMatthias Ringwald                 return;
5720346f8c2cSMatthias Ringwald             }
5721346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_big_syncs != NULL){
5722346f8c2cSMatthias Ringwald                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5723346f8c2cSMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5724346f8c2cSMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5725346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5726346f8c2cSMatthias Ringwald                 return;
5727346f8c2cSMatthias Ringwald             }
5728346f8c2cSMatthias Ringwald #endif
5729346f8c2cSMatthias Ringwald 
5730091e35e3SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
5731091e35e3SMatthias Ringwald 
5732a086dc35SMatthias Ringwald             // no connections left, wait a bit to assert that btstack_crypto isn't waiting for an HCI event
5733091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING: wait 50 ms");
57340c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5735091e35e3SMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5736091e35e3SMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5737091e35e3SMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
5738091e35e3SMatthias Ringwald             break;
5739091e35e3SMatthias Ringwald 
5740b188b5fcSMatthias Ringwald         case HCI_HALTING_W4_CLOSE_TIMER:
5741b188b5fcSMatthias Ringwald             // keep waiting
5742b188b5fcSMatthias Ringwald             break;
5743b188b5fcSMatthias Ringwald 
5744091e35e3SMatthias Ringwald         case HCI_HALTING_CLOSE:
5745091e35e3SMatthias Ringwald             // close left over connections (that had not been properly closed before)
5746b188b5fcSMatthias Ringwald             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5747091e35e3SMatthias Ringwald             hci_discard_connections();
5748091e35e3SMatthias Ringwald 
5749091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, calling off");
5750091e35e3SMatthias Ringwald 
5751091e35e3SMatthias Ringwald             // switch mode
5752091e35e3SMatthias Ringwald             hci_power_control_off();
5753091e35e3SMatthias Ringwald 
5754091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, emitting state");
5755091e35e3SMatthias Ringwald             hci_emit_state();
5756091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, done");
5757091e35e3SMatthias Ringwald             break;
5758091e35e3SMatthias Ringwald 
5759091e35e3SMatthias Ringwald         default:
5760091e35e3SMatthias Ringwald             break;
5761091e35e3SMatthias Ringwald     }
576236916f81SDirk Helbig }
5763091e35e3SMatthias Ringwald 
5764091e35e3SMatthias Ringwald static void hci_falling_asleep_run(void){
5765091e35e3SMatthias Ringwald     hci_connection_t * connection;
5766091e35e3SMatthias Ringwald     switch(hci_stack->substate) {
5767091e35e3SMatthias Ringwald         case HCI_FALLING_ASLEEP_DISCONNECT:
5768091e35e3SMatthias Ringwald             log_info("HCI_STATE_FALLING_ASLEEP");
5769091e35e3SMatthias Ringwald             // close all open connections
5770091e35e3SMatthias Ringwald             connection =  (hci_connection_t *) hci_stack->connections;
5771091e35e3SMatthias Ringwald             if (connection){
5772091e35e3SMatthias Ringwald 
5773091e35e3SMatthias Ringwald                 // send disconnect
5774091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5775091e35e3SMatthias Ringwald 
577647bf68a7SDirk Helbig                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", (void*)connection, (uint16_t)connection->con_handle);
5777091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5778091e35e3SMatthias Ringwald 
5779091e35e3SMatthias Ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
5780091e35e3SMatthias Ringwald                 hci_shutdown_connection(connection);
5781091e35e3SMatthias Ringwald                 return;
5782091e35e3SMatthias Ringwald             }
5783091e35e3SMatthias Ringwald 
5784091e35e3SMatthias Ringwald             if (hci_classic_supported()){
5785091e35e3SMatthias Ringwald                 // disable page and inquiry scan
5786091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5787091e35e3SMatthias Ringwald 
5788091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, disabling inq scans");
5789091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5790091e35e3SMatthias Ringwald 
5791091e35e3SMatthias Ringwald                 // continue in next substate
5792091e35e3SMatthias Ringwald                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5793091e35e3SMatthias Ringwald                 break;
5794091e35e3SMatthias Ringwald             }
5795091e35e3SMatthias Ringwald 
5796091e35e3SMatthias Ringwald             /* fall through */
5797091e35e3SMatthias Ringwald 
5798091e35e3SMatthias Ringwald             case HCI_FALLING_ASLEEP_COMPLETE:
5799091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, calling sleep");
5800091e35e3SMatthias Ringwald                 // switch mode
5801091e35e3SMatthias Ringwald                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5802091e35e3SMatthias Ringwald                 hci_emit_state();
5803091e35e3SMatthias Ringwald                 break;
5804091e35e3SMatthias Ringwald 
5805091e35e3SMatthias Ringwald                 default:
5806091e35e3SMatthias Ringwald                     break;
5807091e35e3SMatthias Ringwald     }
5808091e35e3SMatthias Ringwald }
5809091e35e3SMatthias Ringwald 
581035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
581135454696SMatthias Ringwald 
5812758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
5813758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
5814a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5815baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5816758b46ceSmatthias.ringwald     hci_run();
5817758b46ceSmatthias.ringwald }
5818758b46ceSmatthias.ringwald 
581915a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
5820381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
5821381fbed8Smatthias.ringwald 
58223a9fb326S[email protected]     if (hci_stack->discoverable == enable){
582371fd255dSMatthias Ringwald         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5824381fbed8Smatthias.ringwald         return;
5825381fbed8Smatthias.ringwald     }
5826381fbed8Smatthias.ringwald 
58273a9fb326S[email protected]     hci_stack->discoverable = enable;
5828758b46ceSmatthias.ringwald     hci_update_scan_enable();
5829758b46ceSmatthias.ringwald }
5830b031bebbSmatthias.ringwald 
583115a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
5832758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
5833758b46ceSmatthias.ringwald 
5834758b46ceSmatthias.ringwald     // don't emit event
58353a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
5836758b46ceSmatthias.ringwald 
58373a9fb326S[email protected]     hci_stack->connectable = enable;
5838758b46ceSmatthias.ringwald     hci_update_scan_enable();
5839381fbed8Smatthias.ringwald }
584035454696SMatthias Ringwald #endif
5841381fbed8Smatthias.ringwald 
584215a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
58436535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
58445061f3afS[email protected] }
58455061f3afS[email protected] 
58462b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
58472b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
58482b838201SMatthias Ringwald 
58492b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
58502b838201SMatthias Ringwald     hci_reserve_packet_buffer();
58512b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
58522b838201SMatthias Ringwald 
58532b838201SMatthias Ringwald     uint16_t size = 0;
58542b838201SMatthias Ringwald     uint16_t num_handles = 0;
58552b838201SMatthias Ringwald     packet[size++] = 0x35;
58562b838201SMatthias Ringwald     packet[size++] = 0x0c;
58572b838201SMatthias Ringwald     size++;  // skip param len
58582b838201SMatthias Ringwald     size++;  // skip num handles
58592b838201SMatthias Ringwald 
58602b838201SMatthias Ringwald     // add { handle, packets } entries
58612b838201SMatthias Ringwald     btstack_linked_item_t * it;
58622b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
58632b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
58642b838201SMatthias Ringwald         if (connection->num_packets_completed){
58652b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
58662b838201SMatthias Ringwald             size += 2;
58672b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
58682b838201SMatthias Ringwald             size += 2;
58692b838201SMatthias Ringwald             //
58702b838201SMatthias Ringwald             num_handles++;
58712b838201SMatthias Ringwald             connection->num_packets_completed = 0;
58722b838201SMatthias Ringwald         }
58732b838201SMatthias Ringwald     }
58742b838201SMatthias Ringwald 
58752b838201SMatthias Ringwald     packet[2] = size - 3;
58762b838201SMatthias Ringwald     packet[3] = num_handles;
58772b838201SMatthias Ringwald 
58782b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
58792b838201SMatthias Ringwald 
58802b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
58812b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
58822b838201SMatthias Ringwald 
58832b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
58842b838201SMatthias Ringwald     if (hci_transport_synchronous()){
5885e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5886068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
58872b838201SMatthias Ringwald     }
58882b838201SMatthias Ringwald }
58892b838201SMatthias Ringwald #endif
58902b838201SMatthias Ringwald 
589126fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
589226fe9592SMatthias Ringwald     UNUSED(ds);
589326fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
5894f021201aSMatthias Ringwald     hci_halting_run();
589526fe9592SMatthias Ringwald }
589626fe9592SMatthias Ringwald 
5897f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
58984ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
5899b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5900b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5901b5d8b22bS[email protected]         if (connection) {
590228a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5903b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
5904f30077b7SMatthias Ringwald                 return true;
5905b5d8b22bS[email protected]             }
590628a0332dSMatthias Ringwald         } else {
5907b5d8b22bS[email protected]             // connection gone -> discard further fragments
590828a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5909b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
5910b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
5911b5d8b22bS[email protected]         }
5912b5d8b22bS[email protected]     }
5913f30077b7SMatthias Ringwald     return false;
59142b838201SMatthias Ringwald }
5915b031bebbSmatthias.ringwald 
591668ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
591768ab6207SMatthias Ringwald static bool hci_run_iso_fragments(void){
591868ab6207SMatthias Ringwald     if (hci_stack->iso_fragmentation_total_size > 0u) {
591968ab6207SMatthias Ringwald         // TODO: flow control
592068ab6207SMatthias Ringwald         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
592168ab6207SMatthias Ringwald             hci_send_iso_packet_fragments();
592268ab6207SMatthias Ringwald             return true;
592368ab6207SMatthias Ringwald         }
592468ab6207SMatthias Ringwald     }
592568ab6207SMatthias Ringwald     return false;
592668ab6207SMatthias Ringwald }
592768ab6207SMatthias Ringwald #endif
592868ab6207SMatthias Ringwald 
592935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
59306c0d5426SMatthias Ringwald 
59316c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
59326c0d5426SMatthias Ringwald static bool hci_classic_operation_active(void) {
59336c0d5426SMatthias Ringwald     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
59346c0d5426SMatthias Ringwald         return true;
59356c0d5426SMatthias Ringwald     }
59366c0d5426SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
59376c0d5426SMatthias Ringwald         return true;
59386c0d5426SMatthias Ringwald     }
59396c0d5426SMatthias Ringwald     btstack_linked_item_t * it;
59406c0d5426SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
59416c0d5426SMatthias Ringwald         hci_connection_t *connection = (hci_connection_t *) it;
59426c0d5426SMatthias Ringwald         switch (connection->state) {
59436c0d5426SMatthias Ringwald             case SENT_CREATE_CONNECTION:
59446c0d5426SMatthias Ringwald             case SENT_CANCEL_CONNECTION:
59456c0d5426SMatthias Ringwald             case SENT_DISCONNECT:
59466c0d5426SMatthias Ringwald                 return true;
59476c0d5426SMatthias Ringwald             default:
59486c0d5426SMatthias Ringwald                 break;
59496c0d5426SMatthias Ringwald         }
59506c0d5426SMatthias Ringwald     }
59516c0d5426SMatthias Ringwald     return false;
59526c0d5426SMatthias Ringwald }
59536c0d5426SMatthias Ringwald #endif
59546c0d5426SMatthias Ringwald 
5955f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
5956f30077b7SMatthias Ringwald 
595759d59ecfSMatthias Ringwald     // assert stack is working and classic is active
595859d59ecfSMatthias Ringwald     if (hci_classic_supported() == false)      return false;
595959d59ecfSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
596059d59ecfSMatthias Ringwald 
5961b031bebbSmatthias.ringwald     // decline incoming connections
59623a9fb326S[email protected]     if (hci_stack->decline_reason){
59633a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
59643a9fb326S[email protected]         hci_stack->decline_reason = 0;
59653a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5966f30077b7SMatthias Ringwald         return true;
5967ce4c8fabSmatthias.ringwald     }
596859d59ecfSMatthias Ringwald 
5969baa4881eSMatthias Ringwald     if (hci_stack->gap_tasks_classic != 0){
5970ab4831a3SMatthias Ringwald         hci_run_gap_tasks_classic();
5971f30077b7SMatthias Ringwald         return true;
5972b031bebbSmatthias.ringwald     }
597327741fe7SMatthias Ringwald 
5974f5875de5SMatthias Ringwald     // start/stop inquiry
5975a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
59766c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
59776c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
59786c0d5426SMatthias Ringwald #endif
59796c0d5426SMatthias Ringwald         {
5980f5875de5SMatthias Ringwald             uint8_t duration = hci_stack->inquiry_state;
5981beb3c81dSMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
598230199e24SMatthias Ringwald             if (hci_stack->inquiry_max_period_length != 0){
598330199e24SMatthias Ringwald                 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);
598430199e24SMatthias Ringwald             } else {
5985496bb884SMatthias Ringwald                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
598630199e24SMatthias Ringwald             }
5987f30077b7SMatthias Ringwald             return true;
5988f5875de5SMatthias Ringwald         }
59896c0d5426SMatthias Ringwald     }
5990f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5991f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5992f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
5993f30077b7SMatthias Ringwald         return true;
5994f5875de5SMatthias Ringwald     }
599530199e24SMatthias Ringwald 
599630199e24SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5997bc06f564SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
599830199e24SMatthias Ringwald         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
599930199e24SMatthias Ringwald         return true;
600030199e24SMatthias Ringwald     }
600130199e24SMatthias Ringwald 
6002b7f1ee76SMatthias Ringwald     // remote name request
6003b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
60046c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
60056c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
60066c0d5426SMatthias Ringwald #endif
60076c0d5426SMatthias Ringwald         {
6008b7f1ee76SMatthias Ringwald             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
6009b7f1ee76SMatthias Ringwald             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
6010ee8a36c8SMatthias Ringwald                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
6011f30077b7SMatthias Ringwald             return true;
6012b7f1ee76SMatthias Ringwald         }
60136c0d5426SMatthias Ringwald     }
6014cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
6015cf01e888SMatthias Ringwald     // Local OOB data
601659d59ecfSMatthias Ringwald     if (hci_stack->classic_read_local_oob_data){
6017cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
60181e83575aSMatthias Ringwald         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
6019cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
6020cf01e888SMatthias Ringwald         } else {
6021cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
6022cf01e888SMatthias Ringwald         }
6023cf01e888SMatthias Ringwald     }
6024cf01e888SMatthias Ringwald #endif
60250a51f88bSMatthias Ringwald     // pairing
60260a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
60270a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
6028c26f2c7bSMatthias Ringwald         uint8_t pin_code[PIN_CODE_LEN];
60290a51f88bSMatthias Ringwald         switch (state){
60300a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
6031cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
60323f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
60333f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
60343f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
60350a51f88bSMatthias Ringwald                 break;
60360a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
6037cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60380a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
60390a51f88bSMatthias Ringwald                 break;
60400a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
6041cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
6042d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
60430a51f88bSMatthias Ringwald                 break;
60440a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
6045cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60460a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
60470a51f88bSMatthias Ringwald                 break;
60480a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
6049cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
60500a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
60510a51f88bSMatthias Ringwald                 break;
60520a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
6053cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60540a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
60550a51f88bSMatthias Ringwald                 break;
60560a51f88bSMatthias Ringwald             default:
60570a51f88bSMatthias Ringwald                 break;
60580a51f88bSMatthias Ringwald         }
6059f30077b7SMatthias Ringwald         return true;
6060f30077b7SMatthias Ringwald     }
6061f30077b7SMatthias Ringwald     return false;
60620a51f88bSMatthias Ringwald }
606335454696SMatthias Ringwald #endif
6064b031bebbSmatthias.ringwald 
6065a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
606691097d83SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6067be7ef9d8SMatthias Ringwald 
60687eb5b27eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
60697eb5b27eSMatthias Ringwald static uint8_t hci_le_num_phys(uint8_t phys){
60707eb5b27eSMatthias Ringwald     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
60717eb5b27eSMatthias Ringwald     btstack_assert(phys);
60727eb5b27eSMatthias Ringwald     return num_bits_set[phys];
60737eb5b27eSMatthias Ringwald }
60747eb5b27eSMatthias Ringwald #endif
60757eb5b27eSMatthias Ringwald 
6076c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void){
6077c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
607822f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
6079c42da3bcSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
6080c42da3bcSMatthias Ringwald     } else
6081c42da3bcSMatthias Ringwald #endif
6082c42da3bcSMatthias Ringwald     {
6083c42da3bcSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
6084c42da3bcSMatthias Ringwald     }
6085c42da3bcSMatthias Ringwald }
6086327f7f07SMatthias Ringwald 
6087f346015eSMatthias Ringwald static void
6088f346015eSMatthias Ringwald hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
6089327f7f07SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
609022f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
60917eb5b27eSMatthias Ringwald         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
60927eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_interval[3];
60937eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_window[3];
60947eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_min[3];
60957eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_max[3];
60967eb5b27eSMatthias Ringwald         uint16_t le_connection_latency[3];
60977eb5b27eSMatthias Ringwald         uint16_t le_supervision_timeout[3];
60987eb5b27eSMatthias Ringwald         uint16_t le_minimum_ce_length[3];
60997eb5b27eSMatthias Ringwald         uint16_t le_maximum_ce_length[3];
61007eb5b27eSMatthias Ringwald 
61017eb5b27eSMatthias Ringwald         uint8_t i;
61027eb5b27eSMatthias Ringwald         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
61037eb5b27eSMatthias Ringwald         for (i=0;i<num_phys;i++){
61047eb5b27eSMatthias Ringwald             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
61057eb5b27eSMatthias Ringwald             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
61067eb5b27eSMatthias Ringwald             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
61077eb5b27eSMatthias Ringwald             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
61087eb5b27eSMatthias Ringwald             le_connection_latency[i]       = hci_stack->le_connection_latency;
61097eb5b27eSMatthias Ringwald             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
61107eb5b27eSMatthias Ringwald             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
61117eb5b27eSMatthias Ringwald             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
61127eb5b27eSMatthias Ringwald         }
6113327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_extended_create_connection,
6114f346015eSMatthias Ringwald                      initiator_filter_policy,
6115327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
6116f346015eSMatthias Ringwald                      address_type,                  // peer address type
6117f346015eSMatthias Ringwald                      address,                       // peer bd addr
61187eb5b27eSMatthias Ringwald                      hci_stack->le_connection_phys, // initiating PHY
6119327f7f07SMatthias Ringwald                      le_connection_scan_interval,   // conn scan interval
6120327f7f07SMatthias Ringwald                      le_connection_scan_window,     // conn scan windows
6121327f7f07SMatthias Ringwald                      le_connection_interval_min,    // conn interval min
6122327f7f07SMatthias Ringwald                      le_connection_interval_max,    // conn interval max
6123327f7f07SMatthias Ringwald                      le_connection_latency,         // conn latency
6124327f7f07SMatthias Ringwald                      le_supervision_timeout,        // conn latency
6125327f7f07SMatthias Ringwald                      le_minimum_ce_length,          // min ce length
6126327f7f07SMatthias Ringwald                      le_maximum_ce_length           // max ce length
6127327f7f07SMatthias Ringwald         );
6128d935373dSMatthias Ringwald     } else
6129327f7f07SMatthias Ringwald #endif
6130327f7f07SMatthias Ringwald     {
6131327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
6132327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_interval,  // conn scan interval
6133327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_window,    // conn scan windows
6134f346015eSMatthias Ringwald                      initiator_filter_policy,                 // don't use whitelist
6135f346015eSMatthias Ringwald                      address_type,                            // peer address type
6136f346015eSMatthias Ringwald                      address,                                 // peer bd addr
6137327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,  // our addr type:
6138327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_min,   // conn interval min
6139327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_max,   // conn interval max
6140327f7f07SMatthias Ringwald                      hci_stack->le_connection_latency,        // conn latency
6141327f7f07SMatthias Ringwald                      hci_stack->le_supervision_timeout,       // conn latency
6142327f7f07SMatthias Ringwald                      hci_stack->le_minimum_ce_length,         // min ce length
6143327f7f07SMatthias Ringwald                      hci_stack->le_maximum_ce_length          // max ce length
6144327f7f07SMatthias Ringwald         );
6145327f7f07SMatthias Ringwald     }
6146327f7f07SMatthias Ringwald }
6147c42da3bcSMatthias Ringwald #endif
6148c42da3bcSMatthias Ringwald 
6149be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6150be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6151033393eeSBob Abeles static uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6152be7ef9d8SMatthias Ringwald     uint8_t  operation = 0;
6153be7ef9d8SMatthias Ringwald     if (pos == 0){
6154be7ef9d8SMatthias Ringwald         // first fragment or complete data
6155be7ef9d8SMatthias Ringwald         operation |= 1;
6156be7ef9d8SMatthias Ringwald     }
6157be7ef9d8SMatthias Ringwald     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6158be7ef9d8SMatthias Ringwald         // last fragment or complete data
6159be7ef9d8SMatthias Ringwald         operation |= 2;
6160be7ef9d8SMatthias Ringwald     }
6161be7ef9d8SMatthias Ringwald     return operation;
6162be7ef9d8SMatthias Ringwald }
6163be7ef9d8SMatthias Ringwald #endif
6164be7ef9d8SMatthias Ringwald #endif
6165be7ef9d8SMatthias Ringwald 
61662c052b15SMatthias Ringwald static bool hci_whitelist_modification_pending(void) {
616781ae6c3bSMatthias Ringwald     btstack_linked_list_iterator_t it;
616881ae6c3bSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
616981ae6c3bSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
617081ae6c3bSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
617181ae6c3bSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
617281ae6c3bSMatthias Ringwald             return true;
617381ae6c3bSMatthias Ringwald         }
617481ae6c3bSMatthias Ringwald     }
617581ae6c3bSMatthias Ringwald     return false;
617681ae6c3bSMatthias Ringwald }
617781ae6c3bSMatthias Ringwald 
61782c052b15SMatthias Ringwald static bool hci_whitelist_modification_process(void){
61792c052b15SMatthias Ringwald     // add/remove entries
61802c052b15SMatthias Ringwald     btstack_linked_list_iterator_t it;
61812c052b15SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
61822c052b15SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
61832c052b15SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
61842c052b15SMatthias Ringwald         if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
61852c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
61862c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
61872c052b15SMatthias Ringwald             bd_addr_type_t address_type = entry->address_type;
61882c052b15SMatthias Ringwald             bd_addr_t address;
61892c052b15SMatthias Ringwald             memcpy(address, entry->address, 6);
61902c052b15SMatthias Ringwald             if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
61912c052b15SMatthias Ringwald                 // remove from whitelist if not scheduled for re-addition
61922c052b15SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
61932c052b15SMatthias Ringwald                 btstack_memory_whitelist_entry_free(entry);
61942c052b15SMatthias Ringwald             }
61952c052b15SMatthias Ringwald             hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
61962c052b15SMatthias Ringwald             return true;
61972c052b15SMatthias Ringwald         }
61982c052b15SMatthias Ringwald         if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
61992c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
62002c052b15SMatthias Ringwald             entry->state |= LE_WHITELIST_ON_CONTROLLER;
62012c052b15SMatthias Ringwald             hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
62022c052b15SMatthias Ringwald             return true;
62032c052b15SMatthias Ringwald         }
62042c052b15SMatthias Ringwald     }
62052c052b15SMatthias Ringwald     return false;
62062c052b15SMatthias Ringwald }
62072c052b15SMatthias Ringwald 
6208f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
6209f30077b7SMatthias Ringwald 
621095f31ee8SMatthias Ringwald #if defined(ENABLE_LE_EXTENDED_ADVERTISING) || defined(ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE)
6211f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t lit;
621295f31ee8SMatthias Ringwald #endif
6213f40c73b4SMatthias Ringwald 
62142052d96cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
62152052d96cSMatthias Ringwald     if (hci_stack->le_resolvable_private_address_update_s > 0){
62162052d96cSMatthias Ringwald         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
62172052d96cSMatthias Ringwald         hci_stack->le_resolvable_private_address_update_s = 0;
62182052d96cSMatthias Ringwald         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
62192052d96cSMatthias Ringwald         return true;
62202052d96cSMatthias Ringwald     }
62212052d96cSMatthias Ringwald #endif
62222052d96cSMatthias Ringwald 
6223a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
6224a41310b7SMatthias Ringwald 
622549a6c69cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6226a41310b7SMatthias Ringwald     bool scanning_stop = false;
6227a41310b7SMatthias Ringwald     bool connecting_stop = false;
6228be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6229c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
62304bafedd5SMatthias Ringwald     bool periodic_sync_stop = false;
62314bafedd5SMatthias Ringwald #endif
6232be7ef9d8SMatthias Ringwald #endif
6233c814a904SMatthias Ringwald #endif
6234be7ef9d8SMatthias Ringwald 
623549a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
623649a6c69cSMatthias Ringwald     bool advertising_stop = false;
623749a6c69cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
623849a6c69cSMatthias Ringwald     le_advertising_set_t * advertising_stop_set = NULL;
623949a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
624049a6c69cSMatthias Ringwald     bool periodic_advertising_stop = false;
6241a41310b7SMatthias Ringwald #endif
624249a6c69cSMatthias Ringwald #endif
6243a41310b7SMatthias Ringwald #endif
6244a41310b7SMatthias Ringwald 
62459136bde8SMatthias Ringwald     // check if own address changes
62469ce6dfa1SMatthias Ringwald     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
62479ce6dfa1SMatthias Ringwald     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
62489136bde8SMatthias Ringwald 
624929c24bebSMatthias Ringwald     // check if whitelist needs modification
625081ae6c3bSMatthias Ringwald     bool  whitelist_modification_pending = hci_whitelist_modification_pending();
6251f40c73b4SMatthias Ringwald 
625221debf25SMatthias Ringwald     // check if resolving list needs modification
625321debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
625421debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
62551ffa425cSMatthias Ringwald     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6256ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
625721debf25SMatthias Ringwald         resolving_list_modification_pending = true;
625821debf25SMatthias Ringwald     }
625921debf25SMatthias Ringwald #endif
626029c24bebSMatthias Ringwald 
6261f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
626249a6c69cSMatthias Ringwald 
6263f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
626449a6c69cSMatthias Ringwald     // check if periodic advertiser list needs modification
6265f40c73b4SMatthias Ringwald     bool periodic_list_modification_pending = false;
6266f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6267f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
6268f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6269f40c73b4SMatthias Ringwald         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6270f40c73b4SMatthias Ringwald             periodic_list_modification_pending = true;
6271f40c73b4SMatthias Ringwald             break;
6272f40c73b4SMatthias Ringwald         }
6273f40c73b4SMatthias Ringwald     }
6274f40c73b4SMatthias Ringwald #endif
6275f40c73b4SMatthias Ringwald 
6276fde725feSMatthias Ringwald     // scanning control
62773251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
627829c24bebSMatthias Ringwald         // stop if:
627929c24bebSMatthias Ringwald         // - parameter change required
628029c24bebSMatthias Ringwald         // - it's disabled
628129c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
628221debf25SMatthias Ringwald         // - resolving list modified
628351e51a58SMatthias Ringwald         // - own address changes
628429c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
628521debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
628621debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
6287d54b2c94SMatthias Ringwald             (scanning_uses_whitelist && whitelist_modification_pending) ||
628851e51a58SMatthias Ringwald             resolving_list_modification_pending ||
628951e51a58SMatthias Ringwald             random_address_change){
629021debf25SMatthias Ringwald 
62912d5c2a27SMatthias Ringwald             scanning_stop = true;
6292fde725feSMatthias Ringwald         }
6293fde725feSMatthias Ringwald     }
6294fde725feSMatthias Ringwald 
629529c24bebSMatthias Ringwald     // connecting control
6296f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
6297f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
6298f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
6299f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
6300af64f147SMatthias Ringwald             // stop connecting if:
6301af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
6302af64f147SMatthias Ringwald             // - if it got disabled
630321debf25SMatthias Ringwald             // - resolving list modified
630451e51a58SMatthias Ringwald             // - own address changes
6305f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6306f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
630721debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
630851e51a58SMatthias Ringwald                 resolving_list_modification_pending ||
630951e51a58SMatthias Ringwald                 random_address_change) {
631021debf25SMatthias Ringwald 
631129c24bebSMatthias Ringwald                 connecting_stop = true;
631229c24bebSMatthias Ringwald             }
6313f496d06eSMatthias Ringwald             break;
6314f496d06eSMatthias Ringwald         default:
6315f496d06eSMatthias Ringwald             break;
631629c24bebSMatthias Ringwald     }
631749a6c69cSMatthias Ringwald 
63184bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
631949a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
63204bafedd5SMatthias Ringwald     // periodic sync control
63214bafedd5SMatthias Ringwald     bool sync_with_advertiser_list;
63224bafedd5SMatthias Ringwald     switch(hci_stack->le_periodic_sync_state){
63234bafedd5SMatthias Ringwald         case LE_CONNECTING_DIRECT:
63244bafedd5SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
632549a6c69cSMatthias Ringwald             // stop sync if:
63264bafedd5SMatthias Ringwald             // - sync with advertiser list and advertiser list modification pending
632749a6c69cSMatthias Ringwald             // - if it got disabled
63284bafedd5SMatthias Ringwald             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
63294bafedd5SMatthias Ringwald             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
63304bafedd5SMatthias Ringwald                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
63314bafedd5SMatthias Ringwald                 periodic_sync_stop = true;
63324bafedd5SMatthias Ringwald             }
63334bafedd5SMatthias Ringwald             break;
63344bafedd5SMatthias Ringwald         default:
63354bafedd5SMatthias Ringwald             break;
63364bafedd5SMatthias Ringwald     }
63374bafedd5SMatthias Ringwald #endif
6338d70217a2SMatthias Ringwald #endif
633929c24bebSMatthias Ringwald 
634049a6c69cSMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
634149a6c69cSMatthias Ringwald 
6342d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
634345c102fdSMatthias Ringwald     // le advertisement control
6344935aa76eSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
634529c24bebSMatthias Ringwald         // stop if:
634629c24bebSMatthias Ringwald         // - parameter change required
63479136bde8SMatthias Ringwald         // - random address used in advertising and changes
634829c24bebSMatthias Ringwald         // - it's disabled
6349ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
635021debf25SMatthias Ringwald         // - resolving list modified
635151e51a58SMatthias Ringwald         // - own address changes
6352a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
63539136bde8SMatthias Ringwald         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
63544e5d21eaSMatthias Ringwald         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6355a61834b6SMatthias Ringwald         if (advertising_change ||
63569136bde8SMatthias Ringwald             (advertising_uses_random_address && random_address_change) ||
6357a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
63589136bde8SMatthias Ringwald             (advertising_uses_whitelist && whitelist_modification_pending) ||
635951e51a58SMatthias Ringwald             resolving_list_modification_pending ||
636051e51a58SMatthias Ringwald             random_address_change) {
636121debf25SMatthias Ringwald 
6362fde725feSMatthias Ringwald             advertising_stop = true;
6363fde725feSMatthias Ringwald         }
6364fde725feSMatthias Ringwald     }
6365be7ef9d8SMatthias Ringwald 
6366be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
636722f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6368be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6369be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6370be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6371be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
637253f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6373be7ef9d8SMatthias Ringwald                 // stop if:
6374be7ef9d8SMatthias Ringwald                 // - parameter change required
6375be7ef9d8SMatthias Ringwald                 // - random address used in connectable advertising and changes
6376be7ef9d8SMatthias Ringwald                 // - it's disabled
6377be7ef9d8SMatthias Ringwald                 // - whitelist change required but used for advertisement filter policy
6378be7ef9d8SMatthias Ringwald                 // - resolving list modified
6379be7ef9d8SMatthias Ringwald                 // - own address changes
6380be7ef9d8SMatthias Ringwald                 // - advertisement set will be removed
638157a04237SMatthias Ringwald                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
638257a04237SMatthias Ringwald                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
638353f240c0SMatthias Ringwald                 bool advertising_uses_random_address =
638453f240c0SMatthias Ringwald                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
638553f240c0SMatthias Ringwald                         advertising_connectable;
6386be7ef9d8SMatthias Ringwald                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6387be7ef9d8SMatthias Ringwald                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
638853f240c0SMatthias Ringwald                 bool advertising_set_random_address_change =
638953f240c0SMatthias Ringwald                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
639053f240c0SMatthias Ringwald                 bool advertising_set_will_be_removed =
639153f240c0SMatthias Ringwald                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6392be7ef9d8SMatthias Ringwald                 if (advertising_parameter_change ||
6393be7ef9d8SMatthias Ringwald                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6394be7ef9d8SMatthias Ringwald                     (advertising_enabled == false) ||
6395be7ef9d8SMatthias Ringwald                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6396be7ef9d8SMatthias Ringwald                     resolving_list_modification_pending ||
6397be7ef9d8SMatthias Ringwald                     advertising_set_will_be_removed) {
6398be7ef9d8SMatthias Ringwald 
6399be7ef9d8SMatthias Ringwald                     advertising_stop = true;
6400be7ef9d8SMatthias Ringwald                     advertising_stop_set = advertising_set;
6401be7ef9d8SMatthias Ringwald                     break;
6402be7ef9d8SMatthias Ringwald                 }
6403be7ef9d8SMatthias Ringwald             }
6404c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
640553f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
640653f240c0SMatthias Ringwald                 // stop if:
640753f240c0SMatthias Ringwald                 // - it's disabled
640853f240c0SMatthias Ringwald                 // - parameter change required
640953f240c0SMatthias Ringwald                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
641053f240c0SMatthias Ringwald                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
641153f240c0SMatthias Ringwald                 if ((periodic_enabled == false) || periodic_parameter_change){
641249a6c69cSMatthias Ringwald                     periodic_advertising_stop = true;
641353f240c0SMatthias Ringwald                     advertising_stop_set = advertising_set;
641453f240c0SMatthias Ringwald                 }
641553f240c0SMatthias Ringwald             }
641649a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
641753f240c0SMatthias Ringwald         }
6418be7ef9d8SMatthias Ringwald     }
6419be7ef9d8SMatthias Ringwald #endif
6420be7ef9d8SMatthias Ringwald 
6421a41310b7SMatthias Ringwald #endif
6422fde725feSMatthias Ringwald 
6423a41310b7SMatthias Ringwald 
6424a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
6425a41310b7SMatthias Ringwald 
6426131d4778SMatthias Ringwald 
6427131d4778SMatthias Ringwald     // 2.1 Outgoing connection
6428131d4778SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6429131d4778SMatthias Ringwald     if (connecting_stop){
6430131d4778SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
6431131d4778SMatthias Ringwald         return true;
6432131d4778SMatthias Ringwald     }
6433131d4778SMatthias Ringwald #endif
6434131d4778SMatthias Ringwald 
6435131d4778SMatthias Ringwald     // 2.2 Scanning
6436a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6437a41310b7SMatthias Ringwald     if (scanning_stop){
64385226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
6439c42da3bcSMatthias Ringwald         hci_le_scan_stop();
6440a41310b7SMatthias Ringwald         return true;
6441a41310b7SMatthias Ringwald     }
6442a41310b7SMatthias Ringwald 
6443131d4778SMatthias Ringwald     // 2.3 Periodic Sync
64444bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
644549a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
644649a6c69cSMatthias Ringwald         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
644749a6c69cSMatthias Ringwald         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
644849a6c69cSMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
644949a6c69cSMatthias Ringwald         return true;
645049a6c69cSMatthias Ringwald     }
645149a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
64524bafedd5SMatthias Ringwald     if (periodic_sync_stop){
64534bafedd5SMatthias Ringwald         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
64544bafedd5SMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
64554bafedd5SMatthias Ringwald         return true;
64564bafedd5SMatthias Ringwald     }
645749a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6458a8016f96SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6459a8016f96SMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
6460a41310b7SMatthias Ringwald 
6461131d4778SMatthias Ringwald     // 2.4 Advertising: legacy, extended, periodic
6462a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6463fde725feSMatthias Ringwald     if (advertising_stop){
6464e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
646522f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()) {
6466be7ef9d8SMatthias Ringwald             uint8_t advertising_stop_handle;
6467be7ef9d8SMatthias Ringwald             if (advertising_stop_set != NULL){
6468be7ef9d8SMatthias Ringwald                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6469be7ef9d8SMatthias Ringwald                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6470be7ef9d8SMatthias Ringwald             } else {
6471be7ef9d8SMatthias Ringwald                 advertising_stop_handle = 0;
6472be7ef9d8SMatthias Ringwald                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6473be7ef9d8SMatthias Ringwald             }
6474be7ef9d8SMatthias Ringwald             const uint8_t advertising_handles[] = { advertising_stop_handle };
6475e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6476e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6477e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6478e464cd48SMatthias Ringwald         } else
6479e464cd48SMatthias Ringwald #endif
6480e464cd48SMatthias Ringwald         {
6481be7ef9d8SMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
648245c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6483e464cd48SMatthias Ringwald         }
6484f30077b7SMatthias Ringwald         return true;
648545c102fdSMatthias Ringwald     }
648653f240c0SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6487c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
648849a6c69cSMatthias Ringwald     if (periodic_advertising_stop){
648953f240c0SMatthias Ringwald         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
649053f240c0SMatthias Ringwald         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
649153f240c0SMatthias Ringwald         return true;
649253f240c0SMatthias Ringwald     }
6493c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6494c814a904SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6495a8016f96SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
6496fde725feSMatthias Ringwald 
6497131d4778SMatthias Ringwald 
6498a41310b7SMatthias Ringwald     // Phase 3: modify
6499a41310b7SMatthias Ringwald 
6500137a570aSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6501137a570aSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6502137a570aSMatthias Ringwald         // GAP Privacy, notify clients upon upcoming random address change
6503137a570aSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
65041fa7a4bbSMatthias Ringwald         // notify might cause hci_run to get executed, check if we still can send
6505137a570aSMatthias Ringwald         gap_privacy_clients_notify(hci_stack->le_random_address);
65061fa7a4bbSMatthias Ringwald         if (!hci_can_send_command_packet_now()) {
65071fa7a4bbSMatthias Ringwald             return true;
65081fa7a4bbSMatthias Ringwald         }
6509137a570aSMatthias Ringwald     }
6510137a570aSMatthias Ringwald 
6511137a570aSMatthias Ringwald     // - wait until privacy update completed
6512137a570aSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6513137a570aSMatthias Ringwald         return false;
6514137a570aSMatthias Ringwald     }
6515137a570aSMatthias Ringwald 
651664f9dabaSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
65179136bde8SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
65189136bde8SMatthias Ringwald         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6519ae35a99cSMatthias Ringwald #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6520ae35a99cSMatthias Ringwald         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6521ae35a99cSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6522ae35a99cSMatthias Ringwald #endif
65239136bde8SMatthias Ringwald         return true;
65249136bde8SMatthias Ringwald     }
65259136bde8SMatthias Ringwald 
6526a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6527a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
6528a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
652963671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
653022f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
65317eb5b27eSMatthias Ringwald             // prepare arrays for all phys (LE Coded and LE 1M PHY)
65327eb5b27eSMatthias Ringwald             uint8_t  scan_types[2];
65337eb5b27eSMatthias Ringwald             uint16_t scan_intervals[2];
65347eb5b27eSMatthias Ringwald             uint16_t scan_windows[2];
65357eb5b27eSMatthias Ringwald 
65367eb5b27eSMatthias Ringwald             uint8_t i;
65377eb5b27eSMatthias Ringwald             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
65387eb5b27eSMatthias Ringwald             for (i=0;i<num_phys;i++){
65397eb5b27eSMatthias Ringwald                 scan_types[i]     = hci_stack->le_scan_type;
65407eb5b27eSMatthias Ringwald                 scan_intervals[i] = hci_stack->le_scan_interval;
65417eb5b27eSMatthias Ringwald                 scan_windows[i]   = hci_stack->le_scan_window;
65427eb5b27eSMatthias Ringwald             }
654363671e69SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
65447eb5b27eSMatthias Ringwald                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
654563671e69SMatthias Ringwald         } else
654663671e69SMatthias Ringwald #endif
654763671e69SMatthias Ringwald         {
6548a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6549a41310b7SMatthias Ringwald                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
655063671e69SMatthias Ringwald         }
6551a41310b7SMatthias Ringwald         return true;
6552a41310b7SMatthias Ringwald     }
6553a41310b7SMatthias Ringwald #endif
6554a41310b7SMatthias Ringwald 
6555a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
655645c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
655745c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
65586bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6559e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
656022f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6561e464cd48SMatthias Ringwald             // map advertisment type to advertising event properties
6562e464cd48SMatthias Ringwald             uint16_t adv_event_properties = 0;
656336916f81SDirk Helbig             //                           0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000
656436916f81SDirk Helbig             const uint16_t mapping[] = {       0x13,       0x15,       0x1D,       0x12,       0x10 };
6565e464cd48SMatthias Ringwald             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6566e464cd48SMatthias Ringwald                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6567e464cd48SMatthias Ringwald             }
6568174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6569e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6570e464cd48SMatthias Ringwald                          0,
6571e464cd48SMatthias Ringwald                          adv_event_properties,
6572e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
6573e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
6574e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
6575e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
6576e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
6577e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
6578e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_filter_policy,
6579e464cd48SMatthias Ringwald                          0x7f,  // tx power: no preference
6580e464cd48SMatthias Ringwald                          0x01,  // primary adv phy: LE 1M
6581e464cd48SMatthias Ringwald                          0,     // secondary adv max skip
65825375ad13SMatthias Ringwald                          0x01,  // secondary adv phy
6583e464cd48SMatthias Ringwald                          0,     // adv sid
6584e464cd48SMatthias Ringwald                          0      // scan request notification
6585e464cd48SMatthias Ringwald                          );
6586d935373dSMatthias Ringwald         } else
6587e464cd48SMatthias Ringwald #endif
6588e464cd48SMatthias Ringwald         {
658945c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
659045c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
659145c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
659245c102fdSMatthias Ringwald                          hci_stack->le_advertisements_type,
65936bcfa632SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
659445c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
659545c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
659645c102fdSMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
659745c102fdSMatthias Ringwald                          hci_stack->le_advertisements_filter_policy);
6598e464cd48SMatthias Ringwald         }
6599f30077b7SMatthias Ringwald         return true;
660045c102fdSMatthias Ringwald     }
6601be7ef9d8SMatthias Ringwald 
66029ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
66039ce6dfa1SMatthias Ringwald     // assumption: only set if extended advertising is supported
66049ce6dfa1SMatthias Ringwald     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
66059ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
66069ce6dfa1SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
66079ce6dfa1SMatthias Ringwald         return true;
66089ce6dfa1SMatthias Ringwald     }
66099ce6dfa1SMatthias Ringwald #endif
66109ce6dfa1SMatthias Ringwald 
6611501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6612501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
66137a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
66147a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
66156535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
66166535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
66173c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6618e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
661922f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6620174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6621e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6622e464cd48SMatthias Ringwald         } else
6623e464cd48SMatthias Ringwald #endif
6624e464cd48SMatthias Ringwald         {
66257a85e4f5SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6626e464cd48SMatthias Ringwald         }
6627f30077b7SMatthias Ringwald         return true;
662845c102fdSMatthias Ringwald     }
6629be7ef9d8SMatthias Ringwald 
6630501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6631501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6632f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
6633f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
66346535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
66356535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
66363c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6637e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
663822f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6639174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6640e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6641e464cd48SMatthias Ringwald         } else
6642e464cd48SMatthias Ringwald #endif
6643e464cd48SMatthias Ringwald         {
6644214bfd60SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6645e464cd48SMatthias Ringwald         }
6646f30077b7SMatthias Ringwald         return true;
6647501f56b3SMatthias Ringwald     }
6648be7ef9d8SMatthias Ringwald 
6649be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
665022f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
6651be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6652be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6653be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6654be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6655be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6656be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6657174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6658be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6659be7ef9d8SMatthias Ringwald                 return true;
6660be7ef9d8SMatthias Ringwald             }
6661be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6662be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6663174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6664be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6665be7ef9d8SMatthias Ringwald                              advertising_set->advertising_handle,
666657a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_event_properties,
666757a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_min,
666857a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_max,
666957a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_channel_map,
667057a04237SMatthias Ringwald                              advertising_set->extended_params.own_address_type,
667157a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address_type,
667257a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address,
667357a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_filter_policy,
667457a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_tx_power,
667557a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_phy,
667657a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_max_skip,
667757a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_phy,
667857a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_sid,
667957a04237SMatthias Ringwald                              advertising_set->extended_params.scan_request_notification_enable
6680be7ef9d8SMatthias Ringwald                 );
6681be7ef9d8SMatthias Ringwald                 return true;
6682be7ef9d8SMatthias Ringwald             }
66830f54aa8dSMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
66840f54aa8dSMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
66850f54aa8dSMatthias Ringwald                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
66860f54aa8dSMatthias Ringwald                 return true;
66870f54aa8dSMatthias Ringwald             }
6688be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6689be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->adv_data_pos;
6690be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6691be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6692be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6693be7ef9d8SMatthias Ringwald                     // last fragment or complete data
6694be7ef9d8SMatthias Ringwald                     operation |= 2;
6695be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos = 0;
6696be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6697be7ef9d8SMatthias Ringwald                 } else {
6698be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos += data_to_upload;
6699be7ef9d8SMatthias Ringwald                 }
6700174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
67010cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6702be7ef9d8SMatthias Ringwald                 return true;
6703be7ef9d8SMatthias Ringwald             }
6704be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6705be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->scan_data_pos;
6706be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6707be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6708be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6709be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos = 0;
6710be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6711be7ef9d8SMatthias Ringwald                 } else {
6712be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos += data_to_upload;
6713be7ef9d8SMatthias Ringwald                 }
6714174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
67158ef6d15fSMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6716be7ef9d8SMatthias Ringwald                 return true;
6717be7ef9d8SMatthias Ringwald             }
6718c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
671953f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
672053f240c0SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
672153f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
672253f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
672353f240c0SMatthias Ringwald                              advertising_set->advertising_handle,
672453f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_min,
672553f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_max,
672653f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_properties);
672753f240c0SMatthias Ringwald                 return true;
672853f240c0SMatthias Ringwald             }
672953f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
67300cbe4690SMatthias Ringwald                 uint16_t pos = advertising_set->periodic_data_pos;
673153f240c0SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
673253f240c0SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
673353f240c0SMatthias Ringwald                 if ((operation & 0x02) != 0){
673453f240c0SMatthias Ringwald                     // last fragment or complete data
673553f240c0SMatthias Ringwald                     operation |= 2;
67360cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos = 0;
673753f240c0SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
673853f240c0SMatthias Ringwald                 } else {
67390cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos += data_to_upload;
674053f240c0SMatthias Ringwald                 }
674153f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
67420cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
674353f240c0SMatthias Ringwald                 return true;
674453f240c0SMatthias Ringwald             }
6745c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6746be7ef9d8SMatthias Ringwald         }
6747be7ef9d8SMatthias Ringwald     }
6748be7ef9d8SMatthias Ringwald #endif
6749be7ef9d8SMatthias Ringwald 
6750d70217a2SMatthias Ringwald #endif
67519956955bSMatthias Ringwald 
6752057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6753a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
6754a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
67554bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
67564bafedd5SMatthias Ringwald     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
67574bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
67584bafedd5SMatthias Ringwald #endif
6759057ab60cSMatthias Ringwald #endif
6760057ab60cSMatthias Ringwald 
6761a41310b7SMatthias Ringwald     // LE Whitelist Management
6762a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
67632c052b15SMatthias Ringwald         bool done = hci_whitelist_modification_process();
67642c052b15SMatthias Ringwald         if (done) return true;
676591915b0bSMatthias Ringwald     }
67669956955bSMatthias Ringwald 
676721debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
676821debf25SMatthias Ringwald     // LE Resolving List Management
67692fbf0ed0SMatthias Ringwald     if (resolving_list_modification_pending) {
677021debf25SMatthias Ringwald 		uint16_t i;
67718dc1b1d0SMatthias Ringwald         uint8_t null_16[16];
67728dc1b1d0SMatthias Ringwald         uint8_t local_irk_flipped[16];
67738dc1b1d0SMatthias Ringwald         const uint8_t *local_irk;
677421debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
677521debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
677621debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
677721debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
677821debf25SMatthias Ringwald 				return true;
677921debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
678021debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
678121debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
678221debf25SMatthias Ringwald 				return true;
678321debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
67848dc1b1d0SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6785ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6786ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
6787e8ca66c6SMatthias Ringwald                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6788e8ca66c6SMatthias Ringwald                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6789ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6790ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
679121debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
679221debf25SMatthias Ringwald 				return true;
67938dc1b1d0SMatthias Ringwald             case LE_RESOLVING_LIST_SET_IRK:
67948dc1b1d0SMatthias Ringwald                 // set IRK used by RPA for undirected advertising
67958dc1b1d0SMatthias Ringwald                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
67968dc1b1d0SMatthias Ringwald                 local_irk = gap_get_persistent_irk();
67978dc1b1d0SMatthias Ringwald                 reverse_128(local_irk, local_irk_flipped);
67988dc1b1d0SMatthias Ringwald                 memset(null_16, 0, sizeof(null_16));
67998dc1b1d0SMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
68008dc1b1d0SMatthias Ringwald                              null_16, local_irk_flipped);
68018dc1b1d0SMatthias Ringwald                 return true;
68025f3ccd83SMatthias Ringwald 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
68035f3ccd83SMatthias Ringwald                 // first remove old entries
680402b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
680502b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
680602b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
680702b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
680802b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
680902b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
681002b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
681102b02cffSMatthias Ringwald 					sm_key_t peer_irk;
681202b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
681302b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6814f5228c62SMatthias Ringwald 
6815f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6816f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
6817f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6818f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
6819f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
682095f31ee8SMatthias Ringwald 						if ((int)entry->address_type != peer_identity_addr_type) continue;
6821f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6822f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6823f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6824f5228c62SMatthias Ringwald 					}
6825f5228c62SMatthias Ringwald #endif
6826f5228c62SMatthias Ringwald 
6827ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6828ea151974SMatthias Ringwald 								 peer_identity_addreses);
682902b02cffSMatthias Ringwald 					return true;
683002b02cffSMatthias Ringwald 				}
683102b02cffSMatthias Ringwald 
68325f3ccd83SMatthias Ringwald                 // then add new entries
683321debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
683421debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
683521debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
683602b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
683702b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
683821debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
683921debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
684021debf25SMatthias Ringwald 					sm_key_t peer_irk;
684121debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
684221debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6843e938c062SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
68442b6efc4dSMatthias Ringwald 					local_irk = gap_get_persistent_irk();
684521debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
684621debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
684721debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
684821debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
6849ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6850ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
685121debf25SMatthias Ringwald 					return true;
685221debf25SMatthias Ringwald 				}
6853e8ca66c6SMatthias Ringwald 
6854e8ca66c6SMatthias Ringwald                 // finally, set privacy mode
6855e8ca66c6SMatthias Ringwald                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6856e8ca66c6SMatthias Ringwald                     uint8_t offset = i >> 3;
6857e8ca66c6SMatthias Ringwald                     uint8_t mask = 1 << (i & 7);
6858e8ca66c6SMatthias Ringwald                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6859e8ca66c6SMatthias Ringwald                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6860e8ca66c6SMatthias Ringwald                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6861e8ca66c6SMatthias Ringwald                         // Network Privacy Mode is default
6862e8ca66c6SMatthias Ringwald                         continue;
6863e8ca66c6SMatthias Ringwald                     }
6864e8ca66c6SMatthias Ringwald                     bd_addr_t peer_identity_address;
6865e8ca66c6SMatthias Ringwald                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6866e8ca66c6SMatthias Ringwald                     sm_key_t peer_irk;
6867e8ca66c6SMatthias Ringwald                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6868e8ca66c6SMatthias Ringwald                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6869e8ca66c6SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
6870e8ca66c6SMatthias Ringwald                     // command uses format specifier 'P' that stores 16-byte value without flip
6871e8ca66c6SMatthias Ringwald                     uint8_t peer_irk_flipped[16];
6872e8ca66c6SMatthias Ringwald                     reverse_128(peer_irk, peer_irk_flipped);
6873e8ca66c6SMatthias Ringwald                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6874e8ca66c6SMatthias Ringwald                     return true;
6875e8ca66c6SMatthias Ringwald                 }
687621debf25SMatthias Ringwald 				break;
687702b02cffSMatthias Ringwald 
687821debf25SMatthias Ringwald 			default:
687921debf25SMatthias Ringwald 				break;
688021debf25SMatthias Ringwald 		}
688121debf25SMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
68822fbf0ed0SMatthias Ringwald 	}
688321debf25SMatthias Ringwald #endif
6884a41310b7SMatthias Ringwald 
6885f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6886f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6887f40c73b4SMatthias Ringwald     // LE Whitelist Management
6888f40c73b4SMatthias Ringwald     if (periodic_list_modification_pending){
6889f40c73b4SMatthias Ringwald         // add/remove entries
6890f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6891f40c73b4SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
6892f40c73b4SMatthias Ringwald             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6893f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6894f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6895d946a741SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6896f40c73b4SMatthias Ringwald                 return true;
6897f40c73b4SMatthias Ringwald             }
6898f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6899f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6900f40c73b4SMatthias Ringwald                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
69019e88556bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6902f40c73b4SMatthias Ringwald                 return true;
6903f40c73b4SMatthias Ringwald             }
6904f40c73b4SMatthias Ringwald             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6905f40c73b4SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6906f40c73b4SMatthias Ringwald                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6907f40c73b4SMatthias Ringwald             }
6908f40c73b4SMatthias Ringwald         }
6909f40c73b4SMatthias Ringwald     }
6910f40c73b4SMatthias Ringwald #endif
6911f40c73b4SMatthias Ringwald #endif
6912f40c73b4SMatthias Ringwald 
691398aa715fSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
691498aa715fSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
691598aa715fSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
691698aa715fSMatthias Ringwald     if (hci_stack->le_past_set_default_params){
691798aa715fSMatthias Ringwald         hci_stack->le_past_set_default_params = false;
691898aa715fSMatthias Ringwald         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
691998aa715fSMatthias Ringwald                      hci_stack->le_past_mode,
692098aa715fSMatthias Ringwald                      hci_stack->le_past_skip,
692198aa715fSMatthias Ringwald                      hci_stack->le_past_sync_timeout,
692298aa715fSMatthias Ringwald                      hci_stack->le_past_cte_type);
692398aa715fSMatthias Ringwald         return true;
692498aa715fSMatthias Ringwald     }
692598aa715fSMatthias Ringwald #endif
692698aa715fSMatthias Ringwald #endif
692798aa715fSMatthias Ringwald #endif
692898aa715fSMatthias Ringwald 
6929a086dc35SMatthias Ringwald     // postpone all actions until stack is fully working
693073799937SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
693173799937SMatthias Ringwald 
693273799937SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
693373799937SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
693473799937SMatthias Ringwald 
6935a41310b7SMatthias Ringwald     // Phase 4: restore state
693629c24bebSMatthias Ringwald 
693729c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6938af64f147SMatthias Ringwald     // re-start scanning
693929c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
694029c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
694163671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
694222f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
69434856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
694463671e69SMatthias Ringwald         } else
694563671e69SMatthias Ringwald #endif
694663671e69SMatthias Ringwald         {
69474856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
694863671e69SMatthias Ringwald         }
694929c24bebSMatthias Ringwald         return true;
695029c24bebSMatthias Ringwald     }
695129c24bebSMatthias Ringwald #endif
695229c24bebSMatthias Ringwald 
695313eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6954af64f147SMatthias Ringwald     // re-start connecting
6955af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
69569956955bSMatthias Ringwald         bd_addr_t null_addr;
69579956955bSMatthias Ringwald         memset(null_addr, 0, 6);
69586bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
69596bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
69606f34e9d6SMatthias Ringwald         hci_send_le_create_connection(1, 0, null_addr);
6961f30077b7SMatthias Ringwald         return true;
69629956955bSMatthias Ringwald     }
69634bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
69644bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
69654bafedd5SMatthias Ringwald         switch(hci_stack->le_periodic_sync_request){
69664bafedd5SMatthias Ringwald             case LE_CONNECTING_DIRECT:
69674bafedd5SMatthias Ringwald             case LE_CONNECTING_WHITELIST:
69684bafedd5SMatthias Ringwald                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
69694bafedd5SMatthias Ringwald                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
69704bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_options,
69714bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertising_sid,
69724bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address_type,
69734bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address,
69744bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_skip,
69754bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_timeout,
69764bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_cte_type);
69774bafedd5SMatthias Ringwald                 return true;
69784bafedd5SMatthias Ringwald             default:
69794bafedd5SMatthias Ringwald                 break;
69804bafedd5SMatthias Ringwald         }
69814bafedd5SMatthias Ringwald     }
69824bafedd5SMatthias Ringwald #endif
6983d70217a2SMatthias Ringwald #endif
6984a41310b7SMatthias Ringwald 
6985a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6986a41310b7SMatthias Ringwald     // re-start advertising
6987935aa76eSMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6988a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
6989935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6990b892db1cSMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6991e464cd48SMatthias Ringwald 
6992e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
699322f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6994e464cd48SMatthias Ringwald             const uint8_t advertising_handles[] = { 0 };
6995e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6996e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6997e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6998e464cd48SMatthias Ringwald         } else
6999e464cd48SMatthias Ringwald #endif
7000e464cd48SMatthias Ringwald         {
7001a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
7002e464cd48SMatthias Ringwald         }
7003a41310b7SMatthias Ringwald         return true;
7004a41310b7SMatthias Ringwald     }
7005be7ef9d8SMatthias Ringwald 
7006be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
700722f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
7008be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
7009be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7010be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)) {
7011be7ef9d8SMatthias Ringwald             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7012be7ef9d8SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
70138caa405cSMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
7014be7ef9d8SMatthias Ringwald                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
7015be7ef9d8SMatthias Ringwald                 const uint16_t durations[] = { advertising_set->enable_timeout };
7016be7ef9d8SMatthias Ringwald                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
7017be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
7018be7ef9d8SMatthias Ringwald                 return true;
7019be7ef9d8SMatthias Ringwald             }
7020c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
702153f240c0SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
702253f240c0SMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
702353f240c0SMatthias Ringwald                 uint8_t enable = 1;
702453f240c0SMatthias Ringwald                 if (advertising_set->periodic_include_adi){
702553f240c0SMatthias Ringwald                     enable |= 2;
702653f240c0SMatthias Ringwald                 }
702753f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
702853f240c0SMatthias Ringwald                 return true;
702953f240c0SMatthias Ringwald             }
7030c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7031be7ef9d8SMatthias Ringwald         }
7032be7ef9d8SMatthias Ringwald     }
7033be7ef9d8SMatthias Ringwald #endif
7034a41310b7SMatthias Ringwald #endif
7035a41310b7SMatthias Ringwald 
7036f30077b7SMatthias Ringwald     return false;
70377bdc6798S[email protected] }
70387aa35f6aSMatthias Ringwald 
70397aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
70407aa35f6aSMatthias Ringwald static bool hci_run_iso_tasks(void){
70417aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
70422a6c0f82SMatthias Ringwald 
704326b93350SMatthias Ringwald     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
704440f86dfdSMatthias Ringwald         return false;
704540f86dfdSMatthias Ringwald     }
704640f86dfdSMatthias Ringwald 
70472a6c0f82SMatthias Ringwald     // BIG
70487aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
70497aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
70507aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
70517aa35f6aSMatthias Ringwald         switch (big->state){
70527aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
705340f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
705440f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
70557aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
70567aa35f6aSMatthias Ringwald                 hci_send_cmd(&hci_le_create_big,
70577aa35f6aSMatthias Ringwald                              big->params->big_handle,
70587aa35f6aSMatthias Ringwald                              big->params->advertising_handle,
70597aa35f6aSMatthias Ringwald                              big->params->num_bis,
70607aa35f6aSMatthias Ringwald                              big->params->sdu_interval_us,
70617aa35f6aSMatthias Ringwald                              big->params->max_sdu,
70627aa35f6aSMatthias Ringwald                              big->params->max_transport_latency_ms,
70637aa35f6aSMatthias Ringwald                              big->params->rtn,
70647aa35f6aSMatthias Ringwald                              big->params->phy,
70657aa35f6aSMatthias Ringwald                              big->params->packing,
70667aa35f6aSMatthias Ringwald                              big->params->framing,
70677aa35f6aSMatthias Ringwald                              big->params->encryption,
70687aa35f6aSMatthias Ringwald                              big->params->broadcast_code);
70697aa35f6aSMatthias Ringwald                 return true;
70707aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
70717aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
707285dc435bSDirk Helbig                 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);
70737aa35f6aSMatthias Ringwald                 return true;
70747aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
70757aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
70762a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
7077c1f83111SMatthias Ringwald                 return true;
70787aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
70797aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
7080d1620e55SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
70817aa35f6aSMatthias Ringwald                 return true;
70827aa35f6aSMatthias Ringwald             default:
70837aa35f6aSMatthias Ringwald                 break;
70847aa35f6aSMatthias Ringwald         }
70857aa35f6aSMatthias Ringwald     }
70862a6c0f82SMatthias Ringwald 
70872a6c0f82SMatthias Ringwald     // BIG Sync
70882a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
70892a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
70902a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
70912a6c0f82SMatthias Ringwald         switch (big_sync->state){
70922a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
709340f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
709440f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
70952a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
70962a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_create_sync,
70972a6c0f82SMatthias Ringwald                              big_sync->params->big_handle,
70982a6c0f82SMatthias Ringwald                              big_sync->params->sync_handle,
70992a6c0f82SMatthias Ringwald                              big_sync->params->encryption,
71002a6c0f82SMatthias Ringwald                              big_sync->params->broadcast_code,
71012a6c0f82SMatthias Ringwald                              big_sync->params->mse,
71022a6c0f82SMatthias Ringwald                              big_sync->params->big_sync_timeout_10ms,
71032a6c0f82SMatthias Ringwald                              big_sync->params->num_bis,
71042a6c0f82SMatthias Ringwald                              big_sync->params->bis_indices);
71052a6c0f82SMatthias Ringwald                 return true;
71062a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
71072a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
710885dc435bSDirk Helbig                 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);
71092a6c0f82SMatthias Ringwald                 return true;
71102a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
71112a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
71122a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
7113c1f83111SMatthias Ringwald                 return true;
71142a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
71152a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
71162a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
71172a6c0f82SMatthias Ringwald                 return true;
71182a6c0f82SMatthias Ringwald             default:
71192a6c0f82SMatthias Ringwald                 break;
71202a6c0f82SMatthias Ringwald         }
71212a6c0f82SMatthias Ringwald     }
71222a6c0f82SMatthias Ringwald 
7123d3a89d91SMatthias Ringwald     // CIG
7124d90722d4SMatthias Ringwald     bool cig_active;
7125d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
7126d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
7127d3a89d91SMatthias Ringwald         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
7128d3a89d91SMatthias Ringwald         uint8_t i;
7129444e371eSMatthias Ringwald         // Set CIG Parameters
7130d3a89d91SMatthias Ringwald         uint8_t cis_id[MAX_NR_CIS];
7131d3a89d91SMatthias Ringwald         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7132d3a89d91SMatthias Ringwald         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7133d3a89d91SMatthias Ringwald         uint8_t phy_c_to_p[MAX_NR_CIS];
7134d3a89d91SMatthias Ringwald         uint8_t phy_p_to_c[MAX_NR_CIS];
7135d3a89d91SMatthias Ringwald         uint8_t rtn_c_to_p[MAX_NR_CIS];
7136d3a89d91SMatthias Ringwald         uint8_t rtn_p_to_c[MAX_NR_CIS];
7137d3a89d91SMatthias Ringwald         switch (cig->state) {
7138d3a89d91SMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE:
7139d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7140d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7141d3a89d91SMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7142d3a89d91SMatthias Ringwald                 le_audio_cig_params_t * params = cig->params;
7143d3a89d91SMatthias Ringwald                 for (i = 0; i < params->num_cis; i++) {
7144d3a89d91SMatthias Ringwald                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7145d3a89d91SMatthias Ringwald                     cis_id[i]         = cis_params->cis_id;
7146d3a89d91SMatthias Ringwald                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7147d3a89d91SMatthias Ringwald                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7148d3a89d91SMatthias Ringwald                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7149d3a89d91SMatthias Ringwald                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7150d3a89d91SMatthias Ringwald                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7151d3a89d91SMatthias Ringwald                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7152d3a89d91SMatthias Ringwald                 }
7153d3a89d91SMatthias Ringwald                 hci_send_cmd(&hci_le_set_cig_parameters,
7154d3a89d91SMatthias Ringwald                              cig->cig_id,
7155d3a89d91SMatthias Ringwald                              params->sdu_interval_c_to_p,
7156d3a89d91SMatthias Ringwald                              params->sdu_interval_p_to_c,
7157d3a89d91SMatthias Ringwald                              params->worst_case_sca,
7158d3a89d91SMatthias Ringwald                              params->packing,
7159d3a89d91SMatthias Ringwald                              params->framing,
7160d3a89d91SMatthias Ringwald                              params->max_transport_latency_c_to_p,
7161d3a89d91SMatthias Ringwald                              params->max_transport_latency_p_to_c,
7162d3a89d91SMatthias Ringwald                              params->num_cis,
7163d3a89d91SMatthias Ringwald                              cis_id,
7164d3a89d91SMatthias Ringwald                              max_sdu_c_to_p,
7165d3a89d91SMatthias Ringwald                              max_sdu_p_to_c,
7166d3a89d91SMatthias Ringwald                              phy_c_to_p,
7167d3a89d91SMatthias Ringwald                              phy_p_to_c,
7168d3a89d91SMatthias Ringwald                              rtn_c_to_p,
7169d3a89d91SMatthias Ringwald                              rtn_p_to_c
7170d3a89d91SMatthias Ringwald                 );
7171bb42b5c0SMatthias Ringwald                 return true;
7172444e371eSMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7173bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7174bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7175444e371eSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
71763abcd16cSMatthias Ringwald                 for (i=0;i<cig->num_cis;i++){
71773abcd16cSMatthias Ringwald                     cig->cis_setup_active[i] = true;
71783abcd16cSMatthias Ringwald                 }
7179444e371eSMatthias Ringwald                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7180bb42b5c0SMatthias Ringwald                 return true;
7181f9306a1aSMatthias Ringwald             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7182c5f5d706SMatthias Ringwald                 for ( ; cig->state_vars.next_cis < (cig->num_cis * 2) ; cig->state_vars.next_cis++ ){
7183f9306a1aSMatthias Ringwald                     // find next path to setup
7184f9306a1aSMatthias Ringwald                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7185f9306a1aSMatthias Ringwald                     if (cig->cis_established[cis_index] == false) {
7186f9306a1aSMatthias Ringwald                         continue;
7187f9306a1aSMatthias Ringwald                     }
7188f9306a1aSMatthias Ringwald                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7189f9306a1aSMatthias Ringwald                     bool setup = true;
71908e58e4f7SMatthias Ringwald                     if (cis_direction == 0){
7191f9306a1aSMatthias Ringwald                         // 0 - input - host to controller
7192f9306a1aSMatthias Ringwald                         // we are central => central to peripheral
7193f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7194f9306a1aSMatthias Ringwald                     } else {
7195f9306a1aSMatthias Ringwald                         // 1 - output - controller to host
7196f9306a1aSMatthias Ringwald                         // we are central => peripheral to central
7197f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7198f9306a1aSMatthias Ringwald                     }
7199f9306a1aSMatthias Ringwald                     if (setup){
7200f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7201f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7202f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
720385dc435bSDirk Helbig                         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);
7204f9306a1aSMatthias Ringwald                         return true;
7205f9306a1aSMatthias Ringwald                     }
7206f9306a1aSMatthias Ringwald                 }
7207f9306a1aSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7208d90722d4SMatthias Ringwald                 break;
7209d90722d4SMatthias Ringwald             case LE_AUDIO_CIG_STATE_REMOVE:
7210d90722d4SMatthias Ringwald                 // check if CIG Active
7211d90722d4SMatthias Ringwald                 cig_active = false;
7212d90722d4SMatthias Ringwald                 for (i = 0; i < cig->num_cis; i++) {
7213d90722d4SMatthias Ringwald                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7214d90722d4SMatthias Ringwald                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7215d90722d4SMatthias Ringwald                         if (stream != NULL){
7216d90722d4SMatthias Ringwald                             cig_active = true;
7217d90722d4SMatthias Ringwald                             break;
7218d90722d4SMatthias Ringwald                         }
7219d90722d4SMatthias Ringwald                     }
7220d90722d4SMatthias Ringwald                 }
7221d90722d4SMatthias Ringwald                 if (cig_active == false){
7222d90722d4SMatthias Ringwald                     btstack_linked_list_iterator_remove(&it);
7223d90722d4SMatthias Ringwald                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7224d90722d4SMatthias Ringwald                     return true;
7225d90722d4SMatthias Ringwald                 }
7226d3a89d91SMatthias Ringwald             default:
7227d3a89d91SMatthias Ringwald                 break;
7228d3a89d91SMatthias Ringwald         }
7229d3a89d91SMatthias Ringwald     }
7230d3a89d91SMatthias Ringwald 
7231d90722d4SMatthias Ringwald     // CIS Accept/Reject/Setup ISO Path/Close
723226b93350SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
723326b93350SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
723426b93350SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
723526b93350SMatthias Ringwald         hci_con_handle_t con_handle;
723626b93350SMatthias Ringwald         switch (iso_stream->state){
723726b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_ACCEPT:
723826b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
723926b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
724026b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7241969d876aSMatthias Ringwald                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
724226b93350SMatthias Ringwald                 return true;
724326b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_REJECT:
7244969d876aSMatthias Ringwald                 con_handle = iso_stream->cis_handle;
724526b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
724626b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
724726b93350SMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
724826b93350SMatthias Ringwald                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
724926b93350SMatthias Ringwald                 return true;
725026b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
725126b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
725226b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
725326b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
725485dc435bSDirk Helbig                 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);
725507e32b36SMatthias Ringwald                 return true;
725626b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
725726b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
725826b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
725926b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
726085dc435bSDirk Helbig                 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);
726107e32b36SMatthias Ringwald                 return true;
7262d90722d4SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7263d90722d4SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
726407e32b36SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
726507e32b36SMatthias Ringwald                 return true;
726626b93350SMatthias Ringwald             default:
726726b93350SMatthias Ringwald                 break;
726826b93350SMatthias Ringwald         }
726926b93350SMatthias Ringwald     }
727026b93350SMatthias Ringwald 
72717aa35f6aSMatthias Ringwald     return false;
72727aa35f6aSMatthias Ringwald }
72737aa35f6aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7274b2f949feS[email protected] #endif
72757bdc6798S[email protected] 
727688a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
7277f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
7278a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
727905ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
728032ab9390Smatthias.ringwald 
72810bf6344aS[email protected]         switch(connection->state){
72820bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
72834f3229d8S[email protected]                 switch(connection->address_type){
728435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7285f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
72869da54300S[email protected]                         log_info("sending hci_create_connection");
7287b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
72884f3229d8S[email protected]                         break;
728935454696SMatthias Ringwald #endif
72904f3229d8S[email protected]                     default:
7291a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
7292d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
72939da54300S[email protected]                         log_info("sending hci_le_create_connection");
72946bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
72956bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
72964f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
7297*c769c85cSMatthias Ringwald                         hci_send_le_create_connection(0, connection->address_type, connection->address);
7298b2f949feS[email protected] #endif
7299d70217a2SMatthias Ringwald #endif
73004f3229d8S[email protected]                         break;
73014f3229d8S[email protected]                 }
7302f30077b7SMatthias Ringwald                 return true;
7303ad83dc6aS[email protected] 
730435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
73050bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
7306f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
730776ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
7308895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7309c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7310f30077b7SMatthias Ringwald                     return true;
7311ee025741SMatthias Ringwald                 }
7312ee025741SMatthias Ringwald                 break;
731335454696SMatthias Ringwald #endif
73140bf6344aS[email protected]             case SEND_DISCONNECT:
73150bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
73166ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7317f30077b7SMatthias Ringwald                 return true;
73180bf6344aS[email protected] 
73190bf6344aS[email protected]             default:
73200bf6344aS[email protected]                 break;
7321c7e0c5f6Smatthias.ringwald         }
7322c7e0c5f6Smatthias.ringwald 
7323cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
7324cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
7325cabf004eSMatthias Ringwald 
732694418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
732794418890SMatthias Ringwald 
7328ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
732950f49832SMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7330608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
73318daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
733230e72d78SMatthias Ringwald 
7333e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7334e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
733530e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
7336e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
733732ab9390Smatthias.ringwald             } else {
733832ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
733932ab9390Smatthias.ringwald             }
7340f30077b7SMatthias Ringwald             return true;
734132ab9390Smatthias.ringwald         }
73421d6b20aeS[email protected] 
73438daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
73449da54300S[email protected]             log_info("denying to pin request");
73458daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
734634d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7347f30077b7SMatthias Ringwald             return true;
73484c57c146S[email protected]         }
73494c57c146S[email protected] 
7350c950c316SMatthias Ringwald         // security assessment requires remote features
73512dd8985bSMatthias Ringwald         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7352c950c316SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7353c950c316SMatthias Ringwald             hci_ssp_assess_security_on_io_cap_request(connection);
7354c950c316SMatthias Ringwald             // 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
7355c950c316SMatthias Ringwald         }
7356c950c316SMatthias Ringwald 
73578daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
73588daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7359a8d20135SMatthias Ringwald             // set authentication requirements:
7360a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7361532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7362cb912b12SMatthias Ringwald             connection->io_cap_request_auth_req = hci_stack->ssp_authentication_requirement & 1;
73639faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7364cb912b12SMatthias Ringwald                 connection->io_cap_request_auth_req |= 1;
7365106d6d11S[email protected]             }
7366532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
73678daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7368532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
7369532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7370532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
7371532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
7372532454f9SMatthias Ringwald                     bonding = false;
7373532454f9SMatthias Ringwald                 }
7374532454f9SMatthias Ringwald             }
7375532454f9SMatthias Ringwald             if (bonding){
7376a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
7377cb912b12SMatthias Ringwald                     connection->io_cap_request_auth_req |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7378532454f9SMatthias Ringwald                 } else {
7379cb912b12SMatthias Ringwald                     connection->io_cap_request_auth_req |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7380a8d20135SMatthias Ringwald                 }
7381532454f9SMatthias Ringwald             }
73821849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
73831849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
73841849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
73851849becdSMatthias Ringwald                     have_oob_data |= 1;
73861849becdSMatthias Ringwald             }
73871849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
73881849becdSMatthias Ringwald                 have_oob_data |= 2;
73891849becdSMatthias Ringwald             }
73901849becdSMatthias Ringwald #endif
7391cb912b12SMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, connection->io_cap_request_auth_req);
739211b03efaSMatthias Ringwald             return true;
7393f8fb5f6eS[email protected]         }
739411b03efaSMatthias Ringwald 
73958daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
73968daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
739711b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7398f30077b7SMatthias Ringwald             return true;
739932ab9390Smatthias.ringwald         }
740032ab9390Smatthias.ringwald 
74011849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
74027ca4a7edSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
74037ca4a7edSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
74041849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
74051849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
74061849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
74071849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
74081849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
74091849becdSMatthias Ringwald             // verify P-256 OOB
74101e83575aSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
74111849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
74121849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
74131849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
74141849becdSMatthias Ringwald                 }
74151849becdSMatthias Ringwald             }
74161849becdSMatthias Ringwald             // verify P-192 OOB
74171849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
74181849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
74191849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
74201849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
74211849becdSMatthias Ringwald                 }
74221849becdSMatthias Ringwald             }
74237ca4a7edSMatthias Ringwald 
74247ca4a7edSMatthias Ringwald             // assess security
74257ca4a7edSMatthias Ringwald             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
74267ca4a7edSMatthias Ringwald             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
74277ca4a7edSMatthias Ringwald             if (need_level_4 && !can_reach_level_4){
74287ca4a7edSMatthias Ringwald                 log_info("Level 4 required, but not possible -> abort");
74297ca4a7edSMatthias Ringwald                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
74307ca4a7edSMatthias Ringwald                 // send oob negative reply
74317ca4a7edSMatthias Ringwald                 c_256 = NULL;
74327ca4a7edSMatthias Ringwald                 c_192 = NULL;
74337ca4a7edSMatthias Ringwald             }
74347ca4a7edSMatthias Ringwald 
74351849becdSMatthias Ringwald             // Reply
74361849becdSMatthias Ringwald             if (c_256 != zero) {
74371849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
74381849becdSMatthias Ringwald             } else if (c_192 != zero){
74391849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
74401849becdSMatthias Ringwald             } else {
74411ae74bf3SMatthias Ringwald                 hci_stack->classic_oob_con_handle = connection->con_handle;
74421849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
74431849becdSMatthias Ringwald             }
74441849becdSMatthias Ringwald             return true;
74451849becdSMatthias Ringwald         }
74461849becdSMatthias Ringwald #endif
74471849becdSMatthias Ringwald 
74488daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
74498daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
745034d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7451f30077b7SMatthias Ringwald             return true;
7452dbe1a790S[email protected]         }
7453dbe1a790S[email protected] 
7454367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7455367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7456367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7457367aedc0SMatthias Ringwald             return true;
7458367aedc0SMatthias Ringwald         }
7459367aedc0SMatthias Ringwald 
74608daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
74618daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
746234d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7463f30077b7SMatthias Ringwald             return true;
7464dbe1a790S[email protected]         }
7465afd4e962S[email protected] 
7466ab0c69a9SMatthias Ringwald         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7467ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
74681bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
74696ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
74706ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7471f30077b7SMatthias Ringwald             return true;
7472ad83dc6aS[email protected]         }
747376f27cffSMatthias Ringwald 
74742a75353aSMatthias Ringwald         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
747534d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7476abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
747734d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7478f30077b7SMatthias Ringwald             return true;
7479afd4e962S[email protected]         }
748076f27cffSMatthias Ringwald 
7481dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7482dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7483dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7484f30077b7SMatthias Ringwald             return true;
7485dce78009S[email protected]         }
7486447016ffSMatthias Ringwald 
7487573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7488573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7489573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7490f30077b7SMatthias Ringwald             return true;
7491573897a0SMatthias Ringwald         }
7492447016ffSMatthias Ringwald 
7493447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7494447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7495447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7496447016ffSMatthias Ringwald             return true;
7497447016ffSMatthias Ringwald         }
7498447016ffSMatthias Ringwald 
7499447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7500447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7501447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7502447016ffSMatthias Ringwald             return true;
7503447016ffSMatthias Ringwald         }
7504447016ffSMatthias Ringwald 
7505447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7506447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7507447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7508447016ffSMatthias Ringwald             return true;
7509447016ffSMatthias Ringwald         }
751076f27cffSMatthias Ringwald #endif
751176f27cffSMatthias Ringwald 
751276f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
751376f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
75141714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
75151714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
75161714cbbdSMatthias Ringwald #endif
75176ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
75186ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
75196ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7520f30077b7SMatthias Ringwald                 return true;
752176f27cffSMatthias Ringwald             }
75226ef3696aSMatthias Ringwald         }
7523da886c03S[email protected] 
75246cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
7525f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
7526f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
7527f8ee3071SMatthias Ringwald             case 0:
7528f8ee3071SMatthias Ringwald                 break;
7529f8ee3071SMatthias Ringwald             case 0xffff:
7530f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7531f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7532f30077b7SMatthias Ringwald                 return true;
7533f8ee3071SMatthias Ringwald             default:
7534f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
7535f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7536f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7537f30077b7SMatthias Ringwald                 return true;
7538f8ee3071SMatthias Ringwald         }
753988a03c8dSMatthias Ringwald 
7540140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
7541140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
7542140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
7543140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7544140c0557SMatthias Ringwald             return true;
7545140c0557SMatthias Ringwald         }
7546140c0557SMatthias Ringwald 
7547965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7548278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
7549965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7550278ff8a9SMatthias Ringwald             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);
7551278ff8a9SMatthias Ringwald             return true;
7552278ff8a9SMatthias Ringwald         }
7553278ff8a9SMatthias Ringwald 
755488a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
755588a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
755688a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
755788a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
755888a03c8dSMatthias Ringwald             return true;
755988a03c8dSMatthias Ringwald         }
756022df2fe2SMatthias Ringwald #endif
75619afaa4d4SMatthias Ringwald 
75629afaa4d4SMatthias Ringwald         if (connection->gap_connection_tasks != 0){
756322df2fe2SMatthias Ringwald #ifdef ENABLE_CLASSIC
75649afaa4d4SMatthias Ringwald             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
75659afaa4d4SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
75669afaa4d4SMatthias Ringwald                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
75679afaa4d4SMatthias Ringwald                 return true;
75689afaa4d4SMatthias Ringwald             }
756922df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
757022df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
757122df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
757222df2fe2SMatthias Ringwald                 return true;
75739afaa4d4SMatthias Ringwald             }
75746cdc2862SMatthias Ringwald #endif
757522df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
757622df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
757722df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
757822df2fe2SMatthias Ringwald                 return true;
757922df2fe2SMatthias Ringwald             }
7580ac0f6b83SMatthias Ringwald #ifdef ENABLE_BLE
7581ac0f6b83SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7582ac0f6b83SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7583ac0f6b83SMatthias Ringwald                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7584ac0f6b83SMatthias Ringwald                 return true;
7585ac0f6b83SMatthias Ringwald             }
7586ac0f6b83SMatthias Ringwald #endif
758722df2fe2SMatthias Ringwald         }
7588f8ee3071SMatthias Ringwald 
7589a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
759073cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
759173cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
759273cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7593da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
759473cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7595c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7596d4876126SMatthias Ringwald                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7597f30077b7SMatthias Ringwald                 return true;
759873cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
759973cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
760073cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
760173cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7602d4876126SMatthias Ringwald                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7603f30077b7SMatthias Ringwald                 return true;
760473cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
760573cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
76061e0338ebSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
76071e0338ebSMatthias Ringwald                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7608f30077b7SMatthias Ringwald                 return true;
760973cd8a2aSMatthias Ringwald             default:
761073cd8a2aSMatthias Ringwald                 break;
7611c37a3166S[email protected]         }
76124ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
7613b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
7614b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
7615b90f6e0aSMatthias Ringwald             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);
7616f30077b7SMatthias Ringwald             return true;
7617b90f6e0aSMatthias Ringwald         }
76189007c891SMatthias Ringwald         if (connection->le_subrate_min > 0){
76199007c891SMatthias Ringwald             uint16_t subrate_min = connection->le_subrate_min;
76209007c891SMatthias Ringwald             connection->le_subrate_min = 0;
76219007c891SMatthias Ringwald             hci_send_cmd(&hci_le_subrate_request, connection->con_handle, subrate_min, connection->le_subrate_max, connection->le_subrate_max_latency,
76229007c891SMatthias Ringwald                              connection->le_subrate_continuation_number, connection->le_supervision_timeout);
76239007c891SMatthias Ringwald             return true;
76249007c891SMatthias Ringwald         }
76253bd96807SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
76263bd96807SMatthias Ringwald         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
76273bd96807SMatthias Ringwald             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
76283bd96807SMatthias Ringwald             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
76293bd96807SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
76303bd96807SMatthias Ringwald             return true;
76313bd96807SMatthias Ringwald         }
7632027f4677SMatthias Ringwald         if (connection->le_past_advertising_handle != 0xff){
7633027f4677SMatthias Ringwald             uint8_t advertising_handle = connection->le_past_advertising_handle;
7634027f4677SMatthias Ringwald             connection->le_past_advertising_handle = 0xff;
7635027f4677SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7636027f4677SMatthias Ringwald             return true;
7637027f4677SMatthias Ringwald         }
76383bd96807SMatthias Ringwald #endif
7639c37a3166S[email protected] #endif
7640dbe1a790S[email protected]     }
7641f30077b7SMatthias Ringwald     return false;
7642f30077b7SMatthias Ringwald }
7643c7e0c5f6Smatthias.ringwald 
7644f30077b7SMatthias Ringwald static void hci_run(void){
7645f30077b7SMatthias Ringwald 
7646df9e2780SMatthias Ringwald     // stack state sub statemachines
7647df9e2780SMatthias Ringwald     switch (hci_stack->state) {
7648df9e2780SMatthias Ringwald         case HCI_STATE_INITIALIZING:
7649df9e2780SMatthias Ringwald             hci_initializing_run();
7650d0dea5fbSMatthias Ringwald             break;
7651df9e2780SMatthias Ringwald         case HCI_STATE_HALTING:
7652df9e2780SMatthias Ringwald             hci_halting_run();
7653d0dea5fbSMatthias Ringwald             break;
7654df9e2780SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
7655df9e2780SMatthias Ringwald             hci_falling_asleep_run();
7656d0dea5fbSMatthias Ringwald             break;
7657df9e2780SMatthias Ringwald         default:
7658df9e2780SMatthias Ringwald             break;
7659df9e2780SMatthias Ringwald     }
7660df9e2780SMatthias Ringwald 
7661d0dea5fbSMatthias Ringwald     // allow to run after initialization to working transition
7662d0dea5fbSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING){
7663d0dea5fbSMatthias Ringwald         return;
7664d0dea5fbSMatthias Ringwald     }
7665d0dea5fbSMatthias Ringwald 
7666f30077b7SMatthias Ringwald     bool done;
7667f30077b7SMatthias Ringwald 
7668f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
7669f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
7670f30077b7SMatthias Ringwald     if (done) return;
7671f30077b7SMatthias Ringwald 
767268ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
767368ab6207SMatthias Ringwald     done = hci_run_iso_fragments();
767468ab6207SMatthias Ringwald     if (done) return;
767568ab6207SMatthias Ringwald #endif
767668ab6207SMatthias Ringwald 
7677f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7678f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
7679c69be560SMatthias Ringwald     if (!hci_can_send_command_packet_transport()) return;
7680f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
7681f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
7682f30077b7SMatthias Ringwald         return;
7683f30077b7SMatthias Ringwald     }
7684f30077b7SMatthias Ringwald #endif
7685f30077b7SMatthias Ringwald 
7686f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
7687f30077b7SMatthias Ringwald 
7688f30077b7SMatthias Ringwald     // global/non-connection oriented commands
7689f30077b7SMatthias Ringwald 
7690f30077b7SMatthias Ringwald 
7691f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
7692f30077b7SMatthias Ringwald     // general gap classic
7693f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
7694f30077b7SMatthias Ringwald     if (done) return;
7695f30077b7SMatthias Ringwald #endif
7696f30077b7SMatthias Ringwald 
7697f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
7698f30077b7SMatthias Ringwald     // general gap le
7699f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
7700f30077b7SMatthias Ringwald     if (done) return;
77017aa35f6aSMatthias Ringwald 
77027aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
77037aa35f6aSMatthias Ringwald     // ISO related tasks, e.g. BIG create/terminate/sync
77047aa35f6aSMatthias Ringwald     done = hci_run_iso_tasks();
77057aa35f6aSMatthias Ringwald     if (done) return;
77067aa35f6aSMatthias Ringwald #endif
7707f30077b7SMatthias Ringwald #endif
7708f30077b7SMatthias Ringwald 
7709f30077b7SMatthias Ringwald     // send pending HCI commands
7710df9e2780SMatthias Ringwald     hci_run_general_pending_commands();
77113429f56bSmatthias.ringwald }
771216833f0aSmatthias.ringwald 
77130f076adeSMatthias Ringwald #ifdef ENABLE_CLASSIC
7714d7891039SMatthias Ringwald static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7715d7891039SMatthias Ringwald     // bits 6-9 are 'don't use'
7716d7891039SMatthias Ringwald     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7717d7891039SMatthias Ringwald 
7718d7891039SMatthias Ringwald     // restrict packet types to local and remote supported
7719d7891039SMatthias Ringwald     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7720d7891039SMatthias Ringwald     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7721d7891039SMatthias Ringwald     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7722d7891039SMatthias Ringwald }
77230f076adeSMatthias Ringwald #endif
7724d7891039SMatthias Ringwald 
7725ca6804fdSMatthias Ringwald // funnel for sending cmd packet using single outgoing buffer
7726ed208344SMatthias Ringwald static uint8_t hci_send_prepared_cmd_packet(void) {
7727ca6804fdSMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
7728f91accd3SMatthias Ringwald     // cache opcode
7729f91accd3SMatthias Ringwald     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
7730f91accd3SMatthias Ringwald     // get size
7731ca6804fdSMatthias Ringwald     uint16_t size = 3u + hci_stack->hci_packet_buffer[2u];
7732f91accd3SMatthias Ringwald     // send packet
7733ca6804fdSMatthias Ringwald     uint8_t status = hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
7734ca6804fdSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
7735ca6804fdSMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7736ca6804fdSMatthias Ringwald         hci_release_packet_buffer();
7737ca6804fdSMatthias Ringwald     }
7738ca6804fdSMatthias Ringwald     return status;
7739ca6804fdSMatthias Ringwald }
7740ca6804fdSMatthias Ringwald 
77413e2050f7SMatthias Ringwald uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
774235454696SMatthias Ringwald     // house-keeping
774335454696SMatthias Ringwald 
774435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7745c8e4258aSmatthias.ringwald     bd_addr_t addr;
7746c8e4258aSmatthias.ringwald     hci_connection_t * conn;
7747c123d999SMatthias Ringwald #endif
7748c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
77496f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
77509cbd2215SMatthias Ringwald #endif
7751c8e4258aSmatthias.ringwald 
77526f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
77536f35bb46SMatthias Ringwald     switch (opcode) {
77549cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
77559cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
77569cbd2215SMatthias Ringwald             break;
77579cbd2215SMatthias Ringwald 
77589cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
77596f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7760724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
77619da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
7762c8e4258aSmatthias.ringwald 
776372cf8859SMatthias Ringwald             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
776472cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
776579e0fa07SMatthias Ringwald                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
77663e2050f7SMatthias Ringwald                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
776772cf8859SMatthias Ringwald             }
776872cf8859SMatthias Ringwald 
7769f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7770ad83dc6aS[email protected]             if (!conn) {
777188f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
777217f1ba2aSmatthias.ringwald                 if (!conn) {
777317f1ba2aSmatthias.ringwald                     // notify client that alloc failed
77742deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
77753e2050f7SMatthias Ringwald                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
777617f1ba2aSmatthias.ringwald                 }
7777ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
7778ad83dc6aS[email protected]             }
7779aee5d5c1SMatthias Ringwald 
7780ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
77813e2050f7SMatthias Ringwald             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7782ad83dc6aS[email protected]             switch (conn->state) {
7783ad83dc6aS[email protected]                 // if connection active exists
7784ad83dc6aS[email protected]                 case OPEN:
7785f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
778672cf8859SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
77873e2050f7SMatthias Ringwald                     // packet not sent to controller
77883e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7789672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
7790672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
7791672e36abSMatthias Ringwald                     break;
7792ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
77936c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
77946c0d5426SMatthias Ringwald                     if (hci_classic_operation_active()){
77956c0d5426SMatthias Ringwald                         return ERROR_CODE_SUCCESS;
77966c0d5426SMatthias Ringwald                     }
77976c0d5426SMatthias Ringwald #endif
7798532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7799532f91a5SMatthias Ringwald                     break;
7800ad83dc6aS[email protected]                 default:
7801ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
78023e2050f7SMatthias Ringwald                     // packet not sent to controller
78033e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7804ad83dc6aS[email protected]             }
7805c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
7806229331c6SMatthias Ringwald 
7807229331c6SMatthias Ringwald             // track outgoing connection
7808f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
78096535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
78106f35bb46SMatthias Ringwald             break;
7811ee752bb8SMatthias Ringwald 
78126f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
78139071873aSMatthias Ringwald             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
78149071873aSMatthias Ringwald             if (conn == NULL) {
78159071873aSMatthias Ringwald                 // neither SCO nor ACL connection for con handle
78169071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
78179071873aSMatthias Ringwald             } else {
7818d7891039SMatthias Ringwald                 uint16_t remote_supported_sco_packets;
78199071873aSMatthias Ringwald                 switch (conn->address_type){
78209071873aSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
78219071873aSMatthias Ringwald                         // assert SCO connection does not exit
7822d9290e95SMatthias Ringwald                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
78239071873aSMatthias Ringwald                             return ERROR_CODE_COMMAND_DISALLOWED;
78249071873aSMatthias Ringwald                         }
7825d7891039SMatthias Ringwald                         // cache remote sco packet types
7826d7891039SMatthias Ringwald                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7827d7891039SMatthias Ringwald 
78289071873aSMatthias Ringwald                         // allocate connection struct
782988f925b1SMatthias Ringwald                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
783088f925b1SMatthias Ringwald                                                                       HCI_ROLE_MASTER);
78319071873aSMatthias Ringwald                         if (!conn) {
78329071873aSMatthias Ringwald                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
78339071873aSMatthias Ringwald                         }
7834d7891039SMatthias Ringwald                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
78359071873aSMatthias Ringwald                         break;
78369071873aSMatthias Ringwald                     case BD_ADDR_TYPE_SCO:
78379071873aSMatthias Ringwald                         // update of existing SCO connection
78389071873aSMatthias Ringwald                         break;
78399071873aSMatthias Ringwald                     default:
78409071873aSMatthias Ringwald                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
78419071873aSMatthias Ringwald                 }
78429071873aSMatthias Ringwald             }
7843d9290e95SMatthias Ringwald 
7844d9290e95SMatthias Ringwald             // conn refers to hci connection of type sco now
7845d9290e95SMatthias Ringwald 
78469071873aSMatthias Ringwald             conn->state = SENT_CREATE_CONNECTION;
78479071873aSMatthias Ringwald 
78489071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
78499071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7850f728a932SMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, conn->address, 6);
78519071873aSMatthias Ringwald 
7852ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
7853ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7854ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7855d7891039SMatthias Ringwald 
7856d7891039SMatthias Ringwald             // derive sco payload length from packet types
7857d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
78586f35bb46SMatthias Ringwald             break;
78599071873aSMatthias Ringwald 
78606f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
78619071873aSMatthias Ringwald             // get SCO connection
78629071873aSMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
78639071873aSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
78649071873aSMatthias Ringwald             if (conn == NULL){
78659071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
78669071873aSMatthias Ringwald             }
78679071873aSMatthias Ringwald 
78689071873aSMatthias Ringwald             conn->state = ACCEPTED_CONNECTION_REQUEST;
78699071873aSMatthias Ringwald 
78709071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
78719071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
78729071873aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
78739071873aSMatthias Ringwald 
7874c91e6e4fSMatthias Ringwald             // accept_synchronous_connection? Voice setting at offset 18
7875ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7876ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7877d7891039SMatthias Ringwald 
7878d7891039SMatthias Ringwald             // derive sco payload length from packet types
7879d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
78806f35bb46SMatthias Ringwald             break;
7881ee752bb8SMatthias Ringwald #endif
78824b3e1e19SMatthias Ringwald 
7883a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
7884d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
78856f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7886b04dfa37SMatthias Ringwald             // white list used?
78876f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
7888b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
7889b04dfa37SMatthias Ringwald                 case 0:
7890b04dfa37SMatthias Ringwald                     // whitelist not used
7891b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7892b04dfa37SMatthias Ringwald                     break;
7893b04dfa37SMatthias Ringwald                 case 1:
7894b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7895b04dfa37SMatthias Ringwald                     break;
7896b04dfa37SMatthias Ringwald                 default:
7897b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7898b04dfa37SMatthias Ringwald                     break;
7899b04dfa37SMatthias Ringwald             }
7900c163146eSMatthias Ringwald             // track outgoing connection
79018f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7902c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
79036f35bb46SMatthias Ringwald             break;
79048f7da641SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
79058f7da641SMatthias Ringwald         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
79068f7da641SMatthias Ringwald             // white list used?
79078f7da641SMatthias Ringwald             initiator_filter_policy = packet[3];
79088f7da641SMatthias Ringwald             switch (initiator_filter_policy) {
79098f7da641SMatthias Ringwald                 case 0:
79108f7da641SMatthias Ringwald                     // whitelist not used
79118f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
79128f7da641SMatthias Ringwald                     break;
79138f7da641SMatthias Ringwald                 case 1:
79148f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
79158f7da641SMatthias Ringwald                     break;
79168f7da641SMatthias Ringwald                 default:
79178f7da641SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
79188f7da641SMatthias Ringwald                     break;
79198f7da641SMatthias Ringwald             }
79208f7da641SMatthias Ringwald             // track outgoing connection
79218f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
79228f7da641SMatthias Ringwald             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
79238f7da641SMatthias Ringwald             break;
79248f7da641SMatthias Ringwald #endif
79256f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
79266ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
79276f35bb46SMatthias Ringwald             break;
79289cbd2215SMatthias Ringwald #endif
792991036612SMatthias Ringwald #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7930f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7931f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7932f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7933f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7934f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7935f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7936f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7937f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7938f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_PHY:
7939f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_PHY:
7940f48a5586SMatthias Ringwald             // conection handle is first command parameter
7941f48a5586SMatthias Ringwald             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7942f48a5586SMatthias Ringwald             break;
7943f48a5586SMatthias Ringwald #endif
79444ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
79456f35bb46SMatthias Ringwald         default:
79466f35bb46SMatthias Ringwald             break;
7947b04dfa37SMatthias Ringwald     }
794869a97523S[email protected] 
79493a9fb326S[email protected]     hci_stack->num_cmd_packets--;
79505bb5bc3eS[email protected] 
79515bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
79523e2050f7SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7953a84946b2SMatthias Ringwald     uint8_t status;
7954a84946b2SMatthias Ringwald     if (err == 0){
7955a84946b2SMatthias Ringwald         status = ERROR_CODE_SUCCESS;
7956a84946b2SMatthias Ringwald     } else {
7957a84946b2SMatthias Ringwald         status = ERROR_CODE_HARDWARE_FAILURE;
79583e2050f7SMatthias Ringwald     }
7959a84946b2SMatthias Ringwald     return status;
796031452debSmatthias.ringwald }
79618adf0ddaSmatthias.ringwald 
79622bd8b7e7S[email protected] // disconnect because of security block
79632bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
79642bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
79652bd8b7e7S[email protected]     if (!connection) return;
79662bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
79672bd8b7e7S[email protected] }
79682bd8b7e7S[email protected] 
79692bd8b7e7S[email protected] 
7970dbe1a790S[email protected] // Configure Secure Simple Pairing
7971dbe1a790S[email protected] 
797235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
797335454696SMatthias Ringwald 
7974dbe1a790S[email protected] // enable will enable SSP during init
797515a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
79763a9fb326S[email protected]     hci_stack->ssp_enable = enable;
7977dbe1a790S[email protected] }
7978dbe1a790S[email protected] 
797995d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
798015a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
79812bd8b7e7S[email protected] }
79822bd8b7e7S[email protected] 
7983dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
798415a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
79853a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
7986dbe1a790S[email protected] }
798715a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
79883a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
7989dbe1a790S[email protected] }
7990dbe1a790S[email protected] 
7991a086dc35SMatthias Ringwald // if set, BTstack will confirm a numeric comparison and enter '000000' if requested
799215a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
79933a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
7994dbe1a790S[email protected] }
79955d23aae8SMatthias Ringwald 
79965d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
79975d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
79985d23aae8SMatthias Ringwald }
799922d445d8SMatthias Ringwald bool gap_secure_connections_active(void){
8000eaf85bc8SMatthias Ringwald     return hci_stack->secure_connections_active;
800122d445d8SMatthias Ringwald }
80025d23aae8SMatthias Ringwald 
800335454696SMatthias Ringwald #endif
8004dbe1a790S[email protected] 
800594be1a66SMatthias Ringwald // va_list part of hci_send_cmd
80063e2050f7SMatthias Ringwald uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
8007d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
80089d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
80093e2050f7SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
80109d14b626S[email protected]     }
80119d14b626S[email protected] 
80129d14b626S[email protected]     hci_reserve_packet_buffer();
8013f91accd3SMatthias Ringwald     hci_cmd_create_from_template(hci_stack->hci_packet_buffer, cmd, argptr);
8014ca6804fdSMatthias Ringwald     return hci_send_prepared_cmd_packet();
801594be1a66SMatthias Ringwald }
80169d14b626S[email protected] 
801794be1a66SMatthias Ringwald /**
8018a086dc35SMatthias Ringwald  * pre: num_commands >= 0 - it's allowed to send a command to the controller
801994be1a66SMatthias Ringwald  */
80203e2050f7SMatthias Ringwald uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
80211cd208adSmatthias.ringwald     va_list argptr;
80221cd208adSmatthias.ringwald     va_start(argptr, cmd);
80233e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
80241cd208adSmatthias.ringwald     va_end(argptr);
80253e2050f7SMatthias Ringwald     return status;
802693b8dc03Smatthias.ringwald }
8027c8e4258aSmatthias.ringwald 
80289da9850bSMatthias Ringwald // Forward HCI events and create non-HCI events
8029ee091cf1Smatthias.ringwald 
8030d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
8031fb37a842SMatthias Ringwald     // dump packet
8032d6b06661SMatthias Ringwald     if (dump) {
803392da54c4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
8034d6b06661SMatthias Ringwald     }
80351ef6bb52SMatthias Ringwald 
8036fb37a842SMatthias Ringwald     // dispatch to all event handlers
80371ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
80381ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
80391ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
80401ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
8041d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
80421ef6bb52SMatthias Ringwald     }
8043d6b06661SMatthias Ringwald }
8044d6b06661SMatthias Ringwald 
80459da9850bSMatthias Ringwald static void hci_emit_btstack_event(uint8_t * event, uint16_t size, int dump){
80469da9850bSMatthias Ringwald #ifndef ENABLE_LOG_BTSTACK_EVENTS
80479da9850bSMatthias Ringwald     dump = 0;
80489da9850bSMatthias Ringwald #endif
80499da9850bSMatthias Ringwald     hci_emit_event(event, size, dump);
80509da9850bSMatthias Ringwald }
80519da9850bSMatthias Ringwald 
8052d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
8053fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
80543d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
8055d6b06661SMatthias Ringwald }
8056d6b06661SMatthias Ringwald 
805735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
8058701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
80593bc639ceSMatthias Ringwald     // notify SCO sender if waiting
8060701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
8061701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
80623bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
8063701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
80649da9850bSMatthias Ringwald         hci_dump_btstack_event(event, sizeof(event));
80653d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
80663bc639ceSMatthias Ringwald     }
80673bc639ceSMatthias Ringwald }
80681cfb383eSMatthias Ringwald 
80691cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
80709784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
8071ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
80721cfb383eSMatthias Ringwald 
80731cfb383eSMatthias Ringwald     uint8_t * eir_data;
80741cfb383eSMatthias Ringwald     ad_context_t context;
80751cfb383eSMatthias Ringwald     const uint8_t * name;
80761cfb383eSMatthias Ringwald     uint8_t         name_len;
80771cfb383eSMatthias Ringwald 
80789784dac1SMatthias Ringwald     if (size < 3) return;
80799784dac1SMatthias Ringwald 
80801cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
8081a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
80821cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
80831cfb383eSMatthias Ringwald 
80849784dac1SMatthias Ringwald     switch (event_type){
80859784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
80869784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
80879784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
80889784dac1SMatthias Ringwald             break;
80899784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
80909784dac1SMatthias Ringwald             if (size != 257) return;
80919784dac1SMatthias Ringwald             if (num_responses != 1) return;
80929784dac1SMatthias Ringwald             break;
80939784dac1SMatthias Ringwald         default:
80949784dac1SMatthias Ringwald             return;
80959784dac1SMatthias Ringwald     }
80969784dac1SMatthias Ringwald 
80971cfb383eSMatthias Ringwald     // event[1] is set at the end
80981cfb383eSMatthias Ringwald     int i;
80991cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
81001cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
81011cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
8102ac973fd6SMatthias Ringwald         uint8_t event_size = 27;    // if name is not set by EIR
81031cfb383eSMatthias Ringwald 
81046535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
81050e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
81066535961aSMatthias Ringwald         (void)memcpy(&event[9],
81076535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
81086535961aSMatthias Ringwald                      3); // class of device
81096535961aSMatthias Ringwald         (void)memcpy(&event[12],
81106535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
81116535961aSMatthias Ringwald                      2); // clock offset
81121cfb383eSMatthias Ringwald 
81131cfb383eSMatthias Ringwald         switch (event_type){
81141cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
81151cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
81161cfb383eSMatthias Ringwald                 break;
81171cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
81181cfb383eSMatthias Ringwald                 event[14] = 1;
8119a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
81201cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
81211cfb383eSMatthias Ringwald                 break;
81221cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
81231cfb383eSMatthias Ringwald                 event[14] = 1;
8124a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
812579186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
81261cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
81271cfb383eSMatthias Ringwald                 name = NULL;
8128a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
8129a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
81301cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
81311cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
81321cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
8133ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
81341cfb383eSMatthias Ringwald                     switch (data_type){
81351cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
81361cfb383eSMatthias Ringwald                             if (name) continue;
8137cf373d3aSMatthias Ringwald                             /* fall through */
81381cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
81391cfb383eSMatthias Ringwald                             name = data;
81401cfb383eSMatthias Ringwald                             name_len = data_size;
81411cfb383eSMatthias Ringwald                             break;
8142ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
8143ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
8144ac9136ccSMatthias Ringwald                             event[16] = 1;
81453c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
8146ac9136ccSMatthias Ringwald                             break;
81471cfb383eSMatthias Ringwald                         default:
81481cfb383eSMatthias Ringwald                             break;
81491cfb383eSMatthias Ringwald                     }
81501cfb383eSMatthias Ringwald                 }
81511cfb383eSMatthias Ringwald                 if (name){
8152ac9136ccSMatthias Ringwald                     event[25] = 1;
81531cfb383eSMatthias Ringwald                     // truncate name if needed
81541cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
8155ac9136ccSMatthias Ringwald                     event[26] = len;
8156ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
81571cfb383eSMatthias Ringwald                     event_size += len;
81581cfb383eSMatthias Ringwald                 }
81591cfb383eSMatthias Ringwald                 break;
81607bbeb3adSMilanka Ringwald             default:
81617bbeb3adSMilanka Ringwald                 return;
81621cfb383eSMatthias Ringwald         }
81631cfb383eSMatthias Ringwald         event[1] = event_size - 2;
81649da9850bSMatthias Ringwald         hci_emit_btstack_event(event, event_size, 1);
81651cfb383eSMatthias Ringwald     }
81661cfb383eSMatthias Ringwald }
816735454696SMatthias Ringwald #endif
81683bc639ceSMatthias Ringwald 
816971de195eSMatthias Ringwald void hci_emit_state(void){
81703a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
8171425d1371Smatthias.ringwald     uint8_t event[3];
817280d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
81734ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
81743a9fb326S[email protected]     event[2] = hci_stack->state;
81759da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8176c8e4258aSmatthias.ringwald }
8177c8e4258aSmatthias.ringwald 
817835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
81792deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
8180425d1371Smatthias.ringwald     uint8_t event[13];
8181c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
8182425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
818317f1ba2aSmatthias.ringwald     event[2] = status;
81842deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
81852deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
8186c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
8187c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
81889da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8189c8e4258aSmatthias.ringwald }
819052db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
819152db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
819252db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
819352db98b2SMatthias Ringwald     uint8_t event[4];
819452db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
819552db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
819652db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
81979da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
819852db98b2SMatthias Ringwald }
819935454696SMatthias Ringwald #endif
8200c8e4258aSmatthias.ringwald 
820135454696SMatthias Ringwald #ifdef ENABLE_BLE
8202d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8203667ba9d1SMatthias Ringwald 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){
8204ebd1b979SMatthias Ringwald     uint8_t hci_event[21];
8205ebd1b979SMatthias Ringwald     hci_event[0] = HCI_EVENT_LE_META;
8206ebd1b979SMatthias Ringwald     hci_event[1] = sizeof(hci_event) - 2u;
8207ebd1b979SMatthias Ringwald     hci_event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
8208ebd1b979SMatthias Ringwald     hci_event[3] = status;
8209ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 4, con_handle);
8210ebd1b979SMatthias Ringwald     hci_event[6] = 0; // TODO: role
8211ebd1b979SMatthias Ringwald     hci_event[7] = address_type;
8212ebd1b979SMatthias Ringwald     reverse_bd_addr(address, &hci_event[8]);
8213ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 14, 0); // interval
8214ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 16, 0); // latency
8215ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 18, 0); // supervision timeout
8216ebd1b979SMatthias Ringwald     hci_event[20] = 0; // master clock accuracy
82179da9850bSMatthias Ringwald     hci_emit_btstack_event(hci_event, sizeof(hci_event), 1);
8218ebd1b979SMatthias Ringwald     // emit GAP event, too
8219ebd1b979SMatthias Ringwald     uint8_t gap_event[36];
8220ebd1b979SMatthias Ringwald     hci_create_gap_connection_complete_event(hci_event, gap_event);
82219da9850bSMatthias Ringwald     hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
82224f3229d8S[email protected] }
822335454696SMatthias Ringwald #endif
8224d70217a2SMatthias Ringwald #endif
82254f3229d8S[email protected] 
8226fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
8227fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
8228fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
82299da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
8230fd43c0e0SMatthias Ringwald }
8231fd43c0e0SMatthias Ringwald 
8232fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
8233425d1371Smatthias.ringwald     uint8_t event[6];
82343c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
82354ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
82363c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
8237fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
82383c4d4b90Smatthias.ringwald     event[5] = reason;
82399da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
82403c4d4b90Smatthias.ringwald }
82413c4d4b90Smatthias.ringwald 
8242b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
8243e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
8244425d1371Smatthias.ringwald     uint8_t event[3];
824580d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
82464ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
824743bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
82489da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
824943bfb1bdSmatthias.ringwald }
8250038bc64cSmatthias.ringwald 
8251b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
8252e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
8253425d1371Smatthias.ringwald     uint8_t event[2];
825480d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
82554ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
82569da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8257038bc64cSmatthias.ringwald }
82581b0e3922Smatthias.ringwald 
825935454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
826035454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
826135454696SMatthias Ringwald     uint8_t event[9];
826235454696SMatthias Ringwald     int pos = 0;
826335454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
82644ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
826535454696SMatthias Ringwald     event[pos++] = status;
826635454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
82679da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8268381fbed8Smatthias.ringwald }
8269458bf4e8S[email protected] 
827035454696SMatthias Ringwald 
827135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
827235454696SMatthias Ringwald 
8273b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
8274df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
8275a00031e2S[email protected]     uint8_t event[5];
8276e00caf9cS[email protected]     int pos = 0;
82775611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
8278e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
8279f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
8280e00caf9cS[email protected]     pos += 2;
8281e00caf9cS[email protected]     event[pos++] = level;
82829da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8283e00caf9cS[email protected] }
8284e00caf9cS[email protected] 
828535454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
828635454696SMatthias Ringwald     if (!connection) return LEVEL_0;
82878daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
8288fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
82898daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
8290170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
82914051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
8292a086dc35SMatthias Ringwald     // LEVEL 4 always requires 128 bit encryption key size
82930e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
8294170fafaeSMatthias Ringwald         security_level = LEVEL_3;
8295170fafaeSMatthias Ringwald     }
8296170fafaeSMatthias Ringwald     return security_level;
829735454696SMatthias Ringwald }
829835454696SMatthias Ringwald 
829971fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
830071fd255dSMatthias Ringwald     uint8_t event[4];
830171fd255dSMatthias Ringwald     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
830235454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
830371fd255dSMatthias Ringwald     event[2] = discoverable;
830471fd255dSMatthias Ringwald     event[3] = connectable;
83059da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8306ad83dc6aS[email protected] }
8307ad83dc6aS[email protected] 
830898a2fd1cSMatthias Ringwald // query if remote side supports eSCO
830920dcdd22SMatthias Ringwald bool hci_remote_esco_supported(hci_con_handle_t con_handle){
831098a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
831120dcdd22SMatthias Ringwald     if (!connection) return false;
831276ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
831398a2fd1cSMatthias Ringwald }
831498a2fd1cSMatthias Ringwald 
83150b78a447SMatthias Ringwald uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
83160b78a447SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
83170b78a447SMatthias Ringwald     if (!connection) return 0;
83180b78a447SMatthias Ringwald     return connection->remote_supported_sco_packets;
83190b78a447SMatthias Ringwald }
83200b78a447SMatthias Ringwald 
832167aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
832267aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
832367aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
832467aae551SMatthias Ringwald }
832567aae551SMatthias Ringwald 
83262bd8b7e7S[email protected] // query if remote side supports SSP
832720dcdd22SMatthias Ringwald bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
83282bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
832920dcdd22SMatthias Ringwald     if (!connection) return false;
833067aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
83312bd8b7e7S[email protected] }
83322bd8b7e7S[email protected] 
833320dcdd22SMatthias Ringwald bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
8334df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
8335df3354fcS[email protected] }
8336df3354fcS[email protected] 
83376ffc78ceSMatthias Ringwald /**
83386ffc78ceSMatthias Ringwald  * Check if remote supported features query has completed
83396ffc78ceSMatthias Ringwald  */
83406ffc78ceSMatthias Ringwald bool hci_remote_features_available(hci_con_handle_t handle){
83416ffc78ceSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(handle);
83426ffc78ceSMatthias Ringwald     if (!connection) return false;
83436ffc78ceSMatthias Ringwald     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
83446ffc78ceSMatthias Ringwald }
83456ffc78ceSMatthias Ringwald 
8346d6596031SMatthias Ringwald /**
8347d6596031SMatthias Ringwald  * Trigger remote supported features query
8348d6596031SMatthias Ringwald  */
8349c9742cd1SMatthias Ringwald 
8350c9742cd1SMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
8351c9742cd1SMatthias Ringwald     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
8352c9742cd1SMatthias Ringwald         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
8353c9742cd1SMatthias Ringwald     }
8354c9742cd1SMatthias Ringwald }
8355c9742cd1SMatthias Ringwald 
8356d6596031SMatthias Ringwald void hci_remote_features_query(hci_con_handle_t con_handle){
8357d6596031SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8358d6596031SMatthias Ringwald     if (!connection) return;
8359c9742cd1SMatthias Ringwald     hci_trigger_remote_features_for_connection(connection);
8360d6596031SMatthias Ringwald     hci_run();
8361d6596031SMatthias Ringwald }
8362d6596031SMatthias Ringwald 
8363458bf4e8S[email protected] // GAP API
8364458bf4e8S[email protected] /**
8365458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
8366458bf4e8S[email protected]  * @praram enabled
8367458bf4e8S[email protected]  */
83684c57c146S[email protected] void gap_set_bondable_mode(int enable){
83693a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
8370458bf4e8S[email protected] }
83714ef6443cSMatthias Ringwald /**
83724ef6443cSMatthias Ringwald  * @brief Get bondable mode.
83734ef6443cSMatthias Ringwald  * @return 1 if bondable
83744ef6443cSMatthias Ringwald  */
83754ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
83764ef6443cSMatthias Ringwald     return hci_stack->bondable;
83774ef6443cSMatthias Ringwald }
8378cb230b9dS[email protected] 
8379cb230b9dS[email protected] /**
838034d2123cS[email protected]  * @brief map link keys to security levels
8381cb230b9dS[email protected]  */
838234d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
838334d2123cS[email protected]     switch (link_key_type){
83843c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
83853c68dfa9S[email protected]             return LEVEL_4;
83863c68dfa9S[email protected]         case COMBINATION_KEY:
83873c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
83883c68dfa9S[email protected]             return LEVEL_3;
83893c68dfa9S[email protected]         default:
83903c68dfa9S[email protected]             return LEVEL_2;
83913c68dfa9S[email protected]     }
8392cb230b9dS[email protected] }
8393cb230b9dS[email protected] 
83948b35e16aSMatthias Ringwald /**
83958b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
83968b35e16aSMatthias Ringwald  */
839736c3546bSMatthias Ringwald bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
83988b35e16aSMatthias Ringwald     switch (link_key_type){
83998b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
84008b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
840136c3546bSMatthias Ringwald             return true;
84028b35e16aSMatthias Ringwald         default:
840336c3546bSMatthias Ringwald             return false;
84048b35e16aSMatthias Ringwald     }
84058b35e16aSMatthias Ringwald }
84068b35e16aSMatthias Ringwald 
84078b35e16aSMatthias Ringwald /**
84088b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
84098b35e16aSMatthias Ringwald  */
84107040ba26SMatthias Ringwald bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
84118b35e16aSMatthias Ringwald     switch (link_key_type){
84128b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
84138b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
84147040ba26SMatthias Ringwald             return true;
84158b35e16aSMatthias Ringwald         default:
84167040ba26SMatthias Ringwald             return false;
84178b35e16aSMatthias Ringwald     }
84188b35e16aSMatthias Ringwald }
84198b35e16aSMatthias Ringwald 
8420552b9260SMatthias Ringwald bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
84215127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
8422106d6d11S[email protected]     return level > LEVEL_2;
8423106d6d11S[email protected] }
8424106d6d11S[email protected] 
842534d2123cS[email protected] /**
842634d2123cS[email protected]  * @brief get current security level
842734d2123cS[email protected]  */
842834d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
842934d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
843034d2123cS[email protected]     if (!connection) return LEVEL_0;
843134d2123cS[email protected]     return gap_security_level_for_connection(connection);
843234d2123cS[email protected] }
843334d2123cS[email protected] 
8434cb230b9dS[email protected] /**
8435cb230b9dS[email protected]  * @brief request connection to device to
8436cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
8437cb230b9dS[email protected]  */
843834d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
843934d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
844034d2123cS[email protected]     if (!connection){
8441a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
844234d2123cS[email protected]         return;
844334d2123cS[email protected]     }
8444defbf200SMatthias Ringwald 
8445defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
8446defbf200SMatthias Ringwald 
8447bc00e12cSMatthias Ringwald     // 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)
8448bc00e12cSMatthias Ringwald     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8449bc00e12cSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8450bc00e12cSMatthias Ringwald         requested_level = LEVEL_4;
8451bc00e12cSMatthias Ringwald     }
8452bc00e12cSMatthias Ringwald 
845334d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
845483d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
845583d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
845683d08d7cSMatthias Ringwald 
8457dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
8458dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8459dbd5dcc3SMatthias Ringwald     if (authentication_active){
84601cf0a6c8SMatthias Ringwald         // authentication already active
846183d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
846283d08d7cSMatthias Ringwald             // increase requested level as new level is higher
846383d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
846483d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
846583d08d7cSMatthias Ringwald         }
84661cf0a6c8SMatthias Ringwald     } else {
846783d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
846883d08d7cSMatthias Ringwald         if (requested_level <= current_level){
8469a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
847034d2123cS[email protected]             return;
847134d2123cS[email protected]         }
8472a00031e2S[email protected] 
8473e060c07dSMatthias Ringwald         // store request
847434d2123cS[email protected]         connection->requested_security_level = requested_level;
8475a00031e2S[email protected] 
84761cf0a6c8SMatthias Ringwald         // start to authenticate connection
84771eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
84787fdbaf79SMatthias Ringwald 
84797fdbaf79SMatthias Ringwald         // request remote features if not already active, also trigger hci_run
84807fdbaf79SMatthias Ringwald         hci_remote_features_query(con_handle);
8481e00caf9cS[email protected]     }
84821cf0a6c8SMatthias Ringwald }
8483ad83dc6aS[email protected] 
8484ad83dc6aS[email protected] /**
8485ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
8486ad83dc6aS[email protected]  * @param device
8487ad83dc6aS[email protected]  * @param request MITM protection
8488ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
8489ad83dc6aS[email protected]  */
8490ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8491ad83dc6aS[email protected] 
8492ad83dc6aS[email protected]     // create connection state machine
849388f925b1SMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8494ad83dc6aS[email protected] 
8495ad83dc6aS[email protected]     if (!connection){
8496ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
8497ad83dc6aS[email protected]     }
8498ad83dc6aS[email protected] 
84994cd03f8aSMatthias Ringwald     // delete link key
850015a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
8501ad83dc6aS[email protected] 
8502ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
8503ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
8504ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8505f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8506ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
8507ad83dc6aS[email protected] 
8508ad83dc6aS[email protected]     hci_run();
8509ad83dc6aS[email protected] 
8510ad83dc6aS[email protected]     return 0;
8511ad83dc6aS[email protected] }
85128e618f72S[email protected] 
8513f82b8f4bSMatthias Ringwald uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8514ab0c69a9SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8515ab0c69a9SMatthias Ringwald     if (connection == NULL){
8516ab0c69a9SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8517ab0c69a9SMatthias Ringwald     }
8518ab0c69a9SMatthias Ringwald     if (defer){
8519ab0c69a9SMatthias Ringwald         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8520ab0c69a9SMatthias Ringwald     } else {
8521ab0c69a9SMatthias Ringwald         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8522ab0c69a9SMatthias Ringwald         // trigger disconnect
8523ab0c69a9SMatthias Ringwald         hci_run();
8524ab0c69a9SMatthias Ringwald     }
8525ab0c69a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8526ab0c69a9SMatthias Ringwald }
8527ab0c69a9SMatthias Ringwald 
85288e618f72S[email protected] void gap_set_local_name(const char * local_name){
85298e618f72S[email protected]     hci_stack->local_name = local_name;
8530baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
853159d59ecfSMatthias Ringwald     // also update EIR if not set by user
853259d59ecfSMatthias Ringwald     if (hci_stack->eir_data == NULL){
8533baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
853459d59ecfSMatthias Ringwald     }
853559d59ecfSMatthias Ringwald     hci_run();
85368e618f72S[email protected] }
85371aeec2ebSMatthias Ringwald #endif
85388e618f72S[email protected] 
853935454696SMatthias Ringwald 
854035454696SMatthias Ringwald #ifdef ENABLE_BLE
854135454696SMatthias Ringwald 
8542d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8543d8e8f12aSMatthias Ringwald void gap_start_scan(void){
8544fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
85457bdc6798S[email protected]     hci_run();
85467bdc6798S[email protected] }
85478e618f72S[email protected] 
8548d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
8549fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
85507bdc6798S[email protected]     hci_run();
85517bdc6798S[email protected] }
85524f3229d8S[email protected] 
8553a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8554ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
8555a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8556ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
8557ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
85588b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
8559ef11999fSmatthias.ringwald     hci_run();
8560ef11999fSmatthias.ringwald }
85614f3229d8S[email protected] 
8562a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8563a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8564a7a719e9SMatthias Ringwald }
8565a7a719e9SMatthias Ringwald 
85664856283bSMatthias Ringwald void gap_set_scan_duplicate_filter(bool enabled){
85674856283bSMatthias Ringwald     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
85684856283bSMatthias Ringwald }
85694856283bSMatthias Ringwald 
85707eb5b27eSMatthias Ringwald void gap_set_scan_phys(uint8_t phys){
85717eb5b27eSMatthias Ringwald     // LE Coded and LE 1M PHY
85727eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys = phys & 0x05;
85737eb5b27eSMatthias Ringwald }
85747eb5b27eSMatthias Ringwald 
8575667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type) {
85769cb52963SMatthias Ringwald     // disallow le connection if outgoing already active
8577d32b3f05SMatthias Ringwald     if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
85789cb52963SMatthias Ringwald         log_error("le connect already active");
8579d32b3f05SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
8580d32b3f05SMatthias Ringwald     }
8581d32b3f05SMatthias Ringwald 
85829cb52963SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
85839cb52963SMatthias Ringwald     if (conn == NULL) {
858488f925b1SMatthias Ringwald         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
8585f29c1023SMatthias Ringwald         if (conn == NULL){
85869cb52963SMatthias Ringwald             // alloc failed
8587d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
85889cb52963SMatthias Ringwald             return BTSTACK_MEMORY_ALLOC_FAILED;
85899cb52963SMatthias Ringwald         }
85909cb52963SMatthias Ringwald     } else {
85919cb52963SMatthias Ringwald         switch (conn->state) {
85929cb52963SMatthias Ringwald             case RECEIVED_DISCONNECTION_COMPLETE:
85939cb52963SMatthias Ringwald                 // connection was just disconnected, reset state and allow re-connect
85949cb52963SMatthias Ringwald                 conn->role = HCI_ROLE_MASTER;
85959cb52963SMatthias Ringwald                 break;
85969cb52963SMatthias Ringwald             default:
85979cb52963SMatthias Ringwald                 return ERROR_CODE_COMMAND_DISALLOWED;
85989cb52963SMatthias Ringwald         }
85994f3229d8S[email protected]     }
8600d5b1a89eSMatthias Ringwald 
8601d5b1a89eSMatthias Ringwald     // set le connecting state
8602d5b1a89eSMatthias Ringwald     if (hci_is_le_connection_type(addr_type)){
8603d5b1a89eSMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8604d5b1a89eSMatthias Ringwald     }
8605d5b1a89eSMatthias Ringwald 
86069cb52963SMatthias Ringwald     // trigger connect
8607d8e8f12aSMatthias Ringwald     log_info("gap_connect: send create connection next");
8608b0136355SMatthias Ringwald     conn->state = SEND_CREATE_CONNECTION;
8609b0136355SMatthias Ringwald     hci_run();
8610b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8611b0136355SMatthias Ringwald }
8612b0136355SMatthias Ringwald 
86137851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
8614ca0d6e5aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_le_connection(void){
8615665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
8616a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
86170bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
8618ca0d6e5aSMatthias Ringwald         if (hci_is_le_connection(conn)){
86190bf6344aS[email protected]             switch (conn->state){
8620a6725849S[email protected]                 case SEND_CREATE_CONNECTION:
86217851196eSmatthias.ringwald                 case SENT_CREATE_CONNECTION:
86227851196eSmatthias.ringwald                     return conn;
86237851196eSmatthias.ringwald                 default:
86247851196eSmatthias.ringwald                     break;
86257851196eSmatthias.ringwald             };
86267851196eSmatthias.ringwald         }
8627ca0d6e5aSMatthias Ringwald     }
86287851196eSmatthias.ringwald     return NULL;
86297851196eSmatthias.ringwald }
86307851196eSmatthias.ringwald 
8631d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
863214f2d8f0SMatthias Ringwald     hci_connection_t * conn;
863314f2d8f0SMatthias Ringwald     switch (hci_stack->le_connecting_request){
863414f2d8f0SMatthias Ringwald         case LE_CONNECTING_IDLE:
863514f2d8f0SMatthias Ringwald             break;
863614f2d8f0SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
863714f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
863814f2d8f0SMatthias Ringwald             hci_run();
863914f2d8f0SMatthias Ringwald             break;
864014f2d8f0SMatthias Ringwald         case LE_CONNECTING_DIRECT:
864114f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8642ca0d6e5aSMatthias Ringwald             conn = gap_get_outgoing_le_connection();
864314f2d8f0SMatthias Ringwald             if (conn == NULL){
864414f2d8f0SMatthias Ringwald                 hci_run();
864514f2d8f0SMatthias Ringwald             } else {
86467851196eSmatthias.ringwald                 switch (conn->state){
86477851196eSmatthias.ringwald                     case SEND_CREATE_CONNECTION:
86487851196eSmatthias.ringwald                         // skip sending create connection and emit event instead
86492e77e513S[email protected]                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8650665d90f2SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
86517851196eSmatthias.ringwald                         btstack_memory_hci_connection_free( conn );
86520bf6344aS[email protected]                         break;
8653a6725849S[email protected]                     case SENT_CREATE_CONNECTION:
8654ea04fbd8SMatthias Ringwald                         // let hci_run_general_gap_le cancel outgoing connection
86550bf6344aS[email protected]                         hci_run();
86560bf6344aS[email protected]                         break;
86570bf6344aS[email protected]                     default:
86580bf6344aS[email protected]                         break;
86590bf6344aS[email protected]                 }
866014f2d8f0SMatthias Ringwald             }
866114f2d8f0SMatthias Ringwald             break;
866243dfd98aSMatthias Ringwald         default:
866314f2d8f0SMatthias Ringwald             btstack_unreachable();
866414f2d8f0SMatthias Ringwald             break;
866514f2d8f0SMatthias Ringwald     }
866614f2d8f0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8667e31f89a7S[email protected] }
86684f3229d8S[email protected] 
8669c37a3166S[email protected] /**
86706012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
8671cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8672cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
86736012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
86746012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
86756012052bSMatthias Ringwald  * @param conn_latency, default: 4
86766012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
86776012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
86786012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
86796012052bSMatthias Ringwald  */
86806012052bSMatthias Ringwald 
86810c2c5f79SMatthias Ringwald void gap_set_connection_phys(uint8_t phys){
86820c2c5f79SMatthias Ringwald     // LE Coded, LE 1M, LE 2M PHY
86830c2c5f79SMatthias Ringwald     hci_stack->le_connection_phys = phys & 7;
86840c2c5f79SMatthias Ringwald }
86850c2c5f79SMatthias Ringwald 
86860c2c5f79SMatthias Ringwald #endif
86870c2c5f79SMatthias Ringwald 
8688cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8689cbe54ab2SJakob Krantz                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8690cbe54ab2SJakob Krantz                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8691cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
8692cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
86936012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
86946012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
86956012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
86966012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
86976012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
86986012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
86996012052bSMatthias Ringwald }
87007eb5b27eSMatthias Ringwald 
87016012052bSMatthias Ringwald /**
8702c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
8703c37a3166S[email protected]  * @param handle
8704c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
8705c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
8706c37a3166S[email protected]  * @param conn_latency
8707c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
87086b65794dSMilanka Ringwald  * @return 0 if ok
8709c37a3166S[email protected]  */
8710c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8711c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8712c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8713c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8714c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
8715c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
8716c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
8717c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
871884cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8719cfc59f1bSMatthias Ringwald     hci_run();
8720c37a3166S[email protected]     return 0;
8721c37a3166S[email protected] }
8722c37a3166S[email protected] 
872345c102fdSMatthias Ringwald /**
8724b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
8725b68d7bc3SMatthias Ringwald  * @param handle
8726b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
8727b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
8728b68d7bc3SMatthias Ringwald  * @param conn_latency
8729b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
87306b65794dSMilanka Ringwald  * @return 0 if ok
8731b68d7bc3SMatthias Ringwald  */
8732b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8733b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8734b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8735b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8736b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
8737b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
8738b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
8739b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
8740b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
874109c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
87429da9850bSMatthias Ringwald     hci_emit_btstack_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8743b68d7bc3SMatthias Ringwald     return 0;
8744b68d7bc3SMatthias Ringwald }
8745b68d7bc3SMatthias Ringwald 
87469007c891SMatthias Ringwald uint8_t gap_request_connection_subrating(hci_con_handle_t con_handle, uint16_t subrate_min, uint16_t subrate_max,
87479007c891SMatthias Ringwald                                          uint16_t max_latency, uint16_t continuation_number, uint16_t supervision_timeout){
87489007c891SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
87499007c891SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
87509007c891SMatthias Ringwald 
87519007c891SMatthias Ringwald     connection->le_subrate_min = subrate_min;
87529007c891SMatthias Ringwald     connection->le_subrate_max = subrate_max;
87539007c891SMatthias Ringwald     connection->le_subrate_max_latency = max_latency;
87549007c891SMatthias Ringwald     connection->le_subrate_continuation_number = continuation_number;
87559007c891SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
87569007c891SMatthias Ringwald     hci_run();
87579007c891SMatthias Ringwald     return ERROR_CODE_SUCCESS;
87589007c891SMatthias Ringwald }
87599007c891SMatthias Ringwald 
8760d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
8761d70217a2SMatthias Ringwald 
87625e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87635e05c0afSMatthias Ringwald static void hci_assert_advertisement_set_0_ready(void){
87645e05c0afSMatthias Ringwald     // force advertising set creation for legacy LE Advertising
87655e05c0afSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
87665e05c0afSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
87675e05c0afSMatthias Ringwald     }
87685e05c0afSMatthias Ringwald }
87695e05c0afSMatthias Ringwald #endif
87705e05c0afSMatthias Ringwald 
8771b68d7bc3SMatthias Ringwald /**
877245c102fdSMatthias Ringwald  * @brief Set Advertisement Data
877345c102fdSMatthias Ringwald  * @param advertising_data_length
877445c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
877545c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
877645c102fdSMatthias Ringwald  */
877745c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
877845c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
877945c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
8780501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
87815e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87825e05c0afSMatthias Ringwald     hci_assert_advertisement_set_0_ready();
87835e05c0afSMatthias Ringwald #endif
8784bbc366e6SMatthias Ringwald     hci_run();
878545c102fdSMatthias Ringwald }
8786501f56b3SMatthias Ringwald 
8787501f56b3SMatthias Ringwald /**
8788501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
8789501f56b3SMatthias Ringwald  * @param advertising_data_length
8790501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
8791501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
8792501f56b3SMatthias Ringwald  */
8793501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8794501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
8795501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
8796501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
87975e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87985e05c0afSMatthias Ringwald     hci_assert_advertisement_set_0_ready();
87995e05c0afSMatthias Ringwald #endif
8800bbc366e6SMatthias Ringwald     hci_run();
880145c102fdSMatthias Ringwald }
880245c102fdSMatthias Ringwald 
880345c102fdSMatthias Ringwald /**
880445c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
880545c102fdSMatthias Ringwald  * @param adv_int_min
880645c102fdSMatthias Ringwald  * @param adv_int_max
880745c102fdSMatthias Ringwald  * @param adv_type
880845c102fdSMatthias Ringwald  * @param direct_address_type
880945c102fdSMatthias Ringwald  * @param direct_address
881045c102fdSMatthias Ringwald  * @param channel_map
881145c102fdSMatthias Ringwald  * @param filter_policy
881245c102fdSMatthias Ringwald  *
881345c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
881445c102fdSMatthias Ringwald  */
881545c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8816b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
881745c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
881845c102fdSMatthias Ringwald 
881945c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
882045c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
882145c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
882245c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
882345c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
882445c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
88256535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
88266535961aSMatthias Ringwald                  6);
882745c102fdSMatthias Ringwald 
88286bf435a6SMatthias Ringwald     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
88296bf435a6SMatthias Ringwald     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8830bbc366e6SMatthias Ringwald     hci_run();
883145c102fdSMatthias Ringwald  }
883245c102fdSMatthias Ringwald 
883345c102fdSMatthias Ringwald /**
883445c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
883545c102fdSMatthias Ringwald  * @param enabled
883645c102fdSMatthias Ringwald  */
883745c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
8838a408e724SMatthias Ringwald     if (enabled == 0){
8839a408e724SMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8840a408e724SMatthias Ringwald     } else {
8841a408e724SMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8842a408e724SMatthias Ringwald     }
8843bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
8844cfc59f1bSMatthias Ringwald     hci_run();
884545c102fdSMatthias Ringwald }
884645c102fdSMatthias Ringwald 
8847a5770ecbSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8848a5770ecbSMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8849a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_t it;
8850a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8851a5770ecbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8852a5770ecbSMatthias Ringwald         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8853a5770ecbSMatthias Ringwald         if ( item->advertising_handle == advertising_handle ) {
8854a5770ecbSMatthias Ringwald             return item;
8855a5770ecbSMatthias Ringwald         }
8856a5770ecbSMatthias Ringwald     }
8857a5770ecbSMatthias Ringwald     return NULL;
8858a5770ecbSMatthias Ringwald }
8859a5770ecbSMatthias Ringwald 
88602052d96cSMatthias Ringwald uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
88612052d96cSMatthias Ringwald     hci_stack->le_resolvable_private_address_update_s = update_s;
88622052d96cSMatthias Ringwald     hci_run();
88632052d96cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
88642052d96cSMatthias Ringwald }
88652052d96cSMatthias Ringwald 
8866a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){
88672d0c7965SMatthias Ringwald     // find free advertisement handle. we use LE_EXTENDED_ADVERTISING_LEGACY_HANDLE for non-extended advertising
8868a5770ecbSMatthias Ringwald     uint8_t advertisement_handle;
88692d0c7965SMatthias Ringwald     for (advertisement_handle = LE_EXTENDED_ADVERTISING_LEGACY_HANDLE + 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8870a5770ecbSMatthias Ringwald         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8871a5770ecbSMatthias Ringwald     }
8872a5770ecbSMatthias Ringwald     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8873a5770ecbSMatthias Ringwald     // clear
8874a5770ecbSMatthias Ringwald     memset(storage, 0, sizeof(le_advertising_set_t));
8875a5770ecbSMatthias Ringwald     // copy params
88760cbe4690SMatthias Ringwald     storage->advertising_handle = advertisement_handle;
887757a04237SMatthias Ringwald     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8878a5770ecbSMatthias Ringwald     // add to list
8879a5770ecbSMatthias Ringwald     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8880a5770ecbSMatthias Ringwald     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
88810cbe4690SMatthias Ringwald     *out_advertising_handle = advertisement_handle;
8882a5770ecbSMatthias Ringwald     // set tasks and start
8883a5770ecbSMatthias Ringwald     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8884a5770ecbSMatthias Ringwald     hci_run();
8885a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8886a5770ecbSMatthias Ringwald }
8887a5770ecbSMatthias Ringwald 
8888a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8889a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8890a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
889157a04237SMatthias Ringwald     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8892a5770ecbSMatthias Ringwald     // set tasks and start
8893a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8894a5770ecbSMatthias Ringwald     hci_run();
8895a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8896a5770ecbSMatthias Ringwald }
8897a5770ecbSMatthias Ringwald 
8898a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8899a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8900a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
890157a04237SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8902a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8903a5770ecbSMatthias Ringwald }
8904a5770ecbSMatthias Ringwald 
8905a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8906a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8907a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8908a5770ecbSMatthias Ringwald     memcpy(advertising_set->random_address, random_address, 6);
8909a5770ecbSMatthias Ringwald     // set tasks and start
8910a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8911a5770ecbSMatthias Ringwald     hci_run();
8912a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8913a5770ecbSMatthias Ringwald }
8914a5770ecbSMatthias Ringwald 
89152e4aaf70SMatthias Ringwald uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8916a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8917a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8918a5770ecbSMatthias Ringwald     advertising_set->adv_data = advertising_data;
8919a5770ecbSMatthias Ringwald     advertising_set->adv_data_len = advertising_data_length;
8920a5770ecbSMatthias Ringwald     // set tasks and start
8921a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8922a5770ecbSMatthias Ringwald     hci_run();
8923a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8924a5770ecbSMatthias Ringwald }
8925a5770ecbSMatthias Ringwald 
89262e4aaf70SMatthias Ringwald 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){
8927a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8928a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8929a5770ecbSMatthias Ringwald     advertising_set->scan_data = scan_response_data;
8930a5770ecbSMatthias Ringwald     advertising_set->scan_data_len = scan_response_data_length;
8931a5770ecbSMatthias Ringwald     // set tasks and start
8932a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8933a5770ecbSMatthias Ringwald     hci_run();
8934a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8935a5770ecbSMatthias Ringwald }
8936a5770ecbSMatthias Ringwald 
8937a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8938a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8939a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8940a5770ecbSMatthias Ringwald     advertising_set->enable_timeout = timeout;
8941a5770ecbSMatthias Ringwald     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8942a5770ecbSMatthias Ringwald     // set tasks and start
8943a5770ecbSMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8944a5770ecbSMatthias Ringwald     hci_run();
8945a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8946a5770ecbSMatthias Ringwald }
8947a5770ecbSMatthias Ringwald 
8948a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8949a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8950a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8951a5770ecbSMatthias Ringwald     // set tasks and start
8952a5770ecbSMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8953a5770ecbSMatthias Ringwald     hci_run();
8954a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8955a5770ecbSMatthias Ringwald }
8956a5770ecbSMatthias Ringwald 
8957c814a904SMatthias Ringwald uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8958c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8959c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8960c814a904SMatthias Ringwald     // set tasks and start
8961c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8962c814a904SMatthias Ringwald     hci_run();
8963c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8964c814a904SMatthias Ringwald }
8965c814a904SMatthias Ringwald 
8966c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8967c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8968c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8969c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8970c814a904SMatthias Ringwald     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8971c814a904SMatthias Ringwald     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8972c814a904SMatthias Ringwald     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8973c814a904SMatthias Ringwald     // set tasks and start
8974c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8975c814a904SMatthias Ringwald     hci_run();
8976c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8977c814a904SMatthias Ringwald }
8978c814a904SMatthias Ringwald 
8979c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8980c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8981c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8982c814a904SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8983c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8984c814a904SMatthias Ringwald }
8985c814a904SMatthias Ringwald 
8986c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8987c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8988c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8989c814a904SMatthias Ringwald     advertising_set->periodic_data = periodic_data;
8990c814a904SMatthias Ringwald     advertising_set->periodic_data_len = periodic_data_length;
8991c814a904SMatthias Ringwald     // set tasks and start
8992c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8993c814a904SMatthias Ringwald     hci_run();
8994c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8995c814a904SMatthias Ringwald }
8996c814a904SMatthias Ringwald 
899753f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
899853f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
899953f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
900053f240c0SMatthias Ringwald     // set tasks and start
900153f240c0SMatthias Ringwald     advertising_set->periodic_include_adi = include_adi;
900253f240c0SMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
900353f240c0SMatthias Ringwald     hci_run();
900453f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
900553f240c0SMatthias Ringwald }
900653f240c0SMatthias Ringwald 
900753f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
900853f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
900953f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
901053f240c0SMatthias Ringwald     // set tasks and start
901153f240c0SMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
901253f240c0SMatthias Ringwald     hci_run();
901353f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
901453f240c0SMatthias Ringwald }
901598aa715fSMatthias Ringwald 
90164718c38dSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
901798aa715fSMatthias Ringwald uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
901898aa715fSMatthias Ringwald     hci_stack->le_past_mode = mode;
901998aa715fSMatthias Ringwald     hci_stack->le_past_skip = skip;
902098aa715fSMatthias Ringwald     hci_stack->le_past_sync_timeout = sync_timeout;
902198aa715fSMatthias Ringwald     hci_stack->le_past_cte_type = cte_type;
902298aa715fSMatthias Ringwald     hci_stack->le_past_set_default_params = true;
902398aa715fSMatthias Ringwald     hci_run();
902498aa715fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
902598aa715fSMatthias Ringwald }
902698aa715fSMatthias Ringwald 
90273bd96807SMatthias Ringwald uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
90283bd96807SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
90293bd96807SMatthias Ringwald     if (hci_connection == NULL){
90303bd96807SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
90313bd96807SMatthias Ringwald     }
90323bd96807SMatthias Ringwald     hci_connection->le_past_sync_handle = sync_handle;
90333bd96807SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
90343bd96807SMatthias Ringwald     hci_run();
90353bd96807SMatthias Ringwald     return ERROR_CODE_SUCCESS;
90363bd96807SMatthias Ringwald }
90374718c38dSMatthias Ringwald #endif
90383bd96807SMatthias Ringwald 
9039027f4677SMatthias Ringwald uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
9040027f4677SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9041027f4677SMatthias Ringwald     if (hci_connection == NULL){
9042027f4677SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9043027f4677SMatthias Ringwald     }
9044027f4677SMatthias Ringwald     hci_connection->le_past_advertising_handle = advertising_handle;
9045027f4677SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
9046027f4677SMatthias Ringwald     hci_run();
9047027f4677SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9048027f4677SMatthias Ringwald }
9049027f4677SMatthias Ringwald 
9050c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
905153f240c0SMatthias Ringwald 
9052a5770ecbSMatthias Ringwald #endif
9053a5770ecbSMatthias Ringwald 
905435454696SMatthias Ringwald #endif
905506e5cf96SMatthias Ringwald 
905606e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
905706e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
905806e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
905906e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
906006e5cf96SMatthias Ringwald 
906164068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
906206e5cf96SMatthias Ringwald     // update advertisement parameters, too
906306e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
9064bbc366e6SMatthias Ringwald     hci_run();
906564068776SMatthias Ringwald #endif
906664068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
906706e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
906864068776SMatthias Ringwald #endif
906906e5cf96SMatthias Ringwald }
907006e5cf96SMatthias Ringwald 
90719136bde8SMatthias Ringwald void hci_le_random_address_set(const bd_addr_t random_address){
9072137a570aSMatthias Ringwald     log_info("gap_privacy: hci_le_random_address_set %s", bd_addr_to_str(random_address));
90739136bde8SMatthias Ringwald     memcpy(hci_stack->le_random_address, random_address, 6);
90749136bde8SMatthias Ringwald     hci_stack->le_random_address_set = true;
9075137a570aSMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
90769ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
907722f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()){
90785e05c0afSMatthias Ringwald         hci_assert_advertisement_set_0_ready();
90799ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
90809ce6dfa1SMatthias Ringwald     }
90819ce6dfa1SMatthias Ringwald #endif
90829136bde8SMatthias Ringwald     hci_run();
90839136bde8SMatthias Ringwald }
90849136bde8SMatthias Ringwald 
9085d70217a2SMatthias Ringwald #endif
908645c102fdSMatthias Ringwald 
9087616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
90885917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
90895917a5c5S[email protected]     if (!conn){
90907851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
9091616edd56SMatthias Ringwald         return 0;
90925917a5c5S[email protected]     }
909361972f0aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
909461972f0aSMatthias Ringwald     switch (conn->state){
909561972f0aSMatthias Ringwald         case RECEIVED_DISCONNECTION_COMPLETE:
909661972f0aSMatthias Ringwald             // ignore if remote just disconnected
909761972f0aSMatthias Ringwald             break;
909861972f0aSMatthias Ringwald         case SEND_DISCONNECT:
909961972f0aSMatthias Ringwald         case SENT_DISCONNECT:
910061972f0aSMatthias Ringwald             // disconnect already requested or sent
910161972f0aSMatthias Ringwald             status = ERROR_CODE_COMMAND_DISALLOWED;
910261972f0aSMatthias Ringwald             break;
910361972f0aSMatthias Ringwald         default:
910461972f0aSMatthias Ringwald             // trigger hci_disconnect
91055917a5c5S[email protected]             conn->state = SEND_DISCONNECT;
91065917a5c5S[email protected]             hci_run();
910761972f0aSMatthias Ringwald             break;
910861972f0aSMatthias Ringwald     }
910961972f0aSMatthias Ringwald     return status;
91104f3229d8S[email protected] }
911104a6ef8cSmatthias.ringwald 
9112228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
9113228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9114228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
911522df2fe2SMatthias Ringwald     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
9116228e430cSMatthias Ringwald     hci_run();
9117228e430cSMatthias Ringwald     return 1;
9118228e430cSMatthias Ringwald }
9119228e430cSMatthias Ringwald 
9120a1bf5ae7SMatthias Ringwald /**
9121a1bf5ae7SMatthias Ringwald  * @brief Get connection type
9122a1bf5ae7SMatthias Ringwald  * @param con_handle
9123a1bf5ae7SMatthias Ringwald  * @result connection_type
9124a1bf5ae7SMatthias Ringwald  */
9125a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
9126a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
9127a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
9128a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
9129a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
9130a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9131ad9f3530SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9132ad9f3530SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9133a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
9134a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9135a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
9136f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9137a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
9138a1bf5ae7SMatthias Ringwald         default:
9139a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
9140a1bf5ae7SMatthias Ringwald     }
9141a1bf5ae7SMatthias Ringwald }
9142a1bf5ae7SMatthias Ringwald 
91432dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
91442dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
91452dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
91462dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
91472dceb1d6SMatthias Ringwald }
91482dceb1d6SMatthias Ringwald 
91492dceb1d6SMatthias Ringwald 
915044f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
9151667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
915288a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
915388a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
915488a03c8dSMatthias Ringwald     conn->request_role = role;
915588a03c8dSMatthias Ringwald     hci_run();
9156d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
915788a03c8dSMatthias Ringwald }
915844f858f3SMatthias Ringwald #endif
915988a03c8dSMatthias Ringwald 
9160a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
91614f551432SMatthias Ringwald 
91629d8be771SMatthias Ringwald 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){
9163b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9164b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9165b90f6e0aSMatthias Ringwald 
9166b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
9167b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
9168b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
91699d8be771SMatthias Ringwald     conn->le_phy_update_phy_options = (uint8_t) phy_options;
9170b90f6e0aSMatthias Ringwald 
9171b90f6e0aSMatthias Ringwald     hci_run();
9172b90f6e0aSMatthias Ringwald 
9173b90f6e0aSMatthias Ringwald     return 0;
9174b90f6e0aSMatthias Ringwald }
9175b90f6e0aSMatthias Ringwald 
9176667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9177100da355SMatthias Ringwald 
9178100da355SMatthias Ringwald #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_WHITELIST_ENTRIES) || (MAX_NR_WHITELIST_ENTRIES == 0))
9179100da355SMatthias Ringwald     // incorrect configuration:
9180100da355SMatthias Ringwald     // - as MAX_NR_WHITELIST_ENTRIES is not defined or zero this function always fails
9181100da355SMatthias Ringwald     // - please set MAX_NR_WHITELIST_ENTRIES in btstack_config.h
9182100da355SMatthias Ringwald     btstack_assert(false);
9183100da355SMatthias Ringwald #endif
9184100da355SMatthias Ringwald 
91857a92a9dbSMatthias Ringwald     // check if already in list
91867a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
91877a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
91887a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
91897a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
91907a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
91917a92a9dbSMatthias Ringwald             continue;
91927a92a9dbSMatthias Ringwald         }
91937a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
91947a92a9dbSMatthias Ringwald             continue;
91957a92a9dbSMatthias Ringwald         }
9196caaf5151SMilanka Ringwald 
9197caaf5151SMilanka Ringwald         // if already on controller:
9198caaf5151SMilanka Ringwald         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
9199caaf5151SMilanka Ringwald             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
9200caaf5151SMilanka Ringwald                 // drop remove request
9201caaf5151SMilanka Ringwald                 entry->state = LE_WHITELIST_ON_CONTROLLER;
9202caaf5151SMilanka Ringwald                 return ERROR_CODE_SUCCESS;
9203caaf5151SMilanka Ringwald             } else {
9204caaf5151SMilanka Ringwald                 // disallow as already on controller
92057a92a9dbSMatthias Ringwald                 return ERROR_CODE_COMMAND_DISALLOWED;
92067a92a9dbSMatthias Ringwald             }
9207287379ccSMatthias Ringwald         }
9208caaf5151SMilanka Ringwald 
9209caaf5151SMilanka Ringwald         // assume scheduled to add
9210caaf5151SMilanka Ringwald 		return ERROR_CODE_COMMAND_DISALLOWED;
9211caaf5151SMilanka Ringwald     }
9212caaf5151SMilanka Ringwald 
92137a92a9dbSMatthias Ringwald     // alloc and add to list
9214e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
9215e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9216e83201bcSMatthias Ringwald     entry->address_type = address_type;
92176535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
9218e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
9219665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
9220226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9221ac9c45e0SMatthias Ringwald }
9222ac9c45e0SMatthias Ringwald 
9223667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9224665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9225665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9226665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9227665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
92287a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
92297a92a9dbSMatthias Ringwald             continue;
92307a92a9dbSMatthias Ringwald         }
92317a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
92327a92a9dbSMatthias Ringwald             continue;
92337a92a9dbSMatthias Ringwald         }
9234e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9235e83201bcSMatthias Ringwald             // remove from controller if already present
9236e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9237a3b69fdeSMatthias Ringwald         }  else {
9238226db5efSMatthias Ringwald             // directly remove entry from whitelist
9239665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
9240e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
9241e83201bcSMatthias Ringwald         }
9242a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
9243a3b69fdeSMatthias Ringwald     }
9244a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
924542ff5ba1SMatthias Ringwald }
924642ff5ba1SMatthias Ringwald 
9247226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
9248665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9249665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9250665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9251665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9252e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9253e83201bcSMatthias Ringwald             // remove from controller if already present
9254e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9255e83201bcSMatthias Ringwald             continue;
9256e83201bcSMatthias Ringwald         }
925791915b0bSMatthias Ringwald         // directly remove entry from whitelist
9258665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
9259e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
9260e83201bcSMatthias Ringwald     }
9261226db5efSMatthias Ringwald }
9262226db5efSMatthias Ringwald 
9263a3b69fdeSMatthias Ringwald /**
9264a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
92656b65794dSMilanka Ringwald  * @return 0 if ok
9266a3b69fdeSMatthias Ringwald  */
9267a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
9268a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
9269a3b69fdeSMatthias Ringwald     hci_run();
9270a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9271a3b69fdeSMatthias Ringwald }
9272a3b69fdeSMatthias Ringwald 
9273a3b69fdeSMatthias Ringwald /**
9274a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
9275a3b69fdeSMatthias Ringwald  * @param address_typ
9276a3b69fdeSMatthias Ringwald  * @param address
92776b65794dSMilanka Ringwald  * @return 0 if ok
9278a3b69fdeSMatthias Ringwald  */
9279667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9280a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
9281a3b69fdeSMatthias Ringwald     if (status){
9282a3b69fdeSMatthias Ringwald         return status;
9283a3b69fdeSMatthias Ringwald     }
9284a3b69fdeSMatthias Ringwald     hci_run();
9285a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9286a3b69fdeSMatthias Ringwald }
9287a3b69fdeSMatthias Ringwald 
9288a3b69fdeSMatthias Ringwald /**
9289a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
9290a3b69fdeSMatthias Ringwald  * @param address_typ
9291a3b69fdeSMatthias Ringwald  * @param address
92926b65794dSMilanka Ringwald  * @return 0 if ok
9293a3b69fdeSMatthias Ringwald  */
9294667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9295a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
9296a3b69fdeSMatthias Ringwald     if (status){
9297a3b69fdeSMatthias Ringwald         return status;
9298a3b69fdeSMatthias Ringwald     }
9299a3b69fdeSMatthias Ringwald     hci_run();
9300a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9301a3b69fdeSMatthias Ringwald }
9302a3b69fdeSMatthias Ringwald 
9303226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
9304226db5efSMatthias Ringwald /**
930595e257d9SMatthias Ringwald  * @brief Connect with Whitelist
930695e257d9SMatthias Ringwald  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
93076b65794dSMilanka Ringwald  * @return - if ok
930895e257d9SMatthias Ringwald  */
930995e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
931095e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
931195e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
931295e257d9SMatthias Ringwald     }
931395e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
931495e257d9SMatthias Ringwald     hci_run();
931595e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
931695e257d9SMatthias Ringwald }
931795e257d9SMatthias Ringwald 
931895e257d9SMatthias Ringwald /**
9319226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
9320226db5efSMatthias Ringwald  * @param address_typ
9321226db5efSMatthias Ringwald  * @param address
93226b65794dSMilanka Ringwald  * @return 0 if ok
9323226db5efSMatthias Ringwald  */
9324667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
932595e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9326226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
9327226db5efSMatthias Ringwald     }
9328226db5efSMatthias Ringwald 
9329226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
933063f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
9331226db5efSMatthias Ringwald         return status;
9332226db5efSMatthias Ringwald     }
9333226db5efSMatthias Ringwald 
9334226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9335226db5efSMatthias Ringwald 
9336226db5efSMatthias Ringwald     hci_run();
933795e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9338226db5efSMatthias Ringwald }
9339226db5efSMatthias Ringwald 
9340226db5efSMatthias Ringwald /**
9341226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
9342226db5efSMatthias Ringwald  * @param address_typ
9343226db5efSMatthias Ringwald  * @param address
93446b65794dSMilanka Ringwald  * @return 0 if ok
9345226db5efSMatthias Ringwald  */
9346667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
934795e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
934895e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
934995e257d9SMatthias Ringwald     }
935095e257d9SMatthias Ringwald 
9351226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
935295e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
935395e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
935495e257d9SMatthias Ringwald     }
9355226db5efSMatthias Ringwald     hci_run();
9356226db5efSMatthias Ringwald     return 0;
9357226db5efSMatthias Ringwald }
9358226db5efSMatthias Ringwald 
9359226db5efSMatthias Ringwald /**
9360226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
9361226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
9362226db5efSMatthias Ringwald  */
936395e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
936495e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
936595e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
936695e257d9SMatthias Ringwald     }
9367226db5efSMatthias Ringwald     hci_whitelist_clear();
9368226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9369e83201bcSMatthias Ringwald     hci_run();
937095e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9371ac9c45e0SMatthias Ringwald }
9372c9db5c21SMilanka Ringwald 
9373b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
9374b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9375c9db5c21SMilanka Ringwald     if (!conn) return 0;
9376c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
9377c9db5c21SMilanka Ringwald }
9378d70217a2SMatthias Ringwald #endif
93794f551432SMatthias Ringwald #endif
93804f551432SMatthias Ringwald 
938135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
9382ac9c45e0SMatthias Ringwald /**
9383ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
9384a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
9385ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
9386ff00ed1cSMatthias Ringwald  */
9387ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
9388ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
9389baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
939059d59ecfSMatthias Ringwald     hci_run();
9391ff00ed1cSMatthias Ringwald }
9392ff00ed1cSMatthias Ringwald 
9393ff00ed1cSMatthias Ringwald /**
9394f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
9395f5875de5SMatthias Ringwald  * @param duration in 1.28s units
9396f5875de5SMatthias Ringwald  * @return 0 if ok
9397f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
9398f5875de5SMatthias Ringwald  */
9399f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
940099449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
9401f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9402a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
9403f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9404f5875de5SMatthias Ringwald     }
9405f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
940630199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = 0;
940730199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = 0;
940830199e24SMatthias Ringwald     hci_run();
940930199e24SMatthias Ringwald     return 0;
941030199e24SMatthias Ringwald }
941130199e24SMatthias Ringwald 
941230199e24SMatthias Ringwald uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
941330199e24SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
941430199e24SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
941530199e24SMatthias Ringwald     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
941630199e24SMatthias Ringwald     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
941730199e24SMatthias Ringwald     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
941830199e24SMatthias Ringwald     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
941930199e24SMatthias Ringwald 
942030199e24SMatthias Ringwald     hci_stack->inquiry_state = duration;
942130199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = max_period_length;
942230199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = min_period_length;
9423f5875de5SMatthias Ringwald     hci_run();
9424f5875de5SMatthias Ringwald     return 0;
9425f5875de5SMatthias Ringwald }
9426f5875de5SMatthias Ringwald 
9427f5875de5SMatthias Ringwald /**
9428f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
94296b65794dSMilanka Ringwald  * @return 0 if ok
9430f5875de5SMatthias Ringwald  */
9431f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
9432a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9433f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
9434f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
94359da9850bSMatthias Ringwald         hci_emit_btstack_event(event, sizeof(event), 1);
9436f5875de5SMatthias Ringwald         return 0;
9437f5875de5SMatthias Ringwald     }
943830199e24SMatthias Ringwald     switch (hci_stack->inquiry_state){
943930199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_ACTIVE:
9440f5875de5SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9441f5875de5SMatthias Ringwald             hci_run();
944230199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
944330199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_PERIODIC:
944430199e24SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
944530199e24SMatthias Ringwald             hci_run();
944630199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
944730199e24SMatthias Ringwald         default:
944830199e24SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
944930199e24SMatthias Ringwald     }
9450f5875de5SMatthias Ringwald }
9451f5875de5SMatthias Ringwald 
9452496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
9453496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
9454496bb884SMatthias Ringwald }
9455496bb884SMatthias Ringwald 
94561dc973e7SMatthias Ringwald void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9457c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9458c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9459baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9460c0c8a829SMatthias Ringwald     hci_run();
9461c0c8a829SMatthias Ringwald }
9462c0c8a829SMatthias Ringwald 
9463f50ed5acSAndrey Fominykh void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9464f50ed5acSAndrey Fominykh {
9465f50ed5acSAndrey Fominykh     hci_stack->inquiry_tx_power_level = tx_power;
9466f50ed5acSAndrey Fominykh     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9467f50ed5acSAndrey Fominykh     hci_run();
9468f50ed5acSAndrey Fominykh }
9469f50ed5acSAndrey Fominykh 
9470b7f1ee76SMatthias Ringwald 
9471b7f1ee76SMatthias Ringwald /**
9472b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
9473b7f1ee76SMatthias Ringwald  * @param addr
9474b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
9475b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
9476b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9477b7f1ee76SMatthias Ringwald  */
9478667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9479b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
94806535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9481b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9482b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
9483b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9484b7f1ee76SMatthias Ringwald     hci_run();
9485b7f1ee76SMatthias Ringwald     return 0;
9486b7f1ee76SMatthias Ringwald }
9487b7f1ee76SMatthias Ringwald 
9488667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
94890a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
94906535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
94910a51f88bSMatthias Ringwald     hci_run();
94920a51f88bSMatthias Ringwald     return 0;
94930a51f88bSMatthias Ringwald }
94940a51f88bSMatthias Ringwald 
94950a51f88bSMatthias Ringwald /**
9496aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9497aad97216SMatthias Ringwald  * @param addr
9498aad97216SMatthias Ringwald  * @param pin_data
9499aad97216SMatthias Ringwald  * @param pin_len
9500aad97216SMatthias Ringwald  * @return 0 if ok
9501aad97216SMatthias Ringwald  */
9502667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9503aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9504c26f2c7bSMatthias Ringwald     if (pin_len > PIN_CODE_LEN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9505aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9506aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
9507aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9508aad97216SMatthias Ringwald }
9509aad97216SMatthias Ringwald 
9510aad97216SMatthias Ringwald /**
95110a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
95120a51f88bSMatthias Ringwald  * @param addr
95130a51f88bSMatthias Ringwald  * @param pin
95140a51f88bSMatthias Ringwald  * @return 0 if ok
95150a51f88bSMatthias Ringwald  */
9516667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
95179d78a7ecSMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
95180a51f88bSMatthias Ringwald }
95190a51f88bSMatthias Ringwald 
95200a51f88bSMatthias Ringwald /**
95210a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
95220a51f88bSMatthias Ringwald  * @param addr
95230a51f88bSMatthias Ringwald  * @param pin
95240a51f88bSMatthias Ringwald  * @return 0 if ok
95250a51f88bSMatthias Ringwald  */
95260a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
9527cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95280a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
95290a51f88bSMatthias Ringwald }
95300a51f88bSMatthias Ringwald 
95310a51f88bSMatthias Ringwald /**
95320a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
95330a51f88bSMatthias Ringwald  * @param addr
95340a51f88bSMatthias Ringwald  * @param passkey
95350a51f88bSMatthias Ringwald  * @return 0 if ok
95360a51f88bSMatthias Ringwald  */
9537667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9538cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9539d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
95400a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
95410a51f88bSMatthias Ringwald }
95420a51f88bSMatthias Ringwald 
95430a51f88bSMatthias Ringwald /**
95440a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
95450a51f88bSMatthias Ringwald  * @param addr
95460a51f88bSMatthias Ringwald  * @param pin
95470a51f88bSMatthias Ringwald  * @return 0 if ok
95480a51f88bSMatthias Ringwald  */
9549667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
9550cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95510a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
95520a51f88bSMatthias Ringwald }
95530a51f88bSMatthias Ringwald 
95540a51f88bSMatthias Ringwald /**
95550a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
95560a51f88bSMatthias Ringwald  * @param addr
95570a51f88bSMatthias Ringwald  * @param passkey
95580a51f88bSMatthias Ringwald  * @return 0 if ok
95590a51f88bSMatthias Ringwald  */
9560667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
9561cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95620a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
95630a51f88bSMatthias Ringwald }
95640a51f88bSMatthias Ringwald 
95650a51f88bSMatthias Ringwald /**
95660a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
95670a51f88bSMatthias Ringwald  * @param addr
95680a51f88bSMatthias Ringwald  * @param pin
95690a51f88bSMatthias Ringwald  * @return 0 if ok
95700a51f88bSMatthias Ringwald  */
9571667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
9572cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95730a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
95740a51f88bSMatthias Ringwald }
95750a51f88bSMatthias Ringwald 
9576308eeaffSMatthias Ringwald #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
957744565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
957844565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
957944565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
958044565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
958144565b0cSMatthias Ringwald     hci_run();
958244565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
958344565b0cSMatthias Ringwald }
9584308eeaffSMatthias Ringwald #endif
958544565b0cSMatthias Ringwald 
9586308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
958744565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
95887ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
958944565b0cSMatthias Ringwald }
959044565b0cSMatthias Ringwald 
959144565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
95927ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
959344565b0cSMatthias Ringwald }
959444565b0cSMatthias Ringwald #endif
959544565b0cSMatthias Ringwald 
95961849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
95971849becdSMatthias Ringwald /**
95981849becdSMatthias Ringwald  * @brief Report Remote OOB Data
95991849becdSMatthias Ringwald  * @param bd_addr
96001849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
96011849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
96021849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
96031849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
96041849becdSMatthias Ringwald  */
96051849becdSMatthias Ringwald 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){
96061849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
96071849becdSMatthias Ringwald     if (connection == NULL) {
96081849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
96091849becdSMatthias Ringwald     }
96101849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
96111849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
9612204e8f1dSMatthias Ringwald 
9613204e8f1dSMatthias Ringwald     // ignore P-256 if not supported by us
9614204e8f1dSMatthias Ringwald     if (hci_stack->secure_connections_active){
96151849becdSMatthias Ringwald         connection->classic_oob_c_256 = c_256;
96161849becdSMatthias Ringwald         connection->classic_oob_r_256 = r_256;
9617204e8f1dSMatthias Ringwald     }
9618204e8f1dSMatthias Ringwald 
96191849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
96201849becdSMatthias Ringwald }
9621cf01e888SMatthias Ringwald /**
9622cf01e888SMatthias Ringwald  * @brief Generate new OOB data
9623cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9624cf01e888SMatthias Ringwald  */
9625cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
9626cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
9627cf01e888SMatthias Ringwald     hci_run();
9628cf01e888SMatthias Ringwald }
9629cf01e888SMatthias Ringwald 
96301849becdSMatthias Ringwald #endif
96311849becdSMatthias Ringwald 
9632308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9633308eeaffSMatthias Ringwald uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9634308eeaffSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9635308eeaffSMatthias Ringwald     if (connection == NULL) {
9636308eeaffSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9637308eeaffSMatthias Ringwald     }
9638308eeaffSMatthias Ringwald 
9639308eeaffSMatthias Ringwald     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9640308eeaffSMatthias Ringwald     connection->link_key_type = type;
9641308eeaffSMatthias Ringwald 
9642308eeaffSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9643308eeaffSMatthias Ringwald }
9644308eeaffSMatthias Ringwald 
9645308eeaffSMatthias Ringwald #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9646f5875de5SMatthias Ringwald /**
9647f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9648f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
9649f6858d14SMatthias Ringwald  */
9650b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9651b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
9652f6858d14SMatthias Ringwald }
9653f6858d14SMatthias Ringwald 
9654f6858d14SMatthias Ringwald /**
9655d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9656d950d659SMatthias Ringwald  */
9657d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
9658d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
9659d950d659SMatthias Ringwald }
9660d950d659SMatthias Ringwald 
9661d950d659SMatthias Ringwald /**
9662d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
9663d950d659SMatthias Ringwald  * @return current voice setting
9664d950d659SMatthias Ringwald  */
96650cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
9666d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
9667d950d659SMatthias Ringwald }
9668d950d659SMatthias Ringwald 
9669400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
9670400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
9671400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
9672400ff5abSMatthias Ringwald     if (!transport_name) return 0;
9673400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9674400ff5abSMatthias Ringwald }
9675400ff5abSMatthias Ringwald 
96769427aeb5SMatthias Ringwald static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
967720dcdd22SMatthias Ringwald     uint16_t sco_packet_length = 0;
9678cf119f3bSMatthias Ringwald 
967991dfed7eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
9680a086dc35SMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as many bytes
968173f498e7SMatthias Ringwald     int multiplier;
968273f498e7SMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
968373f498e7SMatthias Ringwald         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
968473f498e7SMatthias Ringwald         multiplier = 2;
968573f498e7SMatthias Ringwald     } else {
968673f498e7SMatthias Ringwald         multiplier = 1;
968773f498e7SMatthias Ringwald     }
968891dfed7eSMatthias Ringwald #endif
968991dfed7eSMatthias Ringwald 
96909427aeb5SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
9691400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
9692400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
9693cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
96949427aeb5SMatthias Ringwald         // @note multiple sco connections not supported currently
96959427aeb5SMatthias Ringwald         sco_packet_length = 3 + 24 * multiplier;
9696400ff5abSMatthias Ringwald     } else {
96979427aeb5SMatthias Ringwald         // 3 byte SCO header + SCO packet length over the air
96989427aeb5SMatthias Ringwald         sco_packet_length = 3 + payload_size * multiplier;
9699d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
9700ad915196SMatthias Ringwald         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
97019427aeb5SMatthias Ringwald             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9702d966a453SMatthias Ringwald         }
9703400ff5abSMatthias Ringwald     }
9704a3069afeSMatthias Ringwald #endif
97055b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
97069427aeb5SMatthias Ringwald     // 3 byte SCO header + SCO packet length over the air
97079427aeb5SMatthias Ringwald     sco_packet_length = 3 + payload_size * multiplier;
97089427aeb5SMatthias Ringwald     // assert that it still fits inside an SCO buffer
97099427aeb5SMatthias Ringwald     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
97109427aeb5SMatthias Ringwald         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
97119427aeb5SMatthias Ringwald     }
97125b7087c7SMatthias Ringwald #endif
9713a3069afeSMatthias Ringwald     return sco_packet_length;
9714b3aad8daSMatthias Ringwald }
9715b3aad8daSMatthias Ringwald 
97169427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
97179427aeb5SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
97189427aeb5SMatthias Ringwald     if (connection != NULL){
97199427aeb5SMatthias Ringwald         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
97209427aeb5SMatthias Ringwald     }
97219427aeb5SMatthias Ringwald     return 0;
97229427aeb5SMatthias Ringwald }
97239427aeb5SMatthias Ringwald 
97249427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length(void){
97259427aeb5SMatthias Ringwald     btstack_linked_list_iterator_t it;
97269427aeb5SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
97279427aeb5SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
97289427aeb5SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
97299427aeb5SMatthias Ringwald         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
97309427aeb5SMatthias Ringwald             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
97319427aeb5SMatthias Ringwald         }
97329427aeb5SMatthias Ringwald     }
97339427aeb5SMatthias Ringwald     return 0;
97349427aeb5SMatthias Ringwald }
97359427aeb5SMatthias Ringwald 
9736c4c88f1bSJakob Krantz /**
9737c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
9738c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
9739c4c88f1bSJakob Krantz */
9740c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
9741c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
9742c4c88f1bSJakob Krantz }
9743c4c88f1bSJakob Krantz 
9744c4c88f1bSJakob Krantz #endif
9745ec111c8bSMatthias Ringwald 
9746ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
9747ec111c8bSMatthias Ringwald     return hci_stack->state;
9748ec111c8bSMatthias Ringwald }
9749ec111c8bSMatthias Ringwald 
975007e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
97515e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
975207e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
975307e010b6SMilanka Ringwald }
975407e010b6SMilanka Ringwald #endif
9755ec111c8bSMatthias Ringwald 
9756d950d659SMatthias Ringwald /**
9757d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
9758d23838ecSMatthias Ringwald  */
9759c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9760d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
9761d23838ecSMatthias Ringwald }
9762d23838ecSMatthias Ringwald 
976371de195eSMatthias Ringwald void hci_disconnect_all(void){
9764665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9765665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9766665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9767665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
976804a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
976904a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
977004a6ef8cSmatthias.ringwald     }
9771d31fba26S[email protected]     hci_run();
977204a6ef8cSmatthias.ringwald }
977333373e40SMatthias Ringwald 
977433373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
977533373e40SMatthias Ringwald     return hci_stack->manufacturer;
977633373e40SMatthias Ringwald }
97779c6e867eSMatthias Ringwald 
97783e329ddfSandryblack #ifdef ENABLE_BLE
97799c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
97809c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
97819c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
97829c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
97839c6e867eSMatthias Ringwald }
97849c6e867eSMatthias Ringwald 
97859c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
9786a086dc35SMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() result in non-encrypted, not-authenticated
97876a79f6baSMatthias Ringwald #endif
97889c6e867eSMatthias Ringwald 
97896d105c71SMatthias Ringwald uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9790c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9791c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
9792c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
97936a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
9794c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9795c7bead46SMatthias Ringwald         if (sm_conn->sm_connection_encrypted != 0u) {
97969c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
97979c6e867eSMatthias Ringwald         }
97986a79f6baSMatthias Ringwald #endif
97996a79f6baSMatthias Ringwald     } else {
9800c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
98018daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9802c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
9803c5fb5ca4SMatthias Ringwald         }
9804c5fb5ca4SMatthias Ringwald #endif
98056a79f6baSMatthias Ringwald     }
9806c5fb5ca4SMatthias Ringwald     return 0;
9807c5fb5ca4SMatthias Ringwald }
98089c6e867eSMatthias Ringwald 
9809ff3f1026SMatthias Ringwald bool gap_authenticated(hci_con_handle_t con_handle){
9810c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9811ff3f1026SMatthias Ringwald     if (hci_connection == NULL) return false;
98125f3981bfSMatthias Ringwald 
9813c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
98146a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98155f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
98165f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9817d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9818d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9819c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9820ff3f1026SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated != 0;
98216a79f6baSMatthias Ringwald #endif
982259a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
98235f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9824f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9825ff3f1026SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
982659a1a47aSMatthias Ringwald #endif
98275f3981bfSMatthias Ringwald         default:
9828ff3f1026SMatthias Ringwald             return false;
98295f3981bfSMatthias Ringwald     }
98309c6e867eSMatthias Ringwald }
98319c6e867eSMatthias Ringwald 
9832f461b3dfSMatthias Ringwald bool gap_secure_connection(hci_con_handle_t con_handle){
9833c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9834c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
98358b35e16aSMatthias Ringwald 
9836c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
98376a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98388b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
98398b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9840d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9841d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9842f461b3dfSMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9843d7dbf891SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc;
98446a79f6baSMatthias Ringwald #endif
984559a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
98468b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9847f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9848f461b3dfSMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
984959a1a47aSMatthias Ringwald #endif
98508b35e16aSMatthias Ringwald         default:
9851f461b3dfSMatthias Ringwald             return false;
98528b35e16aSMatthias Ringwald     }
9853f1dfbe18SMatthias Ringwald }
9854f1dfbe18SMatthias Ringwald 
98551e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
98561e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
98571e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
98581e122704SMatthias Ringwald 
985948f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
98601e122704SMatthias Ringwald 	link_key_t link_key;
98611e122704SMatthias Ringwald 	link_key_type_t link_key_type;
986248f33f37SMatthias Ringwald #endif
98631e122704SMatthias Ringwald 	switch (hci_connection->address_type){
98646a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98651e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
98661e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
9867d9e1bf33SMatthias Ringwald 	    case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9868d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
98691e122704SMatthias Ringwald             return hci_connection->sm_connection.sm_le_db_index >= 0;
98706a79f6baSMatthias Ringwald #endif
98711e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
98721e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
98731e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
98741e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
98751e122704SMatthias Ringwald #endif
98761e122704SMatthias Ringwald 		default:
98771e122704SMatthias Ringwald 			return false;
98781e122704SMatthias Ringwald 	}
98791e122704SMatthias Ringwald }
98801e122704SMatthias Ringwald 
98816a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98829c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
98839c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9884c7bead46SMatthias Ringwald     if (sm_conn == NULL)                             return AUTHORIZATION_UNKNOWN; // wrong connection
9885c7bead46SMatthias Ringwald     if (sm_conn->sm_connection_encrypted == 0u)      return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9886a086dc35SMatthias Ringwald     if (sm_conn->sm_connection_authenticated == 0u)  return AUTHORIZATION_UNKNOWN; // unauthenticated connection cannot be authorized
98879c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
98889c6e867eSMatthias Ringwald }
98899c6e867eSMatthias Ringwald #endif
9890f8ee3071SMatthias Ringwald 
9891f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
9892f8ee3071SMatthias Ringwald 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){
9893f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
98947f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9895f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
9896f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
9897f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
9898f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
9899f8ee3071SMatthias Ringwald     hci_run();
9900f8ee3071SMatthias Ringwald     return 0;
9901f8ee3071SMatthias Ringwald }
9902f8ee3071SMatthias Ringwald 
9903f8ee3071SMatthias Ringwald /**
9904f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
9905f8ee3071SMatthias Ringwald  * @param con_handle
9906f8ee3071SMatthias Ringwald  @ @return 0 if ok
9907f8ee3071SMatthias Ringwald  */
9908f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9909f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99107f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9911f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
9912f8ee3071SMatthias Ringwald     hci_run();
9913f8ee3071SMatthias Ringwald     return 0;
9914f8ee3071SMatthias Ringwald }
9915bea424a5SMatthias Ringwald 
9916140c0557SMatthias Ringwald 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){
9917140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99187f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9919140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
9920140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9921140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9922140c0557SMatthias Ringwald     hci_run();
9923dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9924140c0557SMatthias Ringwald }
9925140c0557SMatthias Ringwald 
9926278ff8a9SMatthias Ringwald 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){
9927278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99287f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9929278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
9930278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
9931278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
9932278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
9933278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
9934278ff8a9SMatthias Ringwald     hci_run();
9935278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9936278ff8a9SMatthias Ringwald }
9937278ff8a9SMatthias Ringwald 
9938bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9939bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
9940bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
9941baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9942bea424a5SMatthias Ringwald     hci_run();
9943bea424a5SMatthias Ringwald }
9944bea424a5SMatthias Ringwald 
9945bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9946bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9947baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9948bea424a5SMatthias Ringwald     hci_run();
9949bea424a5SMatthias Ringwald }
9950bea424a5SMatthias Ringwald 
995132a12730SMatthias Ringwald void gap_set_page_timeout(uint16_t page_timeout){
995232a12730SMatthias Ringwald     hci_stack->page_timeout = page_timeout;
9953baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
995432a12730SMatthias Ringwald     hci_run();
995532a12730SMatthias Ringwald }
995632a12730SMatthias Ringwald 
9957f8ee3071SMatthias Ringwald #endif
9958beceeddeSMatthias Ringwald 
995921debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
996021debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
996121debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
996221debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
996321debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
996421debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
996502b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9966e8ca66c6SMatthias Ringwald     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
996721debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
996802b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
99695f3ccd83SMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
997002b02cffSMatthias Ringwald     }
997102b02cffSMatthias Ringwald }
997202b02cffSMatthias Ringwald 
997302b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
997402b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
997502b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
997602b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
997702b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
997802b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
997902b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
99805f3ccd83SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
998121debf25SMatthias Ringwald 	}
998221debf25SMatthias Ringwald }
9983cf38a091SMatthias Ringwald 
9984cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
99851ffa425cSMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9986cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9987cf38a091SMatthias Ringwald 	}
9988cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9989cf38a091SMatthias Ringwald 		// restart le resolving list update
9990cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9991cf38a091SMatthias Ringwald 	}
9992cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
9993cf38a091SMatthias Ringwald }
9994c3d19a30SMatthias Ringwald 
9995c3d19a30SMatthias Ringwald void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9996c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = privacy_mode;
9997c3d19a30SMatthias Ringwald }
999821debf25SMatthias Ringwald #endif
999921debf25SMatthias Ringwald 
10000f40c73b4SMatthias Ringwald #ifdef ENABLE_BLE
10001f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
10002f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
10003f40c73b4SMatthias Ringwald 
10004f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10005100da355SMatthias Ringwald 
10006100da355SMatthias Ringwald #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES) || (MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES == 0))
10007100da355SMatthias Ringwald     // incorrect configuration:
10008100da355SMatthias Ringwald     // - as MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES is not defined or zero this function always fails
10009100da355SMatthias Ringwald     // - please set MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES in btstack_config.h
10010100da355SMatthias Ringwald     btstack_assert(false);
10011100da355SMatthias Ringwald #endif
10012100da355SMatthias Ringwald 
10013f40c73b4SMatthias Ringwald     // check if already in list
10014f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10015f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10016f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10017f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
10018f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
10019f40c73b4SMatthias Ringwald             continue;
10020f40c73b4SMatthias Ringwald         }
10021f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
10022f40c73b4SMatthias Ringwald             continue;
10023f40c73b4SMatthias Ringwald         }
10024f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
10025f40c73b4SMatthias Ringwald             continue;
10026f40c73b4SMatthias Ringwald         }
10027f40c73b4SMatthias Ringwald         // disallow if already scheduled to add
10028f40c73b4SMatthias Ringwald         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
10029f40c73b4SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
10030f40c73b4SMatthias Ringwald         }
10031f40c73b4SMatthias Ringwald         // still on controller, but scheduled to remove -> re-add
10032f40c73b4SMatthias Ringwald         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
10033f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
10034f40c73b4SMatthias Ringwald     }
10035f40c73b4SMatthias Ringwald     // alloc and add to list
10036f40c73b4SMatthias Ringwald     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
10037f40c73b4SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
10038f40c73b4SMatthias Ringwald     entry->sid = advertising_sid;
10039f40c73b4SMatthias Ringwald     entry->address_type = address_type;
10040f40c73b4SMatthias Ringwald     (void)memcpy(entry->address, address, 6);
10041f40c73b4SMatthias Ringwald     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
10042f40c73b4SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
10043f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10044f40c73b4SMatthias Ringwald }
10045f40c73b4SMatthias Ringwald 
10046f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10047f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10048f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10049f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10050f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
10051f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
10052f40c73b4SMatthias Ringwald             continue;
10053f40c73b4SMatthias Ringwald         }
10054f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
10055f40c73b4SMatthias Ringwald             continue;
10056f40c73b4SMatthias Ringwald         }
10057f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
10058f40c73b4SMatthias Ringwald             continue;
10059f40c73b4SMatthias Ringwald         }
10060f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
10061f40c73b4SMatthias Ringwald             // remove from controller if already present
10062f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
10063f40c73b4SMatthias Ringwald         }  else {
10064f40c73b4SMatthias Ringwald             // directly remove entry from whitelist
10065f40c73b4SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
10066f40c73b4SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
10067f40c73b4SMatthias Ringwald         }
10068f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
10069f40c73b4SMatthias Ringwald     }
10070f40c73b4SMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10071f40c73b4SMatthias Ringwald }
10072f40c73b4SMatthias Ringwald 
10073f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_clear(void){
10074f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10075f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10076f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10077f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
10078f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
10079f40c73b4SMatthias Ringwald             // remove from controller if already present
10080f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
10081f40c73b4SMatthias Ringwald             continue;
10082f40c73b4SMatthias Ringwald         }
10083f40c73b4SMatthias Ringwald         // directly remove entry from whitelist
10084f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
10085f40c73b4SMatthias Ringwald         btstack_memory_periodic_advertiser_list_entry_free(entry);
10086f40c73b4SMatthias Ringwald     }
10087f40c73b4SMatthias Ringwald }
10088f40c73b4SMatthias Ringwald 
10089f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_clear(void){
10090f40c73b4SMatthias Ringwald     hci_periodic_advertiser_list_clear();
10091f40c73b4SMatthias Ringwald     hci_run();
10092f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10093f40c73b4SMatthias Ringwald }
10094f40c73b4SMatthias Ringwald 
10095f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10096f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
10097f40c73b4SMatthias Ringwald     if (status){
10098f40c73b4SMatthias Ringwald         return status;
10099f40c73b4SMatthias Ringwald     }
10100f40c73b4SMatthias Ringwald     hci_run();
10101f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10102f40c73b4SMatthias Ringwald }
10103f40c73b4SMatthias Ringwald 
10104f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10105f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
10106f40c73b4SMatthias Ringwald     if (status){
10107f40c73b4SMatthias Ringwald         return status;
10108f40c73b4SMatthias Ringwald     }
10109f40c73b4SMatthias Ringwald     hci_run();
10110f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10111f40c73b4SMatthias Ringwald }
101124bafedd5SMatthias Ringwald 
101134bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
101144bafedd5SMatthias Ringwald                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
101154bafedd5SMatthias Ringwald     // abort if already active
101164bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
101174bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
101184bafedd5SMatthias Ringwald     }
101194bafedd5SMatthias Ringwald     // store request
101204bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
101214bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_options = options;
101224bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
101234bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
101244bafedd5SMatthias Ringwald     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
101254bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_skip = skip;
101264bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_timeout = sync_timeout;
101274bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
101284bafedd5SMatthias Ringwald 
101294bafedd5SMatthias Ringwald     hci_run();
101304bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101314bafedd5SMatthias Ringwald }
101324bafedd5SMatthias Ringwald 
101334bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync_cancel(void){
101344bafedd5SMatthias Ringwald     // abort if not requested
101354bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
101364bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
101374bafedd5SMatthias Ringwald     }
101384bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
101394bafedd5SMatthias Ringwald     hci_run();
101404bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101414bafedd5SMatthias Ringwald }
101424bafedd5SMatthias Ringwald 
101434bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
1014449a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
1014549a6c69cSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
1014649a6c69cSMatthias Ringwald     }
1014749a6c69cSMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
1014849a6c69cSMatthias Ringwald     hci_run();
1014949a6c69cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
101504bafedd5SMatthias Ringwald }
101514bafedd5SMatthias Ringwald 
10152f40c73b4SMatthias Ringwald #endif
10153f40c73b4SMatthias Ringwald #endif
101544ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
10155969d876aSMatthias Ringwald static hci_iso_stream_t *
10156969d876aSMatthias Ringwald hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id) {
101574ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
10158969d876aSMatthias Ringwald     if (iso_stream != NULL){
101598d72db10SMatthias Ringwald         iso_stream->iso_type = iso_type;
1016026b93350SMatthias Ringwald         iso_stream->state = state;
101618d72db10SMatthias Ringwald         iso_stream->group_id = group_id;
10162969d876aSMatthias Ringwald         iso_stream->stream_id = stream_id;
10163969d876aSMatthias Ringwald         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
10164969d876aSMatthias Ringwald         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
101654ae8623eSMatthias Ringwald         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
101664ae8623eSMatthias Ringwald     }
10167969d876aSMatthias Ringwald     return iso_stream;
101684ae8623eSMatthias Ringwald }
101694ae8623eSMatthias Ringwald 
1017015a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
101714ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
101724ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
101734ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
101744ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10175969d876aSMatthias Ringwald         if (iso_stream->cis_handle == con_handle ) {
101764ae8623eSMatthias Ringwald             return iso_stream;
101774ae8623eSMatthias Ringwald         }
101784ae8623eSMatthias Ringwald     }
101794ae8623eSMatthias Ringwald     return NULL;
101804ae8623eSMatthias Ringwald }
101814ae8623eSMatthias Ringwald 
101824ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
10183969d876aSMatthias Ringwald     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
101844ae8623eSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
101854ae8623eSMatthias Ringwald     btstack_memory_hci_iso_stream_free(iso_stream);
101864ae8623eSMatthias Ringwald }
101874ae8623eSMatthias Ringwald 
10188778463d0SMatthias Ringwald static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
10189778463d0SMatthias Ringwald     btstack_linked_list_iterator_t it;
10190778463d0SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10191778463d0SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10192778463d0SMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10193778463d0SMatthias Ringwald         if ((iso_stream->group_id == group_id) &&
10194778463d0SMatthias Ringwald             (iso_stream->iso_type == iso_type)){
10195778463d0SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
10196778463d0SMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
10197778463d0SMatthias Ringwald         }
10198778463d0SMatthias Ringwald     }
10199778463d0SMatthias Ringwald }
10200778463d0SMatthias Ringwald 
102018d72db10SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t group_id) {
102024ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
102034ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
102044ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
102054ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10206a90016deSMatthias Ringwald         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
102078d72db10SMatthias Ringwald             (iso_stream->group_id == group_id)){
102084ae8623eSMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
102094ae8623eSMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
102104ae8623eSMatthias Ringwald         }
102114ae8623eSMatthias Ringwald     }
102124ae8623eSMatthias Ringwald }
1021336916f81SDirk Helbig 
10214a90016deSMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle){
1021536916f81SDirk Helbig     UNUSED(big_handle);
1021636916f81SDirk Helbig 
102174ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
102184ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
102194ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
102204ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
102214ae8623eSMatthias Ringwald         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
102224ae8623eSMatthias Ringwald             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
102234ae8623eSMatthias Ringwald         }
102244ae8623eSMatthias Ringwald     }
102254ae8623eSMatthias Ringwald }
10226d39e4f95SMatthias Ringwald 
10227d39e4f95SMatthias Ringwald static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
10228d39e4f95SMatthias Ringwald     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
10229d39e4f95SMatthias Ringwald     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
10230d39e4f95SMatthias Ringwald     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
10231d39e4f95SMatthias Ringwald     return (sdu_len_offset + 2 + sdu_len) == size;
10232d39e4f95SMatthias Ringwald }
10233d39e4f95SMatthias Ringwald 
10234750818acSMatthias Ringwald static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size) {
10235750818acSMatthias Ringwald     if (iso_stream == NULL){
10236750818acSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , READ_ISO_CONNECTION_HANDLE(packet));
10237d39e4f95SMatthias Ringwald         return;
10238d39e4f95SMatthias Ringwald     }
10239750818acSMatthias Ringwald 
10240750818acSMatthias Ringwald     if (hci_stack->iso_packet_handler == NULL) {
10241d39e4f95SMatthias Ringwald         return;
10242d39e4f95SMatthias Ringwald     }
10243d39e4f95SMatthias Ringwald 
10244d39e4f95SMatthias Ringwald     // parse header
10245a14c18deSMatthias Ringwald     uint16_t con_handle_and_flags = little_endian_read_16(packet, 0);
10246a14c18deSMatthias Ringwald     uint16_t data_total_length = little_endian_read_16(packet, 2);
10247a14c18deSMatthias Ringwald     uint8_t  pb_flag = (con_handle_and_flags >> 12) & 3;
10248d39e4f95SMatthias Ringwald 
10249d39e4f95SMatthias Ringwald     // assert packet is complete
10250a14c18deSMatthias Ringwald     if ((data_total_length + 4u) != size){
10251d39e4f95SMatthias Ringwald         return;
10252d39e4f95SMatthias Ringwald     }
10253d39e4f95SMatthias Ringwald 
10254d39e4f95SMatthias Ringwald     if ((pb_flag & 0x01) == 0){
10255d39e4f95SMatthias Ringwald         if (pb_flag == 0x02){
10256a14c18deSMatthias Ringwald             // The ISO_SDU_Fragment field contains a header and a complete SDU.
10257d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(packet, size)) {
10258d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
10259d39e4f95SMatthias Ringwald             }
10260d39e4f95SMatthias Ringwald         } else {
10261d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
1026260468fb4SMatthias Ringwald             if (size > sizeof(iso_stream->reassembly_buffer)){
10263d39e4f95SMatthias Ringwald                 return;
10264d39e4f95SMatthias Ringwald             }
10265d39e4f95SMatthias Ringwald             memcpy(iso_stream->reassembly_buffer, packet, size);
10266d39e4f95SMatthias Ringwald             // fix pb_flag
10267d39e4f95SMatthias Ringwald             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
10268d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = size;
10269d39e4f95SMatthias Ringwald         }
10270d39e4f95SMatthias Ringwald     } else {
10271a14c18deSMatthias Ringwald         // ISO_SDU_Fragment contains continuation or last fragment of an SDU
10272a14c18deSMatthias Ringwald         uint8_t ts_flag = (con_handle_and_flags >> 14) & 1;
10273d39e4f95SMatthias Ringwald         if (ts_flag != 0){
10274d39e4f95SMatthias Ringwald            return;
10275d39e4f95SMatthias Ringwald         }
10276d39e4f95SMatthias Ringwald         // append fragment
10277d39e4f95SMatthias Ringwald         if (iso_stream->reassembly_pos == 0){
10278d39e4f95SMatthias Ringwald             return;
10279d39e4f95SMatthias Ringwald         }
1028060468fb4SMatthias Ringwald 
10281a14c18deSMatthias Ringwald         if ((iso_stream->reassembly_pos + data_total_length) > sizeof(iso_stream->reassembly_buffer)){
10282d39e4f95SMatthias Ringwald             // reset reassembly buffer
10283d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
10284d39e4f95SMatthias Ringwald             return;
10285d39e4f95SMatthias Ringwald         }
10286a14c18deSMatthias Ringwald         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], data_total_length);
10287a14c18deSMatthias Ringwald         iso_stream->reassembly_pos += data_total_length;
10288d39e4f95SMatthias Ringwald 
10289d39e4f95SMatthias Ringwald         // deliver if last fragment and SDU complete
10290d39e4f95SMatthias Ringwald         if (pb_flag == 0x03){
10291d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
10292a14c18deSMatthias Ringwald                 // fix data_total_length
1029360468fb4SMatthias Ringwald                 little_endian_store_16(iso_stream->reassembly_buffer, 2, iso_stream->reassembly_pos - HCI_ISO_HEADER_SIZE);
10294d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
10295d39e4f95SMatthias Ringwald             }
10296a14c18deSMatthias Ringwald             // reset reassembly buffer
10297d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
10298d39e4f95SMatthias Ringwald         }
10299d39e4f95SMatthias Ringwald     }
10300d39e4f95SMatthias Ringwald }
10301d39e4f95SMatthias Ringwald 
103027aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
103037aa35f6aSMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
103047aa35f6aSMatthias Ringwald     uint16_t pos = 0;
103057aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103067aa35f6aSMatthias Ringwald     event[pos++] = 4 + (2 * big->num_bis);
103077aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
103087aa35f6aSMatthias Ringwald     event[pos++] = status;
103097aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
103107aa35f6aSMatthias Ringwald     event[pos++] = big->num_bis;
103117aa35f6aSMatthias Ringwald     uint8_t i;
103127aa35f6aSMatthias Ringwald     for (i=0;i<big->num_bis;i++){
103137aa35f6aSMatthias Ringwald         little_endian_store_16(event, pos, big->bis_con_handles[i]);
103147aa35f6aSMatthias Ringwald         pos += 2;
103157aa35f6aSMatthias Ringwald     }
103169da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103177aa35f6aSMatthias Ringwald }
103187aa35f6aSMatthias Ringwald 
10319d3a89d91SMatthias Ringwald static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
10320d3a89d91SMatthias Ringwald     uint8_t event [6 + (MAX_NR_CIS * 2)];
10321d3a89d91SMatthias Ringwald     uint16_t pos = 0;
10322d3a89d91SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
10323d3a89d91SMatthias Ringwald     event[pos++] = 4 + (2 * cig->num_cis);
10324d3a89d91SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
10325d3a89d91SMatthias Ringwald     event[pos++] = status;
10326d3a89d91SMatthias Ringwald     event[pos++] = cig->cig_id;
10327d3a89d91SMatthias Ringwald     event[pos++] = cig->num_cis;
10328d3a89d91SMatthias Ringwald     uint8_t i;
10329d3a89d91SMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10330d3a89d91SMatthias Ringwald         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
10331d3a89d91SMatthias Ringwald         pos += 2;
10332d3a89d91SMatthias Ringwald     }
103339da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
10334d3a89d91SMatthias Ringwald }
10335f06bb90fSMatthias Ringwald 
10336620553bdSMatthias Ringwald static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
10337f06bb90fSMatthias Ringwald     uint16_t pos = 0;
10338f06bb90fSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
10339cf439c63SMatthias Ringwald     event[pos++] = 8;
10340f06bb90fSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
10341f06bb90fSMatthias Ringwald     event[pos++] = status;
10342620553bdSMatthias Ringwald     event[pos++] = iso_stream->group_id;
10343620553bdSMatthias Ringwald     event[pos++] = iso_stream->stream_id;
10344620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->cis_handle);
10345f06bb90fSMatthias Ringwald     pos += 2;
10346620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->acl_handle);
10347cf439c63SMatthias Ringwald     pos += 2;
103487dd97f73SMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->iso_interval_1250us);
103497dd97f73SMatthias Ringwald     pos += 2;
103507dd97f73SMatthias Ringwald     event[pos++] = iso_stream->number_of_subevents;
103517dd97f73SMatthias Ringwald     event[pos++] = iso_stream->burst_number_c_to_p;
103527dd97f73SMatthias Ringwald     event[pos++] = iso_stream->burst_number_p_to_c;
103537dd97f73SMatthias Ringwald     event[pos++] = iso_stream->flush_timeout_c_to_p;
103547dd97f73SMatthias Ringwald     event[pos++] = iso_stream->flush_timeout_p_to_c;
10355620553bdSMatthias Ringwald     return pos;
10356f06bb90fSMatthias Ringwald }
10357f06bb90fSMatthias Ringwald 
1035814045fdbSMatthias Ringwald // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
1035914045fdbSMatthias Ringwald static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
1036014045fdbSMatthias Ringwald     // cache data before finalizing struct
103617dd97f73SMatthias Ringwald     uint8_t event [17];
10362620553bdSMatthias Ringwald     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
10363620553bdSMatthias Ringwald     btstack_assert(pos <= sizeof(event));
1036414045fdbSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
1036514045fdbSMatthias Ringwald         hci_iso_stream_finalize(iso_stream);
1036614045fdbSMatthias Ringwald     }
103679da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
1036814045fdbSMatthias Ringwald }
1036914045fdbSMatthias Ringwald 
103707aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big){
103717aa35f6aSMatthias Ringwald     uint8_t event [4];
103727aa35f6aSMatthias Ringwald     uint16_t pos = 0;
103737aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103747aa35f6aSMatthias Ringwald     event[pos++] = 2;
103757aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
103767aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
103779da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103787aa35f6aSMatthias Ringwald }
103797aa35f6aSMatthias Ringwald 
103802a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
103812a6c0f82SMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
103822a6c0f82SMatthias Ringwald     uint16_t pos = 0;
103832a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103842a6c0f82SMatthias Ringwald     event[pos++] = 4;
103852a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
103862a6c0f82SMatthias Ringwald     event[pos++] = status;
103872a6c0f82SMatthias Ringwald     event[pos++] = big_sync->big_handle;
103882a6c0f82SMatthias Ringwald     event[pos++] = big_sync->num_bis;
103892a6c0f82SMatthias Ringwald     uint8_t i;
103902a6c0f82SMatthias Ringwald     for (i=0;i<big_sync->num_bis;i++){
103912a6c0f82SMatthias Ringwald         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
103922a6c0f82SMatthias Ringwald         pos += 2;
103932a6c0f82SMatthias Ringwald     }
103949da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103952a6c0f82SMatthias Ringwald }
103962a6c0f82SMatthias Ringwald 
10397d04a9afcSMatthias Ringwald static void hci_emit_big_sync_stopped(uint8_t big_handle){
103982a6c0f82SMatthias Ringwald     uint8_t event [4];
103992a6c0f82SMatthias Ringwald     uint16_t pos = 0;
104002a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
104012a6c0f82SMatthias Ringwald     event[pos++] = 2;
104022a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
10403d04a9afcSMatthias Ringwald     event[pos++] = big_handle;
104049da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
104052a6c0f82SMatthias Ringwald }
104062a6c0f82SMatthias Ringwald 
104075ade6657SMatthias Ringwald static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
104085ade6657SMatthias Ringwald     uint8_t event[6];
104095ade6657SMatthias Ringwald     uint16_t pos = 0;
104105ade6657SMatthias Ringwald     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
104115ade6657SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
104125ade6657SMatthias Ringwald     event[pos++] = big->big_handle;
104135ade6657SMatthias Ringwald     event[pos++] = bis_index;
104145ade6657SMatthias Ringwald     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
104159da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
104165ade6657SMatthias Ringwald }
104175ade6657SMatthias Ringwald 
104182c077771SMatthias Ringwald static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
104192c077771SMatthias Ringwald     uint8_t event[4];
104202c077771SMatthias Ringwald     uint16_t pos = 0;
104212c077771SMatthias Ringwald     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
104222c077771SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
104232c077771SMatthias Ringwald     little_endian_store_16(event, pos, cis_con_handle);
104249da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
104252c077771SMatthias Ringwald }
104262c077771SMatthias Ringwald 
104277aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
104287aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
104297aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
104307aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104317aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
104327aa35f6aSMatthias Ringwald         if ( big->big_handle == big_handle ) {
104337aa35f6aSMatthias Ringwald             return big;
104347aa35f6aSMatthias Ringwald         }
104357aa35f6aSMatthias Ringwald     }
104367aa35f6aSMatthias Ringwald     return NULL;
104377aa35f6aSMatthias Ringwald }
104387aa35f6aSMatthias Ringwald 
104392a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
104402a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_t it;
104412a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
104422a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104432a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
104442a6c0f82SMatthias Ringwald         if ( big_sync->big_handle == big_handle ) {
104452a6c0f82SMatthias Ringwald             return big_sync;
104462a6c0f82SMatthias Ringwald         }
104472a6c0f82SMatthias Ringwald     }
104482a6c0f82SMatthias Ringwald     return NULL;
104492a6c0f82SMatthias Ringwald }
104502a6c0f82SMatthias Ringwald 
1045101d4f05fSMatthias Ringwald void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
1045201d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = num_packets;
1045301d4f05fSMatthias Ringwald }
1045401d4f05fSMatthias Ringwald 
10455d3a89d91SMatthias Ringwald static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10456d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_t it;
10457d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10458d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10459d3a89d91SMatthias Ringwald         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10460d3a89d91SMatthias Ringwald         if ( cig->cig_id == cig_id ) {
10461d3a89d91SMatthias Ringwald             return cig;
10462d3a89d91SMatthias Ringwald         }
10463d3a89d91SMatthias Ringwald     }
10464d3a89d91SMatthias Ringwald     return NULL;
10465d3a89d91SMatthias Ringwald }
10466d3a89d91SMatthias Ringwald 
104675ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void){
104682c077771SMatthias Ringwald 
104692c077771SMatthias Ringwald     // BIG
104702c077771SMatthias Ringwald 
104715ade6657SMatthias Ringwald     btstack_linked_list_iterator_t it;
104725ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
104735ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104745ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10475aacb1081SMatthias Ringwald         // track number completed packet timestamps
10476aacb1081SMatthias Ringwald         if (big->num_completed_timestamp_current_valid){
10477aacb1081SMatthias Ringwald             big->num_completed_timestamp_current_valid = false;
10478aacb1081SMatthias Ringwald             if (big->num_completed_timestamp_previous_valid){
10479aacb1081SMatthias Ringwald                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
1048036916f81SDirk Helbig                 int32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10481aacb1081SMatthias Ringwald                 int32_t num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10482aacb1081SMatthias Ringwald                                                                                big->num_completed_timestamp_previous_ms);
10483aacb1081SMatthias Ringwald                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10484aacb1081SMatthias Ringwald                     // to catch up, skip packet on all BIS
10485aacb1081SMatthias Ringwald                     uint8_t i;
10486aacb1081SMatthias Ringwald                     for (i=0;i<big->num_bis;i++){
10487aacb1081SMatthias Ringwald                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10488aacb1081SMatthias Ringwald                         if (iso_stream){
10489aacb1081SMatthias Ringwald                             iso_stream->num_packets_to_skip++;
10490aacb1081SMatthias Ringwald                         }
10491aacb1081SMatthias Ringwald                     }
10492aacb1081SMatthias Ringwald                 }
10493aacb1081SMatthias Ringwald             }
10494aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_valid = true;
10495aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10496aacb1081SMatthias Ringwald         }
10497aacb1081SMatthias Ringwald 
104985ade6657SMatthias Ringwald         if (big->can_send_now_requested){
10499d4e5d4faSMatthias Ringwald             // check if no outgoing iso packets pending and no can send now have to be emitted
105005ade6657SMatthias Ringwald             uint8_t i;
105015ade6657SMatthias Ringwald             bool can_send = true;
10502aacb1081SMatthias Ringwald             uint8_t num_iso_queued_minimum = 0;
105035ade6657SMatthias Ringwald             for (i=0;i<big->num_bis;i++){
105045ade6657SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10505aacb1081SMatthias Ringwald                 if (iso_stream == NULL) continue;
10506aacb1081SMatthias Ringwald                 // handle case where individual ISO packet was sent too late:
10507aacb1081SMatthias Ringwald                 // for each additionally queued packet, a new one needs to get skipped
10508aacb1081SMatthias Ringwald                 if (i==0){
10509aacb1081SMatthias Ringwald                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10510aacb1081SMatthias Ringwald                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10511aacb1081SMatthias Ringwald                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10512aacb1081SMatthias Ringwald                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10513aacb1081SMatthias Ringwald                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10514aacb1081SMatthias Ringwald                 }
10515aacb1081SMatthias Ringwald                 // check if we can send now
10516aacb1081SMatthias Ringwald                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
105175ade6657SMatthias Ringwald                     can_send = false;
105185ade6657SMatthias Ringwald                     break;
105195ade6657SMatthias Ringwald                 }
105205ade6657SMatthias Ringwald             }
105215ade6657SMatthias Ringwald             if (can_send){
105225ade6657SMatthias Ringwald                 // propagate can send now to individual streams
105235ade6657SMatthias Ringwald                 big->can_send_now_requested = false;
105245ade6657SMatthias Ringwald                 for (i=0;i<big->num_bis;i++){
105255ade6657SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
105265ade6657SMatthias Ringwald                     iso_stream->emit_ready_to_send = true;
105275ade6657SMatthias Ringwald                 }
105285ade6657SMatthias Ringwald             }
105295ade6657SMatthias Ringwald         }
105305ade6657SMatthias Ringwald     }
105315ade6657SMatthias Ringwald 
105325ade6657SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return;
105335ade6657SMatthias Ringwald 
105345ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
105355ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
105365ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
105375ade6657SMatthias Ringwald         // report bis ready
105385ade6657SMatthias Ringwald         uint8_t i;
105395ade6657SMatthias Ringwald         for (i=0;i<big->num_bis;i++){
105405ade6657SMatthias Ringwald             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
105415ade6657SMatthias Ringwald             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
105425ade6657SMatthias Ringwald                 iso_stream->emit_ready_to_send = false;
105435ade6657SMatthias Ringwald                 hci_emit_bis_can_send_now(big, i);
105440fc451bcSMatthias Ringwald                 if (hci_stack->hci_packet_buffer_reserved) return;
105455ade6657SMatthias Ringwald             }
105465ade6657SMatthias Ringwald         }
105475ade6657SMatthias Ringwald     }
105482c077771SMatthias Ringwald 
105490fc451bcSMatthias Ringwald 
105502c077771SMatthias Ringwald     // CIS
105512c077771SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
105522c077771SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
105532c077771SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
105542c077771SMatthias Ringwald         if ((iso_stream->can_send_now_requested) &&
105552c077771SMatthias Ringwald             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
105562c077771SMatthias Ringwald             iso_stream->can_send_now_requested = false;
10557969d876aSMatthias Ringwald             hci_emit_cis_can_send_now(iso_stream->cis_handle);
105580fc451bcSMatthias Ringwald             if (hci_stack->hci_packet_buffer_reserved) return;
105592c077771SMatthias Ringwald         }
105602c077771SMatthias Ringwald     }
105615ade6657SMatthias Ringwald }
105625ade6657SMatthias Ringwald 
10563c7308688SMatthias Ringwald static uint8_t gap_big_setup_iso_streams(uint8_t num_bis, uint8_t big_handle){
10564d034696aSMatthias Ringwald     // make big handle unique and usuable for big and big sync
10565c7308688SMatthias Ringwald     if (hci_big_for_handle(big_handle) != NULL){
105667aa35f6aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
105677aa35f6aSMatthias Ringwald     }
10568c7308688SMatthias Ringwald     if (hci_big_sync_for_handle(big_handle) != NULL){
10569d034696aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10570d034696aSMatthias Ringwald     }
10571c7308688SMatthias Ringwald     if (num_bis == 0){
105727aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
105737aa35f6aSMatthias Ringwald     }
10574c7308688SMatthias Ringwald     if (num_bis > MAX_NR_BIS){
105757aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
105767aa35f6aSMatthias Ringwald     }
105777aa35f6aSMatthias Ringwald 
10578fb16346aSMatthias Ringwald     // reserve ISO Streams
10579fb16346aSMatthias Ringwald     uint8_t i;
10580fb16346aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10581c7308688SMatthias Ringwald     for (i=0;i<num_bis;i++){
10582c7308688SMatthias Ringwald         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_handle, i);
10583969d876aSMatthias Ringwald         if (iso_stream == NULL) {
10584969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10585fb16346aSMatthias Ringwald             break;
10586fb16346aSMatthias Ringwald         }
10587fb16346aSMatthias Ringwald     }
10588fb16346aSMatthias Ringwald 
10589fb16346aSMatthias Ringwald     // free structs on error
10590fb16346aSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10591c7308688SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_handle);
10592c7308688SMatthias Ringwald     }
10593c7308688SMatthias Ringwald 
10594c7308688SMatthias Ringwald     return status;
10595c7308688SMatthias Ringwald }
10596c7308688SMatthias Ringwald 
10597c7308688SMatthias Ringwald uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
10598c7308688SMatthias Ringwald     uint8_t status = gap_big_setup_iso_streams(big_params->num_bis, big_params->big_handle);
10599c7308688SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10600fb16346aSMatthias Ringwald         return status;
10601fb16346aSMatthias Ringwald     }
10602fb16346aSMatthias Ringwald 
106037aa35f6aSMatthias Ringwald     le_audio_big_t * big = storage;
106047aa35f6aSMatthias Ringwald     big->big_handle = big_params->big_handle;
106057aa35f6aSMatthias Ringwald     big->params = big_params;
106067aa35f6aSMatthias Ringwald     big->state = LE_AUDIO_BIG_STATE_CREATE;
106077aa35f6aSMatthias Ringwald     big->num_bis = big_params->num_bis;
106087aa35f6aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
106097aa35f6aSMatthias Ringwald 
106107aa35f6aSMatthias Ringwald     hci_run();
106117aa35f6aSMatthias Ringwald 
106127aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
106137aa35f6aSMatthias Ringwald }
106147aa35f6aSMatthias Ringwald 
106152a6c0f82SMatthias Ringwald uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
10616c7308688SMatthias Ringwald     uint8_t status = gap_big_setup_iso_streams(big_sync_params->num_bis, big_sync_params->big_handle);
1061702e19895SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
1061802e19895SMatthias Ringwald         return status;
1061902e19895SMatthias Ringwald     }
1062002e19895SMatthias Ringwald 
106212a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = storage;
106222a6c0f82SMatthias Ringwald     big_sync->big_handle = big_sync_params->big_handle;
106232a6c0f82SMatthias Ringwald     big_sync->params = big_sync_params;
106242a6c0f82SMatthias Ringwald     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
106252a6c0f82SMatthias Ringwald     big_sync->num_bis = big_sync_params->num_bis;
106262a6c0f82SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
106272a6c0f82SMatthias Ringwald 
106282a6c0f82SMatthias Ringwald     hci_run();
106292a6c0f82SMatthias Ringwald 
106302a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106312a6c0f82SMatthias Ringwald }
106322a6c0f82SMatthias Ringwald 
106337aa35f6aSMatthias Ringwald uint8_t gap_big_terminate(uint8_t big_handle){
106347aa35f6aSMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
106357aa35f6aSMatthias Ringwald     if (big == NULL){
106367aa35f6aSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106377aa35f6aSMatthias Ringwald     }
106387aa35f6aSMatthias Ringwald     switch (big->state){
106397aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
106407aa35f6aSMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
106412a6c0f82SMatthias Ringwald             hci_emit_big_terminated(big);
106422a6c0f82SMatthias Ringwald             break;
106432a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
106442a6c0f82SMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
106457aa35f6aSMatthias Ringwald             break;
106467aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
106477aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
106487aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
106497aa35f6aSMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
106507aa35f6aSMatthias Ringwald             hci_run();
106517aa35f6aSMatthias Ringwald             break;
106522a6c0f82SMatthias Ringwald         default:
106532a6c0f82SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
106542a6c0f82SMatthias Ringwald     }
106552a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106562a6c0f82SMatthias Ringwald }
106572a6c0f82SMatthias Ringwald 
106582a6c0f82SMatthias Ringwald uint8_t gap_big_sync_terminate(uint8_t big_handle){
106592a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
106602a6c0f82SMatthias Ringwald     if (big_sync == NULL){
106612a6c0f82SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106622a6c0f82SMatthias Ringwald     }
106632a6c0f82SMatthias Ringwald     switch (big_sync->state){
106642a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
106652a6c0f82SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10666d04a9afcSMatthias Ringwald             hci_emit_big_sync_stopped(big_handle);
106672a6c0f82SMatthias Ringwald             break;
106687aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
106692a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
106702a6c0f82SMatthias Ringwald             break;
106712a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
106722a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
106732a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
106742a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
106752a6c0f82SMatthias Ringwald             hci_run();
106767aa35f6aSMatthias Ringwald             break;
106777aa35f6aSMatthias Ringwald         default:
106787aa35f6aSMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
106797aa35f6aSMatthias Ringwald     }
106807aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
106817aa35f6aSMatthias Ringwald }
10682d39e4f95SMatthias Ringwald 
106835ade6657SMatthias Ringwald uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
106845ade6657SMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
106855ade6657SMatthias Ringwald     if (big == NULL){
106865ade6657SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106875ade6657SMatthias Ringwald     }
106885ade6657SMatthias Ringwald     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
106895ade6657SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
106905ade6657SMatthias Ringwald     }
106915ade6657SMatthias Ringwald     big->can_send_now_requested = true;
106925ade6657SMatthias Ringwald     hci_iso_notify_can_send_now();
106935ade6657SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106945ade6657SMatthias Ringwald }
10695d3a89d91SMatthias Ringwald 
106962c077771SMatthias Ringwald uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
106972c077771SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
106982c077771SMatthias Ringwald     if (iso_stream == NULL){
106992c077771SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
107002c077771SMatthias Ringwald     }
107012c077771SMatthias Ringwald     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
107022c077771SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
107032c077771SMatthias Ringwald     }
107042c077771SMatthias Ringwald     iso_stream->can_send_now_requested = true;
107052c077771SMatthias Ringwald     hci_iso_notify_can_send_now();
107062c077771SMatthias Ringwald     return ERROR_CODE_SUCCESS;
107072c077771SMatthias Ringwald }
107082c077771SMatthias Ringwald 
10709d3a89d91SMatthias Ringwald uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10710d3a89d91SMatthias Ringwald     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10711d3a89d91SMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10712d3a89d91SMatthias Ringwald     }
10713d3a89d91SMatthias Ringwald     if (cig_params->num_cis == 0){
10714d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10715d3a89d91SMatthias Ringwald     }
107163e377057SMatthias Ringwald     if (cig_params->num_cis > MAX_NR_CIS){
10717d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10718d3a89d91SMatthias Ringwald     }
10719d3a89d91SMatthias Ringwald 
10720d3a89d91SMatthias Ringwald     // reserve ISO Streams
10721d3a89d91SMatthias Ringwald     uint8_t i;
10722d3a89d91SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10723d3a89d91SMatthias Ringwald     for (i=0;i<cig_params->num_cis;i++){
10724969d876aSMatthias Ringwald         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS,HCI_ISO_STREAM_STATE_REQUESTED, cig_params->cig_id, i);
1072536468e6fSMatthias Ringwald         if (iso_stream == NULL) {
10726969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10727d3a89d91SMatthias Ringwald             break;
10728d3a89d91SMatthias Ringwald         }
10729d3a89d91SMatthias Ringwald     }
10730d3a89d91SMatthias Ringwald 
10731d3a89d91SMatthias Ringwald     // free structs on error
10732d3a89d91SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10733d3a89d91SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10734d3a89d91SMatthias Ringwald         return status;
10735d3a89d91SMatthias Ringwald     }
10736d3a89d91SMatthias Ringwald 
10737d3a89d91SMatthias Ringwald     le_audio_cig_t * cig = storage;
10738d3a89d91SMatthias Ringwald     cig->cig_id = cig_params->cig_id;
10739d3a89d91SMatthias Ringwald     cig->num_cis = cig_params->num_cis;
10740d3a89d91SMatthias Ringwald     cig->params = cig_params;
10741d3a89d91SMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10742444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10743444e371eSMatthias Ringwald         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10744444e371eSMatthias Ringwald         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
107450f0ba168SMatthias Ringwald         cig->cis_setup_active[i] = false;
107460f0ba168SMatthias Ringwald         cig->cis_established[i] = false;
10747444e371eSMatthias Ringwald     }
10748d3a89d91SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10749d3a89d91SMatthias Ringwald 
10750d3a89d91SMatthias Ringwald     hci_run();
10751d3a89d91SMatthias Ringwald 
10752d3a89d91SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10753d3a89d91SMatthias Ringwald }
10754d3a89d91SMatthias Ringwald 
10755d90722d4SMatthias Ringwald uint8_t gap_cig_remove(uint8_t cig_id){
10756d90722d4SMatthias Ringwald     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10757d90722d4SMatthias Ringwald     if (cig == NULL){
10758d90722d4SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10759d90722d4SMatthias Ringwald     }
10760d90722d4SMatthias Ringwald 
10761d90722d4SMatthias Ringwald     // close active CIS
10762d90722d4SMatthias Ringwald     uint8_t i;
10763d90722d4SMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10764d90722d4SMatthias Ringwald         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
10765d90722d4SMatthias Ringwald         if (stream != NULL){
10766d90722d4SMatthias Ringwald             stream->state = HCI_ISO_STREAM_STATE_W2_CLOSE;
10767d90722d4SMatthias Ringwald         }
10768d90722d4SMatthias Ringwald     }
10769d90722d4SMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_REMOVE;
10770d90722d4SMatthias Ringwald 
10771d90722d4SMatthias Ringwald     hci_run();
10772d90722d4SMatthias Ringwald 
10773d90722d4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10774d90722d4SMatthias Ringwald }
10775d90722d4SMatthias Ringwald 
10776f2e409f3SMatthias Ringwald uint8_t gap_cis_create(uint8_t cig_id, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10777f2e409f3SMatthias Ringwald     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10778444e371eSMatthias Ringwald     if (cig == NULL){
10779444e371eSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10780444e371eSMatthias Ringwald     }
10781444e371eSMatthias Ringwald 
10782444e371eSMatthias Ringwald     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10783444e371eSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
10784444e371eSMatthias Ringwald     }
10785444e371eSMatthias Ringwald 
10786444e371eSMatthias Ringwald     // store ACL Connection Handles
10787444e371eSMatthias Ringwald     uint8_t i;
10788444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
1078956bd2ec0SMatthias Ringwald         // check that all con handles exist and store
10790444e371eSMatthias Ringwald         hci_con_handle_t cis_handle = cis_con_handles[i];
1079136468e6fSMatthias Ringwald         if (cis_handle == HCI_CON_HANDLE_INVALID){
1079236468e6fSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1079336468e6fSMatthias Ringwald         }
10794444e371eSMatthias Ringwald         uint8_t j;
10795444e371eSMatthias Ringwald         bool found = false;
10796444e371eSMatthias Ringwald         for (j=0;j<cig->num_cis;j++){
10797444e371eSMatthias Ringwald             if (cig->cis_con_handles[j] == cis_handle){
10798444e371eSMatthias Ringwald                 cig->acl_con_handles[j] = acl_con_handles[j];
1079956bd2ec0SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
1080056bd2ec0SMatthias Ringwald                 btstack_assert(iso_stream != NULL);
1080156bd2ec0SMatthias Ringwald                 iso_stream->acl_handle = acl_con_handles[j];
1080236468e6fSMatthias Ringwald                 found = true;
10803444e371eSMatthias Ringwald                 break;
10804444e371eSMatthias Ringwald             }
10805444e371eSMatthias Ringwald         }
10806444e371eSMatthias Ringwald         if (!found){
10807444e371eSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10808444e371eSMatthias Ringwald         }
10809444e371eSMatthias Ringwald     }
10810444e371eSMatthias Ringwald 
10811444e371eSMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10812444e371eSMatthias Ringwald     hci_run();
10813444e371eSMatthias Ringwald 
10814444e371eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
10815444e371eSMatthias Ringwald }
10816444e371eSMatthias Ringwald 
10817969d876aSMatthias Ringwald static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10818969d876aSMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
108196fd1d2c8SMatthias Ringwald     if (iso_stream == NULL){
108206fd1d2c8SMatthias Ringwald         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10821969d876aSMatthias Ringwald         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1082226b93350SMatthias Ringwald     }
1082326b93350SMatthias Ringwald 
108246fd1d2c8SMatthias Ringwald     // set next state and continue
108256fd1d2c8SMatthias Ringwald     iso_stream->state = state;
1082626b93350SMatthias Ringwald     hci_run();
1082726b93350SMatthias Ringwald     return ERROR_CODE_SUCCESS;
1082826b93350SMatthias Ringwald }
1082926b93350SMatthias Ringwald 
1083026b93350SMatthias Ringwald uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
1083126b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
1083226b93350SMatthias Ringwald }
1083326b93350SMatthias Ringwald 
1083426b93350SMatthias Ringwald uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
1083526b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
1083626b93350SMatthias Ringwald }
1083726b93350SMatthias Ringwald 
10838137a570aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
1083926b93350SMatthias Ringwald 
10840137a570aSMatthias Ringwald // GAP Privacy - notify clients before random address update
10841137a570aSMatthias Ringwald 
10842137a570aSMatthias Ringwald static bool gap_privacy_client_all_ready(void){
10843137a570aSMatthias Ringwald     // check if all ready
10844137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10845137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10846137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10847137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10848137a570aSMatthias Ringwald         if (client->state != GAP_PRIVACY_CLIENT_STATE_READY){
10849137a570aSMatthias Ringwald             return false;
10850137a570aSMatthias Ringwald         }
10851137a570aSMatthias Ringwald     }
10852137a570aSMatthias Ringwald     return true;
10853137a570aSMatthias Ringwald }
10854137a570aSMatthias Ringwald 
10855137a570aSMatthias Ringwald static void gap_privacy_clients_handle_ready(void){
10856137a570aSMatthias Ringwald     // clear 'ready'
10857137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10858137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10859137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10860137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10861137a570aSMatthias Ringwald         client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10862137a570aSMatthias Ringwald     }
10863137a570aSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
10864137a570aSMatthias Ringwald     hci_run();
10865137a570aSMatthias Ringwald }
10866137a570aSMatthias Ringwald 
10867137a570aSMatthias Ringwald static void gap_privacy_clients_notify(bd_addr_t new_random_address){
10868137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10869137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10870137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10871137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10872137a570aSMatthias Ringwald         if (client->state == GAP_PRIVACY_CLIENT_STATE_IDLE){
10873137a570aSMatthias Ringwald             client->state = GAP_PRIVACY_CLIENT_STATE_PENDING;
10874137a570aSMatthias Ringwald             (*client->callback)(client, new_random_address);
10875137a570aSMatthias Ringwald         }
10876137a570aSMatthias Ringwald     }
10877137a570aSMatthias Ringwald     if (gap_privacy_client_all_ready()){
10878137a570aSMatthias Ringwald         gap_privacy_clients_handle_ready();
10879137a570aSMatthias Ringwald     }
10880137a570aSMatthias Ringwald }
10881137a570aSMatthias Ringwald 
10882137a570aSMatthias Ringwald void gap_privacy_client_register(gap_privacy_client_t * client){
10883137a570aSMatthias Ringwald     client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10884137a570aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10885137a570aSMatthias Ringwald }
10886137a570aSMatthias Ringwald 
10887137a570aSMatthias Ringwald void gap_privacy_client_ready(gap_privacy_client_t * client){
10888137a570aSMatthias Ringwald     client->state = GAP_PRIVACY_CLIENT_STATE_READY;
10889137a570aSMatthias Ringwald     if (gap_privacy_client_all_ready()){
10890137a570aSMatthias Ringwald         gap_privacy_clients_handle_ready();
10891137a570aSMatthias Ringwald     }
10892137a570aSMatthias Ringwald }
10893137a570aSMatthias Ringwald 
10894137a570aSMatthias Ringwald void gap_privacy_client_unregister(gap_privacy_client_t * client){
10895137a570aSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10896137a570aSMatthias Ringwald }
10897137a570aSMatthias Ringwald 
108984ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
10899f40c73b4SMatthias Ringwald 
10900eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1090118976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
1090218976c74SMatthias Ringwald     hci_connection_t * conn;
1090318976c74SMatthias Ringwald 
1090418976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
1090518976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
1090618976c74SMatthias Ringwald 
109077d33cb26SMilanka Ringwald     // setup Controller info
109087d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
109097d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
109107d33cb26SMilanka Ringwald 
1091118976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
1091218976c74SMatthias Ringwald     addr[5] = 0x01;
1091317ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1091418976c74SMatthias Ringwald     conn->con_handle = addr[5];
1091518976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
109167d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1091718976c74SMatthias Ringwald 
1091818976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
1091918976c74SMatthias Ringwald     addr[5] = 0x02;
1092017ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1092118976c74SMatthias Ringwald     conn->con_handle = addr[5];
1092218976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
109237d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1092418976c74SMatthias Ringwald 
1092518976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
1092618976c74SMatthias Ringwald     addr[5] = 0x03;
1092717ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1092818976c74SMatthias Ringwald     conn->con_handle = addr[5];
1092918976c74SMatthias Ringwald     conn->state = OPEN;
109307d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1093118976c74SMatthias Ringwald 
1093218976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
1093318976c74SMatthias Ringwald     addr[5] = 0x04;
1093417ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1093518976c74SMatthias Ringwald     conn->con_handle = addr[5];
1093618976c74SMatthias Ringwald     conn->state = OPEN;
109377d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1093818976c74SMatthias Ringwald 
1093918976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
1094018976c74SMatthias Ringwald     addr[5] = 0x05;
1094117ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
1094218976c74SMatthias Ringwald     conn->con_handle = addr[5];
1094318976c74SMatthias Ringwald     conn->state = OPEN;
109447d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
109458046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
1094618976c74SMatthias Ringwald }
1094718976c74SMatthias Ringwald 
10948eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
10949eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
10950eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10951eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10952eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10953eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
10954eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
10955eddac615SMatthias Ringwald     }
10956eddac615SMatthias Ringwald }
109571470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
10958b6ffb67fSMatthias Ringwald     hci_stack->le_scanning_param_update = false;
109591470db0cSMatthias Ringwald     hci_init_done();
109601470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
109611470db0cSMatthias Ringwald }
10962eddac615SMatthias Ringwald #endif
10963