xref: /btstack/src/hci.c (revision 00220a2b293701714ed8b3be996a25616371a6f0)
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                 uint8_t i = 0;
3068d3a89d91SMatthias Ringwald                 if (status == ERROR_CODE_SUCCESS){
3069d3a89d91SMatthias Ringwald                     // assign CIS handles to pre-allocated CIS
3070d3a89d91SMatthias Ringwald                     btstack_linked_list_iterator_t it;
3071d3a89d91SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3072d3a89d91SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) {
3073d3a89d91SMatthias Ringwald                         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3074d3a89d91SMatthias Ringwald                         if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) &&
3075d3a89d91SMatthias Ringwald                             (iso_stream->iso_type == HCI_ISO_TYPE_CIS)){
3076d3a89d91SMatthias Ringwald                             hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i));
3077969d876aSMatthias Ringwald                             iso_stream->cis_handle  = cis_handle;
3078d3a89d91SMatthias Ringwald                             cig->cis_con_handles[i] = cis_handle;
3079d3a89d91SMatthias Ringwald                             i++;
3080d3a89d91SMatthias Ringwald                         }
3081d3a89d91SMatthias Ringwald                     }
3082444e371eSMatthias Ringwald                     cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST;
3083d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
3084d3a89d91SMatthias Ringwald                 } else {
3085d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
3086d3a89d91SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
3087d3a89d91SMatthias Ringwald                 }
3088d3a89d91SMatthias Ringwald             }
308926b93350SMatthias Ringwald             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3090d3a89d91SMatthias Ringwald             break;
30914ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
30924ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3093d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
30944ae8623eSMatthias Ringwald             }
30954ae8623eSMatthias Ringwald             break;
309642529435SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
309742529435SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3098d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
309942529435SMatthias Ringwald             }
310042529435SMatthias Ringwald             break;
31017aa35f6aSMatthias Ringwald         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
31027aa35f6aSMatthias Ringwald             // lookup BIG by state
31037aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_t it;
31047aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
31057aa35f6aSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
31067aa35f6aSMatthias Ringwald                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
31077aa35f6aSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
31087aa35f6aSMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
31097aa35f6aSMatthias Ringwald                         big->state_vars.next_bis++;
31107aa35f6aSMatthias Ringwald                         if (big->state_vars.next_bis == big->num_bis){
31117aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
31127aa35f6aSMatthias Ringwald                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
31137aa35f6aSMatthias Ringwald                         } else {
31147aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
31157aa35f6aSMatthias Ringwald                         }
31167aa35f6aSMatthias Ringwald                     } else {
31177aa35f6aSMatthias Ringwald                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
31187aa35f6aSMatthias Ringwald                         big->state_vars.status = status;
31192a6c0f82SMatthias Ringwald                     }
31202a6c0f82SMatthias Ringwald                     return;
31212a6c0f82SMatthias Ringwald                 }
31222a6c0f82SMatthias Ringwald             }
31232a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
31242a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
31252a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
31262a6c0f82SMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
31272a6c0f82SMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
31282a6c0f82SMatthias Ringwald                         big_sync->state_vars.next_bis++;
31292a6c0f82SMatthias Ringwald                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
31302a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
31312a6c0f82SMatthias Ringwald                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
31322a6c0f82SMatthias Ringwald                         } else {
31332a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
31342a6c0f82SMatthias Ringwald                         }
31352a6c0f82SMatthias Ringwald                     } else {
31362a6c0f82SMatthias Ringwald                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
31372a6c0f82SMatthias Ringwald                         big_sync->state_vars.status = status;
31382a6c0f82SMatthias Ringwald                     }
31392a6c0f82SMatthias Ringwald                     return;
31402a6c0f82SMatthias Ringwald                 }
31412a6c0f82SMatthias Ringwald             }
3142f9306a1aSMatthias Ringwald             // Lookup CIS via active group operation
3143f9306a1aSMatthias Ringwald             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
314426b93350SMatthias Ringwald                 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
314526b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
314626b93350SMatthias Ringwald 
314726b93350SMatthias Ringwald                     // lookup CIS by state
314826b93350SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
314926b93350SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it)){
315026b93350SMatthias Ringwald                         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3151532211feSMatthias Ringwald                         bool emit_cis_created = false;
315226b93350SMatthias Ringwald                         switch (iso_stream->state){
315326b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT:
315426b93350SMatthias Ringwald                                 if (status != ERROR_CODE_SUCCESS){
3155532211feSMatthias Ringwald                                     emit_cis_created = true;
315626b93350SMatthias Ringwald                                     break;
315726b93350SMatthias Ringwald                                 }
315826b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_c_to_p > 0){
31591418332dSMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
316026b93350SMatthias Ringwald                                 } else {
3161532211feSMatthias Ringwald                                     emit_cis_created = true;
316226b93350SMatthias Ringwald                                 }
316326b93350SMatthias Ringwald                                 break;
316426b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT:
3165*00220a2bSMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_ACTIVE;
3166532211feSMatthias Ringwald                                 emit_cis_created = true;
316726b93350SMatthias Ringwald                                 break;
316826b93350SMatthias Ringwald                             default:
316926b93350SMatthias Ringwald                                 break;
317026b93350SMatthias Ringwald                         }
3171532211feSMatthias Ringwald                         if (emit_cis_created){
317214045fdbSMatthias Ringwald                             hci_cis_handle_created(iso_stream, status);
3173532211feSMatthias Ringwald                         }
317426b93350SMatthias Ringwald                     }
317526b93350SMatthias Ringwald                 } else {
3176f9306a1aSMatthias Ringwald                     cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3177532211feSMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3178f9306a1aSMatthias Ringwald                     if (cig != NULL) {
3179f9306a1aSMatthias Ringwald                         // emit cis created if all ISO Paths have been created
3180f9306a1aSMatthias Ringwald                         // assume we are central
3181f9306a1aSMatthias Ringwald                         uint8_t cis_index     = cig->state_vars.next_cis >> 1;
3182f9306a1aSMatthias Ringwald                         uint8_t cis_direction = cig->state_vars.next_cis & 1;
3183f9306a1aSMatthias Ringwald                         bool outgoing_needed  = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
3184f9306a1aSMatthias Ringwald                         // if outgoing has been setup, or incoming was setup but outgoing not required
3185f9306a1aSMatthias Ringwald                         if ((cis_direction == 1) || (outgoing_needed == false)){
3186532211feSMatthias Ringwald                             // lookup iso stream by cig/cis
3187b5ecaedbSMatthias Ringwald                             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3188532211feSMatthias Ringwald                             while (btstack_linked_list_iterator_has_next(&it)) {
3189532211feSMatthias Ringwald                                 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3190532211feSMatthias Ringwald                                 if ((iso_stream->group_id == cig->cig_id) && (iso_stream->stream_id == cis_index)){
319114045fdbSMatthias Ringwald                                     hci_cis_handle_created(iso_stream, status);
3192532211feSMatthias Ringwald                                 }
3193532211feSMatthias Ringwald                             }
3194f9306a1aSMatthias Ringwald                         }
3195f9306a1aSMatthias Ringwald                         // next state
3196f9306a1aSMatthias Ringwald                         cig->state_vars.next_cis++;
3197f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
3198f9306a1aSMatthias Ringwald                     }
3199f9306a1aSMatthias Ringwald                 }
320026b93350SMatthias Ringwald             }
32012a6c0f82SMatthias Ringwald             break;
32022a6c0f82SMatthias Ringwald         }
32032a6c0f82SMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
32042a6c0f82SMatthias Ringwald             // lookup BIG by state
32052a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_t it;
32062a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
32072a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
32082a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3209d04a9afcSMatthias Ringwald                 uint8_t big_handle = big_sync->big_handle;
32102a6c0f82SMatthias Ringwald                 switch (big_sync->state){
32112a6c0f82SMatthias Ringwald                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3212d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
32132a6c0f82SMatthias Ringwald                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
3214d04a9afcSMatthias Ringwald                         return;
32152a6c0f82SMatthias Ringwald                     default:
3216d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
3217d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
32187aa35f6aSMatthias Ringwald                         return;
32197aa35f6aSMatthias Ringwald                 }
32207aa35f6aSMatthias Ringwald             }
32217aa35f6aSMatthias Ringwald             break;
32227aa35f6aSMatthias Ringwald         }
32234ae8623eSMatthias Ringwald #endif
32244ae8623eSMatthias Ringwald #endif
32256f35bb46SMatthias Ringwald         default:
32266f35bb46SMatthias Ringwald             break;
32274f781026SMatthias Ringwald     }
3228645b7c25SMatthias Ringwald }
32294f781026SMatthias Ringwald 
3230d8905293SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3231d8905293SMatthias Ringwald static void
3232d8905293SMatthias Ringwald hci_iso_create_big_failed(const le_audio_big_t *big, uint8_t status) {
3233d8905293SMatthias Ringwald     hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
3234d8905293SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
3235d8905293SMatthias Ringwald     if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
3236d8905293SMatthias Ringwald         hci_emit_big_created(big, status);
3237d8905293SMatthias Ringwald     } else {
3238d8905293SMatthias Ringwald         hci_emit_big_terminated(big);
3239d8905293SMatthias Ringwald     }
3240d8905293SMatthias Ringwald }
3241d8905293SMatthias Ringwald 
3242d8905293SMatthias Ringwald static void hci_iso_big_sync_failed(const le_audio_big_sync_t *big_sync, uint8_t status) {
3243d8905293SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
3244d8905293SMatthias Ringwald     if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
3245d8905293SMatthias Ringwald         hci_emit_big_sync_created(big_sync, status);
3246d8905293SMatthias Ringwald     } else {
3247d8905293SMatthias Ringwald         hci_emit_big_sync_stopped(big_sync->big_handle);
3248d8905293SMatthias Ringwald     }
3249d8905293SMatthias Ringwald }
3250d8905293SMatthias Ringwald #endif
3251d8905293SMatthias Ringwald 
3252afbf1cd7SMatthias Ringwald static void handle_command_status_event(uint8_t * packet, uint16_t size) {
3253afbf1cd7SMatthias Ringwald     UNUSED(size);
3254afbf1cd7SMatthias Ringwald 
3255afbf1cd7SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
3256afbf1cd7SMatthias Ringwald     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
3257afbf1cd7SMatthias Ringwald 
3258c70df5f8SMatthias Ringwald     // get opcode and command status
3259c70df5f8SMatthias Ringwald     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
3260c70df5f8SMatthias Ringwald 
3261c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
3262c70df5f8SMatthias Ringwald     uint8_t status = hci_event_command_status_get_status(packet);
3263c70df5f8SMatthias Ringwald #endif
3264c70df5f8SMatthias Ringwald 
3265c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3266c70df5f8SMatthias Ringwald     bd_addr_type_t addr_type;
326773bccf35Slouislee91     bd_addr_t addr;
3268c70df5f8SMatthias Ringwald #endif
3269c70df5f8SMatthias Ringwald 
327091036612SMatthias Ringwald #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
3271f48a5586SMatthias Ringwald     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
3272f48a5586SMatthias Ringwald #endif
3273f48a5586SMatthias Ringwald 
3274c70df5f8SMatthias Ringwald     switch (opcode){
3275afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3276c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
32779071873aSMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
3278c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
3279afbf1cd7SMatthias Ringwald #endif
3280afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3281c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
3282afbf1cd7SMatthias Ringwald #endif
3283c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3284afbf1cd7SMatthias Ringwald             addr_type = hci_stack->outgoing_addr_type;
328573bccf35Slouislee91             memcpy(addr, hci_stack->outgoing_addr, 6);
3286afbf1cd7SMatthias Ringwald 
3287afbf1cd7SMatthias Ringwald             // reset outgoing address info
3288afbf1cd7SMatthias Ringwald             memset(hci_stack->outgoing_addr, 0, 6);
3289afbf1cd7SMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
3290afbf1cd7SMatthias Ringwald 
3291afbf1cd7SMatthias Ringwald             // on error
3292afbf1cd7SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3293afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3294afbf1cd7SMatthias Ringwald                 if (hci_is_le_connection_type(addr_type)){
3295afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3296afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3297afbf1cd7SMatthias Ringwald                 }
3298afbf1cd7SMatthias Ringwald #endif
3299afbf1cd7SMatthias Ringwald                 // error => outgoing connection failed
330073bccf35Slouislee91                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3301afbf1cd7SMatthias Ringwald                 if (conn != NULL){
3302afbf1cd7SMatthias Ringwald                     hci_handle_connection_failed(conn, status);
3303afbf1cd7SMatthias Ringwald                 }
3304afbf1cd7SMatthias Ringwald             }
3305c70df5f8SMatthias Ringwald             break;
3306c70df5f8SMatthias Ringwald #endif
3307afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3308c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY:
3309afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
3310afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3311afbf1cd7SMatthias Ringwald             } else {
3312afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3313afbf1cd7SMatthias Ringwald             }
3314c70df5f8SMatthias Ringwald             break;
3315c70df5f8SMatthias Ringwald #endif
3316afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3317c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3318c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3319afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS){
3320d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID);
3321afbf1cd7SMatthias Ringwald             } else {
3322d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3323afbf1cd7SMatthias Ringwald             }
3324c70df5f8SMatthias Ringwald             break;
332515f9bb6dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_BIG:
332615f9bb6dSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
332715f9bb6dSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3328d8905293SMatthias Ringwald                 // get current big
3329d8905293SMatthias Ringwald                 le_audio_big_t * big = hci_big_for_handle(hci_stack->iso_active_operation_group_id);
3330d8905293SMatthias Ringwald                 if (big != NULL){
3331d8905293SMatthias Ringwald                     hci_iso_create_big_failed(big, status);
3332d8905293SMatthias Ringwald                 }
333315f9bb6dSMatthias Ringwald             }
333415f9bb6dSMatthias Ringwald             break;
333515f9bb6dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_CREATE_SYNC:
333615f9bb6dSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
333715f9bb6dSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3338d8905293SMatthias Ringwald                 // get current big sync
3339d8905293SMatthias Ringwald                 le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(hci_stack->iso_active_operation_group_id);
3340d8905293SMatthias Ringwald                 if (big_sync != NULL){
3341d8905293SMatthias Ringwald                     hci_iso_big_sync_failed(big_sync, status);
3342d8905293SMatthias Ringwald                 }
334315f9bb6dSMatthias Ringwald             }
334415f9bb6dSMatthias Ringwald             break;
3345afbf1cd7SMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3346c70df5f8SMatthias Ringwald         default:
3347c70df5f8SMatthias Ringwald             break;
3348c70df5f8SMatthias Ringwald     }
3349afbf1cd7SMatthias Ringwald }
3350afbf1cd7SMatthias Ringwald 
33510ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
3352e4def797SMatthias Ringwald static void hci_create_gap_connection_complete_event(const uint8_t * hci_event, uint8_t * gap_event) {
3353e4def797SMatthias Ringwald     gap_event[0] = HCI_EVENT_META_GAP;
3354e4def797SMatthias Ringwald     gap_event[1] = 36 - 2;
3355e4def797SMatthias Ringwald     gap_event[2] = GAP_SUBEVENT_LE_CONNECTION_COMPLETE;
3356bede2a55SMatthias Ringwald     switch (hci_event_le_meta_get_subevent_code(hci_event)){
3357a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3358e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 11);
3359e4def797SMatthias Ringwald             memset(&gap_event[14], 0, 12);
3360e4def797SMatthias Ringwald             memcpy(&gap_event[26], &hci_event[14], 7);
3361e4def797SMatthias Ringwald             memset(&gap_event[33], 0xff, 3);
33627efb077fSMatthias Ringwald             // Some Controllers incorrectly report a resolved identity address in HCI_SUBEVENT_LE_CONNECTION_COMPLETE.
33637efb077fSMatthias Ringwald             // If an address is resolved, we're working with it, but this event does not provide it.
33647efb077fSMatthias Ringwald             // As a workaround, we map identity addresses to regular addresses.
33657efb077fSMatthias Ringwald             gap_event[7] = gap_event[7] & 1;
3366a9212437SMatthias Ringwald             break;
3367a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
3368e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 30);
3369e4def797SMatthias Ringwald             memset(&gap_event[33], 0xff, 3);
3370a9212437SMatthias Ringwald             break;
3371a9212437SMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
3372e4def797SMatthias Ringwald             memcpy(&gap_event[3], &hci_event[3], 33);
3373a9212437SMatthias Ringwald             break;
3374a9212437SMatthias Ringwald         default:
3375a9212437SMatthias Ringwald             btstack_unreachable();
3376a9212437SMatthias Ringwald             break;
3377a9212437SMatthias Ringwald     }
3378a9212437SMatthias Ringwald }
3379a9212437SMatthias Ringwald 
3380688bcdb4SMatthias Ringwald static void hci_handle_le_connection_complete_event(const uint8_t * hci_event){
338198e0165dSMatthias Ringwald     // create GAP_SUBEVENT_LE_CONNECTION_COMPLETE
3382a9212437SMatthias Ringwald     uint8_t gap_event[36];
3383a9212437SMatthias Ringwald     hci_create_gap_connection_complete_event(hci_event, gap_event);
338460fb273dSMatthias Ringwald 
338598e0165dSMatthias Ringwald     // read fields
3386a9212437SMatthias Ringwald     uint8_t status = gap_subevent_le_connection_complete_get_status(gap_event);
3387a9212437SMatthias Ringwald     hci_role_t role = (hci_role_t) gap_subevent_le_connection_complete_get_role(gap_event);
3388a9212437SMatthias Ringwald     uint16_t conn_interval = gap_subevent_le_connection_complete_get_conn_interval(gap_event);
338998e0165dSMatthias Ringwald 
33900ce3f217SMatthias Ringwald 	// Connection management
3391138e942eSMatthias Ringwald     bd_addr_t addr;
3392a9212437SMatthias Ringwald     gap_subevent_le_connection_complete_get_peer_address(gap_event, addr);
3393138e942eSMatthias Ringwald     bd_addr_type_t addr_type = (bd_addr_type_t) gap_subevent_le_connection_complete_get_peer_address_type(gap_event);
3394138e942eSMatthias Ringwald     hci_con_handle_t con_handle = gap_subevent_le_connection_complete_get_connection_handle(gap_event);
339560fb273dSMatthias Ringwald     log_info("LE Connection_complete (status=%u) type %u, %s", status, addr_type, bd_addr_to_str(addr));
3396138e942eSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
33970ce3f217SMatthias Ringwald 
33980ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
33990ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
340060fb273dSMatthias Ringwald 	if (status){
34010ce3f217SMatthias Ringwald 
34020ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
34030ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
34040ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
34050ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
3406f24eac89SMatthias Ringwald         bool connection_was_cancelled = false;
340760fb273dSMatthias Ringwald 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
3408f24eac89SMatthias Ringwald             connection_was_cancelled = true;
34091f468175SMatthias Ringwald 		    // reset state
34100ce3f217SMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
34110ce3f217SMatthias Ringwald             // get outgoing connection conn struct for direct connect
3412ca0d6e5aSMatthias Ringwald             conn = gap_get_outgoing_le_connection();
34131f4510f5SMatthias Ringwald             // prepare restart if still active
34141f4510f5SMatthias Ringwald             if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
34159fd274a1SMatthias Ringwald                 conn->state = SEND_CREATE_CONNECTION;
34169fd274a1SMatthias Ringwald             }
34170ce3f217SMatthias Ringwald 		}
34180ce3f217SMatthias Ringwald 
3419c1281a25SMatthias Ringwald 		// free connection if cancelled by user (request == IDLE)
3420f24eac89SMatthias Ringwald         bool cancelled_by_user = hci_stack->le_connecting_request == LE_CONNECTING_IDLE;
3421f24eac89SMatthias Ringwald 		if ((conn != NULL) && cancelled_by_user){
34220ce3f217SMatthias Ringwald 			// remove entry
34230ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
34240ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
34250ce3f217SMatthias Ringwald 		}
34264dbe0476SMatthias Ringwald 
3427f24eac89SMatthias Ringwald         // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE for:
3428f24eac89SMatthias Ringwald         // - outgoing error not caused by connection cancel
3429f24eac89SMatthias Ringwald         // - connection cancelled by user
3430f24eac89SMatthias Ringwald         // by this, no event is emitted for intermediate connection cancel required filterlist modification
3431f24eac89SMatthias Ringwald         if ((connection_was_cancelled == false) || cancelled_by_user){
34321f4510f5SMatthias Ringwald             hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
3433f24eac89SMatthias Ringwald         }
34340ce3f217SMatthias Ringwald         return;
34350ce3f217SMatthias Ringwald 	}
34360ce3f217SMatthias Ringwald #endif
34370ce3f217SMatthias Ringwald 
34380ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
343960fb273dSMatthias Ringwald     if (role == HCI_ROLE_MASTER){
34400ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
34415bb205a5SMatthias Ringwald 		// if we're master, it was an outgoing connection
34420ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
34435bb205a5SMatthias Ringwald 
3444a086dc35SMatthias Ringwald         // if an identity addresses was used without enhanced connection complete event,
344558babb64SMatthias Ringwald         // the connection complete event contains the current random address of the peer device.
344658babb64SMatthias Ringwald         // This random address is needed in the case of a re-pairing
344758babb64SMatthias Ringwald         if (hci_event_le_meta_get_subevent_code(hci_event) == HCI_SUBEVENT_LE_CONNECTION_COMPLETE){
34485bb205a5SMatthias Ringwald             conn = gap_get_outgoing_le_connection();
344958babb64SMatthias Ringwald             // if outgoing connection object is available, check if identity address was used.
345058babb64SMatthias Ringwald             // if yes, track resolved random address and provide rpa
34515bb205a5SMatthias Ringwald             // note: we don't update hci le subevent connection complete
34525bb205a5SMatthias Ringwald             if (conn != NULL){
345358babb64SMatthias Ringwald                 if (hci_is_le_identity_address_type(conn->address_type)){
345458babb64SMatthias Ringwald                     memcpy(&gap_event[20], &gap_event[8], 6);
34555bb205a5SMatthias Ringwald                     gap_event[7] = conn->address_type;
34565bb205a5SMatthias Ringwald                     reverse_bd_addr(conn->address, &gap_event[8]);
34575bb205a5SMatthias Ringwald                 }
345858babb64SMatthias Ringwald             }
345958babb64SMatthias Ringwald         }
34605bb205a5SMatthias Ringwald 
34615bb205a5SMatthias Ringwald         // we're done with it
34620ce3f217SMatthias Ringwald         hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
34630ce3f217SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
34640ce3f217SMatthias Ringwald #endif
34650ce3f217SMatthias Ringwald 	} else {
34660ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
34672775f8e2SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
34682775f8e2SMatthias Ringwald         if (hci_le_extended_advertising_supported()) {
3469f7043595SMatthias Ringwald             // advertisement state managed with HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED
3470f7043595SMatthias Ringwald 
3471f7043595SMatthias Ringwald             // if advertisement set terminated event arrives before connection complete, connection struct has been prepared
3472f7043595SMatthias Ringwald             // set missing peer address + address type
3473f7043595SMatthias Ringwald             conn = hci_connection_for_handle(con_handle);
3474f7043595SMatthias Ringwald             if (conn != NULL){
3475f7043595SMatthias Ringwald                 memcpy(conn->address, addr, 6);
3476f7043595SMatthias Ringwald                 conn->address_type = addr_type;
3477f7043595SMatthias Ringwald             }
34782775f8e2SMatthias Ringwald         }
34792775f8e2SMatthias Ringwald         else
34802775f8e2SMatthias Ringwald #endif
34812775f8e2SMatthias Ringwald         {
34822775f8e2SMatthias Ringwald             // if we're slave, it was an incoming connection and advertisements have stopped
3483935aa76eSMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
34842775f8e2SMatthias Ringwald         }
34850ce3f217SMatthias Ringwald #endif
34860ce3f217SMatthias Ringwald 	}
34870ce3f217SMatthias Ringwald 
34880ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
34890ce3f217SMatthias Ringwald 	if (!conn){
349088f925b1SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
34910ce3f217SMatthias Ringwald 	}
34920ce3f217SMatthias Ringwald 
34930ce3f217SMatthias Ringwald 	// no memory, sorry.
34940ce3f217SMatthias Ringwald 	if (!conn){
34950ce3f217SMatthias Ringwald 		return;
34960ce3f217SMatthias Ringwald 	}
34970ce3f217SMatthias Ringwald 
34980ce3f217SMatthias Ringwald 	conn->state = OPEN;
3499138e942eSMatthias Ringwald 	conn->con_handle             = con_handle;
350060fb273dSMatthias Ringwald     conn->le_connection_interval = conn_interval;
35010ce3f217SMatthias Ringwald 
35024639b1e4SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3503ac0f6b83SMatthias Ringwald     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
35044639b1e4SMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_REMOTE_FEATURES)){
3505ac0f6b83SMatthias Ringwald         conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
35064639b1e4SMatthias Ringwald     }
35074639b1e4SMatthias Ringwald #endif
3508ac0f6b83SMatthias Ringwald 
35090ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
351060fb273dSMatthias Ringwald     if (role == HCI_ROLE_SLAVE){
35110ce3f217SMatthias Ringwald         hci_update_advertisements_enabled_for_current_roles();
35120ce3f217SMatthias Ringwald     }
35130ce3f217SMatthias Ringwald #endif
35140ce3f217SMatthias Ringwald 
3515dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
3516dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3517dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
3518dde9ff1eSMatthias Ringwald 
35190ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
35200ce3f217SMatthias Ringwald 
35210ce3f217SMatthias Ringwald 	// restart timer
35220ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
35230ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
35240ce3f217SMatthias Ringwald 
35250ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
35260ce3f217SMatthias Ringwald 
352798e0165dSMatthias Ringwald     // emit GAP_SUBEVENT_LE_CONNECTION_COMPLETE
35289da9850bSMatthias Ringwald     hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
352998e0165dSMatthias Ringwald 
353098e0165dSMatthias Ringwald     // emit BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
35310ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
35320ce3f217SMatthias Ringwald }
35330ce3f217SMatthias Ringwald #endif
35340ce3f217SMatthias Ringwald 
353517c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
353617c6fe5cSMatthias 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){
353717c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
353817c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
35399a8f78c1SMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
35409a8f78c1SMatthias Ringwald     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
354117c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
35429a8f78c1SMatthias Ringwald         // MITM not possible without keyboard or display
354317c6fe5cSMatthias Ringwald         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
354417c6fe5cSMatthias Ringwald         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
35459a8f78c1SMatthias Ringwald 
35469a8f78c1SMatthias Ringwald         // MITM possible if one side has keyboard and the other has keyboard or display
35479a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
35489a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
35499a8f78c1SMatthias Ringwald 
35509a8f78c1SMatthias Ringwald         // MITM not possible if one side has only display and other side has no keyboard
35519a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
35529a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
355317c6fe5cSMatthias Ringwald     }
355417c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
355517c6fe5cSMatthias Ringwald     return true;
355617c6fe5cSMatthias Ringwald }
35573817f9dfSMatthias Ringwald 
3558b3c4163bSMatthias Ringwald static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
35592dd8985bSMatthias Ringwald     // get requested security level
35602dd8985bSMatthias Ringwald     gap_security_level_t requested_security_level = conn->requested_security_level;
35612dd8985bSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
35622dd8985bSMatthias Ringwald         requested_security_level = LEVEL_4;
35632dd8985bSMatthias Ringwald     }
35642dd8985bSMatthias Ringwald 
3565b3c4163bSMatthias Ringwald     // assess security: LEVEL 4 requires SC
35662dd8985bSMatthias Ringwald     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
35672dd8985bSMatthias Ringwald     if ((requested_security_level == LEVEL_4) &&
35682dd8985bSMatthias Ringwald         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
35692dd8985bSMatthias Ringwald         !hci_remote_sc_enabled(conn)){
3570b3c4163bSMatthias Ringwald         log_info("Level 4 required, but SC not supported -> abort");
3571b3c4163bSMatthias Ringwald         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3572b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3573b3c4163bSMatthias Ringwald         return;
3574b3c4163bSMatthias Ringwald     }
3575b3c4163bSMatthias Ringwald 
3576c2414c00SMatthias Ringwald     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3577c2414c00SMatthias Ringwald     // - GAP/MOD/NBON/BV-02-C
3578c2414c00SMatthias Ringwald     // - GAP/DM/NBON/BV-01-C
3579c2414c00SMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3580c2414c00SMatthias Ringwald         switch (conn->io_cap_response_auth_req){
3581c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3582c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3583c2414c00SMatthias Ringwald                 if (hci_stack->bondable == false){
3584c2414c00SMatthias Ringwald                     log_info("Dedicated vs. non-bondable -> abort");
3585c2414c00SMatthias Ringwald                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3586c2414c00SMatthias Ringwald                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3587c2414c00SMatthias Ringwald                     return;
3588c2414c00SMatthias Ringwald                 }
3589c2414c00SMatthias Ringwald             default:
3590c2414c00SMatthias Ringwald                 break;
3591c2414c00SMatthias Ringwald         }
3592c2414c00SMatthias Ringwald     }
3593c2414c00SMatthias Ringwald 
3594b3c4163bSMatthias Ringwald     // assess security based on io capabilities
3595b3c4163bSMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3596b3c4163bSMatthias Ringwald         // responder: fully validate io caps of both sides as well as OOB data
3597b3c4163bSMatthias Ringwald         bool security_possible = false;
3598b3c4163bSMatthias Ringwald         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3599b3c4163bSMatthias Ringwald 
3600b3c4163bSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3601b3c4163bSMatthias Ringwald         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3602b3c4163bSMatthias Ringwald         // so we merge the OOB data availability
3603b3c4163bSMatthias Ringwald         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3604b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_192 != NULL){
3605b3c4163bSMatthias Ringwald             have_oob_data |= 1;
3606b3c4163bSMatthias Ringwald         }
3607b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_256 != NULL){
3608b3c4163bSMatthias Ringwald             have_oob_data |= 2;
3609b3c4163bSMatthias Ringwald         }
3610b3c4163bSMatthias Ringwald         // for up to Level 3, either P-192 as well as P-256 will do
3611b3c4163bSMatthias 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
3612b3c4163bSMatthias Ringwald         // if remote does not SC, we should not receive P-256 data either
3613b3c4163bSMatthias Ringwald         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3614b3c4163bSMatthias Ringwald             security_possible = true;
3615b3c4163bSMatthias Ringwald         }
3616b3c4163bSMatthias Ringwald         // for Level 4, P-256 is needed
3617b3c4163bSMatthias Ringwald         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3618b3c4163bSMatthias Ringwald             security_possible = true;
3619b3c4163bSMatthias Ringwald         }
3620b3c4163bSMatthias Ringwald #endif
3621b3c4163bSMatthias Ringwald 
3622b3c4163bSMatthias Ringwald         if (security_possible == false){
36232dd8985bSMatthias Ringwald             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3624b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3625b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3626b3c4163bSMatthias Ringwald             return;
3627b3c4163bSMatthias Ringwald         }
3628b3c4163bSMatthias Ringwald     } else {
3629b3c4163bSMatthias Ringwald         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
36301fe968f5SMatthias Ringwald #ifndef ENABLE_CLASSIC_PAIRING_OOB
36311fe968f5SMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3632b3c4163bSMatthias Ringwald         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3633b3c4163bSMatthias Ringwald             log_info("Level 3+ required, but no input/output -> abort");
3634b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3635b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3636b3c4163bSMatthias Ringwald             return;
3637b3c4163bSMatthias Ringwald         }
3638b3c4163bSMatthias Ringwald #endif
36391fe968f5SMatthias Ringwald #endif
3640b3c4163bSMatthias Ringwald     }
3641b3c4163bSMatthias Ringwald 
3642b3c4163bSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3643b3c4163bSMatthias Ringwald     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3644b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3645b3c4163bSMatthias Ringwald     } else {
3646b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3647b3c4163bSMatthias Ringwald     }
3648b3c4163bSMatthias Ringwald #endif
3649b3c4163bSMatthias Ringwald }
3650b3c4163bSMatthias Ringwald 
365117c6fe5cSMatthias Ringwald #endif
365217c6fe5cSMatthias Ringwald 
3653c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
36544f781026SMatthias Ringwald 
36554f781026SMatthias Ringwald     uint16_t event_length = packet[1];
36564f781026SMatthias Ringwald 
36574f781026SMatthias Ringwald     // assert packet is complete
36584ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
36594f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
36604f781026SMatthias Ringwald         return;
36614f781026SMatthias Ringwald     }
36624f781026SMatthias Ringwald 
36634f781026SMatthias Ringwald     hci_con_handle_t handle;
36644f781026SMatthias Ringwald     hci_connection_t * conn;
36654f781026SMatthias Ringwald     int i;
36664f781026SMatthias Ringwald 
36674f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
36685e91d96cSMatthias Ringwald     hci_link_type_t link_type;
366948f33f37SMatthias Ringwald     bd_addr_t addr;
3670cef94710SMatthias Ringwald     bd_addr_type_t addr_type;
36714f781026SMatthias Ringwald #endif
36724ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
36734ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream;
36747aa35f6aSMatthias Ringwald     le_audio_big_t   * big;
36752a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync;
36764ae8623eSMatthias Ringwald #endif
367789254d99SMatthias Ringwald #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
367889254d99SMatthias Ringwald     btstack_linked_list_iterator_t it;
367989254d99SMatthias Ringwald #endif
3680759e0a0dSMatthias Ringwald #if defined(ENABLE_LE_EXTENDED_ADVERTISING) && defined(ENABLE_LE_CENTRAL)
368189254d99SMatthias Ringwald     uint8_t advertising_handle;
368289254d99SMatthias Ringwald #endif
36834f781026SMatthias Ringwald 
36844f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
36854f781026SMatthias Ringwald 
36864f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
36874f781026SMatthias Ringwald 
36884f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
36894f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
369056cf178bSmatthias.ringwald             break;
369156cf178bSmatthias.ringwald 
36927ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
3693afbf1cd7SMatthias Ringwald             handle_command_status_event(packet, size);
36947ec5eeaaSmatthias.ringwald             break;
36957ec5eeaaSmatthias.ringwald 
36962e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
36979784dac1SMatthias Ringwald             if (size < 3) return;
36989784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
36994ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
3700d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3701d9a1d8edSMatthias Ringwald             bool notify_sco = false;
3702d9a1d8edSMatthias Ringwald #endif
3703d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3704d9a1d8edSMatthias Ringwald             bool notify_iso = false;
3705d9a1d8edSMatthias Ringwald #endif
37069784dac1SMatthias Ringwald             uint16_t offset = 3;
37079784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
37084ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
37094ea43905SMatthias Ringwald                 offset += 2u;
3710f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
37114ea43905SMatthias Ringwald                 offset += 2u;
37122e440c8aS[email protected] 
37135061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
3714e5413aa0SMatthias Ringwald                 if (conn != NULL) {
371523bed257S[email protected] 
3716ce41473eSMatthias Ringwald                     if (conn->num_packets_sent >= num_packets) {
3717ce41473eSMatthias Ringwald                         conn->num_packets_sent -= num_packets;
3718e35edcc1S[email protected]                     } else {
3719ce41473eSMatthias Ringwald                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3720ce41473eSMatthias Ringwald                         conn->num_packets_sent = 0;
3721e35edcc1S[email protected]                     }
3722ce41473eSMatthias Ringwald                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3723d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3724d9a1d8edSMatthias Ringwald                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3725d9a1d8edSMatthias Ringwald                         notify_sco = true;
3726d9a1d8edSMatthias Ringwald                     }
3727d9a1d8edSMatthias Ringwald #endif
3728e5413aa0SMatthias Ringwald                 }
3729e5413aa0SMatthias Ringwald 
37308ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
37318ad9cf99SMatthias Ringwald                 hci_controller_dump_packets();
37328ad9cf99SMatthias Ringwald #endif
37338ad9cf99SMatthias Ringwald 
3734e5413aa0SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3735e5413aa0SMatthias Ringwald                 if (conn == NULL){
3736c30bd0a5SMatthias Ringwald                     iso_stream = hci_iso_stream_for_con_handle(handle);
3737e5413aa0SMatthias Ringwald                     if (iso_stream != NULL){
3738e5413aa0SMatthias Ringwald                         if (iso_stream->num_packets_sent >= num_packets) {
3739e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent -= num_packets;
3740e5413aa0SMatthias Ringwald                         } else {
3741e5413aa0SMatthias Ringwald                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3742e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent = 0;
3743e5413aa0SMatthias Ringwald                         }
37448d72db10SMatthias Ringwald                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
3745c30bd0a5SMatthias Ringwald                             big = hci_big_for_handle(iso_stream->group_id);
3746fe977b37SMatthias Ringwald                             if (big != NULL){
3747fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_valid = true;
3748fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3749fe977b37SMatthias Ringwald                             }
3750fe977b37SMatthias Ringwald                         }
3751e5413aa0SMatthias Ringwald                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3752e5413aa0SMatthias Ringwald                                  num_packets, handle, iso_stream->num_packets_sent);
3753d9a1d8edSMatthias Ringwald                         notify_iso = true;
3754e5413aa0SMatthias Ringwald                     }
3755d9a1d8edSMatthias Ringwald                 }
3756d9a1d8edSMatthias Ringwald #endif
3757d9a1d8edSMatthias Ringwald             }
3758d9a1d8edSMatthias Ringwald 
3759d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3760d9a1d8edSMatthias Ringwald             if (notify_sco){
3761d9a1d8edSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
3762d9a1d8edSMatthias Ringwald             }
3763d9a1d8edSMatthias Ringwald #endif
3764d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3765d9a1d8edSMatthias Ringwald             if (notify_iso){
37665ade6657SMatthias Ringwald                 hci_iso_notify_can_send_now();
3767e5413aa0SMatthias Ringwald             }
3768e5413aa0SMatthias Ringwald #endif
37696772a24cSmatthias.ringwald             break;
37702e440c8aS[email protected]         }
377135454696SMatthias Ringwald 
377235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
37739afaa4d4SMatthias Ringwald         case HCI_EVENT_FLUSH_OCCURRED:
37749afaa4d4SMatthias Ringwald             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
37759afaa4d4SMatthias Ringwald             handle = hci_event_flush_occurred_get_handle(packet);
37769afaa4d4SMatthias Ringwald             conn = hci_connection_for_handle(handle);
37779afaa4d4SMatthias Ringwald             if (conn) {
37789afaa4d4SMatthias Ringwald                 log_info("Flush occurred, disconnect 0x%04x", handle);
37799afaa4d4SMatthias Ringwald                 conn->state = SEND_DISCONNECT;
37809afaa4d4SMatthias Ringwald             }
37819afaa4d4SMatthias Ringwald             break;
37829afaa4d4SMatthias Ringwald 
3783f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
3784f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3785f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3786f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
37879da9850bSMatthias Ringwald                 hci_emit_btstack_event(event, sizeof(event), 1);
3788f5875de5SMatthias Ringwald             }
3789f5875de5SMatthias Ringwald             break;
3790b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3791b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3792b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3793b7f1ee76SMatthias Ringwald             }
3794b7f1ee76SMatthias Ringwald             break;
37951f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
3796724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
37975e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
379872cf8859SMatthias Ringwald 
379972cf8859SMatthias Ringwald             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
380072cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
380172cf8859SMatthias Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
380272cf8859SMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
380372cf8859SMatthias Ringwald                 break;
380472cf8859SMatthias Ringwald             }
380572cf8859SMatthias Ringwald 
380607e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
38075e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3808d152b6c6SMatthias Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
380907e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
381007e010b6SMilanka Ringwald                     break;
381107e010b6SMilanka Ringwald                 }
381207e010b6SMilanka Ringwald             }
381307e010b6SMilanka Ringwald 
381437eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
38155e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
38165e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
38172e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
38181f7b95a1Smatthias.ringwald             if (!conn) {
381988f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
38201f7b95a1Smatthias.ringwald             }
3821ce4c8fabSmatthias.ringwald             if (!conn) {
3822ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
38234536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3824058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
3825f23819bcSMatthias Ringwald                 hci_run();
3826f23819bcSMatthias Ringwald                 // avoid event to higher layer
3827f23819bcSMatthias Ringwald                 return;
3828ce4c8fabSmatthias.ringwald             }
382932ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
3830f3a16b9aSMatthias Ringwald             // store info about eSCO
38315e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
383276ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
3833f3a16b9aSMatthias Ringwald             }
3834d7891039SMatthias Ringwald             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3835d7891039SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_SCO){
3836182d886dSMatthias Ringwald                 const hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3837182d886dSMatthias Ringwald                 // ACL exists unless fuzzing
3838182d886dSMatthias Ringwald                 if (acl_conn != NULL) {
3839d7891039SMatthias Ringwald                     conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3840d7891039SMatthias Ringwald                 }
3841182d886dSMatthias Ringwald             }
384232ab9390Smatthias.ringwald             hci_run();
38431f7b95a1Smatthias.ringwald             break;
38441f7b95a1Smatthias.ringwald 
38456772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
3846fe1ed1b8Smatthias.ringwald             // Connection management
3847724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
38489da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3849f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
38502e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3851fe1ed1b8Smatthias.ringwald             if (conn) {
3852893b4ccdSMatthias Ringwald                 switch (conn->state){
3853893b4ccdSMatthias Ringwald                     // expected states
3854893b4ccdSMatthias Ringwald                     case ACCEPTED_CONNECTION_REQUEST:
3855893b4ccdSMatthias Ringwald                     case SENT_CREATE_CONNECTION:
3856893b4ccdSMatthias Ringwald                         break;
3857893b4ccdSMatthias Ringwald                     // unexpected state -> ignore
3858893b4ccdSMatthias Ringwald                     default:
3859893b4ccdSMatthias Ringwald                         // don't forward event to app
3860893b4ccdSMatthias Ringwald                         return;
3861893b4ccdSMatthias Ringwald                 }
3862b448a0e7Smatthias.ringwald                 if (!packet[2]){
3863c8e4258aSmatthias.ringwald                     conn->state = OPEN;
3864f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
38656909f064SMatthias Ringwald 
386622df2fe2SMatthias Ringwald                     // trigger write supervision timeout if we're master
3867d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
386822df2fe2SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
38696909f064SMatthias Ringwald                     }
38706909f064SMatthias Ringwald 
387122df2fe2SMatthias Ringwald                     // trigger write automatic flush timeout
38729afaa4d4SMatthias Ringwald                     if (hci_stack->automatic_flush_timeout != 0){
38739afaa4d4SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
38749afaa4d4SMatthias Ringwald                     }
38759afaa4d4SMatthias Ringwald 
3876c785ef68Smatthias.ringwald                     // restart timer
3877528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3878528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
3879c785ef68Smatthias.ringwald 
388018c4a0a3SMatthias Ringwald                     // trigger remote features for dedicated bonding
388118c4a0a3SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
388218c4a0a3SMatthias Ringwald                         hci_trigger_remote_features_for_connection(conn);
388318c4a0a3SMatthias Ringwald                     }
388418c4a0a3SMatthias Ringwald 
38859da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
388643bfb1bdSmatthias.ringwald 
388743bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
3888b448a0e7Smatthias.ringwald                 } else {
38890bbba85bSMatthias Ringwald                     // connection failed
38900bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
3891fe1ed1b8Smatthias.ringwald                 }
3892fe1ed1b8Smatthias.ringwald             }
38936772a24cSmatthias.ringwald             break;
3894fe1ed1b8Smatthias.ringwald 
389544d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3896724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
38971f34df2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
38981f34df2cSMatthias Ringwald             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
3899182d886dSMatthias Ringwald 
3900182d886dSMatthias Ringwald             // SCO exists unless fuzzer
3901182d886dSMatthias Ringwald             if (conn == NULL) break;
39029071873aSMatthias Ringwald 
39039071873aSMatthias Ringwald             if (packet[2] != ERROR_CODE_SUCCESS){
39049071873aSMatthias Ringwald                 // connection failed, remove entry
39051f34df2cSMatthias Ringwald                 hci_handle_connection_failed(conn, packet[2]);
390644d0e3d5S[email protected]                 break;
390744d0e3d5S[email protected]             }
39089071873aSMatthias Ringwald 
39091a06f663S[email protected]             conn->state = OPEN;
3910f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
3911ee752bb8SMatthias Ringwald 
3912d7891039SMatthias Ringwald             // update sco payload length for eSCO connections
3913d7891039SMatthias Ringwald             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3914d7891039SMatthias Ringwald                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3915d7891039SMatthias Ringwald                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3916d7891039SMatthias Ringwald             }
3917d7891039SMatthias Ringwald 
3918ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3919ee752bb8SMatthias Ringwald             // update SCO
3920ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3921ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3922ee752bb8SMatthias Ringwald             }
3923f234b250SMatthias Ringwald             // trigger can send now
3924f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
39251972f31fSMatthias Ringwald                 hci_stack->sco_can_send_now = true;
3926f234b250SMatthias Ringwald             }
3927fa7f2dfdSMatthias Ringwald 
3928a086dc35SMatthias Ringwald             // setup implicit sco flow control
3929fa7f2dfdSMatthias Ringwald             conn->sco_tx_ready = 0;
3930fa7f2dfdSMatthias Ringwald             conn->sco_tx_active  = 0;
3931fa7f2dfdSMatthias Ringwald             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3932fa7f2dfdSMatthias Ringwald 
3933ee752bb8SMatthias Ringwald #endif
3934cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3935cb70c5abSMatthias Ringwald             // configure sco transport
3936cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
3937cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3938cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3939cb70c5abSMatthias Ringwald             }
3940cb70c5abSMatthias Ringwald #endif
394144d0e3d5S[email protected]             break;
394244d0e3d5S[email protected] 
3943afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3944f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
3945afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
3946afd4e962S[email protected]             if (!conn) break;
3947afd4e962S[email protected]             if (!packet[2]){
39482f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
39492f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
39502f5c44baSMatthias Ringwald 
39515ccef624SMatthias Ringwald                 // read extended features if possible
39521ffa425cSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
39531ffa425cSMatthias Ringwald                 && ((conn->remote_supported_features[0] & 2) != 0)) {
39545ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
39555ccef624SMatthias Ringwald                     break;
39565ccef624SMatthias Ringwald                 }
39575ccef624SMatthias Ringwald             }
39585ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
39595ccef624SMatthias Ringwald             break;
39605ccef624SMatthias Ringwald 
39615ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
39625ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
39635ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
39645ccef624SMatthias Ringwald             if (!conn) break;
39655ccef624SMatthias Ringwald             // status = ok, page = 1
396650c51a77SMatthias Ringwald             if (!packet[2]) {
396750c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
396850c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
39695ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
397050c51a77SMatthias Ringwald                 bool done = false;
397150c51a77SMatthias Ringwald                 switch (page_number){
397250c51a77SMatthias Ringwald                     case 1:
39732f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
397450c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
397550c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
397650c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
397750c51a77SMatthias Ringwald                         } else {
397850c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
397950c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
398050c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
398150c51a77SMatthias Ringwald                             }
398250c51a77SMatthias Ringwald                             done = true;
398350c51a77SMatthias Ringwald                         }
398450c51a77SMatthias Ringwald                         break;
398550c51a77SMatthias Ringwald                     case 2:
398650c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
398750c51a77SMatthias Ringwald                         done = true;
398850c51a77SMatthias Ringwald                         break;
398950c51a77SMatthias Ringwald                     default:
399050c51a77SMatthias Ringwald                         break;
399150c51a77SMatthias Ringwald                 }
399250c51a77SMatthias Ringwald                 if (!done) break;
3993afd4e962S[email protected]             }
3994de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
3995afd4e962S[email protected]             break;
3996afd4e962S[email protected] 
39977fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
3998308eeaffSMatthias Ringwald #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
399963c0b2fdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
400063c0b2fdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
400163c0b2fdSMatthias Ringwald             if (!conn) break;
400263c0b2fdSMatthias Ringwald 
400363c0b2fdSMatthias Ringwald             // lookup link key in db if not cached
400463c0b2fdSMatthias Ringwald             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
400563c0b2fdSMatthias Ringwald                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
400663c0b2fdSMatthias Ringwald             }
400763c0b2fdSMatthias Ringwald 
400863c0b2fdSMatthias Ringwald             // response sent by hci_run()
400963c0b2fdSMatthias Ringwald             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
401063c0b2fdSMatthias Ringwald #endif
4011608f51bbSMatthias Ringwald             break;
40127fde4af9Smatthias.ringwald 
40139ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
40141714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
4015f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40169ab95c90S[email protected]             if (!conn) break;
40171714cbbdSMatthias Ringwald 
40181714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
40191714cbbdSMatthias Ringwald 
40203817f9dfSMatthias Ringwald             // CVE-2020-26555: ignore NULL link key
40213817f9dfSMatthias Ringwald             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
40223817f9dfSMatthias Ringwald             if (btstack_is_null(&packet[8], 16)) break;
40233817f9dfSMatthias Ringwald 
40247bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
40259ab95c90S[email protected]             // Change Connection Encryption keeps link key type
40269ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
40279ab95c90S[email protected]                 conn->link_key_type = link_key_type;
40289ab95c90S[email protected]             }
40293817f9dfSMatthias Ringwald 
4030e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
4031e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
4032e9f98c4aSMatthias Ringwald 
4033bec5f683SMatthias Ringwald             // only store link key:
4034bec5f683SMatthias Ringwald             // - if bondable enabled
4035bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
4036af411b3fSMatthias Ringwald             // - if at least one side requests bonding during the IO Capabilities exchange.
4037af411b3fSMatthias Ringwald             // Note: we drop bonding flag in acceptor role if remote doesn't request it
4038af411b3fSMatthias Ringwald             bool bonding_local  = conn->io_cap_request_auth_req  >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4039af411b3fSMatthias Ringwald             bool bonding_remote = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4040af411b3fSMatthias Ringwald             if ((bonding_local == false) && (bonding_remote == false)) break;
40416edaed7fSMatthias Ringwald             // - if security level sufficient
40426edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
404355597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
40447fde4af9Smatthias.ringwald             break;
40459ab95c90S[email protected]         }
40467fde4af9Smatthias.ringwald 
40477fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
40481714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
40491714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40501714cbbdSMatthias Ringwald             if (!conn) break;
40511714cbbdSMatthias Ringwald 
40521714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
4053a800d95eSMatthias Ringwald             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
40543a9fb326S[email protected]             if (!hci_stack->bondable ){
40558daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
40561714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
4057f8fb5f6eS[email protected]                 hci_run();
4058f8fb5f6eS[email protected]                 return;
40594c57c146S[email protected]             }
4060a800d95eSMatthias Ringwald             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
4061a800d95eSMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
4062a800d95eSMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
406350dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
406450dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
406550dcc63cSMatthias Ringwald                 hci_run();
406650dcc63cSMatthias Ringwald                 return;
406750dcc63cSMatthias Ringwald             }
40687fde4af9Smatthias.ringwald             break;
40697fde4af9Smatthias.ringwald 
407050d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
407150d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
407250d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
407350d7398cSMatthias Ringwald             if (!conn) break;
40741714cbbdSMatthias Ringwald 
40758daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
40761714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
407750d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
4078e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
4079d22b82d6SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
4080d22b82d6SMatthias Ringwald             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
4081d22b82d6SMatthias Ringwald #endif
408250d7398cSMatthias Ringwald             break;
408350d7398cSMatthias Ringwald 
40841d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
40851714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
40861714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40871714cbbdSMatthias Ringwald             if (!conn) break;
40881714cbbdSMatthias Ringwald 
4089c950c316SMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
40909671e615SMatthias Ringwald             hci_connection_timestamp(conn);
40911714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
4092dbe1a790S[email protected]             break;
4093dbe1a790S[email protected] 
40941849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
40951849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
40967ca4a7edSMatthias Ringwald             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
40977ca4a7edSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40987ca4a7edSMatthias Ringwald             if (!conn) break;
40997ca4a7edSMatthias Ringwald 
41007ca4a7edSMatthias Ringwald             hci_connection_timestamp(conn);
41017ca4a7edSMatthias Ringwald 
41027ca4a7edSMatthias Ringwald             hci_pairing_started(conn, true);
41037ca4a7edSMatthias Ringwald 
41047ca4a7edSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
41051849becdSMatthias Ringwald             break;
41061849becdSMatthias Ringwald #endif
41071849becdSMatthias Ringwald 
4108dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
410917c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
4110367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4111367aedc0SMatthias Ringwald             if (!conn) break;
4112367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
4113367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
41148daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
4115367aedc0SMatthias Ringwald                 };
4116367aedc0SMatthias Ringwald             } else {
4117367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
4118367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4119367aedc0SMatthias Ringwald                 // don't forward event to app
4120367aedc0SMatthias Ringwald                 hci_run();
4121367aedc0SMatthias Ringwald                 return;
4122367aedc0SMatthias Ringwald             }
4123dbe1a790S[email protected]             break;
4124dbe1a790S[email protected] 
4125dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
4126367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
4127367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
41288daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
4129367aedc0SMatthias Ringwald             };
41301d6b20aeS[email protected]             break;
41311849becdSMatthias Ringwald 
41323dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
41333dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
41343dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
41353dce6128SMatthias Ringwald             if (!conn) break;
41363dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
41373dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
41383dce6128SMatthias Ringwald             break;
413935454696SMatthias Ringwald #endif
41401d6b20aeS[email protected] 
4141f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
4142a355334eSMatthias Ringwald         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4143254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
4144f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
4145f0944df2S[email protected]             if (!conn) break;
4146db3c1f89SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
4147254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
4148254b78eeSMatthias Ringwald                 if (encryption_enabled){
4149573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
4150573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
41518daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
4152573897a0SMatthias Ringwald                     }
4153573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
4154573897a0SMatthias Ringwald                     else {
4155fcaf38b9SMatthias Ringwald 
4156254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
415736c3546bSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
4158254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
4159edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
4160813a09c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4161813a09c6SMatthias Ringwald                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
4162813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-31-C
4163813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-32-C
4164813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-33-C
4165813a09c6SMatthias Ringwald 
4166813a09c6SMatthias Ringwald                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
4167813a09c6SMatthias Ringwald                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
416829d4766dSMatthias Ringwald                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
416929d4766dSMatthias Ringwald                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
4170813a09c6SMatthias Ringwald                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
4171813a09c6SMatthias Ringwald                             }
4172813a09c6SMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
4173813a09c6SMatthias Ringwald                                      conn->link_key_type, new_link_key_type);
4174813a09c6SMatthias Ringwald                             conn->link_key_type = new_link_key_type;
4175813a09c6SMatthias Ringwald #else
4176254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
41779ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4178254b78eeSMatthias Ringwald                             break;
4179813a09c6SMatthias Ringwald #endif
4180254b78eeSMatthias Ringwald                         }
4181254b78eeSMatthias Ringwald 
418262daa441SMatthias Ringwald #ifdef ENABLE_MUTUAL_AUTHENTICATION_FOR_LEGACY_SECURE_CONNECTIONS
4183aa2fe986SMatthias Ringwald                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
4184aa2fe986SMatthias Ringwald                         if (connected_uses_aes_ccm){
4185aa2fe986SMatthias Ringwald                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4186aa2fe986SMatthias Ringwald                         }
418762daa441SMatthias Ringwald #else
418862daa441SMatthias Ringwald                         // We consider even Legacy Secure Connections as authenticated as BTstack mandates encryption
4189a086dc35SMatthias Ringwald                         // with encryption key size > hci_stack->gap_required_encryption_key_size
419062daa441SMatthias Ringwald                         // for all operations that require any security. See BIAS attacks.
4191aa2fe986SMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4192aa2fe986SMatthias Ringwald #endif
4193a355334eSMatthias Ringwald                         // validate encryption key size
4194a355334eSMatthias Ringwald                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
4195a355334eSMatthias Ringwald                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
4196a355334eSMatthias Ringwald                             // already got encryption key size
4197a355334eSMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
4198a355334eSMatthias Ringwald                         } else {
41991ffa425cSMatthias Ringwald                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
42006e058d3fSMatthias Ringwald                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
4201573897a0SMatthias Ringwald                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
42026e058d3fSMatthias Ringwald                             } else {
42036e058d3fSMatthias Ringwald                                 // if not, pretend everything is perfect
42049866fdc7SMatthias Ringwald                                 hci_handle_read_encryption_key_size_complete(conn, 16);
42056e058d3fSMatthias Ringwald                             }
4206573897a0SMatthias Ringwald                         }
4207a355334eSMatthias Ringwald                     }
4208573897a0SMatthias Ringwald #endif
4209f0944df2S[email protected]                 } else {
42108daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
4211f0944df2S[email protected]                 }
42125999ee11SMatthias Ringwald             } else {
42138eae094cSMatthias Ringwald #ifdef ENABLE_CLASSIC
42148eae094cSMatthias Ringwald                 if (!hci_is_le_connection(conn)){
42155999ee11SMatthias Ringwald                     uint8_t status = hci_event_encryption_change_get_status(packet);
42165999ee11SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
42175999ee11SMatthias Ringwald                         conn->bonding_flags &= ~BONDING_DEDICATED;
42185999ee11SMatthias Ringwald                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
42195999ee11SMatthias Ringwald                         conn->bonding_status = status;
42205999ee11SMatthias Ringwald                     }
422127b992efSMatthias Ringwald                     // trigger security update -> level 0
422227b992efSMatthias Ringwald                     hci_handle_mutual_authentication_completed(conn);
4223ad83dc6aS[email protected]                 }
42248eae094cSMatthias Ringwald #endif
42258eae094cSMatthias Ringwald             }
4226573897a0SMatthias Ringwald 
4227f0944df2S[email protected]             break;
4228f0944df2S[email protected] 
422935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
42301eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4231abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
42321eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
42331eb2563eS[email protected]             if (!conn) break;
4234ad83dc6aS[email protected] 
4235dbd5dcc3SMatthias Ringwald             // clear authentication active flag
4236dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
42371714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4238dbd5dcc3SMatthias Ringwald 
4239abdad579SMatthias Ringwald             // authenticated only if auth status == 0
4240abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
4241abdad579SMatthias Ringwald                 // authenticated
42428daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4243abdad579SMatthias Ringwald 
4244131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
42458daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
42461eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4247ad83dc6aS[email protected]                     break;
4248ad83dc6aS[email protected]                 }
4249abdad579SMatthias Ringwald             }
4250abdad579SMatthias Ringwald 
42514aa2f135SMatthias Ringwald             // emit updated security level (will be 0 if not authenticated)
42524aa2f135SMatthias Ringwald             hci_handle_mutual_authentication_completed(conn);
42531eb2563eS[email protected]             break;
42541714cbbdSMatthias Ringwald 
42551714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
42561714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
42571714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
42581714cbbdSMatthias Ringwald             if (!conn) break;
42591714cbbdSMatthias Ringwald 
4260aa2fe986SMatthias Ringwald             // treat successfully paired connection as authenticated
4261aa2fe986SMatthias Ringwald             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4262f3aafff1SMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4263aa2fe986SMatthias Ringwald             }
4264aa2fe986SMatthias Ringwald 
42651714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
42661714cbbdSMatthias Ringwald             break;
426735454696SMatthias Ringwald #endif
426834d2123cS[email protected] 
426986805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
4270ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
4271ccda6e14S[email protected]         // see end of function, too.
4272a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
4273a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
4274f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
427581d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
42764ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
4277c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
42784ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
427981d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4280c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
4281c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
428281d2bdb2SMatthias Ringwald                     if (release_buffer){
428381d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
428481d2bdb2SMatthias Ringwald                     }
4285c6a37cfdSMatthias Ringwald                 }
4286c6a37cfdSMatthias Ringwald             }
428735454696SMatthias Ringwald 
42884ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4289098c2716SMatthias Ringwald             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4290098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size > 0u) {
4291098c2716SMatthias Ringwald                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4292098c2716SMatthias Ringwald                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4293098c2716SMatthias Ringwald                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4294098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_total_size = 0;
4295098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_pos = 0;
4296098c2716SMatthias Ringwald                     if (release_buffer){
4297098c2716SMatthias Ringwald                         hci_release_packet_buffer();
4298098c2716SMatthias Ringwald                     }
4299098c2716SMatthias Ringwald                 }
4300098c2716SMatthias Ringwald             }
4301098c2716SMatthias Ringwald 
43026fd1d2c8SMatthias Ringwald             // finalize iso stream for CIS handle
430315a15be3SMatthias Ringwald             iso_stream = hci_iso_stream_for_con_handle(handle);
43044ae8623eSMatthias Ringwald             if (iso_stream != NULL){
43054ae8623eSMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
43064ae8623eSMatthias Ringwald                 break;
43074ae8623eSMatthias Ringwald             }
43084ae8623eSMatthias Ringwald #endif
43094ae8623eSMatthias Ringwald 
431091036612SMatthias Ringwald #if defined(ENABLE_BLE) && defined (ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND)
4311f48a5586SMatthias Ringwald             if ((handle != HCI_CON_HANDLE_INVALID) && (handle == hci_stack->hci_command_con_handle)){
4312f48a5586SMatthias Ringwald                 // we did not receive a HCI Command Complete or HCI Command Status event for the disconnected connection
4313f48a5586SMatthias Ringwald                 // if needed, we could also track the hci command opcode and simulate a hci command complete with status
4314f48a5586SMatthias Ringwald                 // but the connection has failed anyway, so for now, we only set the num hci commands back to 1
431505acf48bSMatthias Ringwald                 log_info("Disconnect for conn handle 0x%04x in pending HCI command, assume command failed", handle);
431605acf48bSMatthias Ringwald                 hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4317f48a5586SMatthias Ringwald                 hci_stack->num_cmd_packets = 1;
4318f48a5586SMatthias Ringwald             }
4319f48a5586SMatthias Ringwald #endif
4320f48a5586SMatthias Ringwald 
4321c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
4322c6a37cfdSMatthias Ringwald             if (!conn) break;
43231714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
43241714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
43251714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
43261714cbbdSMatthias Ringwald #endif
4327046ec007SMatthias Ringwald 
4328a086dc35SMatthias Ringwald             // emit dedicated bonding event
4329046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4330046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4331046ec007SMatthias Ringwald             }
4332046ec007SMatthias Ringwald 
4333459d27b9SMatthias Ringwald             // mark connection for shutdown, stop timers, reset state
4334459d27b9SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4335459d27b9SMatthias Ringwald             hci_connection_stop_timer(conn);
4336459d27b9SMatthias Ringwald             hci_connection_init(conn);
4337459d27b9SMatthias Ringwald 
433835454696SMatthias Ringwald #ifdef ENABLE_BLE
4339d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4340046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
43412b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
4342bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
43439a2e4658SMatthias Ringwald             }
434435454696SMatthias Ringwald #endif
4345d70217a2SMatthias Ringwald #endif
4346ccda6e14S[email protected]             break;
43476772a24cSmatthias.ringwald 
4348c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
4349313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
4350d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
4351c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
43527586ee35S[email protected]             } else {
43537586ee35S[email protected]                 // if no special requests, just reboot stack
43547586ee35S[email protected]                 hci_power_control_off();
43557586ee35S[email protected]                 hci_power_control_on();
4356c68bdf90Smatthias.ringwald             }
4357c68bdf90Smatthias.ringwald             break;
4358c68bdf90Smatthias.ringwald 
43590e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
43605cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
43615cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
4362c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
4363f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
4364c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4365c4c88f1bSJakob Krantz             if (!conn) break;
436688f925b1SMatthias Ringwald             conn->role = (hci_role_t) packet[9];
43675cf766e8SMatthias Ringwald             break;
43680e6f3837SMatthias Ringwald #endif
43695cf766e8SMatthias Ringwald 
437063fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4371098c2716SMatthias Ringwald             // release packet buffer only for asynchronous transport and if there are not further fragments
43724fa24b5fS[email protected]             if (hci_transport_synchronous()) {
437363fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
43744fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
43754fa24b5fS[email protected]             }
437681d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
4377098c2716SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4378098c2716SMatthias Ringwald             hci_stack->iso_fragmentation_tx_active = 0;
4379098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size) break;
4380098c2716SMatthias Ringwald #endif
4381d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
43825daaa52eSMatthias Ringwald 
43835daaa52eSMatthias Ringwald             // release packet buffer without HCI_EVENT_TRANSPORT_PACKET_SENT (as it will be later)
43845daaa52eSMatthias Ringwald             hci_stack->hci_packet_buffer_reserved = false;
4385701e3307SMatthias Ringwald 
43865ade6657SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
43875ade6657SMatthias Ringwald             hci_iso_notify_can_send_now();
43885ade6657SMatthias Ringwald #endif
438963fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
439063fa3374SMatthias Ringwald 
439135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
439263fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
4393701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
439435454696SMatthias Ringwald #endif
43956b4af23dS[email protected]             break;
43966b4af23dS[email protected] 
439735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
439863fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
439963fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
44001972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = true;
440163fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
440263fa3374SMatthias Ringwald             return;
44031cfb383eSMatthias Ringwald 
4404a086dc35SMatthias Ringwald         // explode inquiry results for easier consumption
44051cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
44061cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
44071cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
44089784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
44091cfb383eSMatthias Ringwald             break;
441035454696SMatthias Ringwald #endif
441163fa3374SMatthias Ringwald 
4412a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
44135909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
44145909f7f2Smatthias.ringwald             switch (packet[2]){
4415d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
441657c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
44176fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
441857c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
44197bdc6798S[email protected]                     break;
4420a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4421a0698cb4SMatthias Ringwald                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4422a0698cb4SMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
4423a0698cb4SMatthias Ringwald                     le_handle_extended_advertisement_report(packet, size);
4424a0698cb4SMatthias Ringwald                     break;
4425ce56b945SMatthias Ringwald                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4426ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4427ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4428ce56b945SMatthias Ringwald                     break;
442989254d99SMatthias Ringwald                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
443089254d99SMatthias Ringwald                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
44312daa339aSMatthias Ringwald                     if (advertising_handle == LE_EXTENDED_ADVERTISING_LEGACY_HANDLE){
44322daa339aSMatthias Ringwald                         // legacy advertisements
44332daa339aSMatthias Ringwald                         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
44342daa339aSMatthias Ringwald                         hci_update_advertisements_enabled_for_current_roles();
44352daa339aSMatthias Ringwald                     } else {
443689254d99SMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
443789254d99SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)) {
443889254d99SMatthias Ringwald                             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
443989254d99SMatthias Ringwald                             if (advertising_set->advertising_handle == advertising_handle){
444089254d99SMatthias Ringwald                                 advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
444189254d99SMatthias Ringwald                             }
444289254d99SMatthias Ringwald                         }
44432775f8e2SMatthias Ringwald                     }
4444f7043595SMatthias Ringwald                     // event may come before le connection complete and announces new connection
4445f7043595SMatthias Ringwald                     if (hci_subevent_le_advertising_set_terminated_get_status(packet) == ERROR_CODE_SUCCESS){
4446f7043595SMatthias Ringwald                         handle = hci_subevent_le_advertising_set_terminated_get_connection_handle(packet);
4447f7043595SMatthias Ringwald                         conn = hci_connection_for_handle(handle);
4448f7043595SMatthias Ringwald                         if (conn == NULL){
444994791381SMatthias Ringwald                             // use placeholder address for peer, will be overwritten in hci_handle_le_connection_complete_event()
445094791381SMatthias Ringwald                             bd_addr_t addr;
445194791381SMatthias Ringwald                             memset(addr, 0, 6);
445294791381SMatthias Ringwald                             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_UNKNOWN, HCI_ROLE_SLAVE);
4453f7043595SMatthias Ringwald                             if (conn != NULL){
4454f7043595SMatthias Ringwald                                 conn->state = ANNOUNCED;
4455f7043595SMatthias Ringwald                                 conn->con_handle = handle;
4456f7043595SMatthias Ringwald                             }
4457f7043595SMatthias Ringwald                         }
4458f7043595SMatthias Ringwald                     }
445989254d99SMatthias Ringwald                     break;
4460a0698cb4SMatthias Ringwald #endif
4461d70217a2SMatthias Ringwald #endif
44625909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
446360fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
446460fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
4465688bcdb4SMatthias Ringwald                     hci_handle_le_connection_complete_event(packet);
44665909f7f2Smatthias.ringwald                     break;
44675909f7f2Smatthias.ringwald 
4468f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4469c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4470c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4471c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
4472c9db5c21SMilanka Ringwald                     if (!conn) break;
4473c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4474c9db5c21SMilanka Ringwald                     break;
447565a46ef3S[email protected] 
447673cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
447773cd8a2aSMatthias Ringwald                     // connection
447873cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
447973cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
448073cd8a2aSMatthias Ringwald                     if (conn) {
448173cd8a2aSMatthias Ringwald                         // read arguments
448273cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
448373cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
448473cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
448573cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
448673cd8a2aSMatthias Ringwald 
448773cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
448873cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
448973cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
449073cd8a2aSMatthias 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);
449173cd8a2aSMatthias Ringwald                         if (update_parameter){
449273cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
449373cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
449473cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
449573cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
449673cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
449773cd8a2aSMatthias Ringwald                         } else {
4498c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
449973cd8a2aSMatthias Ringwald                         }
450073cd8a2aSMatthias Ringwald                     }
450173cd8a2aSMatthias Ringwald                     break;
45020f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
45030f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
45040f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
45050f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
45060f3b27c5SMatthias Ringwald                     if (conn) {
45070f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
45080f3b27c5SMatthias Ringwald                     }
45090f3b27c5SMatthias Ringwald                     break;
45100f3b27c5SMatthias Ringwald #endif
45114ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
45126fd1d2c8SMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_REQUEST:
45136fd1d2c8SMatthias Ringwald                     // incoming CIS request, allocate iso stream object and cache metadata
45146fd1d2c8SMatthias Ringwald                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
45156fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cig_id(packet),
45166fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cis_id(packet));
45176fd1d2c8SMatthias Ringwald                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
45186fd1d2c8SMatthias Ringwald                     if (iso_stream != NULL){
45196fd1d2c8SMatthias Ringwald                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
45206fd1d2c8SMatthias Ringwald                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
45216fd1d2c8SMatthias Ringwald                     }
45226fd1d2c8SMatthias Ringwald                     break;
45234ae8623eSMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
45248e58e4f7SMatthias Ringwald                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
45254ae8623eSMatthias Ringwald                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
45264ae8623eSMatthias Ringwald                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
45278e58e4f7SMatthias Ringwald                         iso_stream = hci_iso_stream_for_con_handle(handle);
45288e58e4f7SMatthias Ringwald                         btstack_assert(iso_stream != NULL);
45297dd97f73SMatthias Ringwald                         // track connection info
45307dd97f73SMatthias Ringwald                         iso_stream->number_of_subevents  = hci_subevent_le_cis_established_get_nse(packet);
45317dd97f73SMatthias Ringwald                         iso_stream->burst_number_c_to_p  = hci_subevent_le_cis_established_get_bn_c_to_p(packet);
45327dd97f73SMatthias Ringwald                         iso_stream->burst_number_p_to_c  = hci_subevent_le_cis_established_get_bn_p_to_c(packet);
45337dd97f73SMatthias Ringwald                         iso_stream->flush_timeout_c_to_p = hci_subevent_le_cis_established_get_ft_c_to_p(packet);
45347dd97f73SMatthias Ringwald                         iso_stream->flush_timeout_p_to_c = hci_subevent_le_cis_established_get_ft_p_to_c(packet);
453526b93350SMatthias Ringwald                         iso_stream->max_sdu_c_to_p       = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
453626b93350SMatthias Ringwald                         iso_stream->max_sdu_p_to_c       = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
45377dd97f73SMatthias Ringwald                         iso_stream->iso_interval_1250us  = hci_subevent_le_cis_established_get_iso_interval(packet);
453826b93350SMatthias Ringwald                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
453926b93350SMatthias Ringwald                             // CIS Accept by Peripheral
454026b93350SMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
454126b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_p_to_c > 0){
454226b93350SMatthias Ringwald                                     // we're peripheral and we will send data
454326b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
454426b93350SMatthias Ringwald                                 } else {
454526b93350SMatthias Ringwald                                     // we're peripheral and we will only receive data
454626b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
454726b93350SMatthias Ringwald                                 }
454826b93350SMatthias Ringwald                             } else {
454914045fdbSMatthias Ringwald                                 hci_cis_handle_created(iso_stream, status);
455026b93350SMatthias Ringwald                             }
455126b93350SMatthias Ringwald                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
455226b93350SMatthias Ringwald                         } else {
455326b93350SMatthias Ringwald                             // CIG Setup by Central
455426b93350SMatthias Ringwald                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
455526b93350SMatthias Ringwald                             btstack_assert(cig != NULL);
455626b93350SMatthias Ringwald                             // update iso stream state
45574ae8623eSMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
45584ae8623eSMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
45594ae8623eSMatthias Ringwald                             } else {
45608e58e4f7SMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
45614ae8623eSMatthias Ringwald                             }
45628e58e4f7SMatthias Ringwald                             // update cig state
4563f06bb90fSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
4564f06bb90fSMatthias Ringwald                                 if (cig->cis_con_handles[i] == handle){
45653abcd16cSMatthias Ringwald                                     cig->cis_setup_active[i] = false;
4566f9306a1aSMatthias Ringwald                                     if (status == ERROR_CODE_SUCCESS){
4567f9306a1aSMatthias Ringwald                                         cig->cis_established[i] = true;
4568f9306a1aSMatthias Ringwald                                     } else {
456914045fdbSMatthias Ringwald                                         hci_cis_handle_created(iso_stream, status);
4570f06bb90fSMatthias Ringwald                                     }
4571f06bb90fSMatthias Ringwald                                 }
4572f06bb90fSMatthias Ringwald                             }
45738e58e4f7SMatthias Ringwald 
45748e58e4f7SMatthias Ringwald                             // trigger iso path setup if complete
45750f0ba168SMatthias Ringwald                             bool cis_setup_active = false;
4576f9306a1aSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
45770f0ba168SMatthias Ringwald                                 cis_setup_active |= cig->cis_setup_active[i];
4578f9306a1aSMatthias Ringwald                             }
45790f0ba168SMatthias Ringwald                             if (cis_setup_active == false){
4580f9306a1aSMatthias Ringwald                                 cig->state_vars.next_cis = 0;
4581f9306a1aSMatthias Ringwald                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
458226b93350SMatthias Ringwald                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
458326b93350SMatthias Ringwald                             }
4584f06bb90fSMatthias Ringwald                         }
45854ae8623eSMatthias Ringwald                     }
45867aa35f6aSMatthias Ringwald                     break;
45877aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
458826b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
45897aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(packet[4]);
45907aa35f6aSMatthias Ringwald                     if (big != NULL){
45917aa35f6aSMatthias Ringwald                         uint8_t status = packet[3];
45927aa35f6aSMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
45937aa35f6aSMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
45945fd415a6SMatthias Ringwald                             uint8_t num_bis = btstack_min(big->num_bis, packet[20]);
4595c30bd0a5SMatthias Ringwald 
45967aa35f6aSMatthias Ringwald                             for (i=0;i<num_bis;i++){
4597fb16346aSMatthias Ringwald                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4598fb16346aSMatthias Ringwald                                 big->bis_con_handles[i] = bis_handle;
4599fb16346aSMatthias Ringwald                                 // assign bis handle
4600fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4601fb16346aSMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
4602c30bd0a5SMatthias Ringwald                                     iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4603fb16346aSMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
46048d72db10SMatthias Ringwald                                         (iso_stream->group_id == big->big_handle)){
4605969d876aSMatthias Ringwald                                         iso_stream->cis_handle = bis_handle;
4606fb16346aSMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4607cd1139aaSMatthias Ringwald                                         break;
4608fb16346aSMatthias Ringwald                                     }
4609fb16346aSMatthias Ringwald                                 }
46107aa35f6aSMatthias Ringwald                             }
46112a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
46127aa35f6aSMatthias Ringwald                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
46137aa35f6aSMatthias Ringwald                                 big->state_vars.next_bis = 0;
46142a6c0f82SMatthias Ringwald                             }
46157aa35f6aSMatthias Ringwald                         } else {
46162a6c0f82SMatthias Ringwald                             // create BIG failed or has been stopped by us
4617d8905293SMatthias Ringwald                             hci_iso_create_big_failed(big, status);
46187aa35f6aSMatthias Ringwald                         }
46197aa35f6aSMatthias Ringwald                     }
46207aa35f6aSMatthias Ringwald                     break;
46217aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4622c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46237aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
46247aa35f6aSMatthias Ringwald                     if (big != NULL){
4625fb16346aSMatthias Ringwald                         // finalize associated ISO streams
4626c30bd0a5SMatthias Ringwald 
4627fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4628fb16346aSMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)){
4629c30bd0a5SMatthias Ringwald                             iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
46308d72db10SMatthias Ringwald                             if (iso_stream->group_id == big->big_handle){
4631969d876aSMatthias Ringwald                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4632fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_remove(&it);
4633fb16346aSMatthias Ringwald                                 btstack_memory_hci_iso_stream_free(iso_stream);
4634fb16346aSMatthias Ringwald                             }
4635fb16346aSMatthias Ringwald                         }
46367aa35f6aSMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
46377aa35f6aSMatthias Ringwald                         switch (big->state){
46387aa35f6aSMatthias Ringwald                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
46397aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, big->state_vars.status);
46407aa35f6aSMatthias Ringwald                                 break;
46417aa35f6aSMatthias Ringwald                             default:
46427aa35f6aSMatthias Ringwald                                 hci_emit_big_terminated(big);
46437aa35f6aSMatthias Ringwald                                 break;
46447aa35f6aSMatthias Ringwald                         }
46457aa35f6aSMatthias Ringwald                     }
46467aa35f6aSMatthias Ringwald                     break;
46472a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4648c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46492a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
46502a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
46512a6c0f82SMatthias Ringwald                         uint8_t status = packet[3];
46522a6c0f82SMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
46532a6c0f82SMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
46545fd415a6SMatthias Ringwald                             uint8_t num_bis = btstack_min(big_sync->num_bis, packet[16]);
46552a6c0f82SMatthias Ringwald                             for (i=0;i<num_bis;i++){
465602e19895SMatthias Ringwald                                 hci_con_handle_t bis_handle = little_endian_read_16(packet, 17 + (2 * i));
465702e19895SMatthias Ringwald                                 big_sync->bis_con_handles[i] = bis_handle;
465802e19895SMatthias Ringwald                                 // setup iso_stream_t
465902e19895SMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
466002e19895SMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
4661c30bd0a5SMatthias Ringwald                                     iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
466202e19895SMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
466302e19895SMatthias Ringwald                                         (iso_stream->group_id == big_sync->big_handle)){
466402e19895SMatthias Ringwald                                         iso_stream->cis_handle = bis_handle;
466502e19895SMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
466602e19895SMatthias Ringwald                                         break;
466702e19895SMatthias Ringwald                                     }
466802e19895SMatthias Ringwald                                 }
46692a6c0f82SMatthias Ringwald                             }
46702a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
46712a6c0f82SMatthias Ringwald                                 // trigger iso path setup
46722a6c0f82SMatthias Ringwald                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
46732a6c0f82SMatthias Ringwald                                 big_sync->state_vars.next_bis = 0;
46742a6c0f82SMatthias Ringwald                             }
46752a6c0f82SMatthias Ringwald                         } else {
46762a6c0f82SMatthias Ringwald                             // create BIG Sync failed or has been stopped by us
4677d8905293SMatthias Ringwald                             hci_iso_big_sync_failed(big_sync, status);
46782a6c0f82SMatthias Ringwald                         }
46792a6c0f82SMatthias Ringwald                     }
46802a6c0f82SMatthias Ringwald                     break;
46812a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4682c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
46832a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
46842a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
4685d04a9afcSMatthias Ringwald                         uint8_t big_handle = packet[4];
46862a6c0f82SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4687d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
46882a6c0f82SMatthias Ringwald                     }
46892a6c0f82SMatthias Ringwald                     break;
46904ae8623eSMatthias Ringwald #endif
46915909f7f2Smatthias.ringwald                 default:
46925909f7f2Smatthias.ringwald                     break;
46935909f7f2Smatthias.ringwald             }
46945909f7f2Smatthias.ringwald             break;
46955909f7f2Smatthias.ringwald #endif
46960b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
46970b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
46980b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
46990b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
47000b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
47010b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
47020b36101dSMatthias Ringwald                     break;
47030b36101dSMatthias Ringwald                 default:
47040b36101dSMatthias Ringwald                     break;
47050b36101dSMatthias Ringwald             }
47060b36101dSMatthias Ringwald             break;
47076772a24cSmatthias.ringwald         default:
47086772a24cSmatthias.ringwald             break;
4709fe1ed1b8Smatthias.ringwald     }
4710fe1ed1b8Smatthias.ringwald 
471167c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
471289db417bSmatthias.ringwald 
471386805605S[email protected]     // notify upper stack
4714d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
471594ab26f8Smatthias.ringwald 
471686805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4717797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4718f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
471905ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4720046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
4721797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
472205ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
4723b0136355SMatthias Ringwald 		}
47248ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
47258ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
47268ad9cf99SMatthias Ringwald #endif
472786805605S[email protected]     }
472886805605S[email protected] 
472994ab26f8Smatthias.ringwald 	// execute main loop
473094ab26f8Smatthias.ringwald 	hci_run();
473116833f0aSmatthias.ringwald }
473216833f0aSmatthias.ringwald 
473335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
47346f28d2eeSMatthias Ringwald 
4735c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
47360b3f95dfSMatthias Ringwald     // lookup connection struct
47372b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
47382b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
47390b3f95dfSMatthias Ringwald     if (!conn) return;
47400b3f95dfSMatthias Ringwald 
47416be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
4742760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4743760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4744a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4745760b20efSMatthias Ringwald             packet[2] = 0x3c;
4746760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
4747760b20efSMatthias Ringwald             size = 63;
47480b3f95dfSMatthias Ringwald         }
47490b3f95dfSMatthias Ringwald     }
4750760b20efSMatthias Ringwald 
4751f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
4752f234b250SMatthias Ringwald         // Nothing to do
4753f234b250SMatthias Ringwald     } else {
475449205f5dSMatthias 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);
4755760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
4756fa7f2dfdSMatthias Ringwald             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4757b1202089SMatthias 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);
4758fa7f2dfdSMatthias Ringwald             if (conn->sco_tx_active == 0){
4759fa7f2dfdSMatthias Ringwald                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4760fa7f2dfdSMatthias Ringwald                     conn->sco_tx_active = 1;
4761fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready = max_sco_packets;
4762fa7f2dfdSMatthias Ringwald                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4763fa7f2dfdSMatthias Ringwald                     hci_notify_if_sco_can_send_now();
476459c33575SMatthias Ringwald                 }
476559c33575SMatthias Ringwald             } else {
4766fa7f2dfdSMatthias Ringwald                 if (conn->sco_tx_ready < max_sco_packets){
4767fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready++;
476859c33575SMatthias Ringwald                 }
4769fa7f2dfdSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
47706f28d2eeSMatthias Ringwald             }
4771760b20efSMatthias Ringwald         }
4772f234b250SMatthias Ringwald     }
47736be3cf7fSMatthias Ringwald #endif
47746be3cf7fSMatthias Ringwald 
47750b3f95dfSMatthias Ringwald     // deliver to app
47760b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
47770b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
47780b3f95dfSMatthias Ringwald     }
47790b3f95dfSMatthias Ringwald 
4780ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4781ed325439SMatthias Ringwald     // We can send one packet for each received packet
4782ed325439SMatthias Ringwald     conn->sco_tx_ready++;
4783ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
4784ed325439SMatthias Ringwald #endif
4785ed325439SMatthias Ringwald 
47860b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
47872b838201SMatthias Ringwald     conn->num_packets_completed++;
47882b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
47892b838201SMatthias Ringwald     hci_run();
47902b838201SMatthias Ringwald #endif
4791c91d150bS[email protected] }
479235454696SMatthias Ringwald #endif
4793c91d150bS[email protected] 
47940a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
47954248f37eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
47964248f37eSMatthias Ringwald     // propagate ISO packets received as ACL
4797062276f9SMatthias Ringwald     hci_iso_stream_t * iso_stream = NULL;
47984248f37eSMatthias Ringwald     if ((packet_type == HCI_ACL_DATA_PACKET) && (size >= HCI_ACL_HEADER_SIZE)){
47994248f37eSMatthias Ringwald         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
48004248f37eSMatthias Ringwald         iso_stream = hci_iso_stream_for_con_handle(con_handle);
48014248f37eSMatthias Ringwald         if (iso_stream != NULL){
48024248f37eSMatthias Ringwald             packet_type = HCI_ISO_DATA_PACKET;
48034248f37eSMatthias Ringwald         }
48044248f37eSMatthias Ringwald     }
48054248f37eSMatthias Ringwald #endif
48064248f37eSMatthias Ringwald 
4807b09f7410SMatthias Ringwald     // don't log internal events unless requested
4808b09f7410SMatthias Ringwald     bool internal_event = (packet_type == HCI_EVENT_PACKET) && (hci_event_packet_get_type(packet) >= BTSTACK_EVENT_FIRST);
4809b09f7410SMatthias Ringwald     bool log_packet = internal_event == false;
4810b09f7410SMatthias Ringwald #ifdef ENABLE_LOG_BTSTACK_EVENTS
4811b09f7410SMatthias Ringwald     log_packet = true;
4812b09f7410SMatthias Ringwald #endif
4813b09f7410SMatthias Ringwald     if (log_packet){
48145bb5bc3eS[email protected]         hci_dump_packet(packet_type, 1, packet, size);
4815b09f7410SMatthias Ringwald     }
4816b09f7410SMatthias Ringwald 
481710e830c9Smatthias.ringwald     switch (packet_type) {
481810e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
481910e830c9Smatthias.ringwald             event_handler(packet, size);
482010e830c9Smatthias.ringwald             break;
482110e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
482210e830c9Smatthias.ringwald             acl_handler(packet, size);
482310e830c9Smatthias.ringwald             break;
482435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4825c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
4826c91d150bS[email protected]             sco_handler(packet, size);
4827202c8a4cSMatthias Ringwald             break;
482835454696SMatthias Ringwald #endif
48290a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
48305027c498SMatthias Ringwald         case HCI_ISO_DATA_PACKET:
4831750818acSMatthias Ringwald             if ((iso_stream == NULL) && (size >= HCI_ISO_HEADER_SIZE)){
4832750818acSMatthias Ringwald                 hci_con_handle_t con_handle = READ_ISO_CONNECTION_HANDLE(packet);
4833750818acSMatthias Ringwald                 iso_stream = hci_iso_stream_for_con_handle(con_handle);
4834750818acSMatthias Ringwald             }
4835750818acSMatthias Ringwald             hci_iso_packet_handler(iso_stream, packet, size);
48365027c498SMatthias Ringwald             break;
48375027c498SMatthias Ringwald #endif
483810e830c9Smatthias.ringwald         default:
483910e830c9Smatthias.ringwald             break;
484010e830c9Smatthias.ringwald     }
484110e830c9Smatthias.ringwald }
484210e830c9Smatthias.ringwald 
4843d6b06661SMatthias Ringwald /**
4844d6b06661SMatthias Ringwald  * @brief Add event packet handler.
4845d6b06661SMatthias Ringwald  */
4846d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4847d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4848d6b06661SMatthias Ringwald }
4849d6b06661SMatthias Ringwald 
485067f708e0SMatthias Ringwald /**
485167f708e0SMatthias Ringwald  * @brief Remove event packet handler.
485267f708e0SMatthias Ringwald  */
485367f708e0SMatthias Ringwald void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
485467f708e0SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
485567f708e0SMatthias Ringwald }
4856d6b06661SMatthias Ringwald 
4857fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
48583d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4859fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
486016833f0aSmatthias.ringwald }
486116833f0aSmatthias.ringwald 
486235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
48638abbe8b5SMatthias Ringwald /**
48648abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
48658abbe8b5SMatthias Ringwald  */
48663d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
48678abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
48688abbe8b5SMatthias Ringwald }
486935454696SMatthias Ringwald #endif
48708abbe8b5SMatthias Ringwald 
48710a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
48725027c498SMatthias Ringwald void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
48735027c498SMatthias Ringwald     hci_stack->iso_packet_handler = handler;
48745027c498SMatthias Ringwald }
48755027c498SMatthias Ringwald #endif
48765027c498SMatthias Ringwald 
487771de195eSMatthias Ringwald static void hci_state_reset(void){
4878595bdbfbS[email protected]     // no connections yet
4879595bdbfbS[email protected]     hci_stack->connections = NULL;
488074308b23Smatthias.ringwald 
488174308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
488274308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
488374308b23Smatthias.ringwald     // hci_stack->connectable = 0;
488474308b23Smatthias.ringwald     // hci_stack->bondable = 1;
4885b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
4886595bdbfbS[email protected] 
488744935e40S[email protected]     // buffer is free
488802c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
488944935e40S[email protected] 
4890595bdbfbS[email protected]     // no pending cmds
4891595bdbfbS[email protected]     hci_stack->decline_reason = 0;
4892595bdbfbS[email protected] 
4893c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
4894c214d65bSMatthias Ringwald 
4895bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
4896496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
489732a12730SMatthias Ringwald 
4898baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic =
489959d59ecfSMatthias Ringwald             GAP_TASK_SET_DEFAULT_LINK_POLICY |
490059d59ecfSMatthias Ringwald             GAP_TASK_SET_CLASS_OF_DEVICE |
490159d59ecfSMatthias Ringwald             GAP_TASK_SET_LOCAL_NAME |
4902bc2dcc03SMatthias Ringwald             GAP_TASK_SET_EIR_DATA |
490332a12730SMatthias Ringwald             GAP_TASK_WRITE_SCAN_ENABLE |
490432a12730SMatthias Ringwald             GAP_TASK_WRITE_PAGE_TIMEOUT;
4905bea424a5SMatthias Ringwald #endif
4906bea424a5SMatthias Ringwald 
4907cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
49088d5f0979SMatthias Ringwald     hci_stack->classic_read_local_oob_data = false;
49091ae74bf3SMatthias Ringwald     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4910cf01e888SMatthias Ringwald #endif
4911cf01e888SMatthias Ringwald 
4912595bdbfbS[email protected]     // LE
4913b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
4914b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
4915b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
4916d70217a2SMatthias Ringwald #endif
4917d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4918a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
491973799937SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
4920b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4921d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4922e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
49234bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
49244bafedd5SMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
49254bafedd5SMatthias Ringwald #endif
4926d70217a2SMatthias Ringwald #endif
4927a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4928935aa76eSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
49296bf435a6SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4930a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4931a61834b6SMatthias Ringwald     }
4932a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
4933a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4934a61834b6SMatthias Ringwald     }
4935a61834b6SMatthias Ringwald #endif
4936d320e123SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4937d320e123SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4938d320e123SMatthias Ringwald #endif
493940f86dfdSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
494026b93350SMatthias Ringwald     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4941d75a6bbfSMatthias Ringwald     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
494240f86dfdSMatthias Ringwald #endif
494391036612SMatthias Ringwald #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
4944f48a5586SMatthias Ringwald     hci_stack->hci_command_con_handle = HCI_CON_HANDLE_INVALID;
4945f48a5586SMatthias Ringwald #endif
4946595bdbfbS[email protected] }
4947595bdbfbS[email protected] 
494835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
49492d5e09d6SMatthias Ringwald /**
49502d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
49512d5e09d6SMatthias Ringwald  */
49522d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
49532d5e09d6SMatthias Ringwald     // store and open remote device db
49542d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
49552d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
49562d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
49572d5e09d6SMatthias Ringwald     }
49582d5e09d6SMatthias Ringwald }
495935454696SMatthias Ringwald #endif
49602d5e09d6SMatthias Ringwald 
49612d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
4962475c8125Smatthias.ringwald 
49633a9fb326S[email protected] #ifdef HAVE_MALLOC
49643a9fb326S[email protected]     if (!hci_stack) {
49653a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
49663a9fb326S[email protected]     }
4967b1202089SMatthias Ringwald     btstack_assert(hci_stack != NULL);
49683a9fb326S[email protected] #else
49693a9fb326S[email protected]     hci_stack = &hci_stack_static;
49703a9fb326S[email protected] #endif
497166fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
49723a9fb326S[email protected] 
4973475c8125Smatthias.ringwald     // reference to use transport layer implementation
49743a9fb326S[email protected]     hci_stack->hci_transport = transport;
4975475c8125Smatthias.ringwald 
497611e23e5fSmatthias.ringwald     // reference to used config
49773a9fb326S[email protected]     hci_stack->config = config;
497811e23e5fSmatthias.ringwald 
497926a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
498026a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
498126a9b6daSMatthias Ringwald 
49828fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
49833a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
49848fcba05dSmatthias.ringwald 
498516833f0aSmatthias.ringwald     // register packet handlers with transport
498610e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
4987f5454fc6Smatthias.ringwald 
49883a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
4989e2386ba1S[email protected] 
4990e2386ba1S[email protected]     // class of device
49913a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
4992a45d6b9fS[email protected] 
4993f20168b8Smatthias.ringwald     // bondable by default
4994f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
4995f20168b8Smatthias.ringwald 
4996e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
499763168530SMatthias Ringwald     // classic name
499863168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
4999c4c88f1bSJakob Krantz 
5000c4c88f1bSJakob Krantz     // Master slave policy
5001c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
5002170fafaeSMatthias Ringwald 
5003b4eb4420SMatthias Ringwald     // Allow Role Switch
5004b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
5005b4eb4420SMatthias Ringwald 
500678315a58SMatthias Ringwald     // Default / minimum security level = 2
500778315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
500878315a58SMatthias Ringwald 
50095dbec6b3SMatthias Ringwald     // Default Security Mode 4
50105dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
50115dbec6b3SMatthias Ringwald 
5012cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
5013cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
5014d821984bSMatthias Ringwald 
5015d821984bSMatthias Ringwald     // Link Supervision Timeout
5016d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
5017d821984bSMatthias Ringwald 
5018c874aa46SMatthias Ringwald     // Page Timeout
5019c874aa46SMatthias Ringwald     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
5020c874aa46SMatthias Ringwald 
5021a086dc35SMatthias Ringwald     // All ACL packet types are enabled
5022028ead5eSMatthias Ringwald     hci_stack->enabled_packet_types_acl = ACL_PACKET_TYPES_ALL;
5023e9f343c8SMatthias Ringwald #endif
502463168530SMatthias Ringwald 
502563048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
50263a9fb326S[email protected]     hci_stack->ssp_enable = 1;
50273a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
50283a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
50293a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
503069a97523S[email protected] 
50315d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
50325d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
50335d23aae8SMatthias Ringwald 
5034fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
5035fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
5036d950d659SMatthias Ringwald 
50370c2c5f79SMatthias Ringwald #ifdef ENABLE_BLE
5038cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
5039cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
5040831711daSMatthias Ringwald     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
5041831711daSMatthias Ringwald     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
5042831711daSMatthias Ringwald     hci_stack->le_connection_latency       =      4;    //    4
5043831711daSMatthias Ringwald     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
504424d14ae3SMatthias Ringwald     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
504524d14ae3SMatthias Ringwald     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
50460c2c5f79SMatthias Ringwald #endif
50470c2c5f79SMatthias Ringwald 
50480c2c5f79SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
50497eb5b27eSMatthias Ringwald     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
50507261e5d8SMatthias Ringwald 
50517261e5d8SMatthias Ringwald     // default LE Scanning
50527eb5b27eSMatthias Ringwald     hci_stack->le_scan_type     =  0x01; // active
50538b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
50548b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
50557eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
5056831711daSMatthias Ringwald #endif
5057831711daSMatthias Ringwald 
50582b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
50592b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
5060ee605458SMatthias Ringwald 
5061ee605458SMatthias Ringwald     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
5062ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_min =                         0x0800;
5063ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_max =                         0x0800;
5064ee605458SMatthias Ringwald     hci_stack->le_advertisements_type =                                      0;
5065ee605458SMatthias Ringwald     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
5066ee605458SMatthias Ringwald     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
5067ee605458SMatthias Ringwald     hci_stack->le_advertisements_channel_map =                            0x07;
5068ee605458SMatthias Ringwald     hci_stack->le_advertisements_filter_policy =                             0;
50692b6ab3e6SMatthias Ringwald #endif
50702b6ab3e6SMatthias Ringwald 
5071831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
5072831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
5073831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
5074831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
5075831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
5076831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
5077831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
5078831711daSMatthias Ringwald 
507901d4f05fSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
508001d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = 1;
508101d4f05fSMatthias Ringwald #endif
508201d4f05fSMatthias Ringwald 
5083c3d19a30SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
5084c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
5085c3d19a30SMatthias Ringwald #endif
5086c3d19a30SMatthias Ringwald 
5087595bdbfbS[email protected]     hci_state_reset();
5088475c8125Smatthias.ringwald }
5089475c8125Smatthias.ringwald 
50904688f216SMatthias Ringwald void hci_deinit(void){
5091b02cfc15SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
50924688f216SMatthias Ringwald #ifdef HAVE_MALLOC
50934688f216SMatthias Ringwald     if (hci_stack) {
50944688f216SMatthias Ringwald         free(hci_stack);
50954688f216SMatthias Ringwald     }
50964688f216SMatthias Ringwald #endif
50974688f216SMatthias Ringwald     hci_stack = NULL;
5098b5bbcbf4SMatthias Ringwald 
5099b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
51004688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
5101b5bbcbf4SMatthias Ringwald #endif
51024688f216SMatthias Ringwald }
51034688f216SMatthias Ringwald 
51043fb36a29SMatthias Ringwald /**
51053fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
51063fb36a29SMatthias Ringwald  */
51073fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
51083fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
51093fb36a29SMatthias Ringwald 
51103fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
51113fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
51123fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
51133fb36a29SMatthias Ringwald     }
51143fb36a29SMatthias Ringwald }
51153fb36a29SMatthias Ringwald 
51166fe16221SMatthias Ringwald void hci_enable_custom_pre_init(void){
51176fe16221SMatthias Ringwald     hci_stack->chipset_pre_init = true;
51186fe16221SMatthias Ringwald }
51196fe16221SMatthias Ringwald 
5120fb55bd0aSMatthias Ringwald /**
5121d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
5122fb55bd0aSMatthias Ringwald  */
5123fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
5124fb55bd0aSMatthias Ringwald     // references to used control implementation
5125fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
5126d0b87befSMatthias Ringwald     // init with transport config
5127d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
5128fb55bd0aSMatthias Ringwald }
5129fb55bd0aSMatthias Ringwald 
51301f9eb2ccSMatthias Ringwald static void hci_discard_connections(void){
5131346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_t it;
5132346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5133346f8c2cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5134a086dc35SMatthias Ringwald         // cancel all l2cap connections by emitting disconnection complete before shutdown (free) connection
5135346f8c2cSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
51361f9eb2ccSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
51371f9eb2ccSMatthias Ringwald         hci_shutdown_connection(connection);
51381f9eb2ccSMatthias Ringwald     }
5139346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5140346f8c2cSMatthias Ringwald     while (hci_stack->iso_streams != NULL){
5141346f8c2cSMatthias Ringwald         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
5142346f8c2cSMatthias Ringwald     }
5143346f8c2cSMatthias Ringwald #endif
51441f9eb2ccSMatthias Ringwald }
51451f9eb2ccSMatthias Ringwald 
514671de195eSMatthias Ringwald void hci_close(void){
5147e6d6524dSMatthias Ringwald 
5148e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
5149404843c1Smatthias.ringwald     // close remote device db
5150a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
5151a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
5152404843c1Smatthias.ringwald     }
5153e6d6524dSMatthias Ringwald #endif
51547224be7eSMatthias Ringwald 
51551f9eb2ccSMatthias Ringwald     hci_discard_connections();
51567224be7eSMatthias Ringwald 
5157f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
51583a9fb326S[email protected] 
51593a9fb326S[email protected] #ifdef HAVE_MALLOC
51603a9fb326S[email protected]     free(hci_stack);
51613a9fb326S[email protected] #endif
51623a9fb326S[email protected]     hci_stack = NULL;
5163404843c1Smatthias.ringwald }
5164404843c1Smatthias.ringwald 
5165cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
5166cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
5167cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
5168cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
5169cb70c5abSMatthias Ringwald }
5170cb70c5abSMatthias Ringwald #endif
5171cb70c5abSMatthias Ringwald 
517235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5173170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
5174a086dc35SMatthias Ringwald     // validate range and set
5175170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
5176170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
5177170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
5178170fafaeSMatthias Ringwald }
517978315a58SMatthias Ringwald 
5180137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
5181137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
51825dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
5183137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
5184137715ebSMatthias Ringwald     } else {
5185137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
5186137715ebSMatthias Ringwald     }
51875dbec6b3SMatthias Ringwald }
51885dbec6b3SMatthias Ringwald 
51895dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
51905dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
51915dbec6b3SMatthias Ringwald }
51925dbec6b3SMatthias Ringwald 
519378315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
519478315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
519578315a58SMatthias Ringwald }
519678315a58SMatthias Ringwald 
519778315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
5198d7387af3SMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
5199d7387af3SMatthias Ringwald         return LEVEL_4;
5200d7387af3SMatthias Ringwald     }
520178315a58SMatthias Ringwald     return hci_stack->gap_security_level;
520278315a58SMatthias Ringwald }
520330cdf3c6SMatthias Ringwald 
52048ad4dfffSMatthias Ringwald void gap_set_minimal_service_security_level(gap_security_level_t security_level){
52058ad4dfffSMatthias Ringwald     hci_stack->gap_minimal_service_security_level = security_level;
52068ad4dfffSMatthias Ringwald }
52078ad4dfffSMatthias Ringwald 
520830cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
520930cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
521030cdf3c6SMatthias Ringwald }
521130cdf3c6SMatthias Ringwald 
521230cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
521330cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
521430cdf3c6SMatthias Ringwald }
5215170fafaeSMatthias Ringwald #endif
5216170fafaeSMatthias Ringwald 
5217170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
521860b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
52199e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
5220baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
522159d59ecfSMatthias Ringwald     hci_run();
52229e61646fS[email protected] }
522376f27cffSMatthias Ringwald 
5224c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
5225c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
5226baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
522759d59ecfSMatthias Ringwald     hci_run();
5228c33e56d3SMatthias Ringwald }
5229c33e56d3SMatthias Ringwald 
5230b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
5231b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
5232b4eb4420SMatthias Ringwald }
5233b4eb4420SMatthias Ringwald 
5234b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
5235b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
5236b4eb4420SMatthias Ringwald }
5237b4eb4420SMatthias Ringwald 
52380c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
52390c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
52400c3eb48dSMatthias Ringwald }
52410c3eb48dSMatthias Ringwald 
52429afaa4d4SMatthias Ringwald void gap_enable_link_watchdog(uint16_t timeout_ms){
52439afaa4d4SMatthias Ringwald     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
52449afaa4d4SMatthias Ringwald }
52459afaa4d4SMatthias Ringwald 
52469afaa4d4SMatthias Ringwald uint16_t hci_automatic_flush_timeout(void){
52479afaa4d4SMatthias Ringwald     return hci_stack->automatic_flush_timeout;
52489afaa4d4SMatthias Ringwald }
52499afaa4d4SMatthias Ringwald 
525076f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
525176f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
525276f27cffSMatthias Ringwald }
525335454696SMatthias Ringwald #endif
52549e61646fS[email protected] 
52556fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
5256f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
5257f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
52586535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
5259f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
5260f456b2d0S[email protected] }
526176f27cffSMatthias Ringwald #endif
5262f456b2d0S[email protected] 
52638d213e1aSmatthias.ringwald // State-Module-Driver overview
52648d213e1aSmatthias.ringwald // state                    module  low-level
52658d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
52668d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
52678d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
52688d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
5269d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
5270d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
5271c7e0c5f6Smatthias.ringwald 
527240d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
52737301ad89Smatthias.ringwald 
5274038bc64cSmatthias.ringwald     // power on
5275f9a30166Smatthias.ringwald     int err = 0;
52763a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
5277d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
5278f9a30166Smatthias.ringwald     }
5279038bc64cSmatthias.ringwald     if (err){
52809da54300S[email protected]         log_error( "POWER_ON failed");
5281038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
5282038bc64cSmatthias.ringwald         return err;
5283038bc64cSmatthias.ringwald     }
5284038bc64cSmatthias.ringwald 
528524b3c629SMatthias Ringwald     // int chipset driver
52863fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
52873fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
52883fb36a29SMatthias Ringwald     }
52893fb36a29SMatthias Ringwald 
529024b3c629SMatthias Ringwald     // init transport
529124b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
529224b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
529324b3c629SMatthias Ringwald     }
529424b3c629SMatthias Ringwald 
529524b3c629SMatthias Ringwald     // open transport
529624b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
5297038bc64cSmatthias.ringwald     if (err){
52989da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
52993a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5300d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5301f9a30166Smatthias.ringwald         }
5302038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
5303038bc64cSmatthias.ringwald         return err;
5304038bc64cSmatthias.ringwald     }
53058d213e1aSmatthias.ringwald     return 0;
53068d213e1aSmatthias.ringwald }
5307038bc64cSmatthias.ringwald 
530840d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
53098d213e1aSmatthias.ringwald 
53109da54300S[email protected]     log_info("hci_power_control_off");
53119418f9c9Smatthias.ringwald 
53128d213e1aSmatthias.ringwald     // close low-level device
531324b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
53148d213e1aSmatthias.ringwald 
53159da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
53169418f9c9Smatthias.ringwald 
53178d213e1aSmatthias.ringwald     // power off
53183a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
5319d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
53208d213e1aSmatthias.ringwald     }
53219418f9c9Smatthias.ringwald 
53229da54300S[email protected]     log_info("hci_power_control_off - control closed");
53239418f9c9Smatthias.ringwald 
53243a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
532572ea5239Smatthias.ringwald }
532672ea5239Smatthias.ringwald 
532740d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
532872ea5239Smatthias.ringwald 
53299da54300S[email protected]     log_info("hci_power_control_sleep");
53303144bce4Smatthias.ringwald 
5331b429b9b7Smatthias.ringwald #if 0
5332b429b9b7Smatthias.ringwald     // don't close serial port during sleep
5333b429b9b7Smatthias.ringwald 
533472ea5239Smatthias.ringwald     // close low-level device
53353a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
5336b429b9b7Smatthias.ringwald #endif
533772ea5239Smatthias.ringwald 
533872ea5239Smatthias.ringwald     // sleep mode
53393a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
5340d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
534172ea5239Smatthias.ringwald     }
5342b429b9b7Smatthias.ringwald 
53433a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
53448d213e1aSmatthias.ringwald }
53458d213e1aSmatthias.ringwald 
534640d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
5347b429b9b7Smatthias.ringwald 
53489da54300S[email protected]     log_info("hci_power_control_wake");
5349b429b9b7Smatthias.ringwald 
5350b429b9b7Smatthias.ringwald     // wake on
53513a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
5352d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
5353b429b9b7Smatthias.ringwald     }
5354b429b9b7Smatthias.ringwald 
5355b429b9b7Smatthias.ringwald #if 0
5356b429b9b7Smatthias.ringwald     // open low-level device
53573a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
5358b429b9b7Smatthias.ringwald     if (err){
53599da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
53603a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5361d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5362b429b9b7Smatthias.ringwald         }
5363b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
5364b429b9b7Smatthias.ringwald         return err;
5365b429b9b7Smatthias.ringwald     }
5366b429b9b7Smatthias.ringwald #endif
5367b429b9b7Smatthias.ringwald 
5368b429b9b7Smatthias.ringwald     return 0;
5369b429b9b7Smatthias.ringwald }
5370b429b9b7Smatthias.ringwald 
53710c88d5efSMatthias Ringwald static void hci_power_enter_initializing_state(void){
537244935e40S[email protected]     // set up state machine
537344935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
537402c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
537544935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
53766fe16221SMatthias Ringwald 
53770535e08cSMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
53786fe16221SMatthias Ringwald     if (hci_stack->chipset_pre_init) {
53796fe16221SMatthias Ringwald         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
53800535e08cSMatthias Ringwald     } else
53810535e08cSMatthias Ringwald #endif
53820535e08cSMatthias Ringwald     {
53835c363727SMatthias Ringwald         hci_stack->substate = HCI_INIT_SEND_RESET;
538444935e40S[email protected]     }
53856fe16221SMatthias Ringwald }
5386b429b9b7Smatthias.ringwald 
53870c88d5efSMatthias Ringwald static void hci_power_enter_halting_state(void){
53880c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
53891e907691SMatthias Ringwald     // drop entries scheduled for removal, mark others for re-adding
53901e907691SMatthias Ringwald     btstack_linked_list_iterator_t it;
53911e907691SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
53921e907691SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
53931e907691SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
53941e907691SMatthias Ringwald         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
53951e907691SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
53961e907691SMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
53971e907691SMatthias Ringwald         } else {
53981e907691SMatthias Ringwald             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
53991e907691SMatthias Ringwald         }
54001e907691SMatthias Ringwald     }
54014718c38dSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5402a2c9d908SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5403e8d160b3SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5404e8d160b3SMatthias Ringwald     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5405e8d160b3SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5406e8d160b3SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5407e8d160b3SMatthias Ringwald         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5408e8d160b3SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
5409e8d160b3SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
5410e8d160b3SMatthias Ringwald         } else {
5411e8d160b3SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5412e8d160b3SMatthias Ringwald             continue;
5413e8d160b3SMatthias Ringwald         }
5414e8d160b3SMatthias Ringwald     }
5415a2c9d908SMatthias Ringwald #endif
54160c88d5efSMatthias Ringwald #endif
54174718c38dSMatthias Ringwald #endif
5418184dbe2fSMatthias Ringwald     // see hci_run
5419184dbe2fSMatthias Ringwald     hci_stack->state = HCI_STATE_HALTING;
54200c88d5efSMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5421184dbe2fSMatthias Ringwald     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5422184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5423184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5424184dbe2fSMatthias Ringwald     btstack_run_loop_add_timer(&hci_stack->timeout);
5425184dbe2fSMatthias Ringwald }
5426184dbe2fSMatthias Ringwald 
542742bd3d77SMatthias Ringwald // returns error
542842bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
542942bd3d77SMatthias Ringwald     int err;
54308d213e1aSmatthias.ringwald     switch (power_mode){
54318d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54328d213e1aSmatthias.ringwald             err = hci_power_control_on();
543342bd3d77SMatthias Ringwald             if (err != 0) {
5434f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
543597b61c7bS[email protected]                 return err;
543697b61c7bS[email protected]             }
54370c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
54388d213e1aSmatthias.ringwald             break;
54398d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54408d213e1aSmatthias.ringwald             // do nothing
54418d213e1aSmatthias.ringwald             break;
54428d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5443b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
54448d213e1aSmatthias.ringwald             break;
54457bbeb3adSMilanka Ringwald         default:
54467bbeb3adSMilanka Ringwald             btstack_assert(false);
54477bbeb3adSMilanka Ringwald             break;
54488d213e1aSmatthias.ringwald     }
544942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
545042bd3d77SMatthias Ringwald }
54517301ad89Smatthias.ringwald 
545242bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
54538d213e1aSmatthias.ringwald     switch (power_mode){
54548d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54558d213e1aSmatthias.ringwald             // do nothing
54568d213e1aSmatthias.ringwald             break;
54578d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54588d213e1aSmatthias.ringwald             // no connections yet, just turn it off
54598d213e1aSmatthias.ringwald             hci_power_control_off();
54608d213e1aSmatthias.ringwald             break;
54618d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5462b546ac54Smatthias.ringwald             // no connections yet, just turn it off
546372ea5239Smatthias.ringwald             hci_power_control_sleep();
54648d213e1aSmatthias.ringwald             break;
54657bbeb3adSMilanka Ringwald         default:
54667bbeb3adSMilanka Ringwald             btstack_assert(false);
54677bbeb3adSMilanka Ringwald             break;
54688d213e1aSmatthias.ringwald     }
546942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
547042bd3d77SMatthias Ringwald }
54717301ad89Smatthias.ringwald 
547242bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
54738d213e1aSmatthias.ringwald     switch (power_mode){
54748d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54758d213e1aSmatthias.ringwald             // do nothing
54768d213e1aSmatthias.ringwald             break;
54778d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54780c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
54798d213e1aSmatthias.ringwald             break;
54808d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5481b546ac54Smatthias.ringwald             // see hci_run
54823a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
548374b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
54848d213e1aSmatthias.ringwald             break;
54857bbeb3adSMilanka Ringwald         default:
54867bbeb3adSMilanka Ringwald             btstack_assert(false);
54877bbeb3adSMilanka Ringwald             break;
54888d213e1aSmatthias.ringwald     }
548942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
549042bd3d77SMatthias Ringwald }
54917301ad89Smatthias.ringwald 
549242bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
54938d213e1aSmatthias.ringwald     switch (power_mode){
54948d213e1aSmatthias.ringwald         case HCI_POWER_ON:
54950c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
54968d213e1aSmatthias.ringwald             break;
54978d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
54988d213e1aSmatthias.ringwald             // do nothing
54998d213e1aSmatthias.ringwald             break;
55008d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5501b546ac54Smatthias.ringwald             // see hci_run
55023a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
550374b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
55048d213e1aSmatthias.ringwald             break;
55057bbeb3adSMilanka Ringwald         default:
55067bbeb3adSMilanka Ringwald             btstack_assert(false);
55077bbeb3adSMilanka Ringwald             break;
55088d213e1aSmatthias.ringwald     }
550900278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
551042bd3d77SMatthias Ringwald }
55118d213e1aSmatthias.ringwald 
551242bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
55138d213e1aSmatthias.ringwald     switch (power_mode){
55148d213e1aSmatthias.ringwald         case HCI_POWER_ON:
55150c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
55168d213e1aSmatthias.ringwald             break;
55178d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
55180c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
55198d213e1aSmatthias.ringwald             break;
55208d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5521b546ac54Smatthias.ringwald             // do nothing
55228d213e1aSmatthias.ringwald             break;
55237bbeb3adSMilanka Ringwald         default:
55247bbeb3adSMilanka Ringwald             btstack_assert(false);
55257bbeb3adSMilanka Ringwald             break;
55268d213e1aSmatthias.ringwald     }
552742bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
552842bd3d77SMatthias Ringwald }
55298d213e1aSmatthias.ringwald 
553042bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
553142bd3d77SMatthias Ringwald     int err;
55328d213e1aSmatthias.ringwald     switch (power_mode){
55338d213e1aSmatthias.ringwald         case HCI_POWER_ON:
55343144bce4Smatthias.ringwald             err = hci_power_control_wake();
55353144bce4Smatthias.ringwald             if (err) return err;
55360c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
55378d213e1aSmatthias.ringwald             break;
55388d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
55390c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
55408d213e1aSmatthias.ringwald             break;
55418d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5542b546ac54Smatthias.ringwald             // do nothing
55438d213e1aSmatthias.ringwald             break;
55447bbeb3adSMilanka Ringwald         default:
55457bbeb3adSMilanka Ringwald             btstack_assert(false);
55467bbeb3adSMilanka Ringwald             break;
55478d213e1aSmatthias.ringwald     }
554842bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
554942bd3d77SMatthias Ringwald }
55507bbeb3adSMilanka Ringwald 
555142bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
555242bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5553bef627f1SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
555424f87726SMatthias Ringwald     int err = 0;
555542bd3d77SMatthias Ringwald     switch (hci_stack->state){
555642bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
555742bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
555842bd3d77SMatthias Ringwald             break;
555942bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
556042bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
556142bd3d77SMatthias Ringwald             break;
556242bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
556342bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
556442bd3d77SMatthias Ringwald             break;
556542bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
556642bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
556742bd3d77SMatthias Ringwald             break;
556842bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
556942bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
557042bd3d77SMatthias Ringwald             break;
557142bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
557242bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
557342bd3d77SMatthias Ringwald             break;
55747bbeb3adSMilanka Ringwald         default:
55757bbeb3adSMilanka Ringwald             btstack_assert(false);
55767bbeb3adSMilanka Ringwald             break;
557711e23e5fSmatthias.ringwald     }
557824f87726SMatthias Ringwald     if (err != 0){
557942bd3d77SMatthias Ringwald         return err;
558042bd3d77SMatthias Ringwald     }
558168d92d03Smatthias.ringwald 
5582038bc64cSmatthias.ringwald     // create internal event
5583ee8bf225Smatthias.ringwald 	hci_emit_state();
5584ee8bf225Smatthias.ringwald 
558568d92d03Smatthias.ringwald 	// trigger next/first action
558668d92d03Smatthias.ringwald 	hci_run();
558768d92d03Smatthias.ringwald 
5588475c8125Smatthias.ringwald     return 0;
5589475c8125Smatthias.ringwald }
5590475c8125Smatthias.ringwald 
559135454696SMatthias Ringwald 
5592091e35e3SMatthias Ringwald static void hci_halting_run(void) {
5593091e35e3SMatthias Ringwald 
5594091e35e3SMatthias Ringwald     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5595091e35e3SMatthias Ringwald 
5596091e35e3SMatthias Ringwald     hci_connection_t *connection;
5597d5f71a7eSMatthias Ringwald #ifdef ENABLE_BLE
5598d5f71a7eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5599a086dc35SMatthias Ringwald     bool stop_advertisements;
5600d5f71a7eSMatthias Ringwald #endif
5601d5f71a7eSMatthias Ringwald #endif
5602091e35e3SMatthias Ringwald 
5603091e35e3SMatthias Ringwald     switch (hci_stack->substate) {
56040c88d5efSMatthias Ringwald         case HCI_HALTING_CLASSIC_STOP:
56050c88d5efSMatthias Ringwald #ifdef ENABLE_CLASSIC
5606911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5607911801caSMatthias Ringwald 
56080c88d5efSMatthias Ringwald             if (hci_stack->connectable || hci_stack->discoverable){
56090c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
56100c88d5efSMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, 0);
56110c88d5efSMatthias Ringwald                 return;
56120c88d5efSMatthias Ringwald             }
56130c88d5efSMatthias Ringwald #endif
56140c88d5efSMatthias Ringwald             /* fall through */
56150c88d5efSMatthias Ringwald 
56160c88d5efSMatthias Ringwald         case HCI_HALTING_LE_ADV_STOP:
56170c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
56180c88d5efSMatthias Ringwald 
56190c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
56200c88d5efSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5621911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5622911801caSMatthias Ringwald 
5623a086dc35SMatthias Ringwald             stop_advertisements = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5624911801caSMatthias Ringwald 
5625911801caSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
562622f987e4SMatthias Ringwald             if (hci_le_extended_advertising_supported()){
5627c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5628911801caSMatthias Ringwald                 btstack_linked_list_iterator_t it;
5629911801caSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5630911801caSMatthias Ringwald                 // stop all periodic advertisements and check if an extended set is active
5631911801caSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
5632911801caSMatthias Ringwald                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5633911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5634911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5635911801caSMatthias Ringwald                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
56360c88d5efSMatthias Ringwald                         return;
56370c88d5efSMatthias Ringwald                     }
5638911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
56390aeb0b24SMatthias Ringwald                         stop_advertisements = true;
5640911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5641911801caSMatthias Ringwald                     }
5642911801caSMatthias Ringwald                 }
5643c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
56440aeb0b24SMatthias Ringwald                 if (stop_advertisements){
5645911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5646911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5647911801caSMatthias Ringwald                     return;
5648911801caSMatthias Ringwald                 }
5649d935373dSMatthias Ringwald             } else
5650a2c9d908SMatthias Ringwald #else /* ENABLE_LE_PERIPHERAL */
5651911801caSMatthias Ringwald             {
5652a086dc35SMatthias Ringwald                 if (stop_advertisements) {
5653911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5654911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5655911801caSMatthias Ringwald                     return;
5656911801caSMatthias Ringwald                 }
5657911801caSMatthias Ringwald             }
5658911801caSMatthias Ringwald #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5659911801caSMatthias Ringwald #endif  /* ENABLE_LE_PERIPHERAL */
5660911801caSMatthias Ringwald #endif  /* ENABLE_BLE */
5661911801caSMatthias Ringwald 
56620c88d5efSMatthias Ringwald             /* fall through */
56630c88d5efSMatthias Ringwald 
56640c88d5efSMatthias Ringwald         case HCI_HALTING_LE_SCAN_STOP:
56650c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5666911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5667091e35e3SMatthias Ringwald 
5668091e35e3SMatthias Ringwald #ifdef ENABLE_BLE
5669091e35e3SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
56700c88d5efSMatthias Ringwald             if (hci_stack->le_scanning_active){
5671c42da3bcSMatthias Ringwald                 hci_le_scan_stop();
56720c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
56730c88d5efSMatthias Ringwald                 return;
56740c88d5efSMatthias Ringwald             }
5675091e35e3SMatthias Ringwald #endif
5676091e35e3SMatthias Ringwald #endif
56770c88d5efSMatthias Ringwald 
56780c88d5efSMatthias Ringwald             /* fall through */
56790c88d5efSMatthias Ringwald 
56800c88d5efSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL:
56810c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5682911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
56830c88d5efSMatthias Ringwald 
5684091e35e3SMatthias Ringwald             // close all open connections
5685091e35e3SMatthias Ringwald             connection = (hci_connection_t *) hci_stack->connections;
5686091e35e3SMatthias Ringwald             if (connection) {
5687091e35e3SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5688091e35e3SMatthias Ringwald 
568947bf68a7SDirk Helbig                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", (void*)connection, con_handle, connection->state);
5690091e35e3SMatthias Ringwald 
569103270f05SMatthias Ringwald                 // check state
569203270f05SMatthias Ringwald                 switch(connection->state) {
569303270f05SMatthias Ringwald                     case SENT_DISCONNECT:
569403270f05SMatthias Ringwald                     case RECEIVED_DISCONNECTION_COMPLETE:
569503270f05SMatthias Ringwald                         // wait until connection is gone
569603270f05SMatthias Ringwald                         return;
569703270f05SMatthias Ringwald                     default:
569803270f05SMatthias Ringwald                         break;
569903270f05SMatthias Ringwald                 }
5700091e35e3SMatthias Ringwald 
5701091e35e3SMatthias Ringwald                 // finally, send the disconnect command
570203270f05SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
5703091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5704091e35e3SMatthias Ringwald                 return;
5705091e35e3SMatthias Ringwald             }
5706091e35e3SMatthias Ringwald 
5707346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5708346f8c2cSMatthias Ringwald             // stop BIGs and BIG Syncs
5709346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_bigs != NULL){
5710346f8c2cSMatthias Ringwald                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5711346f8c2cSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5712346f8c2cSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5713346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5714346f8c2cSMatthias Ringwald                 return;
5715346f8c2cSMatthias Ringwald             }
5716346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_big_syncs != NULL){
5717346f8c2cSMatthias Ringwald                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5718346f8c2cSMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5719346f8c2cSMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5720346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5721346f8c2cSMatthias Ringwald                 return;
5722346f8c2cSMatthias Ringwald             }
5723346f8c2cSMatthias Ringwald #endif
5724346f8c2cSMatthias Ringwald 
5725091e35e3SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
5726091e35e3SMatthias Ringwald 
5727a086dc35SMatthias Ringwald             // no connections left, wait a bit to assert that btstack_crypto isn't waiting for an HCI event
5728091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING: wait 50 ms");
57290c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5730091e35e3SMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5731091e35e3SMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5732091e35e3SMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
5733091e35e3SMatthias Ringwald             break;
5734091e35e3SMatthias Ringwald 
5735b188b5fcSMatthias Ringwald         case HCI_HALTING_W4_CLOSE_TIMER:
5736b188b5fcSMatthias Ringwald             // keep waiting
5737b188b5fcSMatthias Ringwald             break;
5738b188b5fcSMatthias Ringwald 
5739091e35e3SMatthias Ringwald         case HCI_HALTING_CLOSE:
5740091e35e3SMatthias Ringwald             // close left over connections (that had not been properly closed before)
5741b188b5fcSMatthias Ringwald             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5742091e35e3SMatthias Ringwald             hci_discard_connections();
5743091e35e3SMatthias Ringwald 
5744091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, calling off");
5745091e35e3SMatthias Ringwald 
5746091e35e3SMatthias Ringwald             // switch mode
5747091e35e3SMatthias Ringwald             hci_power_control_off();
5748091e35e3SMatthias Ringwald 
5749091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, emitting state");
5750091e35e3SMatthias Ringwald             hci_emit_state();
5751091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, done");
5752091e35e3SMatthias Ringwald             break;
5753091e35e3SMatthias Ringwald 
5754091e35e3SMatthias Ringwald         default:
5755091e35e3SMatthias Ringwald             break;
5756091e35e3SMatthias Ringwald     }
575736916f81SDirk Helbig }
5758091e35e3SMatthias Ringwald 
5759091e35e3SMatthias Ringwald static void hci_falling_asleep_run(void){
5760091e35e3SMatthias Ringwald     hci_connection_t * connection;
5761091e35e3SMatthias Ringwald     switch(hci_stack->substate) {
5762091e35e3SMatthias Ringwald         case HCI_FALLING_ASLEEP_DISCONNECT:
5763091e35e3SMatthias Ringwald             log_info("HCI_STATE_FALLING_ASLEEP");
5764091e35e3SMatthias Ringwald             // close all open connections
5765091e35e3SMatthias Ringwald             connection =  (hci_connection_t *) hci_stack->connections;
5766091e35e3SMatthias Ringwald             if (connection){
5767091e35e3SMatthias Ringwald 
5768091e35e3SMatthias Ringwald                 // send disconnect
5769091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5770091e35e3SMatthias Ringwald 
577147bf68a7SDirk Helbig                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", (void*)connection, (uint16_t)connection->con_handle);
5772091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5773091e35e3SMatthias Ringwald 
5774091e35e3SMatthias Ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
5775091e35e3SMatthias Ringwald                 hci_shutdown_connection(connection);
5776091e35e3SMatthias Ringwald                 return;
5777091e35e3SMatthias Ringwald             }
5778091e35e3SMatthias Ringwald 
5779091e35e3SMatthias Ringwald             if (hci_classic_supported()){
5780091e35e3SMatthias Ringwald                 // disable page and inquiry scan
5781091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5782091e35e3SMatthias Ringwald 
5783091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, disabling inq scans");
5784091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5785091e35e3SMatthias Ringwald 
5786091e35e3SMatthias Ringwald                 // continue in next substate
5787091e35e3SMatthias Ringwald                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5788091e35e3SMatthias Ringwald                 break;
5789091e35e3SMatthias Ringwald             }
5790091e35e3SMatthias Ringwald 
5791091e35e3SMatthias Ringwald             /* fall through */
5792091e35e3SMatthias Ringwald 
5793091e35e3SMatthias Ringwald             case HCI_FALLING_ASLEEP_COMPLETE:
5794091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, calling sleep");
5795091e35e3SMatthias Ringwald                 // switch mode
5796091e35e3SMatthias Ringwald                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5797091e35e3SMatthias Ringwald                 hci_emit_state();
5798091e35e3SMatthias Ringwald                 break;
5799091e35e3SMatthias Ringwald 
5800091e35e3SMatthias Ringwald                 default:
5801091e35e3SMatthias Ringwald                     break;
5802091e35e3SMatthias Ringwald     }
5803091e35e3SMatthias Ringwald }
5804091e35e3SMatthias Ringwald 
580535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
580635454696SMatthias Ringwald 
5807758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
5808758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
5809a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5810baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5811758b46ceSmatthias.ringwald     hci_run();
5812758b46ceSmatthias.ringwald }
5813758b46ceSmatthias.ringwald 
581415a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
5815381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
5816381fbed8Smatthias.ringwald 
58173a9fb326S[email protected]     if (hci_stack->discoverable == enable){
581871fd255dSMatthias Ringwald         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5819381fbed8Smatthias.ringwald         return;
5820381fbed8Smatthias.ringwald     }
5821381fbed8Smatthias.ringwald 
58223a9fb326S[email protected]     hci_stack->discoverable = enable;
5823758b46ceSmatthias.ringwald     hci_update_scan_enable();
5824758b46ceSmatthias.ringwald }
5825b031bebbSmatthias.ringwald 
582615a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
5827758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
5828758b46ceSmatthias.ringwald 
5829758b46ceSmatthias.ringwald     // don't emit event
58303a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
5831758b46ceSmatthias.ringwald 
58323a9fb326S[email protected]     hci_stack->connectable = enable;
5833758b46ceSmatthias.ringwald     hci_update_scan_enable();
5834381fbed8Smatthias.ringwald }
583535454696SMatthias Ringwald #endif
5836381fbed8Smatthias.ringwald 
583715a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
58386535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
58395061f3afS[email protected] }
58405061f3afS[email protected] 
58412b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
58422b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
58432b838201SMatthias Ringwald 
58442b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
58452b838201SMatthias Ringwald     hci_reserve_packet_buffer();
58462b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
58472b838201SMatthias Ringwald 
58482b838201SMatthias Ringwald     uint16_t size = 0;
58492b838201SMatthias Ringwald     uint16_t num_handles = 0;
58502b838201SMatthias Ringwald     packet[size++] = 0x35;
58512b838201SMatthias Ringwald     packet[size++] = 0x0c;
58522b838201SMatthias Ringwald     size++;  // skip param len
58532b838201SMatthias Ringwald     size++;  // skip num handles
58542b838201SMatthias Ringwald 
58552b838201SMatthias Ringwald     // add { handle, packets } entries
58562b838201SMatthias Ringwald     btstack_linked_item_t * it;
58572b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
58582b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
58592b838201SMatthias Ringwald         if (connection->num_packets_completed){
58602b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
58612b838201SMatthias Ringwald             size += 2;
58622b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
58632b838201SMatthias Ringwald             size += 2;
58642b838201SMatthias Ringwald             //
58652b838201SMatthias Ringwald             num_handles++;
58662b838201SMatthias Ringwald             connection->num_packets_completed = 0;
58672b838201SMatthias Ringwald         }
58682b838201SMatthias Ringwald     }
58692b838201SMatthias Ringwald 
58702b838201SMatthias Ringwald     packet[2] = size - 3;
58712b838201SMatthias Ringwald     packet[3] = num_handles;
58722b838201SMatthias Ringwald 
58732b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
58742b838201SMatthias Ringwald 
58752b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
58762b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
58772b838201SMatthias Ringwald 
58782b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
58792b838201SMatthias Ringwald     if (hci_transport_synchronous()){
5880e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5881068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
58822b838201SMatthias Ringwald     }
58832b838201SMatthias Ringwald }
58842b838201SMatthias Ringwald #endif
58852b838201SMatthias Ringwald 
588626fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
588726fe9592SMatthias Ringwald     UNUSED(ds);
588826fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
5889f021201aSMatthias Ringwald     hci_halting_run();
589026fe9592SMatthias Ringwald }
589126fe9592SMatthias Ringwald 
5892f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
58934ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
5894b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5895b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5896b5d8b22bS[email protected]         if (connection) {
589728a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5898b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
5899f30077b7SMatthias Ringwald                 return true;
5900b5d8b22bS[email protected]             }
590128a0332dSMatthias Ringwald         } else {
5902b5d8b22bS[email protected]             // connection gone -> discard further fragments
590328a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5904b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
5905b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
5906b5d8b22bS[email protected]         }
5907b5d8b22bS[email protected]     }
5908f30077b7SMatthias Ringwald     return false;
59092b838201SMatthias Ringwald }
5910b031bebbSmatthias.ringwald 
591168ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
591268ab6207SMatthias Ringwald static bool hci_run_iso_fragments(void){
591368ab6207SMatthias Ringwald     if (hci_stack->iso_fragmentation_total_size > 0u) {
591468ab6207SMatthias Ringwald         // TODO: flow control
591568ab6207SMatthias Ringwald         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
591668ab6207SMatthias Ringwald             hci_send_iso_packet_fragments();
591768ab6207SMatthias Ringwald             return true;
591868ab6207SMatthias Ringwald         }
591968ab6207SMatthias Ringwald     }
592068ab6207SMatthias Ringwald     return false;
592168ab6207SMatthias Ringwald }
592268ab6207SMatthias Ringwald #endif
592368ab6207SMatthias Ringwald 
592435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
59256c0d5426SMatthias Ringwald 
59266c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
59276c0d5426SMatthias Ringwald static bool hci_classic_operation_active(void) {
59286c0d5426SMatthias Ringwald     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
59296c0d5426SMatthias Ringwald         return true;
59306c0d5426SMatthias Ringwald     }
59316c0d5426SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
59326c0d5426SMatthias Ringwald         return true;
59336c0d5426SMatthias Ringwald     }
59346c0d5426SMatthias Ringwald     btstack_linked_item_t * it;
59356c0d5426SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
59366c0d5426SMatthias Ringwald         hci_connection_t *connection = (hci_connection_t *) it;
59376c0d5426SMatthias Ringwald         switch (connection->state) {
59386c0d5426SMatthias Ringwald             case SENT_CREATE_CONNECTION:
59396c0d5426SMatthias Ringwald             case SENT_CANCEL_CONNECTION:
59406c0d5426SMatthias Ringwald             case SENT_DISCONNECT:
59416c0d5426SMatthias Ringwald                 return true;
59426c0d5426SMatthias Ringwald             default:
59436c0d5426SMatthias Ringwald                 break;
59446c0d5426SMatthias Ringwald         }
59456c0d5426SMatthias Ringwald     }
59466c0d5426SMatthias Ringwald     return false;
59476c0d5426SMatthias Ringwald }
59486c0d5426SMatthias Ringwald #endif
59496c0d5426SMatthias Ringwald 
5950f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
5951f30077b7SMatthias Ringwald 
595259d59ecfSMatthias Ringwald     // assert stack is working and classic is active
595359d59ecfSMatthias Ringwald     if (hci_classic_supported() == false)      return false;
595459d59ecfSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
595559d59ecfSMatthias Ringwald 
5956b031bebbSmatthias.ringwald     // decline incoming connections
59573a9fb326S[email protected]     if (hci_stack->decline_reason){
59583a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
59593a9fb326S[email protected]         hci_stack->decline_reason = 0;
59603a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5961f30077b7SMatthias Ringwald         return true;
5962ce4c8fabSmatthias.ringwald     }
596359d59ecfSMatthias Ringwald 
5964baa4881eSMatthias Ringwald     if (hci_stack->gap_tasks_classic != 0){
5965ab4831a3SMatthias Ringwald         hci_run_gap_tasks_classic();
5966f30077b7SMatthias Ringwald         return true;
5967b031bebbSmatthias.ringwald     }
596827741fe7SMatthias Ringwald 
5969f5875de5SMatthias Ringwald     // start/stop inquiry
5970a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
59716c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
59726c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
59736c0d5426SMatthias Ringwald #endif
59746c0d5426SMatthias Ringwald         {
5975f5875de5SMatthias Ringwald             uint8_t duration = hci_stack->inquiry_state;
5976beb3c81dSMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
597730199e24SMatthias Ringwald             if (hci_stack->inquiry_max_period_length != 0){
597830199e24SMatthias 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);
597930199e24SMatthias Ringwald             } else {
5980496bb884SMatthias Ringwald                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
598130199e24SMatthias Ringwald             }
5982f30077b7SMatthias Ringwald             return true;
5983f5875de5SMatthias Ringwald         }
59846c0d5426SMatthias Ringwald     }
5985f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5986f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5987f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
5988f30077b7SMatthias Ringwald         return true;
5989f5875de5SMatthias Ringwald     }
599030199e24SMatthias Ringwald 
599130199e24SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5992bc06f564SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
599330199e24SMatthias Ringwald         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
599430199e24SMatthias Ringwald         return true;
599530199e24SMatthias Ringwald     }
599630199e24SMatthias Ringwald 
5997b7f1ee76SMatthias Ringwald     // remote name request
5998b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
59996c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
60006c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
60016c0d5426SMatthias Ringwald #endif
60026c0d5426SMatthias Ringwald         {
6003b7f1ee76SMatthias Ringwald             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
6004b7f1ee76SMatthias Ringwald             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
6005ee8a36c8SMatthias Ringwald                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
6006f30077b7SMatthias Ringwald             return true;
6007b7f1ee76SMatthias Ringwald         }
60086c0d5426SMatthias Ringwald     }
6009cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
6010cf01e888SMatthias Ringwald     // Local OOB data
601159d59ecfSMatthias Ringwald     if (hci_stack->classic_read_local_oob_data){
6012cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
60131e83575aSMatthias Ringwald         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
6014cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
6015cf01e888SMatthias Ringwald         } else {
6016cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
6017cf01e888SMatthias Ringwald         }
6018cf01e888SMatthias Ringwald     }
6019cf01e888SMatthias Ringwald #endif
60200a51f88bSMatthias Ringwald     // pairing
60210a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
60220a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
6023c26f2c7bSMatthias Ringwald         uint8_t pin_code[PIN_CODE_LEN];
60240a51f88bSMatthias Ringwald         switch (state){
60250a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
6026cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
60273f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
60283f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
60293f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
60300a51f88bSMatthias Ringwald                 break;
60310a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
6032cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60330a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
60340a51f88bSMatthias Ringwald                 break;
60350a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
6036cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
6037d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
60380a51f88bSMatthias Ringwald                 break;
60390a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
6040cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60410a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
60420a51f88bSMatthias Ringwald                 break;
60430a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
6044cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
60450a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
60460a51f88bSMatthias Ringwald                 break;
60470a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
6048cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
60490a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
60500a51f88bSMatthias Ringwald                 break;
60510a51f88bSMatthias Ringwald             default:
60520a51f88bSMatthias Ringwald                 break;
60530a51f88bSMatthias Ringwald         }
6054f30077b7SMatthias Ringwald         return true;
6055f30077b7SMatthias Ringwald     }
6056f30077b7SMatthias Ringwald     return false;
60570a51f88bSMatthias Ringwald }
605835454696SMatthias Ringwald #endif
6059b031bebbSmatthias.ringwald 
6060a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
606191097d83SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6062be7ef9d8SMatthias Ringwald 
60637eb5b27eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
60647eb5b27eSMatthias Ringwald static uint8_t hci_le_num_phys(uint8_t phys){
60657eb5b27eSMatthias Ringwald     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
60667eb5b27eSMatthias Ringwald     btstack_assert(phys);
60677eb5b27eSMatthias Ringwald     return num_bits_set[phys];
60687eb5b27eSMatthias Ringwald }
60697eb5b27eSMatthias Ringwald #endif
60707eb5b27eSMatthias Ringwald 
6071c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void){
6072c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
607322f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
6074c42da3bcSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
6075c42da3bcSMatthias Ringwald     } else
6076c42da3bcSMatthias Ringwald #endif
6077c42da3bcSMatthias Ringwald     {
6078c42da3bcSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
6079c42da3bcSMatthias Ringwald     }
6080c42da3bcSMatthias Ringwald }
6081327f7f07SMatthias Ringwald 
6082f346015eSMatthias Ringwald static void
6083f346015eSMatthias Ringwald hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
6084327f7f07SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
608522f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
60867eb5b27eSMatthias Ringwald         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
60877eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_interval[3];
60887eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_window[3];
60897eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_min[3];
60907eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_max[3];
60917eb5b27eSMatthias Ringwald         uint16_t le_connection_latency[3];
60927eb5b27eSMatthias Ringwald         uint16_t le_supervision_timeout[3];
60937eb5b27eSMatthias Ringwald         uint16_t le_minimum_ce_length[3];
60947eb5b27eSMatthias Ringwald         uint16_t le_maximum_ce_length[3];
60957eb5b27eSMatthias Ringwald 
60967eb5b27eSMatthias Ringwald         uint8_t i;
60977eb5b27eSMatthias Ringwald         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
60987eb5b27eSMatthias Ringwald         for (i=0;i<num_phys;i++){
60997eb5b27eSMatthias Ringwald             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
61007eb5b27eSMatthias Ringwald             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
61017eb5b27eSMatthias Ringwald             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
61027eb5b27eSMatthias Ringwald             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
61037eb5b27eSMatthias Ringwald             le_connection_latency[i]       = hci_stack->le_connection_latency;
61047eb5b27eSMatthias Ringwald             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
61057eb5b27eSMatthias Ringwald             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
61067eb5b27eSMatthias Ringwald             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
61077eb5b27eSMatthias Ringwald         }
6108327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_extended_create_connection,
6109f346015eSMatthias Ringwald                      initiator_filter_policy,
6110327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
6111f346015eSMatthias Ringwald                      address_type,                  // peer address type
6112f346015eSMatthias Ringwald                      address,                       // peer bd addr
61137eb5b27eSMatthias Ringwald                      hci_stack->le_connection_phys, // initiating PHY
6114327f7f07SMatthias Ringwald                      le_connection_scan_interval,   // conn scan interval
6115327f7f07SMatthias Ringwald                      le_connection_scan_window,     // conn scan windows
6116327f7f07SMatthias Ringwald                      le_connection_interval_min,    // conn interval min
6117327f7f07SMatthias Ringwald                      le_connection_interval_max,    // conn interval max
6118327f7f07SMatthias Ringwald                      le_connection_latency,         // conn latency
6119327f7f07SMatthias Ringwald                      le_supervision_timeout,        // conn latency
6120327f7f07SMatthias Ringwald                      le_minimum_ce_length,          // min ce length
6121327f7f07SMatthias Ringwald                      le_maximum_ce_length           // max ce length
6122327f7f07SMatthias Ringwald         );
6123d935373dSMatthias Ringwald     } else
6124327f7f07SMatthias Ringwald #endif
6125327f7f07SMatthias Ringwald     {
6126327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
6127327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_interval,  // conn scan interval
6128327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_window,    // conn scan windows
6129f346015eSMatthias Ringwald                      initiator_filter_policy,                 // don't use whitelist
6130f346015eSMatthias Ringwald                      address_type,                            // peer address type
6131f346015eSMatthias Ringwald                      address,                                 // peer bd addr
6132327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,  // our addr type:
6133327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_min,   // conn interval min
6134327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_max,   // conn interval max
6135327f7f07SMatthias Ringwald                      hci_stack->le_connection_latency,        // conn latency
6136327f7f07SMatthias Ringwald                      hci_stack->le_supervision_timeout,       // conn latency
6137327f7f07SMatthias Ringwald                      hci_stack->le_minimum_ce_length,         // min ce length
6138327f7f07SMatthias Ringwald                      hci_stack->le_maximum_ce_length          // max ce length
6139327f7f07SMatthias Ringwald         );
6140327f7f07SMatthias Ringwald     }
6141327f7f07SMatthias Ringwald }
6142c42da3bcSMatthias Ringwald #endif
6143c42da3bcSMatthias Ringwald 
6144be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6145be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6146033393eeSBob Abeles static uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
6147be7ef9d8SMatthias Ringwald     uint8_t  operation = 0;
6148be7ef9d8SMatthias Ringwald     if (pos == 0){
6149be7ef9d8SMatthias Ringwald         // first fragment or complete data
6150be7ef9d8SMatthias Ringwald         operation |= 1;
6151be7ef9d8SMatthias Ringwald     }
6152be7ef9d8SMatthias Ringwald     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
6153be7ef9d8SMatthias Ringwald         // last fragment or complete data
6154be7ef9d8SMatthias Ringwald         operation |= 2;
6155be7ef9d8SMatthias Ringwald     }
6156be7ef9d8SMatthias Ringwald     return operation;
6157be7ef9d8SMatthias Ringwald }
6158be7ef9d8SMatthias Ringwald #endif
6159be7ef9d8SMatthias Ringwald #endif
6160be7ef9d8SMatthias Ringwald 
61612c052b15SMatthias Ringwald static bool hci_whitelist_modification_pending(void) {
616281ae6c3bSMatthias Ringwald     btstack_linked_list_iterator_t it;
616381ae6c3bSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
616481ae6c3bSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
616581ae6c3bSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
616681ae6c3bSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
616781ae6c3bSMatthias Ringwald             return true;
616881ae6c3bSMatthias Ringwald         }
616981ae6c3bSMatthias Ringwald     }
617081ae6c3bSMatthias Ringwald     return false;
617181ae6c3bSMatthias Ringwald }
617281ae6c3bSMatthias Ringwald 
61732c052b15SMatthias Ringwald static bool hci_whitelist_modification_process(void){
61742c052b15SMatthias Ringwald     // add/remove entries
61752c052b15SMatthias Ringwald     btstack_linked_list_iterator_t it;
61762c052b15SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
61772c052b15SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
61782c052b15SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
61792c052b15SMatthias Ringwald         if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
61802c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
61812c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
61822c052b15SMatthias Ringwald             bd_addr_type_t address_type = entry->address_type;
61832c052b15SMatthias Ringwald             bd_addr_t address;
61842c052b15SMatthias Ringwald             memcpy(address, entry->address, 6);
61852c052b15SMatthias Ringwald             if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
61862c052b15SMatthias Ringwald                 // remove from whitelist if not scheduled for re-addition
61872c052b15SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
61882c052b15SMatthias Ringwald                 btstack_memory_whitelist_entry_free(entry);
61892c052b15SMatthias Ringwald             }
61902c052b15SMatthias Ringwald             hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
61912c052b15SMatthias Ringwald             return true;
61922c052b15SMatthias Ringwald         }
61932c052b15SMatthias Ringwald         if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
61942c052b15SMatthias Ringwald             entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
61952c052b15SMatthias Ringwald             entry->state |= LE_WHITELIST_ON_CONTROLLER;
61962c052b15SMatthias Ringwald             hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
61972c052b15SMatthias Ringwald             return true;
61982c052b15SMatthias Ringwald         }
61992c052b15SMatthias Ringwald     }
62002c052b15SMatthias Ringwald     return false;
62012c052b15SMatthias Ringwald }
62022c052b15SMatthias Ringwald 
6203f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
6204f30077b7SMatthias Ringwald 
6205f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t lit;
6206f9aa0bbcSMatthias Ringwald     UNUSED(lit);
6207f40c73b4SMatthias Ringwald 
62082052d96cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
62092052d96cSMatthias Ringwald     if (hci_stack->le_resolvable_private_address_update_s > 0){
62102052d96cSMatthias Ringwald         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
62112052d96cSMatthias Ringwald         hci_stack->le_resolvable_private_address_update_s = 0;
62122052d96cSMatthias Ringwald         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
62132052d96cSMatthias Ringwald         return true;
62142052d96cSMatthias Ringwald     }
62152052d96cSMatthias Ringwald #endif
62162052d96cSMatthias Ringwald 
6217a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
6218a41310b7SMatthias Ringwald 
621949a6c69cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6220a41310b7SMatthias Ringwald     bool scanning_stop = false;
6221a41310b7SMatthias Ringwald     bool connecting_stop = false;
6222be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6223c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
62244bafedd5SMatthias Ringwald     bool periodic_sync_stop = false;
62254bafedd5SMatthias Ringwald #endif
6226be7ef9d8SMatthias Ringwald #endif
6227c814a904SMatthias Ringwald #endif
6228be7ef9d8SMatthias Ringwald 
622949a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
623049a6c69cSMatthias Ringwald     bool advertising_stop = false;
623149a6c69cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
623249a6c69cSMatthias Ringwald     le_advertising_set_t * advertising_stop_set = NULL;
623349a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
623449a6c69cSMatthias Ringwald     bool periodic_advertising_stop = false;
6235a41310b7SMatthias Ringwald #endif
623649a6c69cSMatthias Ringwald #endif
6237a41310b7SMatthias Ringwald #endif
6238a41310b7SMatthias Ringwald 
62399136bde8SMatthias Ringwald     // check if own address changes
62409ce6dfa1SMatthias Ringwald     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
62419ce6dfa1SMatthias Ringwald     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
62429136bde8SMatthias Ringwald 
624329c24bebSMatthias Ringwald     // check if whitelist needs modification
624481ae6c3bSMatthias Ringwald     bool  whitelist_modification_pending = hci_whitelist_modification_pending();
6245f40c73b4SMatthias Ringwald 
624621debf25SMatthias Ringwald     // check if resolving list needs modification
624721debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
624821debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
62491ffa425cSMatthias Ringwald     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
6250ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
625121debf25SMatthias Ringwald         resolving_list_modification_pending = true;
625221debf25SMatthias Ringwald     }
625321debf25SMatthias Ringwald #endif
625429c24bebSMatthias Ringwald 
6255f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
625649a6c69cSMatthias Ringwald 
6257f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
625849a6c69cSMatthias Ringwald     // check if periodic advertiser list needs modification
6259f40c73b4SMatthias Ringwald     bool periodic_list_modification_pending = false;
6260f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6261f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
6262f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6263f40c73b4SMatthias Ringwald         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
6264f40c73b4SMatthias Ringwald             periodic_list_modification_pending = true;
6265f40c73b4SMatthias Ringwald             break;
6266f40c73b4SMatthias Ringwald         }
6267f40c73b4SMatthias Ringwald     }
6268f40c73b4SMatthias Ringwald #endif
6269f40c73b4SMatthias Ringwald 
6270fde725feSMatthias Ringwald     // scanning control
62713251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
627229c24bebSMatthias Ringwald         // stop if:
627329c24bebSMatthias Ringwald         // - parameter change required
627429c24bebSMatthias Ringwald         // - it's disabled
627529c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
627621debf25SMatthias Ringwald         // - resolving list modified
627751e51a58SMatthias Ringwald         // - own address changes
627829c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
627921debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
628021debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
6281d54b2c94SMatthias Ringwald             (scanning_uses_whitelist && whitelist_modification_pending) ||
628251e51a58SMatthias Ringwald             resolving_list_modification_pending ||
628351e51a58SMatthias Ringwald             random_address_change){
628421debf25SMatthias Ringwald 
62852d5c2a27SMatthias Ringwald             scanning_stop = true;
6286fde725feSMatthias Ringwald         }
6287fde725feSMatthias Ringwald     }
6288fde725feSMatthias Ringwald 
628929c24bebSMatthias Ringwald     // connecting control
6290f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
6291f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
6292f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
6293f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
6294af64f147SMatthias Ringwald             // stop connecting if:
6295af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
6296af64f147SMatthias Ringwald             // - if it got disabled
629721debf25SMatthias Ringwald             // - resolving list modified
629851e51a58SMatthias Ringwald             // - own address changes
6299f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
6300f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
630121debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
630251e51a58SMatthias Ringwald                 resolving_list_modification_pending ||
630351e51a58SMatthias Ringwald                 random_address_change) {
630421debf25SMatthias Ringwald 
630529c24bebSMatthias Ringwald                 connecting_stop = true;
630629c24bebSMatthias Ringwald             }
6307f496d06eSMatthias Ringwald             break;
6308f496d06eSMatthias Ringwald         default:
6309f496d06eSMatthias Ringwald             break;
631029c24bebSMatthias Ringwald     }
631149a6c69cSMatthias Ringwald 
63124bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
631349a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
63144bafedd5SMatthias Ringwald     // periodic sync control
63154bafedd5SMatthias Ringwald     bool sync_with_advertiser_list;
63164bafedd5SMatthias Ringwald     switch(hci_stack->le_periodic_sync_state){
63174bafedd5SMatthias Ringwald         case LE_CONNECTING_DIRECT:
63184bafedd5SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
631949a6c69cSMatthias Ringwald             // stop sync if:
63204bafedd5SMatthias Ringwald             // - sync with advertiser list and advertiser list modification pending
632149a6c69cSMatthias Ringwald             // - if it got disabled
63224bafedd5SMatthias Ringwald             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
63234bafedd5SMatthias Ringwald             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
63244bafedd5SMatthias Ringwald                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
63254bafedd5SMatthias Ringwald                 periodic_sync_stop = true;
63264bafedd5SMatthias Ringwald             }
63274bafedd5SMatthias Ringwald             break;
63284bafedd5SMatthias Ringwald         default:
63294bafedd5SMatthias Ringwald             break;
63304bafedd5SMatthias Ringwald     }
63314bafedd5SMatthias Ringwald #endif
6332d70217a2SMatthias Ringwald #endif
633329c24bebSMatthias Ringwald 
633449a6c69cSMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
633549a6c69cSMatthias Ringwald 
6336d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
633745c102fdSMatthias Ringwald     // le advertisement control
6338935aa76eSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
633929c24bebSMatthias Ringwald         // stop if:
634029c24bebSMatthias Ringwald         // - parameter change required
63419136bde8SMatthias Ringwald         // - random address used in advertising and changes
634229c24bebSMatthias Ringwald         // - it's disabled
6343ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
634421debf25SMatthias Ringwald         // - resolving list modified
634551e51a58SMatthias Ringwald         // - own address changes
6346a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
63479136bde8SMatthias Ringwald         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
63484e5d21eaSMatthias Ringwald         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6349a61834b6SMatthias Ringwald         if (advertising_change ||
63509136bde8SMatthias Ringwald             (advertising_uses_random_address && random_address_change) ||
6351a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
63529136bde8SMatthias Ringwald             (advertising_uses_whitelist && whitelist_modification_pending) ||
635351e51a58SMatthias Ringwald             resolving_list_modification_pending ||
635451e51a58SMatthias Ringwald             random_address_change) {
635521debf25SMatthias Ringwald 
6356fde725feSMatthias Ringwald             advertising_stop = true;
6357fde725feSMatthias Ringwald         }
6358fde725feSMatthias Ringwald     }
6359be7ef9d8SMatthias Ringwald 
6360be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
636122f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported() && (advertising_stop == false)){
6362be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6363be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6364be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6365be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
636653f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6367be7ef9d8SMatthias Ringwald                 // stop if:
6368be7ef9d8SMatthias Ringwald                 // - parameter change required
6369be7ef9d8SMatthias Ringwald                 // - random address used in connectable advertising and changes
6370be7ef9d8SMatthias Ringwald                 // - it's disabled
6371be7ef9d8SMatthias Ringwald                 // - whitelist change required but used for advertisement filter policy
6372be7ef9d8SMatthias Ringwald                 // - resolving list modified
6373be7ef9d8SMatthias Ringwald                 // - own address changes
6374be7ef9d8SMatthias Ringwald                 // - advertisement set will be removed
637557a04237SMatthias Ringwald                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
637657a04237SMatthias Ringwald                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
637753f240c0SMatthias Ringwald                 bool advertising_uses_random_address =
637853f240c0SMatthias Ringwald                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
637953f240c0SMatthias Ringwald                         advertising_connectable;
6380be7ef9d8SMatthias Ringwald                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6381be7ef9d8SMatthias Ringwald                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
638253f240c0SMatthias Ringwald                 bool advertising_set_random_address_change =
638353f240c0SMatthias Ringwald                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
638453f240c0SMatthias Ringwald                 bool advertising_set_will_be_removed =
638553f240c0SMatthias Ringwald                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6386be7ef9d8SMatthias Ringwald                 if (advertising_parameter_change ||
6387be7ef9d8SMatthias Ringwald                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6388be7ef9d8SMatthias Ringwald                     (advertising_enabled == false) ||
6389be7ef9d8SMatthias Ringwald                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6390be7ef9d8SMatthias Ringwald                     resolving_list_modification_pending ||
6391be7ef9d8SMatthias Ringwald                     advertising_set_will_be_removed) {
6392be7ef9d8SMatthias Ringwald 
6393be7ef9d8SMatthias Ringwald                     advertising_stop = true;
6394be7ef9d8SMatthias Ringwald                     advertising_stop_set = advertising_set;
6395be7ef9d8SMatthias Ringwald                     break;
6396be7ef9d8SMatthias Ringwald                 }
6397be7ef9d8SMatthias Ringwald             }
6398c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
639953f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
640053f240c0SMatthias Ringwald                 // stop if:
640153f240c0SMatthias Ringwald                 // - it's disabled
640253f240c0SMatthias Ringwald                 // - parameter change required
640353f240c0SMatthias Ringwald                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
640453f240c0SMatthias Ringwald                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
640553f240c0SMatthias Ringwald                 if ((periodic_enabled == false) || periodic_parameter_change){
640649a6c69cSMatthias Ringwald                     periodic_advertising_stop = true;
640753f240c0SMatthias Ringwald                     advertising_stop_set = advertising_set;
640853f240c0SMatthias Ringwald                 }
640953f240c0SMatthias Ringwald             }
641049a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
641153f240c0SMatthias Ringwald         }
6412be7ef9d8SMatthias Ringwald     }
6413be7ef9d8SMatthias Ringwald #endif
6414be7ef9d8SMatthias Ringwald 
6415a41310b7SMatthias Ringwald #endif
6416fde725feSMatthias Ringwald 
6417a41310b7SMatthias Ringwald 
6418a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
6419a41310b7SMatthias Ringwald 
6420131d4778SMatthias Ringwald 
6421131d4778SMatthias Ringwald     // 2.1 Outgoing connection
6422131d4778SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6423131d4778SMatthias Ringwald     if (connecting_stop){
6424131d4778SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
6425131d4778SMatthias Ringwald         return true;
6426131d4778SMatthias Ringwald     }
6427131d4778SMatthias Ringwald #endif
6428131d4778SMatthias Ringwald 
6429131d4778SMatthias Ringwald     // 2.2 Scanning
6430a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6431a41310b7SMatthias Ringwald     if (scanning_stop){
64325226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
6433c42da3bcSMatthias Ringwald         hci_le_scan_stop();
6434a41310b7SMatthias Ringwald         return true;
6435a41310b7SMatthias Ringwald     }
6436a41310b7SMatthias Ringwald 
6437131d4778SMatthias Ringwald     // 2.3 Periodic Sync
64384bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
643949a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
644049a6c69cSMatthias Ringwald         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
644149a6c69cSMatthias Ringwald         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
644249a6c69cSMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
644349a6c69cSMatthias Ringwald         return true;
644449a6c69cSMatthias Ringwald     }
644549a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
64464bafedd5SMatthias Ringwald     if (periodic_sync_stop){
64474bafedd5SMatthias Ringwald         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
64484bafedd5SMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
64494bafedd5SMatthias Ringwald         return true;
64504bafedd5SMatthias Ringwald     }
645149a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6452a8016f96SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6453a8016f96SMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
6454a41310b7SMatthias Ringwald 
6455131d4778SMatthias Ringwald     // 2.4 Advertising: legacy, extended, periodic
6456a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6457fde725feSMatthias Ringwald     if (advertising_stop){
6458e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
645922f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()) {
6460be7ef9d8SMatthias Ringwald             uint8_t advertising_stop_handle;
6461be7ef9d8SMatthias Ringwald             if (advertising_stop_set != NULL){
6462be7ef9d8SMatthias Ringwald                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6463be7ef9d8SMatthias Ringwald                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6464be7ef9d8SMatthias Ringwald             } else {
6465be7ef9d8SMatthias Ringwald                 advertising_stop_handle = 0;
6466be7ef9d8SMatthias Ringwald                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6467be7ef9d8SMatthias Ringwald             }
6468be7ef9d8SMatthias Ringwald             const uint8_t advertising_handles[] = { advertising_stop_handle };
6469e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6470e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6471e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6472e464cd48SMatthias Ringwald         } else
6473e464cd48SMatthias Ringwald #endif
6474e464cd48SMatthias Ringwald         {
6475be7ef9d8SMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
647645c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6477e464cd48SMatthias Ringwald         }
6478f30077b7SMatthias Ringwald         return true;
647945c102fdSMatthias Ringwald     }
648053f240c0SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6481c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
648249a6c69cSMatthias Ringwald     if (periodic_advertising_stop){
648353f240c0SMatthias Ringwald         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
648453f240c0SMatthias Ringwald         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
648553f240c0SMatthias Ringwald         return true;
648653f240c0SMatthias Ringwald     }
6487c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6488c814a904SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6489a8016f96SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
6490fde725feSMatthias Ringwald 
6491131d4778SMatthias Ringwald 
6492a41310b7SMatthias Ringwald     // Phase 3: modify
6493a41310b7SMatthias Ringwald 
6494137a570aSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY) {
6495137a570aSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
6496137a570aSMatthias Ringwald         // GAP Privacy, notify clients upon upcoming random address change
6497137a570aSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
64981fa7a4bbSMatthias Ringwald         // notify might cause hci_run to get executed, check if we still can send
6499137a570aSMatthias Ringwald         gap_privacy_clients_notify(hci_stack->le_random_address);
65001fa7a4bbSMatthias Ringwald         if (!hci_can_send_command_packet_now()) {
65011fa7a4bbSMatthias Ringwald             return true;
65021fa7a4bbSMatthias Ringwald         }
6503137a570aSMatthias Ringwald     }
6504137a570aSMatthias Ringwald 
6505137a570aSMatthias Ringwald     // - wait until privacy update completed
6506137a570aSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PRIVACY_PENDING) != 0){
6507137a570aSMatthias Ringwald         return false;
6508137a570aSMatthias Ringwald     }
6509137a570aSMatthias Ringwald 
651064f9dabaSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
65119136bde8SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
65129136bde8SMatthias Ringwald         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6513ae35a99cSMatthias Ringwald #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6514ae35a99cSMatthias Ringwald         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6515ae35a99cSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6516ae35a99cSMatthias Ringwald #endif
65179136bde8SMatthias Ringwald         return true;
65189136bde8SMatthias Ringwald     }
65199136bde8SMatthias Ringwald 
6520a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6521a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
6522a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
652363671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
652422f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
65257eb5b27eSMatthias Ringwald             // prepare arrays for all phys (LE Coded and LE 1M PHY)
65267eb5b27eSMatthias Ringwald             uint8_t  scan_types[2];
65277eb5b27eSMatthias Ringwald             uint16_t scan_intervals[2];
65287eb5b27eSMatthias Ringwald             uint16_t scan_windows[2];
65297eb5b27eSMatthias Ringwald 
65307eb5b27eSMatthias Ringwald             uint8_t i;
65317eb5b27eSMatthias Ringwald             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
65327eb5b27eSMatthias Ringwald             for (i=0;i<num_phys;i++){
65337eb5b27eSMatthias Ringwald                 scan_types[i]     = hci_stack->le_scan_type;
65347eb5b27eSMatthias Ringwald                 scan_intervals[i] = hci_stack->le_scan_interval;
65357eb5b27eSMatthias Ringwald                 scan_windows[i]   = hci_stack->le_scan_window;
65367eb5b27eSMatthias Ringwald             }
653763671e69SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
65387eb5b27eSMatthias Ringwald                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
653963671e69SMatthias Ringwald         } else
654063671e69SMatthias Ringwald #endif
654163671e69SMatthias Ringwald         {
6542a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6543a41310b7SMatthias Ringwald                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
654463671e69SMatthias Ringwald         }
6545a41310b7SMatthias Ringwald         return true;
6546a41310b7SMatthias Ringwald     }
6547a41310b7SMatthias Ringwald #endif
6548a41310b7SMatthias Ringwald 
6549a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
655045c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
655145c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
65526bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6553e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
655422f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6555e464cd48SMatthias Ringwald             // map advertisment type to advertising event properties
6556e464cd48SMatthias Ringwald             uint16_t adv_event_properties = 0;
655736916f81SDirk Helbig             //                           0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000
655836916f81SDirk Helbig             const uint16_t mapping[] = {       0x13,       0x15,       0x1D,       0x12,       0x10 };
6559e464cd48SMatthias Ringwald             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6560e464cd48SMatthias Ringwald                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6561e464cd48SMatthias Ringwald             }
6562174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6563e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6564e464cd48SMatthias Ringwald                          0,
6565e464cd48SMatthias Ringwald                          adv_event_properties,
6566e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
6567e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
6568e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
6569e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
6570e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
6571e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
6572e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_filter_policy,
6573e464cd48SMatthias Ringwald                          0x7f,  // tx power: no preference
6574e464cd48SMatthias Ringwald                          0x01,  // primary adv phy: LE 1M
6575e464cd48SMatthias Ringwald                          0,     // secondary adv max skip
65765375ad13SMatthias Ringwald                          0x01,  // secondary adv phy
6577e464cd48SMatthias Ringwald                          0,     // adv sid
6578e464cd48SMatthias Ringwald                          0      // scan request notification
6579e464cd48SMatthias Ringwald                          );
6580d935373dSMatthias Ringwald         } else
6581e464cd48SMatthias Ringwald #endif
6582e464cd48SMatthias Ringwald         {
658345c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
658445c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
658545c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
658645c102fdSMatthias Ringwald                          hci_stack->le_advertisements_type,
65876bcfa632SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
658845c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
658945c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
659045c102fdSMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
659145c102fdSMatthias Ringwald                          hci_stack->le_advertisements_filter_policy);
6592e464cd48SMatthias Ringwald         }
6593f30077b7SMatthias Ringwald         return true;
659445c102fdSMatthias Ringwald     }
6595be7ef9d8SMatthias Ringwald 
65969ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
65979ce6dfa1SMatthias Ringwald     // assumption: only set if extended advertising is supported
65989ce6dfa1SMatthias Ringwald     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
65999ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
66009ce6dfa1SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
66019ce6dfa1SMatthias Ringwald         return true;
66029ce6dfa1SMatthias Ringwald     }
66039ce6dfa1SMatthias Ringwald #endif
66049ce6dfa1SMatthias Ringwald 
6605501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6606501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
66077a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
66087a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
66096535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
66106535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
66113c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6612e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
661322f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6614174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6615e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6616e464cd48SMatthias Ringwald         } else
6617e464cd48SMatthias Ringwald #endif
6618e464cd48SMatthias Ringwald         {
66197a85e4f5SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6620e464cd48SMatthias Ringwald         }
6621f30077b7SMatthias Ringwald         return true;
662245c102fdSMatthias Ringwald     }
6623be7ef9d8SMatthias Ringwald 
6624501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6625501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6626f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
6627f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
66286535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
66296535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
66303c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6631e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
663222f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6633174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6634e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6635e464cd48SMatthias Ringwald         } else
6636e464cd48SMatthias Ringwald #endif
6637e464cd48SMatthias Ringwald         {
6638214bfd60SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6639e464cd48SMatthias Ringwald         }
6640f30077b7SMatthias Ringwald         return true;
6641501f56b3SMatthias Ringwald     }
6642be7ef9d8SMatthias Ringwald 
6643be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
664422f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
6645be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6646be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6647be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6648be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6649be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6650be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6651174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6652be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6653be7ef9d8SMatthias Ringwald                 return true;
6654be7ef9d8SMatthias Ringwald             }
6655be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6656be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6657174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6658be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6659be7ef9d8SMatthias Ringwald                              advertising_set->advertising_handle,
666057a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_event_properties,
666157a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_min,
666257a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_max,
666357a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_channel_map,
666457a04237SMatthias Ringwald                              advertising_set->extended_params.own_address_type,
666557a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address_type,
666657a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address,
666757a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_filter_policy,
666857a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_tx_power,
666957a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_phy,
667057a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_max_skip,
667157a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_phy,
667257a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_sid,
667357a04237SMatthias Ringwald                              advertising_set->extended_params.scan_request_notification_enable
6674be7ef9d8SMatthias Ringwald                 );
6675be7ef9d8SMatthias Ringwald                 return true;
6676be7ef9d8SMatthias Ringwald             }
66770f54aa8dSMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
66780f54aa8dSMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
66790f54aa8dSMatthias Ringwald                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
66800f54aa8dSMatthias Ringwald                 return true;
66810f54aa8dSMatthias Ringwald             }
6682be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6683be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->adv_data_pos;
6684be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6685be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6686be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6687be7ef9d8SMatthias Ringwald                     // last fragment or complete data
6688be7ef9d8SMatthias Ringwald                     operation |= 2;
6689be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos = 0;
6690be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6691be7ef9d8SMatthias Ringwald                 } else {
6692be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos += data_to_upload;
6693be7ef9d8SMatthias Ringwald                 }
6694174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
66950cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6696be7ef9d8SMatthias Ringwald                 return true;
6697be7ef9d8SMatthias Ringwald             }
6698be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6699be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->scan_data_pos;
6700be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6701be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6702be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6703be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos = 0;
6704be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6705be7ef9d8SMatthias Ringwald                 } else {
6706be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos += data_to_upload;
6707be7ef9d8SMatthias Ringwald                 }
6708174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
67098ef6d15fSMatthias 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]);
6710be7ef9d8SMatthias Ringwald                 return true;
6711be7ef9d8SMatthias Ringwald             }
6712c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
671353f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
671453f240c0SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
671553f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
671653f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
671753f240c0SMatthias Ringwald                              advertising_set->advertising_handle,
671853f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_min,
671953f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_max,
672053f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_properties);
672153f240c0SMatthias Ringwald                 return true;
672253f240c0SMatthias Ringwald             }
672353f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
67240cbe4690SMatthias Ringwald                 uint16_t pos = advertising_set->periodic_data_pos;
672553f240c0SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
672653f240c0SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
672753f240c0SMatthias Ringwald                 if ((operation & 0x02) != 0){
672853f240c0SMatthias Ringwald                     // last fragment or complete data
672953f240c0SMatthias Ringwald                     operation |= 2;
67300cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos = 0;
673153f240c0SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
673253f240c0SMatthias Ringwald                 } else {
67330cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos += data_to_upload;
673453f240c0SMatthias Ringwald                 }
673553f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
67360cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
673753f240c0SMatthias Ringwald                 return true;
673853f240c0SMatthias Ringwald             }
6739c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6740be7ef9d8SMatthias Ringwald         }
6741be7ef9d8SMatthias Ringwald     }
6742be7ef9d8SMatthias Ringwald #endif
6743be7ef9d8SMatthias Ringwald 
6744d70217a2SMatthias Ringwald #endif
67459956955bSMatthias Ringwald 
6746057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6747a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
6748a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
67494bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
67504bafedd5SMatthias Ringwald     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
67514bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
67524bafedd5SMatthias Ringwald #endif
6753057ab60cSMatthias Ringwald #endif
6754057ab60cSMatthias Ringwald 
6755a41310b7SMatthias Ringwald     // LE Whitelist Management
6756a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
67572c052b15SMatthias Ringwald         bool done = hci_whitelist_modification_process();
67582c052b15SMatthias Ringwald         if (done) return true;
675991915b0bSMatthias Ringwald     }
67609956955bSMatthias Ringwald 
676121debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
676221debf25SMatthias Ringwald     // LE Resolving List Management
67632fbf0ed0SMatthias Ringwald     if (resolving_list_modification_pending) {
676421debf25SMatthias Ringwald 		uint16_t i;
67658dc1b1d0SMatthias Ringwald         uint8_t null_16[16];
67668dc1b1d0SMatthias Ringwald         uint8_t local_irk_flipped[16];
67678dc1b1d0SMatthias Ringwald         const uint8_t *local_irk;
676821debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
676921debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
677021debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
677121debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
677221debf25SMatthias Ringwald 				return true;
677321debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
677421debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
677521debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
677621debf25SMatthias Ringwald 				return true;
677721debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
67788dc1b1d0SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SET_IRK;
6779ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6780ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
6781e8ca66c6SMatthias Ringwald                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6782e8ca66c6SMatthias Ringwald                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6783ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6784ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
678521debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
678621debf25SMatthias Ringwald 				return true;
67878dc1b1d0SMatthias Ringwald             case LE_RESOLVING_LIST_SET_IRK:
67888dc1b1d0SMatthias Ringwald                 // set IRK used by RPA for undirected advertising
67898dc1b1d0SMatthias Ringwald                 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
67908dc1b1d0SMatthias Ringwald                 local_irk = gap_get_persistent_irk();
67918dc1b1d0SMatthias Ringwald                 reverse_128(local_irk, local_irk_flipped);
67928dc1b1d0SMatthias Ringwald                 memset(null_16, 0, sizeof(null_16));
67938dc1b1d0SMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_resolving_list, BD_ADDR_TYPE_LE_PUBLIC, null_16,
67948dc1b1d0SMatthias Ringwald                              null_16, local_irk_flipped);
67958dc1b1d0SMatthias Ringwald                 return true;
67965f3ccd83SMatthias Ringwald 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
67975f3ccd83SMatthias Ringwald                 // first remove old entries
679802b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
679902b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
680002b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
680102b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
680202b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
680302b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
680402b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
680502b02cffSMatthias Ringwald 					sm_key_t peer_irk;
680602b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
680702b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6808f5228c62SMatthias Ringwald 
6809f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6810f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
6811f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6812f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
6813f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6814f5228c62SMatthias Ringwald 						if (entry->address_type != peer_identity_addr_type) continue;
6815f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6816f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6817f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6818f5228c62SMatthias Ringwald 					}
6819f5228c62SMatthias Ringwald #endif
6820f5228c62SMatthias Ringwald 
6821ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6822ea151974SMatthias Ringwald 								 peer_identity_addreses);
682302b02cffSMatthias Ringwald 					return true;
682402b02cffSMatthias Ringwald 				}
682502b02cffSMatthias Ringwald 
68265f3ccd83SMatthias Ringwald                 // then add new entries
682721debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
682821debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
682921debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
683002b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
683102b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
683221debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
683321debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
683421debf25SMatthias Ringwald 					sm_key_t peer_irk;
683521debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
683621debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6837e938c062SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
68382b6efc4dSMatthias Ringwald 					local_irk = gap_get_persistent_irk();
683921debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
684021debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
684121debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
684221debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
6843ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6844ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
684521debf25SMatthias Ringwald 					return true;
684621debf25SMatthias Ringwald 				}
6847e8ca66c6SMatthias Ringwald 
6848e8ca66c6SMatthias Ringwald                 // finally, set privacy mode
6849e8ca66c6SMatthias Ringwald                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6850e8ca66c6SMatthias Ringwald                     uint8_t offset = i >> 3;
6851e8ca66c6SMatthias Ringwald                     uint8_t mask = 1 << (i & 7);
6852e8ca66c6SMatthias Ringwald                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6853e8ca66c6SMatthias Ringwald                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6854e8ca66c6SMatthias Ringwald                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6855e8ca66c6SMatthias Ringwald                         // Network Privacy Mode is default
6856e8ca66c6SMatthias Ringwald                         continue;
6857e8ca66c6SMatthias Ringwald                     }
6858e8ca66c6SMatthias Ringwald                     bd_addr_t peer_identity_address;
6859e8ca66c6SMatthias Ringwald                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6860e8ca66c6SMatthias Ringwald                     sm_key_t peer_irk;
6861e8ca66c6SMatthias Ringwald                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6862e8ca66c6SMatthias Ringwald                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6863e8ca66c6SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
6864e8ca66c6SMatthias Ringwald                     // command uses format specifier 'P' that stores 16-byte value without flip
6865e8ca66c6SMatthias Ringwald                     uint8_t peer_irk_flipped[16];
6866e8ca66c6SMatthias Ringwald                     reverse_128(peer_irk, peer_irk_flipped);
6867e8ca66c6SMatthias Ringwald                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6868e8ca66c6SMatthias Ringwald                     return true;
6869e8ca66c6SMatthias Ringwald                 }
687021debf25SMatthias Ringwald 				break;
687102b02cffSMatthias Ringwald 
687221debf25SMatthias Ringwald 			default:
687321debf25SMatthias Ringwald 				break;
687421debf25SMatthias Ringwald 		}
687521debf25SMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
68762fbf0ed0SMatthias Ringwald 	}
687721debf25SMatthias Ringwald #endif
6878a41310b7SMatthias Ringwald 
6879f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6880f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6881f40c73b4SMatthias Ringwald     // LE Whitelist Management
6882f40c73b4SMatthias Ringwald     if (periodic_list_modification_pending){
6883f40c73b4SMatthias Ringwald         // add/remove entries
6884f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6885f40c73b4SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
6886f40c73b4SMatthias Ringwald             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6887f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6888f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6889d946a741SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6890f40c73b4SMatthias Ringwald                 return true;
6891f40c73b4SMatthias Ringwald             }
6892f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6893f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6894f40c73b4SMatthias Ringwald                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
68959e88556bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_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_ON_CONTROLLER) == 0){
6899f40c73b4SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6900f40c73b4SMatthias Ringwald                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6901f40c73b4SMatthias Ringwald             }
6902f40c73b4SMatthias Ringwald         }
6903f40c73b4SMatthias Ringwald     }
6904f40c73b4SMatthias Ringwald #endif
6905f40c73b4SMatthias Ringwald #endif
6906f40c73b4SMatthias Ringwald 
690798aa715fSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
690898aa715fSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
690998aa715fSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
691098aa715fSMatthias Ringwald     if (hci_stack->le_past_set_default_params){
691198aa715fSMatthias Ringwald         hci_stack->le_past_set_default_params = false;
691298aa715fSMatthias Ringwald         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
691398aa715fSMatthias Ringwald                      hci_stack->le_past_mode,
691498aa715fSMatthias Ringwald                      hci_stack->le_past_skip,
691598aa715fSMatthias Ringwald                      hci_stack->le_past_sync_timeout,
691698aa715fSMatthias Ringwald                      hci_stack->le_past_cte_type);
691798aa715fSMatthias Ringwald         return true;
691898aa715fSMatthias Ringwald     }
691998aa715fSMatthias Ringwald #endif
692098aa715fSMatthias Ringwald #endif
692198aa715fSMatthias Ringwald #endif
692298aa715fSMatthias Ringwald 
6923a086dc35SMatthias Ringwald     // postpone all actions until stack is fully working
692473799937SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
692573799937SMatthias Ringwald 
692673799937SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
692773799937SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
692873799937SMatthias Ringwald 
6929a41310b7SMatthias Ringwald     // Phase 4: restore state
693029c24bebSMatthias Ringwald 
693129c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6932af64f147SMatthias Ringwald     // re-start scanning
693329c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
693429c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
693563671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
693622f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
69374856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
693863671e69SMatthias Ringwald         } else
693963671e69SMatthias Ringwald #endif
694063671e69SMatthias Ringwald         {
69414856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
694263671e69SMatthias Ringwald         }
694329c24bebSMatthias Ringwald         return true;
694429c24bebSMatthias Ringwald     }
694529c24bebSMatthias Ringwald #endif
694629c24bebSMatthias Ringwald 
694713eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6948af64f147SMatthias Ringwald     // re-start connecting
6949af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
69509956955bSMatthias Ringwald         bd_addr_t null_addr;
69519956955bSMatthias Ringwald         memset(null_addr, 0, 6);
69526bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
69536bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
69546f34e9d6SMatthias Ringwald         hci_send_le_create_connection(1, 0, null_addr);
6955f30077b7SMatthias Ringwald         return true;
69569956955bSMatthias Ringwald     }
69574bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
69584bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
69594bafedd5SMatthias Ringwald         switch(hci_stack->le_periodic_sync_request){
69604bafedd5SMatthias Ringwald             case LE_CONNECTING_DIRECT:
69614bafedd5SMatthias Ringwald             case LE_CONNECTING_WHITELIST:
69624bafedd5SMatthias Ringwald                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
69634bafedd5SMatthias Ringwald                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
69644bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_options,
69654bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertising_sid,
69664bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address_type,
69674bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address,
69684bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_skip,
69694bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_timeout,
69704bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_cte_type);
69714bafedd5SMatthias Ringwald                 return true;
69724bafedd5SMatthias Ringwald             default:
69734bafedd5SMatthias Ringwald                 break;
69744bafedd5SMatthias Ringwald         }
69754bafedd5SMatthias Ringwald     }
69764bafedd5SMatthias Ringwald #endif
6977d70217a2SMatthias Ringwald #endif
6978a41310b7SMatthias Ringwald 
6979a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6980a41310b7SMatthias Ringwald     // re-start advertising
6981935aa76eSMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6982a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
6983935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6984b892db1cSMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6985e464cd48SMatthias Ringwald 
6986e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
698722f987e4SMatthias Ringwald         if (hci_le_extended_advertising_supported()){
6988e464cd48SMatthias Ringwald             const uint8_t advertising_handles[] = { 0 };
6989e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6990e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6991e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6992e464cd48SMatthias Ringwald         } else
6993e464cd48SMatthias Ringwald #endif
6994e464cd48SMatthias Ringwald         {
6995a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6996e464cd48SMatthias Ringwald         }
6997a41310b7SMatthias Ringwald         return true;
6998a41310b7SMatthias Ringwald     }
6999be7ef9d8SMatthias Ringwald 
7000be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
700122f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()) {
7002be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
7003be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7004be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)) {
7005be7ef9d8SMatthias Ringwald             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7006be7ef9d8SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
70078caa405cSMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
7008be7ef9d8SMatthias Ringwald                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
7009be7ef9d8SMatthias Ringwald                 const uint16_t durations[] = { advertising_set->enable_timeout };
7010be7ef9d8SMatthias Ringwald                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
7011be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
7012be7ef9d8SMatthias Ringwald                 return true;
7013be7ef9d8SMatthias Ringwald             }
7014c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
701553f240c0SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
701653f240c0SMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
701753f240c0SMatthias Ringwald                 uint8_t enable = 1;
701853f240c0SMatthias Ringwald                 if (advertising_set->periodic_include_adi){
701953f240c0SMatthias Ringwald                     enable |= 2;
702053f240c0SMatthias Ringwald                 }
702153f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
702253f240c0SMatthias Ringwald                 return true;
702353f240c0SMatthias Ringwald             }
7024c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
7025be7ef9d8SMatthias Ringwald         }
7026be7ef9d8SMatthias Ringwald     }
7027be7ef9d8SMatthias Ringwald #endif
7028a41310b7SMatthias Ringwald #endif
7029a41310b7SMatthias Ringwald 
7030f30077b7SMatthias Ringwald     return false;
70317bdc6798S[email protected] }
70327aa35f6aSMatthias Ringwald 
70337aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
70347aa35f6aSMatthias Ringwald static bool hci_run_iso_tasks(void){
70357aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
70362a6c0f82SMatthias Ringwald 
703726b93350SMatthias Ringwald     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
703840f86dfdSMatthias Ringwald         return false;
703940f86dfdSMatthias Ringwald     }
704040f86dfdSMatthias Ringwald 
70412a6c0f82SMatthias Ringwald     // BIG
70427aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
70437aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
70447aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
70457aa35f6aSMatthias Ringwald         switch (big->state){
70467aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
704740f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
704840f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
70497aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
70507aa35f6aSMatthias Ringwald                 hci_send_cmd(&hci_le_create_big,
70517aa35f6aSMatthias Ringwald                              big->params->big_handle,
70527aa35f6aSMatthias Ringwald                              big->params->advertising_handle,
70537aa35f6aSMatthias Ringwald                              big->params->num_bis,
70547aa35f6aSMatthias Ringwald                              big->params->sdu_interval_us,
70557aa35f6aSMatthias Ringwald                              big->params->max_sdu,
70567aa35f6aSMatthias Ringwald                              big->params->max_transport_latency_ms,
70577aa35f6aSMatthias Ringwald                              big->params->rtn,
70587aa35f6aSMatthias Ringwald                              big->params->phy,
70597aa35f6aSMatthias Ringwald                              big->params->packing,
70607aa35f6aSMatthias Ringwald                              big->params->framing,
70617aa35f6aSMatthias Ringwald                              big->params->encryption,
70627aa35f6aSMatthias Ringwald                              big->params->broadcast_code);
70637aa35f6aSMatthias Ringwald                 return true;
70647aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
70657aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
706685dc435bSDirk 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);
70677aa35f6aSMatthias Ringwald                 return true;
70687aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
70697aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
70702a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
7071c1f83111SMatthias Ringwald                 return true;
70727aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
70737aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
7074d1620e55SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
70757aa35f6aSMatthias Ringwald                 return true;
70767aa35f6aSMatthias Ringwald             default:
70777aa35f6aSMatthias Ringwald                 break;
70787aa35f6aSMatthias Ringwald         }
70797aa35f6aSMatthias Ringwald     }
70802a6c0f82SMatthias Ringwald 
70812a6c0f82SMatthias Ringwald     // BIG Sync
70822a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
70832a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
70842a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
70852a6c0f82SMatthias Ringwald         switch (big_sync->state){
70862a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
708740f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
708840f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
70892a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
70902a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_create_sync,
70912a6c0f82SMatthias Ringwald                              big_sync->params->big_handle,
70922a6c0f82SMatthias Ringwald                              big_sync->params->sync_handle,
70932a6c0f82SMatthias Ringwald                              big_sync->params->encryption,
70942a6c0f82SMatthias Ringwald                              big_sync->params->broadcast_code,
70952a6c0f82SMatthias Ringwald                              big_sync->params->mse,
70962a6c0f82SMatthias Ringwald                              big_sync->params->big_sync_timeout_10ms,
70972a6c0f82SMatthias Ringwald                              big_sync->params->num_bis,
70982a6c0f82SMatthias Ringwald                              big_sync->params->bis_indices);
70992a6c0f82SMatthias Ringwald                 return true;
71002a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
71012a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
710285dc435bSDirk 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);
71032a6c0f82SMatthias Ringwald                 return true;
71042a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
71052a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
71062a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
7107c1f83111SMatthias Ringwald                 return true;
71082a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
71092a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
71102a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
71112a6c0f82SMatthias Ringwald                 return true;
71122a6c0f82SMatthias Ringwald             default:
71132a6c0f82SMatthias Ringwald                 break;
71142a6c0f82SMatthias Ringwald         }
71152a6c0f82SMatthias Ringwald     }
71162a6c0f82SMatthias Ringwald 
7117d3a89d91SMatthias Ringwald     // CIG
7118d90722d4SMatthias Ringwald     bool cig_active;
7119d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
7120d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
7121d3a89d91SMatthias Ringwald         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
7122d3a89d91SMatthias Ringwald         uint8_t i;
7123444e371eSMatthias Ringwald         // Set CIG Parameters
7124d3a89d91SMatthias Ringwald         uint8_t cis_id[MAX_NR_CIS];
7125d3a89d91SMatthias Ringwald         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
7126d3a89d91SMatthias Ringwald         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
7127d3a89d91SMatthias Ringwald         uint8_t phy_c_to_p[MAX_NR_CIS];
7128d3a89d91SMatthias Ringwald         uint8_t phy_p_to_c[MAX_NR_CIS];
7129d3a89d91SMatthias Ringwald         uint8_t rtn_c_to_p[MAX_NR_CIS];
7130d3a89d91SMatthias Ringwald         uint8_t rtn_p_to_c[MAX_NR_CIS];
7131d3a89d91SMatthias Ringwald         switch (cig->state) {
7132d3a89d91SMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE:
7133d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7134d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7135d3a89d91SMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
7136d3a89d91SMatthias Ringwald                 le_audio_cig_params_t * params = cig->params;
7137d3a89d91SMatthias Ringwald                 for (i = 0; i < params->num_cis; i++) {
7138d3a89d91SMatthias Ringwald                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
7139d3a89d91SMatthias Ringwald                     cis_id[i]         = cis_params->cis_id;
7140d3a89d91SMatthias Ringwald                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
7141d3a89d91SMatthias Ringwald                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
7142d3a89d91SMatthias Ringwald                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
7143d3a89d91SMatthias Ringwald                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
7144d3a89d91SMatthias Ringwald                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
7145d3a89d91SMatthias Ringwald                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
7146d3a89d91SMatthias Ringwald                 }
7147d3a89d91SMatthias Ringwald                 hci_send_cmd(&hci_le_set_cig_parameters,
7148d3a89d91SMatthias Ringwald                              cig->cig_id,
7149d3a89d91SMatthias Ringwald                              params->sdu_interval_c_to_p,
7150d3a89d91SMatthias Ringwald                              params->sdu_interval_p_to_c,
7151d3a89d91SMatthias Ringwald                              params->worst_case_sca,
7152d3a89d91SMatthias Ringwald                              params->packing,
7153d3a89d91SMatthias Ringwald                              params->framing,
7154d3a89d91SMatthias Ringwald                              params->max_transport_latency_c_to_p,
7155d3a89d91SMatthias Ringwald                              params->max_transport_latency_p_to_c,
7156d3a89d91SMatthias Ringwald                              params->num_cis,
7157d3a89d91SMatthias Ringwald                              cis_id,
7158d3a89d91SMatthias Ringwald                              max_sdu_c_to_p,
7159d3a89d91SMatthias Ringwald                              max_sdu_p_to_c,
7160d3a89d91SMatthias Ringwald                              phy_c_to_p,
7161d3a89d91SMatthias Ringwald                              phy_p_to_c,
7162d3a89d91SMatthias Ringwald                              rtn_c_to_p,
7163d3a89d91SMatthias Ringwald                              rtn_p_to_c
7164d3a89d91SMatthias Ringwald                 );
7165bb42b5c0SMatthias Ringwald                 return true;
7166444e371eSMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE_CIS:
7167bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7168bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7169444e371eSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
71703abcd16cSMatthias Ringwald                 for (i=0;i<cig->num_cis;i++){
71713abcd16cSMatthias Ringwald                     cig->cis_setup_active[i] = true;
71723abcd16cSMatthias Ringwald                 }
7173444e371eSMatthias Ringwald                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
7174bb42b5c0SMatthias Ringwald                 return true;
7175f9306a1aSMatthias Ringwald             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
7176c5f5d706SMatthias Ringwald                 for ( ; cig->state_vars.next_cis < (cig->num_cis * 2) ; cig->state_vars.next_cis++ ){
7177f9306a1aSMatthias Ringwald                     // find next path to setup
7178f9306a1aSMatthias Ringwald                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
7179f9306a1aSMatthias Ringwald                     if (cig->cis_established[cis_index] == false) {
7180f9306a1aSMatthias Ringwald                         continue;
7181f9306a1aSMatthias Ringwald                     }
7182f9306a1aSMatthias Ringwald                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
7183f9306a1aSMatthias Ringwald                     bool setup = true;
71848e58e4f7SMatthias Ringwald                     if (cis_direction == 0){
7185f9306a1aSMatthias Ringwald                         // 0 - input - host to controller
7186f9306a1aSMatthias Ringwald                         // we are central => central to peripheral
7187f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
7188f9306a1aSMatthias Ringwald                     } else {
7189f9306a1aSMatthias Ringwald                         // 1 - output - controller to host
7190f9306a1aSMatthias Ringwald                         // we are central => peripheral to central
7191f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
7192f9306a1aSMatthias Ringwald                     }
7193f9306a1aSMatthias Ringwald                     if (setup){
7194f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
7195f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
7196f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
719785dc435bSDirk 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);
7198f9306a1aSMatthias Ringwald                         return true;
7199f9306a1aSMatthias Ringwald                     }
7200f9306a1aSMatthias Ringwald                 }
7201f9306a1aSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
7202d90722d4SMatthias Ringwald                 break;
7203d90722d4SMatthias Ringwald             case LE_AUDIO_CIG_STATE_REMOVE:
7204d90722d4SMatthias Ringwald                 // check if CIG Active
7205d90722d4SMatthias Ringwald                 cig_active = false;
7206d90722d4SMatthias Ringwald                 for (i = 0; i < cig->num_cis; i++) {
7207d90722d4SMatthias Ringwald                     if (cig->cis_con_handles[i] != HCI_CON_HANDLE_INVALID){
7208d90722d4SMatthias Ringwald                         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
7209d90722d4SMatthias Ringwald                         if (stream != NULL){
7210d90722d4SMatthias Ringwald                             cig_active = true;
7211d90722d4SMatthias Ringwald                             break;
7212d90722d4SMatthias Ringwald                         }
7213d90722d4SMatthias Ringwald                     }
7214d90722d4SMatthias Ringwald                 }
7215d90722d4SMatthias Ringwald                 if (cig_active == false){
7216d90722d4SMatthias Ringwald                     btstack_linked_list_iterator_remove(&it);
7217d90722d4SMatthias Ringwald                     hci_send_cmd(&hci_le_remove_cig, cig->cig_id);
7218d90722d4SMatthias Ringwald                     return true;
7219d90722d4SMatthias Ringwald                 }
7220d3a89d91SMatthias Ringwald             default:
7221d3a89d91SMatthias Ringwald                 break;
7222d3a89d91SMatthias Ringwald         }
7223d3a89d91SMatthias Ringwald     }
7224d3a89d91SMatthias Ringwald 
7225d90722d4SMatthias Ringwald     // CIS Accept/Reject/Setup ISO Path/Close
722626b93350SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
722726b93350SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
722826b93350SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
722926b93350SMatthias Ringwald         hci_con_handle_t con_handle;
723026b93350SMatthias Ringwald         switch (iso_stream->state){
723126b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_ACCEPT:
723226b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
723326b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
723426b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
7235969d876aSMatthias Ringwald                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
723626b93350SMatthias Ringwald                 return true;
723726b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_REJECT:
7238969d876aSMatthias Ringwald                 con_handle = iso_stream->cis_handle;
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;
724126b93350SMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
724226b93350SMatthias Ringwald                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
724326b93350SMatthias Ringwald                 return true;
724426b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
724526b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
724626b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
724726b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
724885dc435bSDirk 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);
724907e32b36SMatthias Ringwald                 return true;
725026b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
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_OUTPUT;
725485dc435bSDirk 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);
725507e32b36SMatthias Ringwald                 return true;
7256d90722d4SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_CLOSE:
7257d90722d4SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_DISCONNECTED;
725807e32b36SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, iso_stream->cis_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
725907e32b36SMatthias Ringwald                 return true;
726026b93350SMatthias Ringwald             default:
726126b93350SMatthias Ringwald                 break;
726226b93350SMatthias Ringwald         }
726326b93350SMatthias Ringwald     }
726426b93350SMatthias Ringwald 
72657aa35f6aSMatthias Ringwald     return false;
72667aa35f6aSMatthias Ringwald }
72677aa35f6aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
7268b2f949feS[email protected] #endif
72697bdc6798S[email protected] 
727088a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
7271f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
7272a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
727305ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
727432ab9390Smatthias.ringwald 
72750bf6344aS[email protected]         switch(connection->state){
72760bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
72774f3229d8S[email protected]                 switch(connection->address_type){
727835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7279f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
72809da54300S[email protected]                         log_info("sending hci_create_connection");
7281b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
72824f3229d8S[email protected]                         break;
728335454696SMatthias Ringwald #endif
72844f3229d8S[email protected]                     default:
7285a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
7286d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
72879da54300S[email protected]                         log_info("sending hci_le_create_connection");
72886bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
72896bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
7290f346015eSMatthias Ringwald                         hci_send_le_create_connection(0, connection->address_type, connection->address);
72914f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
7292b2f949feS[email protected] #endif
7293d70217a2SMatthias Ringwald #endif
72944f3229d8S[email protected]                         break;
72954f3229d8S[email protected]                 }
7296f30077b7SMatthias Ringwald                 return true;
7297ad83dc6aS[email protected] 
729835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
72990bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
7300f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
730176ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
7302895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
7303c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
7304f30077b7SMatthias Ringwald                     return true;
7305ee025741SMatthias Ringwald                 }
7306ee025741SMatthias Ringwald                 break;
730735454696SMatthias Ringwald #endif
73080bf6344aS[email protected]             case SEND_DISCONNECT:
73090bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
73106ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7311f30077b7SMatthias Ringwald                 return true;
73120bf6344aS[email protected] 
73130bf6344aS[email protected]             default:
73140bf6344aS[email protected]                 break;
7315c7e0c5f6Smatthias.ringwald         }
7316c7e0c5f6Smatthias.ringwald 
7317cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
7318cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
7319cabf004eSMatthias Ringwald 
732094418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
732194418890SMatthias Ringwald 
7322ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
732350f49832SMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
7324608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
73258daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
732630e72d78SMatthias Ringwald 
7327e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
7328e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
732930e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
7330e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
733132ab9390Smatthias.ringwald             } else {
733232ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
733332ab9390Smatthias.ringwald             }
7334f30077b7SMatthias Ringwald             return true;
733532ab9390Smatthias.ringwald         }
73361d6b20aeS[email protected] 
73378daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
73389da54300S[email protected]             log_info("denying to pin request");
73398daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
734034d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
7341f30077b7SMatthias Ringwald             return true;
73424c57c146S[email protected]         }
73434c57c146S[email protected] 
7344c950c316SMatthias Ringwald         // security assessment requires remote features
73452dd8985bSMatthias Ringwald         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
7346c950c316SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
7347c950c316SMatthias Ringwald             hci_ssp_assess_security_on_io_cap_request(connection);
7348c950c316SMatthias 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
7349c950c316SMatthias Ringwald         }
7350c950c316SMatthias Ringwald 
73518daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
73528daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7353a8d20135SMatthias Ringwald             // set authentication requirements:
7354a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7355532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7356cb912b12SMatthias Ringwald             connection->io_cap_request_auth_req = hci_stack->ssp_authentication_requirement & 1;
73579faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
7358cb912b12SMatthias Ringwald                 connection->io_cap_request_auth_req |= 1;
7359106d6d11S[email protected]             }
7360532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
73618daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7362532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
7363532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7364532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
7365532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
7366532454f9SMatthias Ringwald                     bonding = false;
7367532454f9SMatthias Ringwald                 }
7368532454f9SMatthias Ringwald             }
7369532454f9SMatthias Ringwald             if (bonding){
7370a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
7371cb912b12SMatthias Ringwald                     connection->io_cap_request_auth_req |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7372532454f9SMatthias Ringwald                 } else {
7373cb912b12SMatthias Ringwald                     connection->io_cap_request_auth_req |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7374a8d20135SMatthias Ringwald                 }
7375532454f9SMatthias Ringwald             }
73761849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
73771849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
73781849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
73791849becdSMatthias Ringwald                     have_oob_data |= 1;
73801849becdSMatthias Ringwald             }
73811849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
73821849becdSMatthias Ringwald                 have_oob_data |= 2;
73831849becdSMatthias Ringwald             }
73841849becdSMatthias Ringwald #endif
7385cb912b12SMatthias 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);
738611b03efaSMatthias Ringwald             return true;
7387f8fb5f6eS[email protected]         }
738811b03efaSMatthias Ringwald 
73898daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
73908daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
739111b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7392f30077b7SMatthias Ringwald             return true;
739332ab9390Smatthias.ringwald         }
739432ab9390Smatthias.ringwald 
73951849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
73967ca4a7edSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
73977ca4a7edSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
73981849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
73991849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
74001849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
74011849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
74021849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
74031849becdSMatthias Ringwald             // verify P-256 OOB
74041e83575aSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
74051849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
74061849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
74071849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
74081849becdSMatthias Ringwald                 }
74091849becdSMatthias Ringwald             }
74101849becdSMatthias Ringwald             // verify P-192 OOB
74111849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
74121849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
74131849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
74141849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
74151849becdSMatthias Ringwald                 }
74161849becdSMatthias Ringwald             }
74177ca4a7edSMatthias Ringwald 
74187ca4a7edSMatthias Ringwald             // assess security
74197ca4a7edSMatthias Ringwald             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
74207ca4a7edSMatthias Ringwald             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
74217ca4a7edSMatthias Ringwald             if (need_level_4 && !can_reach_level_4){
74227ca4a7edSMatthias Ringwald                 log_info("Level 4 required, but not possible -> abort");
74237ca4a7edSMatthias Ringwald                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
74247ca4a7edSMatthias Ringwald                 // send oob negative reply
74257ca4a7edSMatthias Ringwald                 c_256 = NULL;
74267ca4a7edSMatthias Ringwald                 c_192 = NULL;
74277ca4a7edSMatthias Ringwald             }
74287ca4a7edSMatthias Ringwald 
74291849becdSMatthias Ringwald             // Reply
74301849becdSMatthias Ringwald             if (c_256 != zero) {
74311849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
74321849becdSMatthias Ringwald             } else if (c_192 != zero){
74331849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
74341849becdSMatthias Ringwald             } else {
74351ae74bf3SMatthias Ringwald                 hci_stack->classic_oob_con_handle = connection->con_handle;
74361849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
74371849becdSMatthias Ringwald             }
74381849becdSMatthias Ringwald             return true;
74391849becdSMatthias Ringwald         }
74401849becdSMatthias Ringwald #endif
74411849becdSMatthias Ringwald 
74428daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
74438daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
744434d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7445f30077b7SMatthias Ringwald             return true;
7446dbe1a790S[email protected]         }
7447dbe1a790S[email protected] 
7448367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7449367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7450367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7451367aedc0SMatthias Ringwald             return true;
7452367aedc0SMatthias Ringwald         }
7453367aedc0SMatthias Ringwald 
74548daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
74558daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
745634d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7457f30077b7SMatthias Ringwald             return true;
7458dbe1a790S[email protected]         }
7459afd4e962S[email protected] 
7460ab0c69a9SMatthias Ringwald         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7461ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
74621bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
74636ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
74646ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7465f30077b7SMatthias Ringwald             return true;
7466ad83dc6aS[email protected]         }
746776f27cffSMatthias Ringwald 
74682a75353aSMatthias Ringwald         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
746934d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7470abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
747134d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7472f30077b7SMatthias Ringwald             return true;
7473afd4e962S[email protected]         }
747476f27cffSMatthias Ringwald 
7475dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7476dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7477dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7478f30077b7SMatthias Ringwald             return true;
7479dce78009S[email protected]         }
7480447016ffSMatthias Ringwald 
7481573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7482573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7483573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7484f30077b7SMatthias Ringwald             return true;
7485573897a0SMatthias Ringwald         }
7486447016ffSMatthias Ringwald 
7487447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7488447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7489447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7490447016ffSMatthias Ringwald             return true;
7491447016ffSMatthias Ringwald         }
7492447016ffSMatthias Ringwald 
7493447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7494447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7495447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7496447016ffSMatthias Ringwald             return true;
7497447016ffSMatthias Ringwald         }
7498447016ffSMatthias Ringwald 
7499447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7500447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7501447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7502447016ffSMatthias Ringwald             return true;
7503447016ffSMatthias Ringwald         }
750476f27cffSMatthias Ringwald #endif
750576f27cffSMatthias Ringwald 
750676f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
750776f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
75081714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
75091714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
75101714cbbdSMatthias Ringwald #endif
75116ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
75126ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
75136ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7514f30077b7SMatthias Ringwald                 return true;
751576f27cffSMatthias Ringwald             }
75166ef3696aSMatthias Ringwald         }
7517da886c03S[email protected] 
75186cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
7519f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
7520f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
7521f8ee3071SMatthias Ringwald             case 0:
7522f8ee3071SMatthias Ringwald                 break;
7523f8ee3071SMatthias Ringwald             case 0xffff:
7524f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7525f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7526f30077b7SMatthias Ringwald                 return true;
7527f8ee3071SMatthias Ringwald             default:
7528f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
7529f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7530f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7531f30077b7SMatthias Ringwald                 return true;
7532f8ee3071SMatthias Ringwald         }
753388a03c8dSMatthias Ringwald 
7534140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
7535140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
7536140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
7537140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7538140c0557SMatthias Ringwald             return true;
7539140c0557SMatthias Ringwald         }
7540140c0557SMatthias Ringwald 
7541965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7542278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
7543965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7544278ff8a9SMatthias 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);
7545278ff8a9SMatthias Ringwald             return true;
7546278ff8a9SMatthias Ringwald         }
7547278ff8a9SMatthias Ringwald 
754888a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
754988a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
755088a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
755188a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
755288a03c8dSMatthias Ringwald             return true;
755388a03c8dSMatthias Ringwald         }
755422df2fe2SMatthias Ringwald #endif
75559afaa4d4SMatthias Ringwald 
75569afaa4d4SMatthias Ringwald         if (connection->gap_connection_tasks != 0){
755722df2fe2SMatthias Ringwald #ifdef ENABLE_CLASSIC
75589afaa4d4SMatthias Ringwald             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
75599afaa4d4SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
75609afaa4d4SMatthias Ringwald                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
75619afaa4d4SMatthias Ringwald                 return true;
75629afaa4d4SMatthias Ringwald             }
756322df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
756422df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
756522df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
756622df2fe2SMatthias Ringwald                 return true;
75679afaa4d4SMatthias Ringwald             }
75686cdc2862SMatthias Ringwald #endif
756922df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
757022df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
757122df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
757222df2fe2SMatthias Ringwald                 return true;
757322df2fe2SMatthias Ringwald             }
7574ac0f6b83SMatthias Ringwald #ifdef ENABLE_BLE
7575ac0f6b83SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7576ac0f6b83SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7577ac0f6b83SMatthias Ringwald                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7578ac0f6b83SMatthias Ringwald                 return true;
7579ac0f6b83SMatthias Ringwald             }
7580ac0f6b83SMatthias Ringwald #endif
758122df2fe2SMatthias Ringwald         }
7582f8ee3071SMatthias Ringwald 
7583a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
758473cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
758573cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
758673cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7587da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
758873cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7589c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7590d4876126SMatthias Ringwald                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7591f30077b7SMatthias Ringwald                 return true;
759273cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
759373cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
759473cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
759573cd8a2aSMatthias Ringwald                              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_NEGATIVE_REPLY:
759973cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
76001e0338ebSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
76011e0338ebSMatthias Ringwald                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7602f30077b7SMatthias Ringwald                 return true;
760373cd8a2aSMatthias Ringwald             default:
760473cd8a2aSMatthias Ringwald                 break;
7605c37a3166S[email protected]         }
76064ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
7607b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
7608b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
7609b90f6e0aSMatthias 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);
7610f30077b7SMatthias Ringwald             return true;
7611b90f6e0aSMatthias Ringwald         }
76129007c891SMatthias Ringwald         if (connection->le_subrate_min > 0){
76139007c891SMatthias Ringwald             uint16_t subrate_min = connection->le_subrate_min;
76149007c891SMatthias Ringwald             connection->le_subrate_min = 0;
76159007c891SMatthias Ringwald             hci_send_cmd(&hci_le_subrate_request, connection->con_handle, subrate_min, connection->le_subrate_max, connection->le_subrate_max_latency,
76169007c891SMatthias Ringwald                              connection->le_subrate_continuation_number, connection->le_supervision_timeout);
76179007c891SMatthias Ringwald             return true;
76189007c891SMatthias Ringwald         }
76193bd96807SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
76203bd96807SMatthias Ringwald         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
76213bd96807SMatthias Ringwald             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
76223bd96807SMatthias Ringwald             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
76233bd96807SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
76243bd96807SMatthias Ringwald             return true;
76253bd96807SMatthias Ringwald         }
7626027f4677SMatthias Ringwald         if (connection->le_past_advertising_handle != 0xff){
7627027f4677SMatthias Ringwald             uint8_t advertising_handle = connection->le_past_advertising_handle;
7628027f4677SMatthias Ringwald             connection->le_past_advertising_handle = 0xff;
7629027f4677SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7630027f4677SMatthias Ringwald             return true;
7631027f4677SMatthias Ringwald         }
76323bd96807SMatthias Ringwald #endif
7633c37a3166S[email protected] #endif
7634dbe1a790S[email protected]     }
7635f30077b7SMatthias Ringwald     return false;
7636f30077b7SMatthias Ringwald }
7637c7e0c5f6Smatthias.ringwald 
7638f30077b7SMatthias Ringwald static void hci_run(void){
7639f30077b7SMatthias Ringwald 
7640df9e2780SMatthias Ringwald     // stack state sub statemachines
7641df9e2780SMatthias Ringwald     switch (hci_stack->state) {
7642df9e2780SMatthias Ringwald         case HCI_STATE_INITIALIZING:
7643df9e2780SMatthias Ringwald             hci_initializing_run();
7644d0dea5fbSMatthias Ringwald             break;
7645df9e2780SMatthias Ringwald         case HCI_STATE_HALTING:
7646df9e2780SMatthias Ringwald             hci_halting_run();
7647d0dea5fbSMatthias Ringwald             break;
7648df9e2780SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
7649df9e2780SMatthias Ringwald             hci_falling_asleep_run();
7650d0dea5fbSMatthias Ringwald             break;
7651df9e2780SMatthias Ringwald         default:
7652df9e2780SMatthias Ringwald             break;
7653df9e2780SMatthias Ringwald     }
7654df9e2780SMatthias Ringwald 
7655d0dea5fbSMatthias Ringwald     // allow to run after initialization to working transition
7656d0dea5fbSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING){
7657d0dea5fbSMatthias Ringwald         return;
7658d0dea5fbSMatthias Ringwald     }
7659d0dea5fbSMatthias Ringwald 
7660f30077b7SMatthias Ringwald     bool done;
7661f30077b7SMatthias Ringwald 
7662f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
7663f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
7664f30077b7SMatthias Ringwald     if (done) return;
7665f30077b7SMatthias Ringwald 
766668ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
766768ab6207SMatthias Ringwald     done = hci_run_iso_fragments();
766868ab6207SMatthias Ringwald     if (done) return;
766968ab6207SMatthias Ringwald #endif
767068ab6207SMatthias Ringwald 
7671f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7672f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
7673c69be560SMatthias Ringwald     if (!hci_can_send_command_packet_transport()) return;
7674f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
7675f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
7676f30077b7SMatthias Ringwald         return;
7677f30077b7SMatthias Ringwald     }
7678f30077b7SMatthias Ringwald #endif
7679f30077b7SMatthias Ringwald 
7680f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
7681f30077b7SMatthias Ringwald 
7682f30077b7SMatthias Ringwald     // global/non-connection oriented commands
7683f30077b7SMatthias Ringwald 
7684f30077b7SMatthias Ringwald 
7685f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
7686f30077b7SMatthias Ringwald     // general gap classic
7687f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
7688f30077b7SMatthias Ringwald     if (done) return;
7689f30077b7SMatthias Ringwald #endif
7690f30077b7SMatthias Ringwald 
7691f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
7692f30077b7SMatthias Ringwald     // general gap le
7693f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
7694f30077b7SMatthias Ringwald     if (done) return;
76957aa35f6aSMatthias Ringwald 
76967aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
76977aa35f6aSMatthias Ringwald     // ISO related tasks, e.g. BIG create/terminate/sync
76987aa35f6aSMatthias Ringwald     done = hci_run_iso_tasks();
76997aa35f6aSMatthias Ringwald     if (done) return;
77007aa35f6aSMatthias Ringwald #endif
7701f30077b7SMatthias Ringwald #endif
7702f30077b7SMatthias Ringwald 
7703f30077b7SMatthias Ringwald     // send pending HCI commands
7704df9e2780SMatthias Ringwald     hci_run_general_pending_commands();
77053429f56bSmatthias.ringwald }
770616833f0aSmatthias.ringwald 
77070f076adeSMatthias Ringwald #ifdef ENABLE_CLASSIC
7708d7891039SMatthias Ringwald static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7709d7891039SMatthias Ringwald     // bits 6-9 are 'don't use'
7710d7891039SMatthias Ringwald     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7711d7891039SMatthias Ringwald 
7712d7891039SMatthias Ringwald     // restrict packet types to local and remote supported
7713d7891039SMatthias Ringwald     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7714d7891039SMatthias Ringwald     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7715d7891039SMatthias Ringwald     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7716d7891039SMatthias Ringwald }
77170f076adeSMatthias Ringwald #endif
7718d7891039SMatthias Ringwald 
7719ca6804fdSMatthias Ringwald // funnel for sending cmd packet using single outgoing buffer
7720ed208344SMatthias Ringwald static uint8_t hci_send_prepared_cmd_packet(void) {
7721ca6804fdSMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
7722f91accd3SMatthias Ringwald     // cache opcode
7723f91accd3SMatthias Ringwald     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
7724f91accd3SMatthias Ringwald     // get size
7725ca6804fdSMatthias Ringwald     uint16_t size = 3u + hci_stack->hci_packet_buffer[2u];
7726f91accd3SMatthias Ringwald     // send packet
7727ca6804fdSMatthias Ringwald     uint8_t status = hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
7728ca6804fdSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
7729ca6804fdSMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7730ca6804fdSMatthias Ringwald         hci_release_packet_buffer();
7731ca6804fdSMatthias Ringwald     }
7732ca6804fdSMatthias Ringwald     return status;
7733ca6804fdSMatthias Ringwald }
7734ca6804fdSMatthias Ringwald 
77353e2050f7SMatthias Ringwald uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
773635454696SMatthias Ringwald     // house-keeping
773735454696SMatthias Ringwald 
773835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7739c8e4258aSmatthias.ringwald     bd_addr_t addr;
7740c8e4258aSmatthias.ringwald     hci_connection_t * conn;
7741c123d999SMatthias Ringwald #endif
7742c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
77436f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
77449cbd2215SMatthias Ringwald #endif
7745c8e4258aSmatthias.ringwald 
77466f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
77476f35bb46SMatthias Ringwald     switch (opcode) {
77489cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
77499cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
77509cbd2215SMatthias Ringwald             break;
77519cbd2215SMatthias Ringwald 
77529cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
77536f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7754724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
77559da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
7756c8e4258aSmatthias.ringwald 
775772cf8859SMatthias Ringwald             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
775872cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
775979e0fa07SMatthias Ringwald                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
77603e2050f7SMatthias Ringwald                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
776172cf8859SMatthias Ringwald             }
776272cf8859SMatthias Ringwald 
7763f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7764ad83dc6aS[email protected]             if (!conn) {
776588f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
776617f1ba2aSmatthias.ringwald                 if (!conn) {
776717f1ba2aSmatthias.ringwald                     // notify client that alloc failed
77682deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
77693e2050f7SMatthias Ringwald                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
777017f1ba2aSmatthias.ringwald                 }
7771ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
7772ad83dc6aS[email protected]             }
7773aee5d5c1SMatthias Ringwald 
7774ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
77753e2050f7SMatthias Ringwald             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7776ad83dc6aS[email protected]             switch (conn->state) {
7777ad83dc6aS[email protected]                 // if connection active exists
7778ad83dc6aS[email protected]                 case OPEN:
7779f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
778072cf8859SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
77813e2050f7SMatthias Ringwald                     // packet not sent to controller
77823e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7783672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
7784672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
7785672e36abSMatthias Ringwald                     break;
7786ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
77876c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
77886c0d5426SMatthias Ringwald                     if (hci_classic_operation_active()){
77896c0d5426SMatthias Ringwald                         return ERROR_CODE_SUCCESS;
77906c0d5426SMatthias Ringwald                     }
77916c0d5426SMatthias Ringwald #endif
7792532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7793532f91a5SMatthias Ringwald                     break;
7794ad83dc6aS[email protected]                 default:
7795ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
77963e2050f7SMatthias Ringwald                     // packet not sent to controller
77973e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7798ad83dc6aS[email protected]             }
7799c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
7800229331c6SMatthias Ringwald 
7801229331c6SMatthias Ringwald             // track outgoing connection
7802f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
78036535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
78046f35bb46SMatthias Ringwald             break;
7805ee752bb8SMatthias Ringwald 
78066f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
78079071873aSMatthias Ringwald             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
78089071873aSMatthias Ringwald             if (conn == NULL) {
78099071873aSMatthias Ringwald                 // neither SCO nor ACL connection for con handle
78109071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
78119071873aSMatthias Ringwald             } else {
7812d7891039SMatthias Ringwald                 uint16_t remote_supported_sco_packets;
78139071873aSMatthias Ringwald                 switch (conn->address_type){
78149071873aSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
78159071873aSMatthias Ringwald                         // assert SCO connection does not exit
7816d9290e95SMatthias Ringwald                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
78179071873aSMatthias Ringwald                             return ERROR_CODE_COMMAND_DISALLOWED;
78189071873aSMatthias Ringwald                         }
7819d7891039SMatthias Ringwald                         // cache remote sco packet types
7820d7891039SMatthias Ringwald                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7821d7891039SMatthias Ringwald 
78229071873aSMatthias Ringwald                         // allocate connection struct
782388f925b1SMatthias Ringwald                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
782488f925b1SMatthias Ringwald                                                                       HCI_ROLE_MASTER);
78259071873aSMatthias Ringwald                         if (!conn) {
78269071873aSMatthias Ringwald                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
78279071873aSMatthias Ringwald                         }
7828d7891039SMatthias Ringwald                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
78299071873aSMatthias Ringwald                         break;
78309071873aSMatthias Ringwald                     case BD_ADDR_TYPE_SCO:
78319071873aSMatthias Ringwald                         // update of existing SCO connection
78329071873aSMatthias Ringwald                         break;
78339071873aSMatthias Ringwald                     default:
78349071873aSMatthias Ringwald                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
78359071873aSMatthias Ringwald                 }
78369071873aSMatthias Ringwald             }
7837d9290e95SMatthias Ringwald 
7838d9290e95SMatthias Ringwald             // conn refers to hci connection of type sco now
7839d9290e95SMatthias Ringwald 
78409071873aSMatthias Ringwald             conn->state = SENT_CREATE_CONNECTION;
78419071873aSMatthias Ringwald 
78429071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
78439071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
7844f728a932SMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, conn->address, 6);
78459071873aSMatthias Ringwald 
7846ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
7847ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7848ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7849d7891039SMatthias Ringwald 
7850d7891039SMatthias Ringwald             // derive sco payload length from packet types
7851d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
78526f35bb46SMatthias Ringwald             break;
78539071873aSMatthias Ringwald 
78546f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
78559071873aSMatthias Ringwald             // get SCO connection
78569071873aSMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
78579071873aSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
78589071873aSMatthias Ringwald             if (conn == NULL){
78599071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
78609071873aSMatthias Ringwald             }
78619071873aSMatthias Ringwald 
78629071873aSMatthias Ringwald             conn->state = ACCEPTED_CONNECTION_REQUEST;
78639071873aSMatthias Ringwald 
78649071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
78659071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
78669071873aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
78679071873aSMatthias Ringwald 
7868c91e6e4fSMatthias Ringwald             // accept_synchronous_connection? Voice setting at offset 18
7869ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7870ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7871d7891039SMatthias Ringwald 
7872d7891039SMatthias Ringwald             // derive sco payload length from packet types
7873d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
78746f35bb46SMatthias Ringwald             break;
7875ee752bb8SMatthias Ringwald #endif
78764b3e1e19SMatthias Ringwald 
7877a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
7878d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
78796f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7880b04dfa37SMatthias Ringwald             // white list used?
78816f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
7882b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
7883b04dfa37SMatthias Ringwald                 case 0:
7884b04dfa37SMatthias Ringwald                     // whitelist not used
7885b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7886b04dfa37SMatthias Ringwald                     break;
7887b04dfa37SMatthias Ringwald                 case 1:
7888b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7889b04dfa37SMatthias Ringwald                     break;
7890b04dfa37SMatthias Ringwald                 default:
7891b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7892b04dfa37SMatthias Ringwald                     break;
7893b04dfa37SMatthias Ringwald             }
7894c163146eSMatthias Ringwald             // track outgoing connection
78958f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7896c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
78976f35bb46SMatthias Ringwald             break;
78988f7da641SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
78998f7da641SMatthias Ringwald         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
79008f7da641SMatthias Ringwald             // white list used?
79018f7da641SMatthias Ringwald             initiator_filter_policy = packet[3];
79028f7da641SMatthias Ringwald             switch (initiator_filter_policy) {
79038f7da641SMatthias Ringwald                 case 0:
79048f7da641SMatthias Ringwald                     // whitelist not used
79058f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
79068f7da641SMatthias Ringwald                     break;
79078f7da641SMatthias Ringwald                 case 1:
79088f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
79098f7da641SMatthias Ringwald                     break;
79108f7da641SMatthias Ringwald                 default:
79118f7da641SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
79128f7da641SMatthias Ringwald                     break;
79138f7da641SMatthias Ringwald             }
79148f7da641SMatthias Ringwald             // track outgoing connection
79158f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
79168f7da641SMatthias Ringwald             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
79178f7da641SMatthias Ringwald             break;
79188f7da641SMatthias Ringwald #endif
79196f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
79206ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
79216f35bb46SMatthias Ringwald             break;
79229cbd2215SMatthias Ringwald #endif
792391036612SMatthias Ringwald #ifdef ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS_WORKAROUND
7924f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CONNECTION_UPDATE:
7925f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_REMOTE_USED_FEATURES:
7926f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_START_ENCRYPTION:
7927f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_REQUEST_REPLY:
7928f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_LONG_TERM_KEY_NEGATIVE_REPLY:
7929f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY:
7930f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY:
7931f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_DATA_LENGTH:
7932f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_PHY:
7933f48a5586SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_PHY:
7934f48a5586SMatthias Ringwald             // conection handle is first command parameter
7935f48a5586SMatthias Ringwald             hci_stack->hci_command_con_handle = little_endian_read_16(packet, 3);
7936f48a5586SMatthias Ringwald             break;
7937f48a5586SMatthias Ringwald #endif
79384ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
79396f35bb46SMatthias Ringwald         default:
79406f35bb46SMatthias Ringwald             break;
7941b04dfa37SMatthias Ringwald     }
794269a97523S[email protected] 
79433a9fb326S[email protected]     hci_stack->num_cmd_packets--;
79445bb5bc3eS[email protected] 
79455bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
79463e2050f7SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
7947a84946b2SMatthias Ringwald     uint8_t status;
7948a84946b2SMatthias Ringwald     if (err == 0){
7949a84946b2SMatthias Ringwald         status = ERROR_CODE_SUCCESS;
7950a84946b2SMatthias Ringwald     } else {
7951a84946b2SMatthias Ringwald         status = ERROR_CODE_HARDWARE_FAILURE;
79523e2050f7SMatthias Ringwald     }
7953a84946b2SMatthias Ringwald     return status;
795431452debSmatthias.ringwald }
79558adf0ddaSmatthias.ringwald 
79562bd8b7e7S[email protected] // disconnect because of security block
79572bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
79582bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
79592bd8b7e7S[email protected]     if (!connection) return;
79602bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
79612bd8b7e7S[email protected] }
79622bd8b7e7S[email protected] 
79632bd8b7e7S[email protected] 
7964dbe1a790S[email protected] // Configure Secure Simple Pairing
7965dbe1a790S[email protected] 
796635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
796735454696SMatthias Ringwald 
7968dbe1a790S[email protected] // enable will enable SSP during init
796915a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
79703a9fb326S[email protected]     hci_stack->ssp_enable = enable;
7971dbe1a790S[email protected] }
7972dbe1a790S[email protected] 
797395d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
797415a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
79752bd8b7e7S[email protected] }
79762bd8b7e7S[email protected] 
7977dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
797815a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
79793a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
7980dbe1a790S[email protected] }
798115a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
79823a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
7983dbe1a790S[email protected] }
7984dbe1a790S[email protected] 
7985a086dc35SMatthias Ringwald // if set, BTstack will confirm a numeric comparison and enter '000000' if requested
798615a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
79873a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
7988dbe1a790S[email protected] }
79895d23aae8SMatthias Ringwald 
79905d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
79915d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
79925d23aae8SMatthias Ringwald }
799322d445d8SMatthias Ringwald bool gap_secure_connections_active(void){
7994eaf85bc8SMatthias Ringwald     return hci_stack->secure_connections_active;
799522d445d8SMatthias Ringwald }
79965d23aae8SMatthias Ringwald 
799735454696SMatthias Ringwald #endif
7998dbe1a790S[email protected] 
799994be1a66SMatthias Ringwald // va_list part of hci_send_cmd
80003e2050f7SMatthias Ringwald uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
8001d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
80029d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
80033e2050f7SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
80049d14b626S[email protected]     }
80059d14b626S[email protected] 
80069d14b626S[email protected]     hci_reserve_packet_buffer();
8007f91accd3SMatthias Ringwald     hci_cmd_create_from_template(hci_stack->hci_packet_buffer, cmd, argptr);
8008ca6804fdSMatthias Ringwald     return hci_send_prepared_cmd_packet();
800994be1a66SMatthias Ringwald }
80109d14b626S[email protected] 
801194be1a66SMatthias Ringwald /**
8012a086dc35SMatthias Ringwald  * pre: num_commands >= 0 - it's allowed to send a command to the controller
801394be1a66SMatthias Ringwald  */
80143e2050f7SMatthias Ringwald uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
80151cd208adSmatthias.ringwald     va_list argptr;
80161cd208adSmatthias.ringwald     va_start(argptr, cmd);
80173e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
80181cd208adSmatthias.ringwald     va_end(argptr);
80193e2050f7SMatthias Ringwald     return status;
802093b8dc03Smatthias.ringwald }
8021c8e4258aSmatthias.ringwald 
80229da9850bSMatthias Ringwald // Forward HCI events and create non-HCI events
8023ee091cf1Smatthias.ringwald 
8024d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
8025fb37a842SMatthias Ringwald     // dump packet
8026d6b06661SMatthias Ringwald     if (dump) {
802792da54c4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
8028d6b06661SMatthias Ringwald     }
80291ef6bb52SMatthias Ringwald 
8030fb37a842SMatthias Ringwald     // dispatch to all event handlers
80311ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
80321ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
80331ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
80341ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
8035d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
80361ef6bb52SMatthias Ringwald     }
8037d6b06661SMatthias Ringwald }
8038d6b06661SMatthias Ringwald 
80399da9850bSMatthias Ringwald static void hci_emit_btstack_event(uint8_t * event, uint16_t size, int dump){
80409da9850bSMatthias Ringwald #ifndef ENABLE_LOG_BTSTACK_EVENTS
80419da9850bSMatthias Ringwald     dump = 0;
80429da9850bSMatthias Ringwald #endif
80439da9850bSMatthias Ringwald     hci_emit_event(event, size, dump);
80449da9850bSMatthias Ringwald }
80459da9850bSMatthias Ringwald 
8046d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
8047fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
80483d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
8049d6b06661SMatthias Ringwald }
8050d6b06661SMatthias Ringwald 
805135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
8052701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
80533bc639ceSMatthias Ringwald     // notify SCO sender if waiting
8054701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
8055701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
80563bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
8057701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
80589da9850bSMatthias Ringwald         hci_dump_btstack_event(event, sizeof(event));
80593d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
80603bc639ceSMatthias Ringwald     }
80613bc639ceSMatthias Ringwald }
80621cfb383eSMatthias Ringwald 
80631cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
80649784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
8065ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
80661cfb383eSMatthias Ringwald 
80671cfb383eSMatthias Ringwald     uint8_t * eir_data;
80681cfb383eSMatthias Ringwald     ad_context_t context;
80691cfb383eSMatthias Ringwald     const uint8_t * name;
80701cfb383eSMatthias Ringwald     uint8_t         name_len;
80711cfb383eSMatthias Ringwald 
80729784dac1SMatthias Ringwald     if (size < 3) return;
80739784dac1SMatthias Ringwald 
80741cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
8075a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
80761cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
80771cfb383eSMatthias Ringwald 
80789784dac1SMatthias Ringwald     switch (event_type){
80799784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
80809784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
80819784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
80829784dac1SMatthias Ringwald             break;
80839784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
80849784dac1SMatthias Ringwald             if (size != 257) return;
80859784dac1SMatthias Ringwald             if (num_responses != 1) return;
80869784dac1SMatthias Ringwald             break;
80879784dac1SMatthias Ringwald         default:
80889784dac1SMatthias Ringwald             return;
80899784dac1SMatthias Ringwald     }
80909784dac1SMatthias Ringwald 
80911cfb383eSMatthias Ringwald     // event[1] is set at the end
80921cfb383eSMatthias Ringwald     int i;
80931cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
80941cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
80951cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
8096ac973fd6SMatthias Ringwald         uint8_t event_size = 27;    // if name is not set by EIR
80971cfb383eSMatthias Ringwald 
80986535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
80990e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
81006535961aSMatthias Ringwald         (void)memcpy(&event[9],
81016535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
81026535961aSMatthias Ringwald                      3); // class of device
81036535961aSMatthias Ringwald         (void)memcpy(&event[12],
81046535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
81056535961aSMatthias Ringwald                      2); // clock offset
81061cfb383eSMatthias Ringwald 
81071cfb383eSMatthias Ringwald         switch (event_type){
81081cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
81091cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
81101cfb383eSMatthias Ringwald                 break;
81111cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
81121cfb383eSMatthias Ringwald                 event[14] = 1;
8113a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
81141cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
81151cfb383eSMatthias Ringwald                 break;
81161cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
81171cfb383eSMatthias Ringwald                 event[14] = 1;
8118a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
811979186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
81201cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
81211cfb383eSMatthias Ringwald                 name = NULL;
8122a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
8123a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
81241cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
81251cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
81261cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
8127ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
81281cfb383eSMatthias Ringwald                     switch (data_type){
81291cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
81301cfb383eSMatthias Ringwald                             if (name) continue;
8131cf373d3aSMatthias Ringwald                             /* fall through */
81321cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
81331cfb383eSMatthias Ringwald                             name = data;
81341cfb383eSMatthias Ringwald                             name_len = data_size;
81351cfb383eSMatthias Ringwald                             break;
8136ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
8137ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
8138ac9136ccSMatthias Ringwald                             event[16] = 1;
81393c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
8140ac9136ccSMatthias Ringwald                             break;
81411cfb383eSMatthias Ringwald                         default:
81421cfb383eSMatthias Ringwald                             break;
81431cfb383eSMatthias Ringwald                     }
81441cfb383eSMatthias Ringwald                 }
81451cfb383eSMatthias Ringwald                 if (name){
8146ac9136ccSMatthias Ringwald                     event[25] = 1;
81471cfb383eSMatthias Ringwald                     // truncate name if needed
81481cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
8149ac9136ccSMatthias Ringwald                     event[26] = len;
8150ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
81511cfb383eSMatthias Ringwald                     event_size += len;
81521cfb383eSMatthias Ringwald                 }
81531cfb383eSMatthias Ringwald                 break;
81547bbeb3adSMilanka Ringwald             default:
81557bbeb3adSMilanka Ringwald                 return;
81561cfb383eSMatthias Ringwald         }
81571cfb383eSMatthias Ringwald         event[1] = event_size - 2;
81589da9850bSMatthias Ringwald         hci_emit_btstack_event(event, event_size, 1);
81591cfb383eSMatthias Ringwald     }
81601cfb383eSMatthias Ringwald }
816135454696SMatthias Ringwald #endif
81623bc639ceSMatthias Ringwald 
816371de195eSMatthias Ringwald void hci_emit_state(void){
81643a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
8165425d1371Smatthias.ringwald     uint8_t event[3];
816680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
81674ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
81683a9fb326S[email protected]     event[2] = hci_stack->state;
81699da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8170c8e4258aSmatthias.ringwald }
8171c8e4258aSmatthias.ringwald 
817235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
81732deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
8174425d1371Smatthias.ringwald     uint8_t event[13];
8175c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
8176425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
817717f1ba2aSmatthias.ringwald     event[2] = status;
81782deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
81792deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
8180c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
8181c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
81829da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8183c8e4258aSmatthias.ringwald }
818452db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
818552db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
818652db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
818752db98b2SMatthias Ringwald     uint8_t event[4];
818852db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
818952db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
819052db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
81919da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
819252db98b2SMatthias Ringwald }
819335454696SMatthias Ringwald #endif
8194c8e4258aSmatthias.ringwald 
819535454696SMatthias Ringwald #ifdef ENABLE_BLE
8196d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8197667ba9d1SMatthias 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){
8198ebd1b979SMatthias Ringwald     uint8_t hci_event[21];
8199ebd1b979SMatthias Ringwald     hci_event[0] = HCI_EVENT_LE_META;
8200ebd1b979SMatthias Ringwald     hci_event[1] = sizeof(hci_event) - 2u;
8201ebd1b979SMatthias Ringwald     hci_event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
8202ebd1b979SMatthias Ringwald     hci_event[3] = status;
8203ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 4, con_handle);
8204ebd1b979SMatthias Ringwald     hci_event[6] = 0; // TODO: role
8205ebd1b979SMatthias Ringwald     hci_event[7] = address_type;
8206ebd1b979SMatthias Ringwald     reverse_bd_addr(address, &hci_event[8]);
8207ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 14, 0); // interval
8208ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 16, 0); // latency
8209ebd1b979SMatthias Ringwald     little_endian_store_16(hci_event, 18, 0); // supervision timeout
8210ebd1b979SMatthias Ringwald     hci_event[20] = 0; // master clock accuracy
82119da9850bSMatthias Ringwald     hci_emit_btstack_event(hci_event, sizeof(hci_event), 1);
8212ebd1b979SMatthias Ringwald     // emit GAP event, too
8213ebd1b979SMatthias Ringwald     uint8_t gap_event[36];
8214ebd1b979SMatthias Ringwald     hci_create_gap_connection_complete_event(hci_event, gap_event);
82159da9850bSMatthias Ringwald     hci_emit_btstack_event(gap_event, sizeof(gap_event), 1);
82164f3229d8S[email protected] }
821735454696SMatthias Ringwald #endif
8218d70217a2SMatthias Ringwald #endif
82194f3229d8S[email protected] 
8220fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
8221fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
8222fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
82239da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
8224fd43c0e0SMatthias Ringwald }
8225fd43c0e0SMatthias Ringwald 
8226fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
8227425d1371Smatthias.ringwald     uint8_t event[6];
82283c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
82294ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
82303c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
8231fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
82323c4d4b90Smatthias.ringwald     event[5] = reason;
82339da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
82343c4d4b90Smatthias.ringwald }
82353c4d4b90Smatthias.ringwald 
8236b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
8237e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
8238425d1371Smatthias.ringwald     uint8_t event[3];
823980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
82404ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
824143bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
82429da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
824343bfb1bdSmatthias.ringwald }
8244038bc64cSmatthias.ringwald 
8245b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
8246e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
8247425d1371Smatthias.ringwald     uint8_t event[2];
824880d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
82494ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
82509da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8251038bc64cSmatthias.ringwald }
82521b0e3922Smatthias.ringwald 
825335454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
825435454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
825535454696SMatthias Ringwald     uint8_t event[9];
825635454696SMatthias Ringwald     int pos = 0;
825735454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
82584ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
825935454696SMatthias Ringwald     event[pos++] = status;
826035454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
82619da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8262381fbed8Smatthias.ringwald }
8263458bf4e8S[email protected] 
826435454696SMatthias Ringwald 
826535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
826635454696SMatthias Ringwald 
8267b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
8268df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
8269a00031e2S[email protected]     uint8_t event[5];
8270e00caf9cS[email protected]     int pos = 0;
82715611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
8272e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
8273f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
8274e00caf9cS[email protected]     pos += 2;
8275e00caf9cS[email protected]     event[pos++] = level;
82769da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8277e00caf9cS[email protected] }
8278e00caf9cS[email protected] 
827935454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
828035454696SMatthias Ringwald     if (!connection) return LEVEL_0;
82818daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
8282fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
82838daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
8284170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
82854051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
8286a086dc35SMatthias Ringwald     // LEVEL 4 always requires 128 bit encryption key size
82870e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
8288170fafaeSMatthias Ringwald         security_level = LEVEL_3;
8289170fafaeSMatthias Ringwald     }
8290170fafaeSMatthias Ringwald     return security_level;
829135454696SMatthias Ringwald }
829235454696SMatthias Ringwald 
829371fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
829471fd255dSMatthias Ringwald     uint8_t event[4];
829571fd255dSMatthias Ringwald     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
829635454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
829771fd255dSMatthias Ringwald     event[2] = discoverable;
829871fd255dSMatthias Ringwald     event[3] = connectable;
82999da9850bSMatthias Ringwald     hci_emit_btstack_event(event, sizeof(event), 1);
8300ad83dc6aS[email protected] }
8301ad83dc6aS[email protected] 
830298a2fd1cSMatthias Ringwald // query if remote side supports eSCO
830320dcdd22SMatthias Ringwald bool hci_remote_esco_supported(hci_con_handle_t con_handle){
830498a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
830520dcdd22SMatthias Ringwald     if (!connection) return false;
830676ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
830798a2fd1cSMatthias Ringwald }
830898a2fd1cSMatthias Ringwald 
83090b78a447SMatthias Ringwald uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
83100b78a447SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
83110b78a447SMatthias Ringwald     if (!connection) return 0;
83120b78a447SMatthias Ringwald     return connection->remote_supported_sco_packets;
83130b78a447SMatthias Ringwald }
83140b78a447SMatthias Ringwald 
831567aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
831667aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
831767aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
831867aae551SMatthias Ringwald }
831967aae551SMatthias Ringwald 
83202bd8b7e7S[email protected] // query if remote side supports SSP
832120dcdd22SMatthias Ringwald bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
83222bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
832320dcdd22SMatthias Ringwald     if (!connection) return false;
832467aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
83252bd8b7e7S[email protected] }
83262bd8b7e7S[email protected] 
832720dcdd22SMatthias Ringwald bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
8328df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
8329df3354fcS[email protected] }
8330df3354fcS[email protected] 
83316ffc78ceSMatthias Ringwald /**
83326ffc78ceSMatthias Ringwald  * Check if remote supported features query has completed
83336ffc78ceSMatthias Ringwald  */
83346ffc78ceSMatthias Ringwald bool hci_remote_features_available(hci_con_handle_t handle){
83356ffc78ceSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(handle);
83366ffc78ceSMatthias Ringwald     if (!connection) return false;
83376ffc78ceSMatthias Ringwald     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
83386ffc78ceSMatthias Ringwald }
83396ffc78ceSMatthias Ringwald 
8340d6596031SMatthias Ringwald /**
8341d6596031SMatthias Ringwald  * Trigger remote supported features query
8342d6596031SMatthias Ringwald  */
8343c9742cd1SMatthias Ringwald 
8344c9742cd1SMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
8345c9742cd1SMatthias Ringwald     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
8346c9742cd1SMatthias Ringwald         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
8347c9742cd1SMatthias Ringwald     }
8348c9742cd1SMatthias Ringwald }
8349c9742cd1SMatthias Ringwald 
8350d6596031SMatthias Ringwald void hci_remote_features_query(hci_con_handle_t con_handle){
8351d6596031SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8352d6596031SMatthias Ringwald     if (!connection) return;
8353c9742cd1SMatthias Ringwald     hci_trigger_remote_features_for_connection(connection);
8354d6596031SMatthias Ringwald     hci_run();
8355d6596031SMatthias Ringwald }
8356d6596031SMatthias Ringwald 
8357458bf4e8S[email protected] // GAP API
8358458bf4e8S[email protected] /**
8359458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
8360458bf4e8S[email protected]  * @praram enabled
8361458bf4e8S[email protected]  */
83624c57c146S[email protected] void gap_set_bondable_mode(int enable){
83633a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
8364458bf4e8S[email protected] }
83654ef6443cSMatthias Ringwald /**
83664ef6443cSMatthias Ringwald  * @brief Get bondable mode.
83674ef6443cSMatthias Ringwald  * @return 1 if bondable
83684ef6443cSMatthias Ringwald  */
83694ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
83704ef6443cSMatthias Ringwald     return hci_stack->bondable;
83714ef6443cSMatthias Ringwald }
8372cb230b9dS[email protected] 
8373cb230b9dS[email protected] /**
837434d2123cS[email protected]  * @brief map link keys to security levels
8375cb230b9dS[email protected]  */
837634d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
837734d2123cS[email protected]     switch (link_key_type){
83783c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
83793c68dfa9S[email protected]             return LEVEL_4;
83803c68dfa9S[email protected]         case COMBINATION_KEY:
83813c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
83823c68dfa9S[email protected]             return LEVEL_3;
83833c68dfa9S[email protected]         default:
83843c68dfa9S[email protected]             return LEVEL_2;
83853c68dfa9S[email protected]     }
8386cb230b9dS[email protected] }
8387cb230b9dS[email protected] 
83888b35e16aSMatthias Ringwald /**
83898b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
83908b35e16aSMatthias Ringwald  */
839136c3546bSMatthias Ringwald bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
83928b35e16aSMatthias Ringwald     switch (link_key_type){
83938b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
83948b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
839536c3546bSMatthias Ringwald             return true;
83968b35e16aSMatthias Ringwald         default:
839736c3546bSMatthias Ringwald             return false;
83988b35e16aSMatthias Ringwald     }
83998b35e16aSMatthias Ringwald }
84008b35e16aSMatthias Ringwald 
84018b35e16aSMatthias Ringwald /**
84028b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
84038b35e16aSMatthias Ringwald  */
84047040ba26SMatthias Ringwald bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
84058b35e16aSMatthias Ringwald     switch (link_key_type){
84068b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
84078b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
84087040ba26SMatthias Ringwald             return true;
84098b35e16aSMatthias Ringwald         default:
84107040ba26SMatthias Ringwald             return false;
84118b35e16aSMatthias Ringwald     }
84128b35e16aSMatthias Ringwald }
84138b35e16aSMatthias Ringwald 
8414552b9260SMatthias Ringwald bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
84155127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
8416106d6d11S[email protected]     return level > LEVEL_2;
8417106d6d11S[email protected] }
8418106d6d11S[email protected] 
841934d2123cS[email protected] /**
842034d2123cS[email protected]  * @brief get current security level
842134d2123cS[email protected]  */
842234d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
842334d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
842434d2123cS[email protected]     if (!connection) return LEVEL_0;
842534d2123cS[email protected]     return gap_security_level_for_connection(connection);
842634d2123cS[email protected] }
842734d2123cS[email protected] 
8428cb230b9dS[email protected] /**
8429cb230b9dS[email protected]  * @brief request connection to device to
8430cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
8431cb230b9dS[email protected]  */
843234d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
843334d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
843434d2123cS[email protected]     if (!connection){
8435a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
843634d2123cS[email protected]         return;
843734d2123cS[email protected]     }
8438defbf200SMatthias Ringwald 
8439defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
8440defbf200SMatthias Ringwald 
8441bc00e12cSMatthias 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)
8442bc00e12cSMatthias Ringwald     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8443bc00e12cSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8444bc00e12cSMatthias Ringwald         requested_level = LEVEL_4;
8445bc00e12cSMatthias Ringwald     }
8446bc00e12cSMatthias Ringwald 
844734d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
844883d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
844983d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
845083d08d7cSMatthias Ringwald 
8451dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
8452dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8453dbd5dcc3SMatthias Ringwald     if (authentication_active){
84541cf0a6c8SMatthias Ringwald         // authentication already active
845583d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
845683d08d7cSMatthias Ringwald             // increase requested level as new level is higher
845783d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
845883d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
845983d08d7cSMatthias Ringwald         }
84601cf0a6c8SMatthias Ringwald     } else {
846183d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
846283d08d7cSMatthias Ringwald         if (requested_level <= current_level){
8463a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
846434d2123cS[email protected]             return;
846534d2123cS[email protected]         }
8466a00031e2S[email protected] 
8467e060c07dSMatthias Ringwald         // store request
846834d2123cS[email protected]         connection->requested_security_level = requested_level;
8469a00031e2S[email protected] 
84701cf0a6c8SMatthias Ringwald         // start to authenticate connection
84711eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
84727fdbaf79SMatthias Ringwald 
84737fdbaf79SMatthias Ringwald         // request remote features if not already active, also trigger hci_run
84747fdbaf79SMatthias Ringwald         hci_remote_features_query(con_handle);
8475e00caf9cS[email protected]     }
84761cf0a6c8SMatthias Ringwald }
8477ad83dc6aS[email protected] 
8478ad83dc6aS[email protected] /**
8479ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
8480ad83dc6aS[email protected]  * @param device
8481ad83dc6aS[email protected]  * @param request MITM protection
8482ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
8483ad83dc6aS[email protected]  */
8484ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8485ad83dc6aS[email protected] 
8486ad83dc6aS[email protected]     // create connection state machine
848788f925b1SMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8488ad83dc6aS[email protected] 
8489ad83dc6aS[email protected]     if (!connection){
8490ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
8491ad83dc6aS[email protected]     }
8492ad83dc6aS[email protected] 
84934cd03f8aSMatthias Ringwald     // delete link key
849415a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
8495ad83dc6aS[email protected] 
8496ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
8497ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
8498ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8499f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8500ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
8501ad83dc6aS[email protected] 
8502ad83dc6aS[email protected]     hci_run();
8503ad83dc6aS[email protected] 
8504ad83dc6aS[email protected]     return 0;
8505ad83dc6aS[email protected] }
85068e618f72S[email protected] 
8507f82b8f4bSMatthias Ringwald uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8508ab0c69a9SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8509ab0c69a9SMatthias Ringwald     if (connection == NULL){
8510ab0c69a9SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8511ab0c69a9SMatthias Ringwald     }
8512ab0c69a9SMatthias Ringwald     if (defer){
8513ab0c69a9SMatthias Ringwald         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8514ab0c69a9SMatthias Ringwald     } else {
8515ab0c69a9SMatthias Ringwald         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8516ab0c69a9SMatthias Ringwald         // trigger disconnect
8517ab0c69a9SMatthias Ringwald         hci_run();
8518ab0c69a9SMatthias Ringwald     }
8519ab0c69a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8520ab0c69a9SMatthias Ringwald }
8521ab0c69a9SMatthias Ringwald 
85228e618f72S[email protected] void gap_set_local_name(const char * local_name){
85238e618f72S[email protected]     hci_stack->local_name = local_name;
8524baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
852559d59ecfSMatthias Ringwald     // also update EIR if not set by user
852659d59ecfSMatthias Ringwald     if (hci_stack->eir_data == NULL){
8527baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
852859d59ecfSMatthias Ringwald     }
852959d59ecfSMatthias Ringwald     hci_run();
85308e618f72S[email protected] }
85311aeec2ebSMatthias Ringwald #endif
85328e618f72S[email protected] 
853335454696SMatthias Ringwald 
853435454696SMatthias Ringwald #ifdef ENABLE_BLE
853535454696SMatthias Ringwald 
8536d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8537d8e8f12aSMatthias Ringwald void gap_start_scan(void){
8538fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
85397bdc6798S[email protected]     hci_run();
85407bdc6798S[email protected] }
85418e618f72S[email protected] 
8542d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
8543fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
85447bdc6798S[email protected]     hci_run();
85457bdc6798S[email protected] }
85464f3229d8S[email protected] 
8547a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8548ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
8549a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8550ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
8551ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
85528b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
8553ef11999fSmatthias.ringwald     hci_run();
8554ef11999fSmatthias.ringwald }
85554f3229d8S[email protected] 
8556a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8557a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8558a7a719e9SMatthias Ringwald }
8559a7a719e9SMatthias Ringwald 
85604856283bSMatthias Ringwald void gap_set_scan_duplicate_filter(bool enabled){
85614856283bSMatthias Ringwald     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
85624856283bSMatthias Ringwald }
85634856283bSMatthias Ringwald 
85647eb5b27eSMatthias Ringwald void gap_set_scan_phys(uint8_t phys){
85657eb5b27eSMatthias Ringwald     // LE Coded and LE 1M PHY
85667eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys = phys & 0x05;
85677eb5b27eSMatthias Ringwald }
85687eb5b27eSMatthias Ringwald 
8569667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type) {
85709cb52963SMatthias Ringwald     // disallow le connection if outgoing already active
8571d32b3f05SMatthias Ringwald     if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
85729cb52963SMatthias Ringwald         log_error("le connect already active");
8573d32b3f05SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
8574d32b3f05SMatthias Ringwald     }
8575d32b3f05SMatthias Ringwald 
85769cb52963SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
85779cb52963SMatthias Ringwald     if (conn == NULL) {
857888f925b1SMatthias Ringwald         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
8579f29c1023SMatthias Ringwald         if (conn == NULL){
85809cb52963SMatthias Ringwald             // alloc failed
8581d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
85829cb52963SMatthias Ringwald             return BTSTACK_MEMORY_ALLOC_FAILED;
85839cb52963SMatthias Ringwald         }
85849cb52963SMatthias Ringwald     } else {
85859cb52963SMatthias Ringwald         switch (conn->state) {
85869cb52963SMatthias Ringwald             case RECEIVED_DISCONNECTION_COMPLETE:
85879cb52963SMatthias Ringwald                 // connection was just disconnected, reset state and allow re-connect
85889cb52963SMatthias Ringwald                 conn->role = HCI_ROLE_MASTER;
85899cb52963SMatthias Ringwald                 break;
85909cb52963SMatthias Ringwald             default:
85919cb52963SMatthias Ringwald                 return ERROR_CODE_COMMAND_DISALLOWED;
85929cb52963SMatthias Ringwald         }
85934f3229d8S[email protected]     }
8594d5b1a89eSMatthias Ringwald 
8595d5b1a89eSMatthias Ringwald     // set le connecting state
8596d5b1a89eSMatthias Ringwald     if (hci_is_le_connection_type(addr_type)){
8597d5b1a89eSMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8598d5b1a89eSMatthias Ringwald     }
8599d5b1a89eSMatthias Ringwald 
86009cb52963SMatthias Ringwald     // trigger connect
8601d8e8f12aSMatthias Ringwald     log_info("gap_connect: send create connection next");
8602b0136355SMatthias Ringwald     conn->state = SEND_CREATE_CONNECTION;
8603b0136355SMatthias Ringwald     hci_run();
8604b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8605b0136355SMatthias Ringwald }
8606b0136355SMatthias Ringwald 
86077851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
8608ca0d6e5aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_le_connection(void){
8609665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
8610a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
86110bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
8612ca0d6e5aSMatthias Ringwald         if (hci_is_le_connection(conn)){
86130bf6344aS[email protected]             switch (conn->state){
8614a6725849S[email protected]                 case SEND_CREATE_CONNECTION:
86157851196eSmatthias.ringwald                 case SENT_CREATE_CONNECTION:
86167851196eSmatthias.ringwald                     return conn;
86177851196eSmatthias.ringwald                 default:
86187851196eSmatthias.ringwald                     break;
86197851196eSmatthias.ringwald             };
86207851196eSmatthias.ringwald         }
8621ca0d6e5aSMatthias Ringwald     }
86227851196eSmatthias.ringwald     return NULL;
86237851196eSmatthias.ringwald }
86247851196eSmatthias.ringwald 
8625d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
862614f2d8f0SMatthias Ringwald     hci_connection_t * conn;
862714f2d8f0SMatthias Ringwald     switch (hci_stack->le_connecting_request){
862814f2d8f0SMatthias Ringwald         case LE_CONNECTING_IDLE:
862914f2d8f0SMatthias Ringwald             break;
863014f2d8f0SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
863114f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
863214f2d8f0SMatthias Ringwald             hci_run();
863314f2d8f0SMatthias Ringwald             break;
863414f2d8f0SMatthias Ringwald         case LE_CONNECTING_DIRECT:
863514f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8636ca0d6e5aSMatthias Ringwald             conn = gap_get_outgoing_le_connection();
863714f2d8f0SMatthias Ringwald             if (conn == NULL){
863814f2d8f0SMatthias Ringwald                 hci_run();
863914f2d8f0SMatthias Ringwald             } else {
86407851196eSmatthias.ringwald                 switch (conn->state){
86417851196eSmatthias.ringwald                     case SEND_CREATE_CONNECTION:
86427851196eSmatthias.ringwald                         // skip sending create connection and emit event instead
86432e77e513S[email protected]                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8644665d90f2SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
86457851196eSmatthias.ringwald                         btstack_memory_hci_connection_free( conn );
86460bf6344aS[email protected]                         break;
8647a6725849S[email protected]                     case SENT_CREATE_CONNECTION:
8648ea04fbd8SMatthias Ringwald                         // let hci_run_general_gap_le cancel outgoing connection
86490bf6344aS[email protected]                         hci_run();
86500bf6344aS[email protected]                         break;
86510bf6344aS[email protected]                     default:
86520bf6344aS[email protected]                         break;
86530bf6344aS[email protected]                 }
865414f2d8f0SMatthias Ringwald             }
865514f2d8f0SMatthias Ringwald             break;
865643dfd98aSMatthias Ringwald         default:
865714f2d8f0SMatthias Ringwald             btstack_unreachable();
865814f2d8f0SMatthias Ringwald             break;
865914f2d8f0SMatthias Ringwald     }
866014f2d8f0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8661e31f89a7S[email protected] }
86624f3229d8S[email protected] 
8663c37a3166S[email protected] /**
86646012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
8665cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8666cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
86676012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
86686012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
86696012052bSMatthias Ringwald  * @param conn_latency, default: 4
86706012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
86716012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
86726012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
86736012052bSMatthias Ringwald  */
86746012052bSMatthias Ringwald 
86750c2c5f79SMatthias Ringwald void gap_set_connection_phys(uint8_t phys){
86760c2c5f79SMatthias Ringwald     // LE Coded, LE 1M, LE 2M PHY
86770c2c5f79SMatthias Ringwald     hci_stack->le_connection_phys = phys & 7;
86780c2c5f79SMatthias Ringwald }
86790c2c5f79SMatthias Ringwald 
86800c2c5f79SMatthias Ringwald #endif
86810c2c5f79SMatthias Ringwald 
8682cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8683cbe54ab2SJakob Krantz                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8684cbe54ab2SJakob Krantz                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8685cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
8686cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
86876012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
86886012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
86896012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
86906012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
86916012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
86926012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
86936012052bSMatthias Ringwald }
86947eb5b27eSMatthias Ringwald 
86956012052bSMatthias Ringwald /**
8696c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
8697c37a3166S[email protected]  * @param handle
8698c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
8699c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
8700c37a3166S[email protected]  * @param conn_latency
8701c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
87026b65794dSMilanka Ringwald  * @return 0 if ok
8703c37a3166S[email protected]  */
8704c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8705c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8706c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8707c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8708c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
8709c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
8710c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
8711c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
871284cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8713cfc59f1bSMatthias Ringwald     hci_run();
8714c37a3166S[email protected]     return 0;
8715c37a3166S[email protected] }
8716c37a3166S[email protected] 
871745c102fdSMatthias Ringwald /**
8718b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
8719b68d7bc3SMatthias Ringwald  * @param handle
8720b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
8721b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
8722b68d7bc3SMatthias Ringwald  * @param conn_latency
8723b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
87246b65794dSMilanka Ringwald  * @return 0 if ok
8725b68d7bc3SMatthias Ringwald  */
8726b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8727b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8728b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8729b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8730b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
8731b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
8732b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
8733b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
8734b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
873509c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
87369da9850bSMatthias Ringwald     hci_emit_btstack_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8737b68d7bc3SMatthias Ringwald     return 0;
8738b68d7bc3SMatthias Ringwald }
8739b68d7bc3SMatthias Ringwald 
87409007c891SMatthias Ringwald uint8_t gap_request_connection_subrating(hci_con_handle_t con_handle, uint16_t subrate_min, uint16_t subrate_max,
87419007c891SMatthias Ringwald                                          uint16_t max_latency, uint16_t continuation_number, uint16_t supervision_timeout){
87429007c891SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
87439007c891SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
87449007c891SMatthias Ringwald 
87459007c891SMatthias Ringwald     connection->le_subrate_min = subrate_min;
87469007c891SMatthias Ringwald     connection->le_subrate_max = subrate_max;
87479007c891SMatthias Ringwald     connection->le_subrate_max_latency = max_latency;
87489007c891SMatthias Ringwald     connection->le_subrate_continuation_number = continuation_number;
87499007c891SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
87509007c891SMatthias Ringwald     hci_run();
87519007c891SMatthias Ringwald     return ERROR_CODE_SUCCESS;
87529007c891SMatthias Ringwald }
87539007c891SMatthias Ringwald 
8754d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
8755d70217a2SMatthias Ringwald 
87565e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87575e05c0afSMatthias Ringwald static void hci_assert_advertisement_set_0_ready(void){
87585e05c0afSMatthias Ringwald     // force advertising set creation for legacy LE Advertising
87595e05c0afSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
87605e05c0afSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
87615e05c0afSMatthias Ringwald     }
87625e05c0afSMatthias Ringwald }
87635e05c0afSMatthias Ringwald #endif
87645e05c0afSMatthias Ringwald 
8765b68d7bc3SMatthias Ringwald /**
876645c102fdSMatthias Ringwald  * @brief Set Advertisement Data
876745c102fdSMatthias Ringwald  * @param advertising_data_length
876845c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
876945c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
877045c102fdSMatthias Ringwald  */
877145c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
877245c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
877345c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
8774501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
87755e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87765e05c0afSMatthias Ringwald     hci_assert_advertisement_set_0_ready();
87775e05c0afSMatthias Ringwald #endif
8778bbc366e6SMatthias Ringwald     hci_run();
877945c102fdSMatthias Ringwald }
8780501f56b3SMatthias Ringwald 
8781501f56b3SMatthias Ringwald /**
8782501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
8783501f56b3SMatthias Ringwald  * @param advertising_data_length
8784501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
8785501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
8786501f56b3SMatthias Ringwald  */
8787501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8788501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
8789501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
8790501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
87915e05c0afSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
87925e05c0afSMatthias Ringwald     hci_assert_advertisement_set_0_ready();
87935e05c0afSMatthias Ringwald #endif
8794bbc366e6SMatthias Ringwald     hci_run();
879545c102fdSMatthias Ringwald }
879645c102fdSMatthias Ringwald 
879745c102fdSMatthias Ringwald /**
879845c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
879945c102fdSMatthias Ringwald  * @param adv_int_min
880045c102fdSMatthias Ringwald  * @param adv_int_max
880145c102fdSMatthias Ringwald  * @param adv_type
880245c102fdSMatthias Ringwald  * @param direct_address_type
880345c102fdSMatthias Ringwald  * @param direct_address
880445c102fdSMatthias Ringwald  * @param channel_map
880545c102fdSMatthias Ringwald  * @param filter_policy
880645c102fdSMatthias Ringwald  *
880745c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
880845c102fdSMatthias Ringwald  */
880945c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8810b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
881145c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
881245c102fdSMatthias Ringwald 
881345c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
881445c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
881545c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
881645c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
881745c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
881845c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
88196535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
88206535961aSMatthias Ringwald                  6);
882145c102fdSMatthias Ringwald 
88226bf435a6SMatthias Ringwald     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
88236bf435a6SMatthias Ringwald     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8824bbc366e6SMatthias Ringwald     hci_run();
882545c102fdSMatthias Ringwald  }
882645c102fdSMatthias Ringwald 
882745c102fdSMatthias Ringwald /**
882845c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
882945c102fdSMatthias Ringwald  * @param enabled
883045c102fdSMatthias Ringwald  */
883145c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
8832a408e724SMatthias Ringwald     if (enabled == 0){
8833a408e724SMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8834a408e724SMatthias Ringwald     } else {
8835a408e724SMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8836a408e724SMatthias Ringwald     }
8837bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
8838cfc59f1bSMatthias Ringwald     hci_run();
883945c102fdSMatthias Ringwald }
884045c102fdSMatthias Ringwald 
8841a5770ecbSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8842a5770ecbSMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8843a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_t it;
8844a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8845a5770ecbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8846a5770ecbSMatthias Ringwald         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8847a5770ecbSMatthias Ringwald         if ( item->advertising_handle == advertising_handle ) {
8848a5770ecbSMatthias Ringwald             return item;
8849a5770ecbSMatthias Ringwald         }
8850a5770ecbSMatthias Ringwald     }
8851a5770ecbSMatthias Ringwald     return NULL;
8852a5770ecbSMatthias Ringwald }
8853a5770ecbSMatthias Ringwald 
88542052d96cSMatthias Ringwald uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
88552052d96cSMatthias Ringwald     hci_stack->le_resolvable_private_address_update_s = update_s;
88562052d96cSMatthias Ringwald     hci_run();
88572052d96cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
88582052d96cSMatthias Ringwald }
88592052d96cSMatthias Ringwald 
8860a5770ecbSMatthias 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){
88612d0c7965SMatthias Ringwald     // find free advertisement handle. we use LE_EXTENDED_ADVERTISING_LEGACY_HANDLE for non-extended advertising
8862a5770ecbSMatthias Ringwald     uint8_t advertisement_handle;
88632d0c7965SMatthias Ringwald     for (advertisement_handle = LE_EXTENDED_ADVERTISING_LEGACY_HANDLE + 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8864a5770ecbSMatthias Ringwald         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8865a5770ecbSMatthias Ringwald     }
8866a5770ecbSMatthias Ringwald     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8867a5770ecbSMatthias Ringwald     // clear
8868a5770ecbSMatthias Ringwald     memset(storage, 0, sizeof(le_advertising_set_t));
8869a5770ecbSMatthias Ringwald     // copy params
88700cbe4690SMatthias Ringwald     storage->advertising_handle = advertisement_handle;
887157a04237SMatthias Ringwald     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8872a5770ecbSMatthias Ringwald     // add to list
8873a5770ecbSMatthias Ringwald     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8874a5770ecbSMatthias Ringwald     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
88750cbe4690SMatthias Ringwald     *out_advertising_handle = advertisement_handle;
8876a5770ecbSMatthias Ringwald     // set tasks and start
8877a5770ecbSMatthias Ringwald     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8878a5770ecbSMatthias Ringwald     hci_run();
8879a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8880a5770ecbSMatthias Ringwald }
8881a5770ecbSMatthias Ringwald 
8882a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8883a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8884a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
888557a04237SMatthias Ringwald     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8886a5770ecbSMatthias Ringwald     // set tasks and start
8887a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8888a5770ecbSMatthias Ringwald     hci_run();
8889a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8890a5770ecbSMatthias Ringwald }
8891a5770ecbSMatthias Ringwald 
8892a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8893a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8894a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
889557a04237SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8896a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8897a5770ecbSMatthias Ringwald }
8898a5770ecbSMatthias Ringwald 
8899a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8900a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8901a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8902a5770ecbSMatthias Ringwald     memcpy(advertising_set->random_address, random_address, 6);
8903a5770ecbSMatthias Ringwald     // set tasks and start
8904a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8905a5770ecbSMatthias Ringwald     hci_run();
8906a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8907a5770ecbSMatthias Ringwald }
8908a5770ecbSMatthias Ringwald 
89092e4aaf70SMatthias Ringwald uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8910a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8911a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8912a5770ecbSMatthias Ringwald     advertising_set->adv_data = advertising_data;
8913a5770ecbSMatthias Ringwald     advertising_set->adv_data_len = advertising_data_length;
8914a5770ecbSMatthias Ringwald     // set tasks and start
8915a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8916a5770ecbSMatthias Ringwald     hci_run();
8917a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8918a5770ecbSMatthias Ringwald }
8919a5770ecbSMatthias Ringwald 
89202e4aaf70SMatthias 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){
8921a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8922a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8923a5770ecbSMatthias Ringwald     advertising_set->scan_data = scan_response_data;
8924a5770ecbSMatthias Ringwald     advertising_set->scan_data_len = scan_response_data_length;
8925a5770ecbSMatthias Ringwald     // set tasks and start
8926a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8927a5770ecbSMatthias Ringwald     hci_run();
8928a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8929a5770ecbSMatthias Ringwald }
8930a5770ecbSMatthias Ringwald 
8931a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8932a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8933a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8934a5770ecbSMatthias Ringwald     advertising_set->enable_timeout = timeout;
8935a5770ecbSMatthias Ringwald     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8936a5770ecbSMatthias Ringwald     // set tasks and start
8937a5770ecbSMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8938a5770ecbSMatthias Ringwald     hci_run();
8939a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8940a5770ecbSMatthias Ringwald }
8941a5770ecbSMatthias Ringwald 
8942a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8943a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8944a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8945a5770ecbSMatthias Ringwald     // set tasks and start
8946a5770ecbSMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8947a5770ecbSMatthias Ringwald     hci_run();
8948a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8949a5770ecbSMatthias Ringwald }
8950a5770ecbSMatthias Ringwald 
8951c814a904SMatthias Ringwald uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8952c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8953c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8954c814a904SMatthias Ringwald     // set tasks and start
8955c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8956c814a904SMatthias Ringwald     hci_run();
8957c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8958c814a904SMatthias Ringwald }
8959c814a904SMatthias Ringwald 
8960c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8961c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8962c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8963c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8964c814a904SMatthias Ringwald     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8965c814a904SMatthias Ringwald     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8966c814a904SMatthias Ringwald     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8967c814a904SMatthias Ringwald     // set tasks and start
8968c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8969c814a904SMatthias Ringwald     hci_run();
8970c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8971c814a904SMatthias Ringwald }
8972c814a904SMatthias Ringwald 
8973c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8974c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8975c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8976c814a904SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8977c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8978c814a904SMatthias Ringwald }
8979c814a904SMatthias Ringwald 
8980c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8981c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8982c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8983c814a904SMatthias Ringwald     advertising_set->periodic_data = periodic_data;
8984c814a904SMatthias Ringwald     advertising_set->periodic_data_len = periodic_data_length;
8985c814a904SMatthias Ringwald     // set tasks and start
8986c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8987c814a904SMatthias Ringwald     hci_run();
8988c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8989c814a904SMatthias Ringwald }
8990c814a904SMatthias Ringwald 
899153f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
899253f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
899353f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
899453f240c0SMatthias Ringwald     // set tasks and start
899553f240c0SMatthias Ringwald     advertising_set->periodic_include_adi = include_adi;
899653f240c0SMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
899753f240c0SMatthias Ringwald     hci_run();
899853f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
899953f240c0SMatthias Ringwald }
900053f240c0SMatthias Ringwald 
900153f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
900253f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
900353f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
900453f240c0SMatthias Ringwald     // set tasks and start
900553f240c0SMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
900653f240c0SMatthias Ringwald     hci_run();
900753f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
900853f240c0SMatthias Ringwald }
900998aa715fSMatthias Ringwald 
90104718c38dSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
901198aa715fSMatthias 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){
901298aa715fSMatthias Ringwald     hci_stack->le_past_mode = mode;
901398aa715fSMatthias Ringwald     hci_stack->le_past_skip = skip;
901498aa715fSMatthias Ringwald     hci_stack->le_past_sync_timeout = sync_timeout;
901598aa715fSMatthias Ringwald     hci_stack->le_past_cte_type = cte_type;
901698aa715fSMatthias Ringwald     hci_stack->le_past_set_default_params = true;
901798aa715fSMatthias Ringwald     hci_run();
901898aa715fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
901998aa715fSMatthias Ringwald }
902098aa715fSMatthias Ringwald 
90213bd96807SMatthias 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){
90223bd96807SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
90233bd96807SMatthias Ringwald     if (hci_connection == NULL){
90243bd96807SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
90253bd96807SMatthias Ringwald     }
90263bd96807SMatthias Ringwald     hci_connection->le_past_sync_handle = sync_handle;
90273bd96807SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
90283bd96807SMatthias Ringwald     hci_run();
90293bd96807SMatthias Ringwald     return ERROR_CODE_SUCCESS;
90303bd96807SMatthias Ringwald }
90314718c38dSMatthias Ringwald #endif
90323bd96807SMatthias Ringwald 
9033027f4677SMatthias Ringwald uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
9034027f4677SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9035027f4677SMatthias Ringwald     if (hci_connection == NULL){
9036027f4677SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9037027f4677SMatthias Ringwald     }
9038027f4677SMatthias Ringwald     hci_connection->le_past_advertising_handle = advertising_handle;
9039027f4677SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
9040027f4677SMatthias Ringwald     hci_run();
9041027f4677SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9042027f4677SMatthias Ringwald }
9043027f4677SMatthias Ringwald 
9044c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
904553f240c0SMatthias Ringwald 
9046a5770ecbSMatthias Ringwald #endif
9047a5770ecbSMatthias Ringwald 
904835454696SMatthias Ringwald #endif
904906e5cf96SMatthias Ringwald 
905006e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
905106e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
905206e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
905306e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
905406e5cf96SMatthias Ringwald 
905564068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
905606e5cf96SMatthias Ringwald     // update advertisement parameters, too
905706e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
9058bbc366e6SMatthias Ringwald     hci_run();
905964068776SMatthias Ringwald #endif
906064068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
906106e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
906264068776SMatthias Ringwald #endif
906306e5cf96SMatthias Ringwald }
906406e5cf96SMatthias Ringwald 
90659136bde8SMatthias Ringwald void hci_le_random_address_set(const bd_addr_t random_address){
9066137a570aSMatthias Ringwald     log_info("gap_privacy: hci_le_random_address_set %s", bd_addr_to_str(random_address));
90679136bde8SMatthias Ringwald     memcpy(hci_stack->le_random_address, random_address, 6);
90689136bde8SMatthias Ringwald     hci_stack->le_random_address_set = true;
9069137a570aSMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_PRIVACY_NOTIFY;
90709ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
907122f987e4SMatthias Ringwald     if (hci_le_extended_advertising_supported()){
90725e05c0afSMatthias Ringwald         hci_assert_advertisement_set_0_ready();
90739ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
90749ce6dfa1SMatthias Ringwald     }
90759ce6dfa1SMatthias Ringwald #endif
90769136bde8SMatthias Ringwald     hci_run();
90779136bde8SMatthias Ringwald }
90789136bde8SMatthias Ringwald 
9079d70217a2SMatthias Ringwald #endif
908045c102fdSMatthias Ringwald 
9081616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
90825917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
90835917a5c5S[email protected]     if (!conn){
90847851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
9085616edd56SMatthias Ringwald         return 0;
90865917a5c5S[email protected]     }
908761972f0aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
908861972f0aSMatthias Ringwald     switch (conn->state){
908961972f0aSMatthias Ringwald         case RECEIVED_DISCONNECTION_COMPLETE:
909061972f0aSMatthias Ringwald             // ignore if remote just disconnected
909161972f0aSMatthias Ringwald             break;
909261972f0aSMatthias Ringwald         case SEND_DISCONNECT:
909361972f0aSMatthias Ringwald         case SENT_DISCONNECT:
909461972f0aSMatthias Ringwald             // disconnect already requested or sent
909561972f0aSMatthias Ringwald             status = ERROR_CODE_COMMAND_DISALLOWED;
909661972f0aSMatthias Ringwald             break;
909761972f0aSMatthias Ringwald         default:
909861972f0aSMatthias Ringwald             // trigger hci_disconnect
90995917a5c5S[email protected]             conn->state = SEND_DISCONNECT;
91005917a5c5S[email protected]             hci_run();
910161972f0aSMatthias Ringwald             break;
910261972f0aSMatthias Ringwald     }
910361972f0aSMatthias Ringwald     return status;
91044f3229d8S[email protected] }
910504a6ef8cSmatthias.ringwald 
9106228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
9107228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9108228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
910922df2fe2SMatthias Ringwald     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
9110228e430cSMatthias Ringwald     hci_run();
9111228e430cSMatthias Ringwald     return 1;
9112228e430cSMatthias Ringwald }
9113228e430cSMatthias Ringwald 
9114a1bf5ae7SMatthias Ringwald /**
9115a1bf5ae7SMatthias Ringwald  * @brief Get connection type
9116a1bf5ae7SMatthias Ringwald  * @param con_handle
9117a1bf5ae7SMatthias Ringwald  * @result connection_type
9118a1bf5ae7SMatthias Ringwald  */
9119a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
9120a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
9121a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
9122a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
9123a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
9124a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9125ad9f3530SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9126ad9f3530SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9127a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
9128a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9129a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
9130f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9131a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
9132a1bf5ae7SMatthias Ringwald         default:
9133a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
9134a1bf5ae7SMatthias Ringwald     }
9135a1bf5ae7SMatthias Ringwald }
9136a1bf5ae7SMatthias Ringwald 
91372dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
91382dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
91392dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
91402dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
91412dceb1d6SMatthias Ringwald }
91422dceb1d6SMatthias Ringwald 
91432dceb1d6SMatthias Ringwald 
914444f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
9145667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
914688a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
914788a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
914888a03c8dSMatthias Ringwald     conn->request_role = role;
914988a03c8dSMatthias Ringwald     hci_run();
9150d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
915188a03c8dSMatthias Ringwald }
915244f858f3SMatthias Ringwald #endif
915388a03c8dSMatthias Ringwald 
9154a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
91554f551432SMatthias Ringwald 
91569d8be771SMatthias 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){
9157b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9158b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9159b90f6e0aSMatthias Ringwald 
9160b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
9161b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
9162b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
91639d8be771SMatthias Ringwald     conn->le_phy_update_phy_options = (uint8_t) phy_options;
9164b90f6e0aSMatthias Ringwald 
9165b90f6e0aSMatthias Ringwald     hci_run();
9166b90f6e0aSMatthias Ringwald 
9167b90f6e0aSMatthias Ringwald     return 0;
9168b90f6e0aSMatthias Ringwald }
9169b90f6e0aSMatthias Ringwald 
9170667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9171100da355SMatthias Ringwald 
9172100da355SMatthias Ringwald #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_WHITELIST_ENTRIES) || (MAX_NR_WHITELIST_ENTRIES == 0))
9173100da355SMatthias Ringwald     // incorrect configuration:
9174100da355SMatthias Ringwald     // - as MAX_NR_WHITELIST_ENTRIES is not defined or zero this function always fails
9175100da355SMatthias Ringwald     // - please set MAX_NR_WHITELIST_ENTRIES in btstack_config.h
9176100da355SMatthias Ringwald     btstack_assert(false);
9177100da355SMatthias Ringwald #endif
9178100da355SMatthias Ringwald 
91797a92a9dbSMatthias Ringwald     // check if already in list
91807a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
91817a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
91827a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
91837a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
91847a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
91857a92a9dbSMatthias Ringwald             continue;
91867a92a9dbSMatthias Ringwald         }
91877a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
91887a92a9dbSMatthias Ringwald             continue;
91897a92a9dbSMatthias Ringwald         }
9190caaf5151SMilanka Ringwald 
9191caaf5151SMilanka Ringwald         // if already on controller:
9192caaf5151SMilanka Ringwald         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
9193caaf5151SMilanka Ringwald             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
9194caaf5151SMilanka Ringwald                 // drop remove request
9195caaf5151SMilanka Ringwald                 entry->state = LE_WHITELIST_ON_CONTROLLER;
9196caaf5151SMilanka Ringwald                 return ERROR_CODE_SUCCESS;
9197caaf5151SMilanka Ringwald             } else {
9198caaf5151SMilanka Ringwald                 // disallow as already on controller
91997a92a9dbSMatthias Ringwald                 return ERROR_CODE_COMMAND_DISALLOWED;
92007a92a9dbSMatthias Ringwald             }
9201287379ccSMatthias Ringwald         }
9202caaf5151SMilanka Ringwald 
9203caaf5151SMilanka Ringwald         // assume scheduled to add
9204caaf5151SMilanka Ringwald 		return ERROR_CODE_COMMAND_DISALLOWED;
9205caaf5151SMilanka Ringwald     }
9206caaf5151SMilanka Ringwald 
92077a92a9dbSMatthias Ringwald     // alloc and add to list
9208e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
9209e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9210e83201bcSMatthias Ringwald     entry->address_type = address_type;
92116535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
9212e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
9213665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
9214226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9215ac9c45e0SMatthias Ringwald }
9216ac9c45e0SMatthias Ringwald 
9217667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9218665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9219665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9220665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9221665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
92227a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
92237a92a9dbSMatthias Ringwald             continue;
92247a92a9dbSMatthias Ringwald         }
92257a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
92267a92a9dbSMatthias Ringwald             continue;
92277a92a9dbSMatthias Ringwald         }
9228e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9229e83201bcSMatthias Ringwald             // remove from controller if already present
9230e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9231a3b69fdeSMatthias Ringwald         }  else {
9232226db5efSMatthias Ringwald             // directly remove entry from whitelist
9233665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
9234e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
9235e83201bcSMatthias Ringwald         }
9236a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
9237a3b69fdeSMatthias Ringwald     }
9238a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
923942ff5ba1SMatthias Ringwald }
924042ff5ba1SMatthias Ringwald 
9241226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
9242665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9243665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
9244665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9245665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
9246e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
9247e83201bcSMatthias Ringwald             // remove from controller if already present
9248e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
9249e83201bcSMatthias Ringwald             continue;
9250e83201bcSMatthias Ringwald         }
925191915b0bSMatthias Ringwald         // directly remove entry from whitelist
9252665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
9253e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
9254e83201bcSMatthias Ringwald     }
9255226db5efSMatthias Ringwald }
9256226db5efSMatthias Ringwald 
9257a3b69fdeSMatthias Ringwald /**
9258a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
92596b65794dSMilanka Ringwald  * @return 0 if ok
9260a3b69fdeSMatthias Ringwald  */
9261a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
9262a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
9263a3b69fdeSMatthias Ringwald     hci_run();
9264a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9265a3b69fdeSMatthias Ringwald }
9266a3b69fdeSMatthias Ringwald 
9267a3b69fdeSMatthias Ringwald /**
9268a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
9269a3b69fdeSMatthias Ringwald  * @param address_typ
9270a3b69fdeSMatthias Ringwald  * @param address
92716b65794dSMilanka Ringwald  * @return 0 if ok
9272a3b69fdeSMatthias Ringwald  */
9273667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
9274a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
9275a3b69fdeSMatthias Ringwald     if (status){
9276a3b69fdeSMatthias Ringwald         return status;
9277a3b69fdeSMatthias Ringwald     }
9278a3b69fdeSMatthias Ringwald     hci_run();
9279a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9280a3b69fdeSMatthias Ringwald }
9281a3b69fdeSMatthias Ringwald 
9282a3b69fdeSMatthias Ringwald /**
9283a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
9284a3b69fdeSMatthias Ringwald  * @param address_typ
9285a3b69fdeSMatthias Ringwald  * @param address
92866b65794dSMilanka Ringwald  * @return 0 if ok
9287a3b69fdeSMatthias Ringwald  */
9288667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
9289a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
9290a3b69fdeSMatthias Ringwald     if (status){
9291a3b69fdeSMatthias Ringwald         return status;
9292a3b69fdeSMatthias Ringwald     }
9293a3b69fdeSMatthias Ringwald     hci_run();
9294a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
9295a3b69fdeSMatthias Ringwald }
9296a3b69fdeSMatthias Ringwald 
9297226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
9298226db5efSMatthias Ringwald /**
929995e257d9SMatthias Ringwald  * @brief Connect with Whitelist
930095e257d9SMatthias Ringwald  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
93016b65794dSMilanka Ringwald  * @return - if ok
930295e257d9SMatthias Ringwald  */
930395e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
930495e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
930595e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
930695e257d9SMatthias Ringwald     }
930795e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
930895e257d9SMatthias Ringwald     hci_run();
930995e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
931095e257d9SMatthias Ringwald }
931195e257d9SMatthias Ringwald 
931295e257d9SMatthias Ringwald /**
9313226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
9314226db5efSMatthias Ringwald  * @param address_typ
9315226db5efSMatthias Ringwald  * @param address
93166b65794dSMilanka Ringwald  * @return 0 if ok
9317226db5efSMatthias Ringwald  */
9318667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
931995e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
9320226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
9321226db5efSMatthias Ringwald     }
9322226db5efSMatthias Ringwald 
9323226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
932463f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
9325226db5efSMatthias Ringwald         return status;
9326226db5efSMatthias Ringwald     }
9327226db5efSMatthias Ringwald 
9328226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
9329226db5efSMatthias Ringwald 
9330226db5efSMatthias Ringwald     hci_run();
933195e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9332226db5efSMatthias Ringwald }
9333226db5efSMatthias Ringwald 
9334226db5efSMatthias Ringwald /**
9335226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
9336226db5efSMatthias Ringwald  * @param address_typ
9337226db5efSMatthias Ringwald  * @param address
93386b65794dSMilanka Ringwald  * @return 0 if ok
9339226db5efSMatthias Ringwald  */
9340667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
934195e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
934295e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
934395e257d9SMatthias Ringwald     }
934495e257d9SMatthias Ringwald 
9345226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
934695e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
934795e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
934895e257d9SMatthias Ringwald     }
9349226db5efSMatthias Ringwald     hci_run();
9350226db5efSMatthias Ringwald     return 0;
9351226db5efSMatthias Ringwald }
9352226db5efSMatthias Ringwald 
9353226db5efSMatthias Ringwald /**
9354226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
9355226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
9356226db5efSMatthias Ringwald  */
935795e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
935895e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
935995e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
936095e257d9SMatthias Ringwald     }
9361226db5efSMatthias Ringwald     hci_whitelist_clear();
9362226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
9363e83201bcSMatthias Ringwald     hci_run();
936495e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9365ac9c45e0SMatthias Ringwald }
9366c9db5c21SMilanka Ringwald 
9367b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
9368b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
9369c9db5c21SMilanka Ringwald     if (!conn) return 0;
9370c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
9371c9db5c21SMilanka Ringwald }
9372d70217a2SMatthias Ringwald #endif
93734f551432SMatthias Ringwald #endif
93744f551432SMatthias Ringwald 
937535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
9376ac9c45e0SMatthias Ringwald /**
9377ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
9378a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
9379ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
9380ff00ed1cSMatthias Ringwald  */
9381ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
9382ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
9383baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
938459d59ecfSMatthias Ringwald     hci_run();
9385ff00ed1cSMatthias Ringwald }
9386ff00ed1cSMatthias Ringwald 
9387ff00ed1cSMatthias Ringwald /**
9388f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
9389f5875de5SMatthias Ringwald  * @param duration in 1.28s units
9390f5875de5SMatthias Ringwald  * @return 0 if ok
9391f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
9392f5875de5SMatthias Ringwald  */
9393f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
939499449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
9395f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9396a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
9397f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9398f5875de5SMatthias Ringwald     }
9399f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
940030199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = 0;
940130199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = 0;
940230199e24SMatthias Ringwald     hci_run();
940330199e24SMatthias Ringwald     return 0;
940430199e24SMatthias Ringwald }
940530199e24SMatthias Ringwald 
940630199e24SMatthias Ringwald uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
940730199e24SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
940830199e24SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
940930199e24SMatthias Ringwald     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
941030199e24SMatthias Ringwald     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
941130199e24SMatthias Ringwald     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
941230199e24SMatthias Ringwald     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
941330199e24SMatthias Ringwald 
941430199e24SMatthias Ringwald     hci_stack->inquiry_state = duration;
941530199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = max_period_length;
941630199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = min_period_length;
9417f5875de5SMatthias Ringwald     hci_run();
9418f5875de5SMatthias Ringwald     return 0;
9419f5875de5SMatthias Ringwald }
9420f5875de5SMatthias Ringwald 
9421f5875de5SMatthias Ringwald /**
9422f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
94236b65794dSMilanka Ringwald  * @return 0 if ok
9424f5875de5SMatthias Ringwald  */
9425f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
9426a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9427f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
9428f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
94299da9850bSMatthias Ringwald         hci_emit_btstack_event(event, sizeof(event), 1);
9430f5875de5SMatthias Ringwald         return 0;
9431f5875de5SMatthias Ringwald     }
943230199e24SMatthias Ringwald     switch (hci_stack->inquiry_state){
943330199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_ACTIVE:
9434f5875de5SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9435f5875de5SMatthias Ringwald             hci_run();
943630199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
943730199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_PERIODIC:
943830199e24SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
943930199e24SMatthias Ringwald             hci_run();
944030199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
944130199e24SMatthias Ringwald         default:
944230199e24SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
944330199e24SMatthias Ringwald     }
9444f5875de5SMatthias Ringwald }
9445f5875de5SMatthias Ringwald 
9446496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
9447496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
9448496bb884SMatthias Ringwald }
9449496bb884SMatthias Ringwald 
94501dc973e7SMatthias Ringwald void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9451c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9452c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9453baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9454c0c8a829SMatthias Ringwald     hci_run();
9455c0c8a829SMatthias Ringwald }
9456c0c8a829SMatthias Ringwald 
9457f50ed5acSAndrey Fominykh void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9458f50ed5acSAndrey Fominykh {
9459f50ed5acSAndrey Fominykh     hci_stack->inquiry_tx_power_level = tx_power;
9460f50ed5acSAndrey Fominykh     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9461f50ed5acSAndrey Fominykh     hci_run();
9462f50ed5acSAndrey Fominykh }
9463f50ed5acSAndrey Fominykh 
9464b7f1ee76SMatthias Ringwald 
9465b7f1ee76SMatthias Ringwald /**
9466b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
9467b7f1ee76SMatthias Ringwald  * @param addr
9468b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
9469b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
9470b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9471b7f1ee76SMatthias Ringwald  */
9472667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9473b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
94746535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9475b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9476b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
9477b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9478b7f1ee76SMatthias Ringwald     hci_run();
9479b7f1ee76SMatthias Ringwald     return 0;
9480b7f1ee76SMatthias Ringwald }
9481b7f1ee76SMatthias Ringwald 
9482667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
94830a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
94846535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
94850a51f88bSMatthias Ringwald     hci_run();
94860a51f88bSMatthias Ringwald     return 0;
94870a51f88bSMatthias Ringwald }
94880a51f88bSMatthias Ringwald 
94890a51f88bSMatthias Ringwald /**
9490aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9491aad97216SMatthias Ringwald  * @param addr
9492aad97216SMatthias Ringwald  * @param pin_data
9493aad97216SMatthias Ringwald  * @param pin_len
9494aad97216SMatthias Ringwald  * @return 0 if ok
9495aad97216SMatthias Ringwald  */
9496667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9497aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9498c26f2c7bSMatthias Ringwald     if (pin_len > PIN_CODE_LEN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
9499aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9500aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
9501aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9502aad97216SMatthias Ringwald }
9503aad97216SMatthias Ringwald 
9504aad97216SMatthias Ringwald /**
95050a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
95060a51f88bSMatthias Ringwald  * @param addr
95070a51f88bSMatthias Ringwald  * @param pin
95080a51f88bSMatthias Ringwald  * @return 0 if ok
95090a51f88bSMatthias Ringwald  */
9510667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
95119d78a7ecSMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
95120a51f88bSMatthias Ringwald }
95130a51f88bSMatthias Ringwald 
95140a51f88bSMatthias Ringwald /**
95150a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
95160a51f88bSMatthias Ringwald  * @param addr
95170a51f88bSMatthias Ringwald  * @param pin
95180a51f88bSMatthias Ringwald  * @return 0 if ok
95190a51f88bSMatthias Ringwald  */
95200a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
9521cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95220a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
95230a51f88bSMatthias Ringwald }
95240a51f88bSMatthias Ringwald 
95250a51f88bSMatthias Ringwald /**
95260a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
95270a51f88bSMatthias Ringwald  * @param addr
95280a51f88bSMatthias Ringwald  * @param passkey
95290a51f88bSMatthias Ringwald  * @return 0 if ok
95300a51f88bSMatthias Ringwald  */
9531667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9532cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9533d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
95340a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
95350a51f88bSMatthias Ringwald }
95360a51f88bSMatthias Ringwald 
95370a51f88bSMatthias Ringwald /**
95380a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
95390a51f88bSMatthias Ringwald  * @param addr
95400a51f88bSMatthias Ringwald  * @param pin
95410a51f88bSMatthias Ringwald  * @return 0 if ok
95420a51f88bSMatthias Ringwald  */
9543667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
9544cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95450a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
95460a51f88bSMatthias Ringwald }
95470a51f88bSMatthias Ringwald 
95480a51f88bSMatthias Ringwald /**
95490a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
95500a51f88bSMatthias Ringwald  * @param addr
95510a51f88bSMatthias Ringwald  * @param passkey
95520a51f88bSMatthias Ringwald  * @return 0 if ok
95530a51f88bSMatthias Ringwald  */
9554667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
9555cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95560a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
95570a51f88bSMatthias Ringwald }
95580a51f88bSMatthias Ringwald 
95590a51f88bSMatthias Ringwald /**
95600a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
95610a51f88bSMatthias Ringwald  * @param addr
95620a51f88bSMatthias Ringwald  * @param pin
95630a51f88bSMatthias Ringwald  * @return 0 if ok
95640a51f88bSMatthias Ringwald  */
9565667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
9566cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
95670a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
95680a51f88bSMatthias Ringwald }
95690a51f88bSMatthias Ringwald 
9570308eeaffSMatthias Ringwald #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
957144565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
957244565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
957344565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
957444565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
957544565b0cSMatthias Ringwald     hci_run();
957644565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
957744565b0cSMatthias Ringwald }
9578308eeaffSMatthias Ringwald #endif
957944565b0cSMatthias Ringwald 
9580308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
958144565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
95827ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
958344565b0cSMatthias Ringwald }
958444565b0cSMatthias Ringwald 
958544565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
95867ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
958744565b0cSMatthias Ringwald }
958844565b0cSMatthias Ringwald #endif
958944565b0cSMatthias Ringwald 
95901849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
95911849becdSMatthias Ringwald /**
95921849becdSMatthias Ringwald  * @brief Report Remote OOB Data
95931849becdSMatthias Ringwald  * @param bd_addr
95941849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
95951849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
95961849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
95971849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
95981849becdSMatthias Ringwald  */
95991849becdSMatthias 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){
96001849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
96011849becdSMatthias Ringwald     if (connection == NULL) {
96021849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
96031849becdSMatthias Ringwald     }
96041849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
96051849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
9606204e8f1dSMatthias Ringwald 
9607204e8f1dSMatthias Ringwald     // ignore P-256 if not supported by us
9608204e8f1dSMatthias Ringwald     if (hci_stack->secure_connections_active){
96091849becdSMatthias Ringwald         connection->classic_oob_c_256 = c_256;
96101849becdSMatthias Ringwald         connection->classic_oob_r_256 = r_256;
9611204e8f1dSMatthias Ringwald     }
9612204e8f1dSMatthias Ringwald 
96131849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
96141849becdSMatthias Ringwald }
9615cf01e888SMatthias Ringwald /**
9616cf01e888SMatthias Ringwald  * @brief Generate new OOB data
9617cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9618cf01e888SMatthias Ringwald  */
9619cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
9620cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
9621cf01e888SMatthias Ringwald     hci_run();
9622cf01e888SMatthias Ringwald }
9623cf01e888SMatthias Ringwald 
96241849becdSMatthias Ringwald #endif
96251849becdSMatthias Ringwald 
9626308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9627308eeaffSMatthias Ringwald uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9628308eeaffSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9629308eeaffSMatthias Ringwald     if (connection == NULL) {
9630308eeaffSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9631308eeaffSMatthias Ringwald     }
9632308eeaffSMatthias Ringwald 
9633308eeaffSMatthias Ringwald     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9634308eeaffSMatthias Ringwald     connection->link_key_type = type;
9635308eeaffSMatthias Ringwald 
9636308eeaffSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9637308eeaffSMatthias Ringwald }
9638308eeaffSMatthias Ringwald 
9639308eeaffSMatthias Ringwald #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9640f5875de5SMatthias Ringwald /**
9641f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9642f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
9643f6858d14SMatthias Ringwald  */
9644b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9645b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
9646f6858d14SMatthias Ringwald }
9647f6858d14SMatthias Ringwald 
9648f6858d14SMatthias Ringwald /**
9649d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9650d950d659SMatthias Ringwald  */
9651d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
9652d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
9653d950d659SMatthias Ringwald }
9654d950d659SMatthias Ringwald 
9655d950d659SMatthias Ringwald /**
9656d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
9657d950d659SMatthias Ringwald  * @return current voice setting
9658d950d659SMatthias Ringwald  */
96590cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
9660d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
9661d950d659SMatthias Ringwald }
9662d950d659SMatthias Ringwald 
9663400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
9664400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
9665400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
9666400ff5abSMatthias Ringwald     if (!transport_name) return 0;
9667400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9668400ff5abSMatthias Ringwald }
9669400ff5abSMatthias Ringwald 
96709427aeb5SMatthias Ringwald static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
967120dcdd22SMatthias Ringwald     uint16_t sco_packet_length = 0;
9672cf119f3bSMatthias Ringwald 
967391dfed7eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
9674a086dc35SMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as many bytes
967573f498e7SMatthias Ringwald     int multiplier;
967673f498e7SMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
967773f498e7SMatthias Ringwald         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
967873f498e7SMatthias Ringwald         multiplier = 2;
967973f498e7SMatthias Ringwald     } else {
968073f498e7SMatthias Ringwald         multiplier = 1;
968173f498e7SMatthias Ringwald     }
968291dfed7eSMatthias Ringwald #endif
968391dfed7eSMatthias Ringwald 
96849427aeb5SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
9685400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
9686400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
9687cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
96889427aeb5SMatthias Ringwald         // @note multiple sco connections not supported currently
96899427aeb5SMatthias Ringwald         sco_packet_length = 3 + 24 * multiplier;
9690400ff5abSMatthias Ringwald     } else {
96919427aeb5SMatthias Ringwald         // 3 byte SCO header + SCO packet length over the air
96929427aeb5SMatthias Ringwald         sco_packet_length = 3 + payload_size * multiplier;
9693d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
9694ad915196SMatthias Ringwald         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
96959427aeb5SMatthias Ringwald             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9696d966a453SMatthias Ringwald         }
9697400ff5abSMatthias Ringwald     }
9698a3069afeSMatthias Ringwald #endif
96995b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
97009427aeb5SMatthias Ringwald     // 3 byte SCO header + SCO packet length over the air
97019427aeb5SMatthias Ringwald     sco_packet_length = 3 + payload_size * multiplier;
97029427aeb5SMatthias Ringwald     // assert that it still fits inside an SCO buffer
97039427aeb5SMatthias Ringwald     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
97049427aeb5SMatthias Ringwald         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
97059427aeb5SMatthias Ringwald     }
97065b7087c7SMatthias Ringwald #endif
9707a3069afeSMatthias Ringwald     return sco_packet_length;
9708b3aad8daSMatthias Ringwald }
9709b3aad8daSMatthias Ringwald 
97109427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
97119427aeb5SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
97129427aeb5SMatthias Ringwald     if (connection != NULL){
97139427aeb5SMatthias Ringwald         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
97149427aeb5SMatthias Ringwald     }
97159427aeb5SMatthias Ringwald     return 0;
97169427aeb5SMatthias Ringwald }
97179427aeb5SMatthias Ringwald 
97189427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length(void){
97199427aeb5SMatthias Ringwald     btstack_linked_list_iterator_t it;
97209427aeb5SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
97219427aeb5SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
97229427aeb5SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
97239427aeb5SMatthias Ringwald         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
97249427aeb5SMatthias Ringwald             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
97259427aeb5SMatthias Ringwald         }
97269427aeb5SMatthias Ringwald     }
97279427aeb5SMatthias Ringwald     return 0;
97289427aeb5SMatthias Ringwald }
97299427aeb5SMatthias Ringwald 
9730c4c88f1bSJakob Krantz /**
9731c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
9732c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
9733c4c88f1bSJakob Krantz */
9734c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
9735c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
9736c4c88f1bSJakob Krantz }
9737c4c88f1bSJakob Krantz 
9738c4c88f1bSJakob Krantz #endif
9739ec111c8bSMatthias Ringwald 
9740ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
9741ec111c8bSMatthias Ringwald     return hci_stack->state;
9742ec111c8bSMatthias Ringwald }
9743ec111c8bSMatthias Ringwald 
974407e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
97455e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
974607e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
974707e010b6SMilanka Ringwald }
974807e010b6SMilanka Ringwald #endif
9749ec111c8bSMatthias Ringwald 
9750d950d659SMatthias Ringwald /**
9751d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
9752d23838ecSMatthias Ringwald  */
9753c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9754d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
9755d23838ecSMatthias Ringwald }
9756d23838ecSMatthias Ringwald 
975771de195eSMatthias Ringwald void hci_disconnect_all(void){
9758665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9759665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9760665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9761665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
976204a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
976304a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
976404a6ef8cSmatthias.ringwald     }
9765d31fba26S[email protected]     hci_run();
976604a6ef8cSmatthias.ringwald }
976733373e40SMatthias Ringwald 
976833373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
976933373e40SMatthias Ringwald     return hci_stack->manufacturer;
977033373e40SMatthias Ringwald }
97719c6e867eSMatthias Ringwald 
97723e329ddfSandryblack #ifdef ENABLE_BLE
97739c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
97749c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
97759c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
97769c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
97779c6e867eSMatthias Ringwald }
97789c6e867eSMatthias Ringwald 
97799c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
9780a086dc35SMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() result in non-encrypted, not-authenticated
97816a79f6baSMatthias Ringwald #endif
97829c6e867eSMatthias Ringwald 
97836d105c71SMatthias Ringwald uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9784c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9785c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
9786c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
97876a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
9788c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9789c7bead46SMatthias Ringwald         if (sm_conn->sm_connection_encrypted != 0u) {
97909c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
97919c6e867eSMatthias Ringwald         }
97926a79f6baSMatthias Ringwald #endif
97936a79f6baSMatthias Ringwald     } else {
9794c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
97958daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9796c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
9797c5fb5ca4SMatthias Ringwald         }
9798c5fb5ca4SMatthias Ringwald #endif
97996a79f6baSMatthias Ringwald     }
9800c5fb5ca4SMatthias Ringwald     return 0;
9801c5fb5ca4SMatthias Ringwald }
98029c6e867eSMatthias Ringwald 
9803ff3f1026SMatthias Ringwald bool gap_authenticated(hci_con_handle_t con_handle){
9804c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9805ff3f1026SMatthias Ringwald     if (hci_connection == NULL) return false;
98065f3981bfSMatthias Ringwald 
9807c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
98086a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98095f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
98105f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9811d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9812d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9813c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9814ff3f1026SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated != 0;
98156a79f6baSMatthias Ringwald #endif
981659a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
98175f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9818f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9819ff3f1026SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
982059a1a47aSMatthias Ringwald #endif
98215f3981bfSMatthias Ringwald         default:
9822ff3f1026SMatthias Ringwald             return false;
98235f3981bfSMatthias Ringwald     }
98249c6e867eSMatthias Ringwald }
98259c6e867eSMatthias Ringwald 
9826f461b3dfSMatthias Ringwald bool gap_secure_connection(hci_con_handle_t con_handle){
9827c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9828c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
98298b35e16aSMatthias Ringwald 
9830c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
98316a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98328b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
98338b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9834d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9835d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
9836f461b3dfSMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9837d7dbf891SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc;
98386a79f6baSMatthias Ringwald #endif
983959a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
98408b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9841f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9842f461b3dfSMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
984359a1a47aSMatthias Ringwald #endif
98448b35e16aSMatthias Ringwald         default:
9845f461b3dfSMatthias Ringwald             return false;
98468b35e16aSMatthias Ringwald     }
9847f1dfbe18SMatthias Ringwald }
9848f1dfbe18SMatthias Ringwald 
98491e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
98501e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
98511e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
98521e122704SMatthias Ringwald 
985348f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
98541e122704SMatthias Ringwald 	link_key_t link_key;
98551e122704SMatthias Ringwald 	link_key_type_t link_key_type;
985648f33f37SMatthias Ringwald #endif
98571e122704SMatthias Ringwald 	switch (hci_connection->address_type){
98586a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98591e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
98601e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
9861d9e1bf33SMatthias Ringwald 	    case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
9862d9e1bf33SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
98631e122704SMatthias Ringwald             return hci_connection->sm_connection.sm_le_db_index >= 0;
98646a79f6baSMatthias Ringwald #endif
98651e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
98661e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
98671e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
98681e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
98691e122704SMatthias Ringwald #endif
98701e122704SMatthias Ringwald 		default:
98711e122704SMatthias Ringwald 			return false;
98721e122704SMatthias Ringwald 	}
98731e122704SMatthias Ringwald }
98741e122704SMatthias Ringwald 
98756a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
98769c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
98779c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
9878c7bead46SMatthias Ringwald     if (sm_conn == NULL)                             return AUTHORIZATION_UNKNOWN; // wrong connection
9879c7bead46SMatthias Ringwald     if (sm_conn->sm_connection_encrypted == 0u)      return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
9880a086dc35SMatthias Ringwald     if (sm_conn->sm_connection_authenticated == 0u)  return AUTHORIZATION_UNKNOWN; // unauthenticated connection cannot be authorized
98819c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
98829c6e867eSMatthias Ringwald }
98839c6e867eSMatthias Ringwald #endif
9884f8ee3071SMatthias Ringwald 
9885f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
9886f8ee3071SMatthias 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){
9887f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
98887f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9889f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
9890f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
9891f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
9892f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
9893f8ee3071SMatthias Ringwald     hci_run();
9894f8ee3071SMatthias Ringwald     return 0;
9895f8ee3071SMatthias Ringwald }
9896f8ee3071SMatthias Ringwald 
9897f8ee3071SMatthias Ringwald /**
9898f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
9899f8ee3071SMatthias Ringwald  * @param con_handle
9900f8ee3071SMatthias Ringwald  @ @return 0 if ok
9901f8ee3071SMatthias Ringwald  */
9902f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9903f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99047f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9905f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
9906f8ee3071SMatthias Ringwald     hci_run();
9907f8ee3071SMatthias Ringwald     return 0;
9908f8ee3071SMatthias Ringwald }
9909bea424a5SMatthias Ringwald 
9910140c0557SMatthias 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){
9911140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99127f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9913140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
9914140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9915140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9916140c0557SMatthias Ringwald     hci_run();
9917dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9918140c0557SMatthias Ringwald }
9919140c0557SMatthias Ringwald 
9920278ff8a9SMatthias 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){
9921278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
99227f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9923278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
9924278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
9925278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
9926278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
9927278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
9928278ff8a9SMatthias Ringwald     hci_run();
9929278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9930278ff8a9SMatthias Ringwald }
9931278ff8a9SMatthias Ringwald 
9932bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9933bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
9934bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
9935baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9936bea424a5SMatthias Ringwald     hci_run();
9937bea424a5SMatthias Ringwald }
9938bea424a5SMatthias Ringwald 
9939bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9940bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9941baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9942bea424a5SMatthias Ringwald     hci_run();
9943bea424a5SMatthias Ringwald }
9944bea424a5SMatthias Ringwald 
994532a12730SMatthias Ringwald void gap_set_page_timeout(uint16_t page_timeout){
994632a12730SMatthias Ringwald     hci_stack->page_timeout = page_timeout;
9947baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
994832a12730SMatthias Ringwald     hci_run();
994932a12730SMatthias Ringwald }
995032a12730SMatthias Ringwald 
9951f8ee3071SMatthias Ringwald #endif
9952beceeddeSMatthias Ringwald 
995321debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
995421debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
995521debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
995621debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
995721debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
995821debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
995902b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9960e8ca66c6SMatthias Ringwald     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
996121debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
996202b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
99635f3ccd83SMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
996402b02cffSMatthias Ringwald     }
996502b02cffSMatthias Ringwald }
996602b02cffSMatthias Ringwald 
996702b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
996802b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
996902b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
997002b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
997102b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
997202b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
997302b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
99745f3ccd83SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
997521debf25SMatthias Ringwald 	}
997621debf25SMatthias Ringwald }
9977cf38a091SMatthias Ringwald 
9978cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
99791ffa425cSMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9980cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9981cf38a091SMatthias Ringwald 	}
9982cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9983cf38a091SMatthias Ringwald 		// restart le resolving list update
9984cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9985cf38a091SMatthias Ringwald 	}
9986cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
9987cf38a091SMatthias Ringwald }
9988c3d19a30SMatthias Ringwald 
9989c3d19a30SMatthias Ringwald void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9990c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = privacy_mode;
9991c3d19a30SMatthias Ringwald }
999221debf25SMatthias Ringwald #endif
999321debf25SMatthias Ringwald 
9994f40c73b4SMatthias Ringwald #ifdef ENABLE_BLE
9995f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
9996f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9997f40c73b4SMatthias Ringwald 
9998f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9999100da355SMatthias Ringwald 
10000100da355SMatthias Ringwald #if !defined(HAVE_MALLOC) && (!defined(MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES) || (MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES == 0))
10001100da355SMatthias Ringwald     // incorrect configuration:
10002100da355SMatthias Ringwald     // - as MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES is not defined or zero this function always fails
10003100da355SMatthias Ringwald     // - please set MAX_NR_PERIODIC_ADVERTISER_LIST_ENTRIES in btstack_config.h
10004100da355SMatthias Ringwald     btstack_assert(false);
10005100da355SMatthias Ringwald #endif
10006100da355SMatthias Ringwald 
10007f40c73b4SMatthias Ringwald     // check if already in list
10008f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10009f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10010f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10011f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
10012f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
10013f40c73b4SMatthias Ringwald             continue;
10014f40c73b4SMatthias Ringwald         }
10015f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
10016f40c73b4SMatthias Ringwald             continue;
10017f40c73b4SMatthias Ringwald         }
10018f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
10019f40c73b4SMatthias Ringwald             continue;
10020f40c73b4SMatthias Ringwald         }
10021f40c73b4SMatthias Ringwald         // disallow if already scheduled to add
10022f40c73b4SMatthias Ringwald         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
10023f40c73b4SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
10024f40c73b4SMatthias Ringwald         }
10025f40c73b4SMatthias Ringwald         // still on controller, but scheduled to remove -> re-add
10026f40c73b4SMatthias Ringwald         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
10027f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
10028f40c73b4SMatthias Ringwald     }
10029f40c73b4SMatthias Ringwald     // alloc and add to list
10030f40c73b4SMatthias Ringwald     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
10031f40c73b4SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
10032f40c73b4SMatthias Ringwald     entry->sid = advertising_sid;
10033f40c73b4SMatthias Ringwald     entry->address_type = address_type;
10034f40c73b4SMatthias Ringwald     (void)memcpy(entry->address, address, 6);
10035f40c73b4SMatthias Ringwald     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
10036f40c73b4SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
10037f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10038f40c73b4SMatthias Ringwald }
10039f40c73b4SMatthias Ringwald 
10040f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10041f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10042f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10043f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10044f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
10045f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
10046f40c73b4SMatthias Ringwald             continue;
10047f40c73b4SMatthias Ringwald         }
10048f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
10049f40c73b4SMatthias Ringwald             continue;
10050f40c73b4SMatthias Ringwald         }
10051f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
10052f40c73b4SMatthias Ringwald             continue;
10053f40c73b4SMatthias Ringwald         }
10054f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
10055f40c73b4SMatthias Ringwald             // remove from controller if already present
10056f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
10057f40c73b4SMatthias Ringwald         }  else {
10058f40c73b4SMatthias Ringwald             // directly remove entry from whitelist
10059f40c73b4SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
10060f40c73b4SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
10061f40c73b4SMatthias Ringwald         }
10062f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
10063f40c73b4SMatthias Ringwald     }
10064f40c73b4SMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10065f40c73b4SMatthias Ringwald }
10066f40c73b4SMatthias Ringwald 
10067f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_clear(void){
10068f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
10069f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
10070f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10071f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
10072f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
10073f40c73b4SMatthias Ringwald             // remove from controller if already present
10074f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
10075f40c73b4SMatthias Ringwald             continue;
10076f40c73b4SMatthias Ringwald         }
10077f40c73b4SMatthias Ringwald         // directly remove entry from whitelist
10078f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
10079f40c73b4SMatthias Ringwald         btstack_memory_periodic_advertiser_list_entry_free(entry);
10080f40c73b4SMatthias Ringwald     }
10081f40c73b4SMatthias Ringwald }
10082f40c73b4SMatthias Ringwald 
10083f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_clear(void){
10084f40c73b4SMatthias Ringwald     hci_periodic_advertiser_list_clear();
10085f40c73b4SMatthias Ringwald     hci_run();
10086f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10087f40c73b4SMatthias Ringwald }
10088f40c73b4SMatthias Ringwald 
10089f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10090f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
10091f40c73b4SMatthias Ringwald     if (status){
10092f40c73b4SMatthias Ringwald         return status;
10093f40c73b4SMatthias Ringwald     }
10094f40c73b4SMatthias Ringwald     hci_run();
10095f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10096f40c73b4SMatthias Ringwald }
10097f40c73b4SMatthias Ringwald 
10098f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
10099f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
10100f40c73b4SMatthias Ringwald     if (status){
10101f40c73b4SMatthias Ringwald         return status;
10102f40c73b4SMatthias Ringwald     }
10103f40c73b4SMatthias Ringwald     hci_run();
10104f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10105f40c73b4SMatthias Ringwald }
101064bafedd5SMatthias Ringwald 
101074bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
101084bafedd5SMatthias Ringwald                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
101094bafedd5SMatthias Ringwald     // abort if already active
101104bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
101114bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
101124bafedd5SMatthias Ringwald     }
101134bafedd5SMatthias Ringwald     // store request
101144bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
101154bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_options = options;
101164bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
101174bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
101184bafedd5SMatthias Ringwald     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
101194bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_skip = skip;
101204bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_timeout = sync_timeout;
101214bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
101224bafedd5SMatthias Ringwald 
101234bafedd5SMatthias Ringwald     hci_run();
101244bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101254bafedd5SMatthias Ringwald }
101264bafedd5SMatthias Ringwald 
101274bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync_cancel(void){
101284bafedd5SMatthias Ringwald     // abort if not requested
101294bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
101304bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
101314bafedd5SMatthias Ringwald     }
101324bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
101334bafedd5SMatthias Ringwald     hci_run();
101344bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101354bafedd5SMatthias Ringwald }
101364bafedd5SMatthias Ringwald 
101374bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
1013849a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
1013949a6c69cSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
1014049a6c69cSMatthias Ringwald     }
1014149a6c69cSMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
1014249a6c69cSMatthias Ringwald     hci_run();
1014349a6c69cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
101444bafedd5SMatthias Ringwald }
101454bafedd5SMatthias Ringwald 
10146f40c73b4SMatthias Ringwald #endif
10147f40c73b4SMatthias Ringwald #endif
101484ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
10149969d876aSMatthias Ringwald static hci_iso_stream_t *
10150969d876aSMatthias 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) {
101514ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
10152969d876aSMatthias Ringwald     if (iso_stream != NULL){
101538d72db10SMatthias Ringwald         iso_stream->iso_type = iso_type;
1015426b93350SMatthias Ringwald         iso_stream->state = state;
101558d72db10SMatthias Ringwald         iso_stream->group_id = group_id;
10156969d876aSMatthias Ringwald         iso_stream->stream_id = stream_id;
10157969d876aSMatthias Ringwald         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
10158969d876aSMatthias Ringwald         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
101594ae8623eSMatthias Ringwald         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
101604ae8623eSMatthias Ringwald     }
10161969d876aSMatthias Ringwald     return iso_stream;
101624ae8623eSMatthias Ringwald }
101634ae8623eSMatthias Ringwald 
1016415a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
101654ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
101664ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
101674ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
101684ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10169969d876aSMatthias Ringwald         if (iso_stream->cis_handle == con_handle ) {
101704ae8623eSMatthias Ringwald             return iso_stream;
101714ae8623eSMatthias Ringwald         }
101724ae8623eSMatthias Ringwald     }
101734ae8623eSMatthias Ringwald     return NULL;
101744ae8623eSMatthias Ringwald }
101754ae8623eSMatthias Ringwald 
101764ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
10177969d876aSMatthias Ringwald     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
101784ae8623eSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
101794ae8623eSMatthias Ringwald     btstack_memory_hci_iso_stream_free(iso_stream);
101804ae8623eSMatthias Ringwald }
101814ae8623eSMatthias Ringwald 
10182778463d0SMatthias Ringwald static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
10183778463d0SMatthias Ringwald     btstack_linked_list_iterator_t it;
10184778463d0SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
10185778463d0SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10186778463d0SMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10187778463d0SMatthias Ringwald         if ((iso_stream->group_id == group_id) &&
10188778463d0SMatthias Ringwald             (iso_stream->iso_type == iso_type)){
10189778463d0SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
10190778463d0SMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
10191778463d0SMatthias Ringwald         }
10192778463d0SMatthias Ringwald     }
10193778463d0SMatthias Ringwald }
10194778463d0SMatthias Ringwald 
101958d72db10SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t group_id) {
101964ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
101974ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
101984ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
101994ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
10200a90016deSMatthias Ringwald         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
102018d72db10SMatthias Ringwald             (iso_stream->group_id == group_id)){
102024ae8623eSMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
102034ae8623eSMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
102044ae8623eSMatthias Ringwald         }
102054ae8623eSMatthias Ringwald     }
102064ae8623eSMatthias Ringwald }
1020736916f81SDirk Helbig 
10208a90016deSMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle){
1020936916f81SDirk Helbig     UNUSED(big_handle);
1021036916f81SDirk Helbig 
102114ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
102124ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
102134ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
102144ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
102154ae8623eSMatthias Ringwald         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
102164ae8623eSMatthias Ringwald             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
102174ae8623eSMatthias Ringwald         }
102184ae8623eSMatthias Ringwald     }
102194ae8623eSMatthias Ringwald }
10220d39e4f95SMatthias Ringwald 
10221d39e4f95SMatthias Ringwald static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
10222d39e4f95SMatthias Ringwald     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
10223d39e4f95SMatthias Ringwald     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
10224d39e4f95SMatthias Ringwald     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
10225d39e4f95SMatthias Ringwald     return (sdu_len_offset + 2 + sdu_len) == size;
10226d39e4f95SMatthias Ringwald }
10227d39e4f95SMatthias Ringwald 
10228750818acSMatthias Ringwald static void hci_iso_packet_handler(hci_iso_stream_t *iso_stream, uint8_t *packet, uint16_t size) {
10229750818acSMatthias Ringwald     if (iso_stream == NULL){
10230750818acSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , READ_ISO_CONNECTION_HANDLE(packet));
10231d39e4f95SMatthias Ringwald         return;
10232d39e4f95SMatthias Ringwald     }
10233750818acSMatthias Ringwald 
10234750818acSMatthias Ringwald     if (hci_stack->iso_packet_handler == NULL) {
10235d39e4f95SMatthias Ringwald         return;
10236d39e4f95SMatthias Ringwald     }
10237d39e4f95SMatthias Ringwald 
10238d39e4f95SMatthias Ringwald     // parse header
10239a14c18deSMatthias Ringwald     uint16_t con_handle_and_flags = little_endian_read_16(packet, 0);
10240a14c18deSMatthias Ringwald     uint16_t data_total_length = little_endian_read_16(packet, 2);
10241a14c18deSMatthias Ringwald     uint8_t  pb_flag = (con_handle_and_flags >> 12) & 3;
10242d39e4f95SMatthias Ringwald 
10243d39e4f95SMatthias Ringwald     // assert packet is complete
10244a14c18deSMatthias Ringwald     if ((data_total_length + 4u) != size){
10245d39e4f95SMatthias Ringwald         return;
10246d39e4f95SMatthias Ringwald     }
10247d39e4f95SMatthias Ringwald 
10248d39e4f95SMatthias Ringwald     if ((pb_flag & 0x01) == 0){
10249d39e4f95SMatthias Ringwald         if (pb_flag == 0x02){
10250a14c18deSMatthias Ringwald             // The ISO_SDU_Fragment field contains a header and a complete SDU.
10251d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(packet, size)) {
10252d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
10253d39e4f95SMatthias Ringwald             }
10254d39e4f95SMatthias Ringwald         } else {
10255d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
1025660468fb4SMatthias Ringwald             if (size > sizeof(iso_stream->reassembly_buffer)){
10257d39e4f95SMatthias Ringwald                 return;
10258d39e4f95SMatthias Ringwald             }
10259d39e4f95SMatthias Ringwald             memcpy(iso_stream->reassembly_buffer, packet, size);
10260d39e4f95SMatthias Ringwald             // fix pb_flag
10261d39e4f95SMatthias Ringwald             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
10262d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = size;
10263d39e4f95SMatthias Ringwald         }
10264d39e4f95SMatthias Ringwald     } else {
10265a14c18deSMatthias Ringwald         // ISO_SDU_Fragment contains continuation or last fragment of an SDU
10266a14c18deSMatthias Ringwald         uint8_t ts_flag = (con_handle_and_flags >> 14) & 1;
10267d39e4f95SMatthias Ringwald         if (ts_flag != 0){
10268d39e4f95SMatthias Ringwald            return;
10269d39e4f95SMatthias Ringwald         }
10270d39e4f95SMatthias Ringwald         // append fragment
10271d39e4f95SMatthias Ringwald         if (iso_stream->reassembly_pos == 0){
10272d39e4f95SMatthias Ringwald             return;
10273d39e4f95SMatthias Ringwald         }
1027460468fb4SMatthias Ringwald 
10275a14c18deSMatthias Ringwald         if ((iso_stream->reassembly_pos + data_total_length) > sizeof(iso_stream->reassembly_buffer)){
10276d39e4f95SMatthias Ringwald             // reset reassembly buffer
10277d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
10278d39e4f95SMatthias Ringwald             return;
10279d39e4f95SMatthias Ringwald         }
10280a14c18deSMatthias Ringwald         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], data_total_length);
10281a14c18deSMatthias Ringwald         iso_stream->reassembly_pos += data_total_length;
10282d39e4f95SMatthias Ringwald 
10283d39e4f95SMatthias Ringwald         // deliver if last fragment and SDU complete
10284d39e4f95SMatthias Ringwald         if (pb_flag == 0x03){
10285d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
10286a14c18deSMatthias Ringwald                 // fix data_total_length
1028760468fb4SMatthias Ringwald                 little_endian_store_16(iso_stream->reassembly_buffer, 2, iso_stream->reassembly_pos - HCI_ISO_HEADER_SIZE);
10288d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
10289d39e4f95SMatthias Ringwald             }
10290a14c18deSMatthias Ringwald             // reset reassembly buffer
10291d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
10292d39e4f95SMatthias Ringwald         }
10293d39e4f95SMatthias Ringwald     }
10294d39e4f95SMatthias Ringwald }
10295d39e4f95SMatthias Ringwald 
102967aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
102977aa35f6aSMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
102987aa35f6aSMatthias Ringwald     uint16_t pos = 0;
102997aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103007aa35f6aSMatthias Ringwald     event[pos++] = 4 + (2 * big->num_bis);
103017aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
103027aa35f6aSMatthias Ringwald     event[pos++] = status;
103037aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
103047aa35f6aSMatthias Ringwald     event[pos++] = big->num_bis;
103057aa35f6aSMatthias Ringwald     uint8_t i;
103067aa35f6aSMatthias Ringwald     for (i=0;i<big->num_bis;i++){
103077aa35f6aSMatthias Ringwald         little_endian_store_16(event, pos, big->bis_con_handles[i]);
103087aa35f6aSMatthias Ringwald         pos += 2;
103097aa35f6aSMatthias Ringwald     }
103109da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103117aa35f6aSMatthias Ringwald }
103127aa35f6aSMatthias Ringwald 
10313d3a89d91SMatthias Ringwald static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
10314d3a89d91SMatthias Ringwald     uint8_t event [6 + (MAX_NR_CIS * 2)];
10315d3a89d91SMatthias Ringwald     uint16_t pos = 0;
10316d3a89d91SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
10317d3a89d91SMatthias Ringwald     event[pos++] = 4 + (2 * cig->num_cis);
10318d3a89d91SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
10319d3a89d91SMatthias Ringwald     event[pos++] = status;
10320d3a89d91SMatthias Ringwald     event[pos++] = cig->cig_id;
10321d3a89d91SMatthias Ringwald     event[pos++] = cig->num_cis;
10322d3a89d91SMatthias Ringwald     uint8_t i;
10323d3a89d91SMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10324d3a89d91SMatthias Ringwald         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
10325d3a89d91SMatthias Ringwald         pos += 2;
10326d3a89d91SMatthias Ringwald     }
103279da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
10328d3a89d91SMatthias Ringwald }
10329f06bb90fSMatthias Ringwald 
10330620553bdSMatthias Ringwald static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
10331f06bb90fSMatthias Ringwald     uint16_t pos = 0;
10332f06bb90fSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
10333cf439c63SMatthias Ringwald     event[pos++] = 8;
10334f06bb90fSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
10335f06bb90fSMatthias Ringwald     event[pos++] = status;
10336620553bdSMatthias Ringwald     event[pos++] = iso_stream->group_id;
10337620553bdSMatthias Ringwald     event[pos++] = iso_stream->stream_id;
10338620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->cis_handle);
10339f06bb90fSMatthias Ringwald     pos += 2;
10340620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->acl_handle);
10341cf439c63SMatthias Ringwald     pos += 2;
103427dd97f73SMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->iso_interval_1250us);
103437dd97f73SMatthias Ringwald     pos += 2;
103447dd97f73SMatthias Ringwald     event[pos++] = iso_stream->number_of_subevents;
103457dd97f73SMatthias Ringwald     event[pos++] = iso_stream->burst_number_c_to_p;
103467dd97f73SMatthias Ringwald     event[pos++] = iso_stream->burst_number_p_to_c;
103477dd97f73SMatthias Ringwald     event[pos++] = iso_stream->flush_timeout_c_to_p;
103487dd97f73SMatthias Ringwald     event[pos++] = iso_stream->flush_timeout_p_to_c;
10349620553bdSMatthias Ringwald     return pos;
10350f06bb90fSMatthias Ringwald }
10351f06bb90fSMatthias Ringwald 
1035214045fdbSMatthias Ringwald // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
1035314045fdbSMatthias Ringwald static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
1035414045fdbSMatthias Ringwald     // cache data before finalizing struct
103557dd97f73SMatthias Ringwald     uint8_t event [17];
10356620553bdSMatthias Ringwald     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
10357620553bdSMatthias Ringwald     btstack_assert(pos <= sizeof(event));
1035814045fdbSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
1035914045fdbSMatthias Ringwald         hci_iso_stream_finalize(iso_stream);
1036014045fdbSMatthias Ringwald     }
103619da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
1036214045fdbSMatthias Ringwald }
1036314045fdbSMatthias Ringwald 
103647aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big){
103657aa35f6aSMatthias Ringwald     uint8_t event [4];
103667aa35f6aSMatthias Ringwald     uint16_t pos = 0;
103677aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103687aa35f6aSMatthias Ringwald     event[pos++] = 2;
103697aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
103707aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
103719da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103727aa35f6aSMatthias Ringwald }
103737aa35f6aSMatthias Ringwald 
103742a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
103752a6c0f82SMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
103762a6c0f82SMatthias Ringwald     uint16_t pos = 0;
103772a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103782a6c0f82SMatthias Ringwald     event[pos++] = 4;
103792a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
103802a6c0f82SMatthias Ringwald     event[pos++] = status;
103812a6c0f82SMatthias Ringwald     event[pos++] = big_sync->big_handle;
103822a6c0f82SMatthias Ringwald     event[pos++] = big_sync->num_bis;
103832a6c0f82SMatthias Ringwald     uint8_t i;
103842a6c0f82SMatthias Ringwald     for (i=0;i<big_sync->num_bis;i++){
103852a6c0f82SMatthias Ringwald         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
103862a6c0f82SMatthias Ringwald         pos += 2;
103872a6c0f82SMatthias Ringwald     }
103889da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103892a6c0f82SMatthias Ringwald }
103902a6c0f82SMatthias Ringwald 
10391d04a9afcSMatthias Ringwald static void hci_emit_big_sync_stopped(uint8_t big_handle){
103922a6c0f82SMatthias Ringwald     uint8_t event [4];
103932a6c0f82SMatthias Ringwald     uint16_t pos = 0;
103942a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
103952a6c0f82SMatthias Ringwald     event[pos++] = 2;
103962a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
10397d04a9afcSMatthias Ringwald     event[pos++] = big_handle;
103989da9850bSMatthias Ringwald     hci_emit_btstack_event(event, pos, 0);
103992a6c0f82SMatthias Ringwald }
104002a6c0f82SMatthias Ringwald 
104015ade6657SMatthias Ringwald static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
104025ade6657SMatthias Ringwald     uint8_t event[6];
104035ade6657SMatthias Ringwald     uint16_t pos = 0;
104045ade6657SMatthias Ringwald     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
104055ade6657SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
104065ade6657SMatthias Ringwald     event[pos++] = big->big_handle;
104075ade6657SMatthias Ringwald     event[pos++] = bis_index;
104085ade6657SMatthias Ringwald     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
104099da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
104105ade6657SMatthias Ringwald }
104115ade6657SMatthias Ringwald 
104122c077771SMatthias Ringwald static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
104132c077771SMatthias Ringwald     uint8_t event[4];
104142c077771SMatthias Ringwald     uint16_t pos = 0;
104152c077771SMatthias Ringwald     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
104162c077771SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
104172c077771SMatthias Ringwald     little_endian_store_16(event, pos, cis_con_handle);
104189da9850bSMatthias Ringwald     hci_emit_btstack_event(&event[0], sizeof(event), 0);  // don't dump
104192c077771SMatthias Ringwald }
104202c077771SMatthias Ringwald 
104217aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
104227aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
104237aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
104247aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104257aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
104267aa35f6aSMatthias Ringwald         if ( big->big_handle == big_handle ) {
104277aa35f6aSMatthias Ringwald             return big;
104287aa35f6aSMatthias Ringwald         }
104297aa35f6aSMatthias Ringwald     }
104307aa35f6aSMatthias Ringwald     return NULL;
104317aa35f6aSMatthias Ringwald }
104327aa35f6aSMatthias Ringwald 
104332a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
104342a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_t it;
104352a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
104362a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104372a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
104382a6c0f82SMatthias Ringwald         if ( big_sync->big_handle == big_handle ) {
104392a6c0f82SMatthias Ringwald             return big_sync;
104402a6c0f82SMatthias Ringwald         }
104412a6c0f82SMatthias Ringwald     }
104422a6c0f82SMatthias Ringwald     return NULL;
104432a6c0f82SMatthias Ringwald }
104442a6c0f82SMatthias Ringwald 
1044501d4f05fSMatthias Ringwald void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
1044601d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = num_packets;
1044701d4f05fSMatthias Ringwald }
1044801d4f05fSMatthias Ringwald 
10449d3a89d91SMatthias Ringwald static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10450d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_t it;
10451d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10452d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10453d3a89d91SMatthias Ringwald         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10454d3a89d91SMatthias Ringwald         if ( cig->cig_id == cig_id ) {
10455d3a89d91SMatthias Ringwald             return cig;
10456d3a89d91SMatthias Ringwald         }
10457d3a89d91SMatthias Ringwald     }
10458d3a89d91SMatthias Ringwald     return NULL;
10459d3a89d91SMatthias Ringwald }
10460d3a89d91SMatthias Ringwald 
104615ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void){
104622c077771SMatthias Ringwald 
104632c077771SMatthias Ringwald     // BIG
104642c077771SMatthias Ringwald 
104655ade6657SMatthias Ringwald     btstack_linked_list_iterator_t it;
104665ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
104675ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
104685ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10469aacb1081SMatthias Ringwald         // track number completed packet timestamps
10470aacb1081SMatthias Ringwald         if (big->num_completed_timestamp_current_valid){
10471aacb1081SMatthias Ringwald             big->num_completed_timestamp_current_valid = false;
10472aacb1081SMatthias Ringwald             if (big->num_completed_timestamp_previous_valid){
10473aacb1081SMatthias Ringwald                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
1047436916f81SDirk Helbig                 int32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10475aacb1081SMatthias Ringwald                 int32_t num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10476aacb1081SMatthias Ringwald                                                                                big->num_completed_timestamp_previous_ms);
10477aacb1081SMatthias Ringwald                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10478aacb1081SMatthias Ringwald                     // to catch up, skip packet on all BIS
10479aacb1081SMatthias Ringwald                     uint8_t i;
10480aacb1081SMatthias Ringwald                     for (i=0;i<big->num_bis;i++){
10481aacb1081SMatthias Ringwald                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10482aacb1081SMatthias Ringwald                         if (iso_stream){
10483aacb1081SMatthias Ringwald                             iso_stream->num_packets_to_skip++;
10484aacb1081SMatthias Ringwald                         }
10485aacb1081SMatthias Ringwald                     }
10486aacb1081SMatthias Ringwald                 }
10487aacb1081SMatthias Ringwald             }
10488aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_valid = true;
10489aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10490aacb1081SMatthias Ringwald         }
10491aacb1081SMatthias Ringwald 
104925ade6657SMatthias Ringwald         if (big->can_send_now_requested){
10493d4e5d4faSMatthias Ringwald             // check if no outgoing iso packets pending and no can send now have to be emitted
104945ade6657SMatthias Ringwald             uint8_t i;
104955ade6657SMatthias Ringwald             bool can_send = true;
10496aacb1081SMatthias Ringwald             uint8_t num_iso_queued_minimum = 0;
104975ade6657SMatthias Ringwald             for (i=0;i<big->num_bis;i++){
104985ade6657SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10499aacb1081SMatthias Ringwald                 if (iso_stream == NULL) continue;
10500aacb1081SMatthias Ringwald                 // handle case where individual ISO packet was sent too late:
10501aacb1081SMatthias Ringwald                 // for each additionally queued packet, a new one needs to get skipped
10502aacb1081SMatthias Ringwald                 if (i==0){
10503aacb1081SMatthias Ringwald                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10504aacb1081SMatthias Ringwald                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10505aacb1081SMatthias Ringwald                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10506aacb1081SMatthias Ringwald                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10507aacb1081SMatthias Ringwald                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10508aacb1081SMatthias Ringwald                 }
10509aacb1081SMatthias Ringwald                 // check if we can send now
10510aacb1081SMatthias Ringwald                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
105115ade6657SMatthias Ringwald                     can_send = false;
105125ade6657SMatthias Ringwald                     break;
105135ade6657SMatthias Ringwald                 }
105145ade6657SMatthias Ringwald             }
105155ade6657SMatthias Ringwald             if (can_send){
105165ade6657SMatthias Ringwald                 // propagate can send now to individual streams
105175ade6657SMatthias Ringwald                 big->can_send_now_requested = false;
105185ade6657SMatthias Ringwald                 for (i=0;i<big->num_bis;i++){
105195ade6657SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
105205ade6657SMatthias Ringwald                     iso_stream->emit_ready_to_send = true;
105215ade6657SMatthias Ringwald                 }
105225ade6657SMatthias Ringwald             }
105235ade6657SMatthias Ringwald         }
105245ade6657SMatthias Ringwald     }
105255ade6657SMatthias Ringwald 
105265ade6657SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return;
105275ade6657SMatthias Ringwald 
105285ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
105295ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
105305ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
105315ade6657SMatthias Ringwald         // report bis ready
105325ade6657SMatthias Ringwald         uint8_t i;
105335ade6657SMatthias Ringwald         for (i=0;i<big->num_bis;i++){
105345ade6657SMatthias Ringwald             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
105355ade6657SMatthias Ringwald             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
105365ade6657SMatthias Ringwald                 iso_stream->emit_ready_to_send = false;
105375ade6657SMatthias Ringwald                 hci_emit_bis_can_send_now(big, i);
105380fc451bcSMatthias Ringwald                 if (hci_stack->hci_packet_buffer_reserved) return;
105395ade6657SMatthias Ringwald             }
105405ade6657SMatthias Ringwald         }
105415ade6657SMatthias Ringwald     }
105422c077771SMatthias Ringwald 
105430fc451bcSMatthias Ringwald 
105442c077771SMatthias Ringwald     // CIS
105452c077771SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
105462c077771SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
105472c077771SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
105482c077771SMatthias Ringwald         if ((iso_stream->can_send_now_requested) &&
105492c077771SMatthias Ringwald             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
105502c077771SMatthias Ringwald             iso_stream->can_send_now_requested = false;
10551969d876aSMatthias Ringwald             hci_emit_cis_can_send_now(iso_stream->cis_handle);
105520fc451bcSMatthias Ringwald             if (hci_stack->hci_packet_buffer_reserved) return;
105532c077771SMatthias Ringwald         }
105542c077771SMatthias Ringwald     }
105555ade6657SMatthias Ringwald }
105565ade6657SMatthias Ringwald 
10557c7308688SMatthias Ringwald static uint8_t gap_big_setup_iso_streams(uint8_t num_bis, uint8_t big_handle){
10558d034696aSMatthias Ringwald     // make big handle unique and usuable for big and big sync
10559c7308688SMatthias Ringwald     if (hci_big_for_handle(big_handle) != NULL){
105607aa35f6aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
105617aa35f6aSMatthias Ringwald     }
10562c7308688SMatthias Ringwald     if (hci_big_sync_for_handle(big_handle) != NULL){
10563d034696aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10564d034696aSMatthias Ringwald     }
10565c7308688SMatthias Ringwald     if (num_bis == 0){
105667aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
105677aa35f6aSMatthias Ringwald     }
10568c7308688SMatthias Ringwald     if (num_bis > MAX_NR_BIS){
105697aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
105707aa35f6aSMatthias Ringwald     }
105717aa35f6aSMatthias Ringwald 
10572fb16346aSMatthias Ringwald     // reserve ISO Streams
10573fb16346aSMatthias Ringwald     uint8_t i;
10574fb16346aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10575c7308688SMatthias Ringwald     for (i=0;i<num_bis;i++){
10576c7308688SMatthias Ringwald         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_handle, i);
10577969d876aSMatthias Ringwald         if (iso_stream == NULL) {
10578969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10579fb16346aSMatthias Ringwald             break;
10580fb16346aSMatthias Ringwald         }
10581fb16346aSMatthias Ringwald     }
10582fb16346aSMatthias Ringwald 
10583fb16346aSMatthias Ringwald     // free structs on error
10584fb16346aSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10585c7308688SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_handle);
10586c7308688SMatthias Ringwald     }
10587c7308688SMatthias Ringwald 
10588c7308688SMatthias Ringwald     return status;
10589c7308688SMatthias Ringwald }
10590c7308688SMatthias Ringwald 
10591c7308688SMatthias Ringwald uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
10592c7308688SMatthias Ringwald     uint8_t status = gap_big_setup_iso_streams(big_params->num_bis, big_params->big_handle);
10593c7308688SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10594fb16346aSMatthias Ringwald         return status;
10595fb16346aSMatthias Ringwald     }
10596fb16346aSMatthias Ringwald 
105977aa35f6aSMatthias Ringwald     le_audio_big_t * big = storage;
105987aa35f6aSMatthias Ringwald     big->big_handle = big_params->big_handle;
105997aa35f6aSMatthias Ringwald     big->params = big_params;
106007aa35f6aSMatthias Ringwald     big->state = LE_AUDIO_BIG_STATE_CREATE;
106017aa35f6aSMatthias Ringwald     big->num_bis = big_params->num_bis;
106027aa35f6aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
106037aa35f6aSMatthias Ringwald 
106047aa35f6aSMatthias Ringwald     hci_run();
106057aa35f6aSMatthias Ringwald 
106067aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
106077aa35f6aSMatthias Ringwald }
106087aa35f6aSMatthias Ringwald 
106092a6c0f82SMatthias Ringwald uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
10610c7308688SMatthias Ringwald     uint8_t status = gap_big_setup_iso_streams(big_sync_params->num_bis, big_sync_params->big_handle);
1061102e19895SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
1061202e19895SMatthias Ringwald         return status;
1061302e19895SMatthias Ringwald     }
1061402e19895SMatthias Ringwald 
106152a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = storage;
106162a6c0f82SMatthias Ringwald     big_sync->big_handle = big_sync_params->big_handle;
106172a6c0f82SMatthias Ringwald     big_sync->params = big_sync_params;
106182a6c0f82SMatthias Ringwald     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
106192a6c0f82SMatthias Ringwald     big_sync->num_bis = big_sync_params->num_bis;
106202a6c0f82SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
106212a6c0f82SMatthias Ringwald 
106222a6c0f82SMatthias Ringwald     hci_run();
106232a6c0f82SMatthias Ringwald 
106242a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106252a6c0f82SMatthias Ringwald }
106262a6c0f82SMatthias Ringwald 
106277aa35f6aSMatthias Ringwald uint8_t gap_big_terminate(uint8_t big_handle){
106287aa35f6aSMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
106297aa35f6aSMatthias Ringwald     if (big == NULL){
106307aa35f6aSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106317aa35f6aSMatthias Ringwald     }
106327aa35f6aSMatthias Ringwald     switch (big->state){
106337aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
106347aa35f6aSMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
106352a6c0f82SMatthias Ringwald             hci_emit_big_terminated(big);
106362a6c0f82SMatthias Ringwald             break;
106372a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
106382a6c0f82SMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
106397aa35f6aSMatthias Ringwald             break;
106407aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
106417aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
106427aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
106437aa35f6aSMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
106447aa35f6aSMatthias Ringwald             hci_run();
106457aa35f6aSMatthias Ringwald             break;
106462a6c0f82SMatthias Ringwald         default:
106472a6c0f82SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
106482a6c0f82SMatthias Ringwald     }
106492a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106502a6c0f82SMatthias Ringwald }
106512a6c0f82SMatthias Ringwald 
106522a6c0f82SMatthias Ringwald uint8_t gap_big_sync_terminate(uint8_t big_handle){
106532a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
106542a6c0f82SMatthias Ringwald     if (big_sync == NULL){
106552a6c0f82SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106562a6c0f82SMatthias Ringwald     }
106572a6c0f82SMatthias Ringwald     switch (big_sync->state){
106582a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
106592a6c0f82SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10660d04a9afcSMatthias Ringwald             hci_emit_big_sync_stopped(big_handle);
106612a6c0f82SMatthias Ringwald             break;
106627aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
106632a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
106642a6c0f82SMatthias Ringwald             break;
106652a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
106662a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
106672a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
106682a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
106692a6c0f82SMatthias Ringwald             hci_run();
106707aa35f6aSMatthias Ringwald             break;
106717aa35f6aSMatthias Ringwald         default:
106727aa35f6aSMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
106737aa35f6aSMatthias Ringwald     }
106747aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
106757aa35f6aSMatthias Ringwald }
10676d39e4f95SMatthias Ringwald 
106775ade6657SMatthias Ringwald uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
106785ade6657SMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
106795ade6657SMatthias Ringwald     if (big == NULL){
106805ade6657SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106815ade6657SMatthias Ringwald     }
106825ade6657SMatthias Ringwald     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
106835ade6657SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
106845ade6657SMatthias Ringwald     }
106855ade6657SMatthias Ringwald     big->can_send_now_requested = true;
106865ade6657SMatthias Ringwald     hci_iso_notify_can_send_now();
106875ade6657SMatthias Ringwald     return ERROR_CODE_SUCCESS;
106885ade6657SMatthias Ringwald }
10689d3a89d91SMatthias Ringwald 
106902c077771SMatthias Ringwald uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
106912c077771SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
106922c077771SMatthias Ringwald     if (iso_stream == NULL){
106932c077771SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
106942c077771SMatthias Ringwald     }
106952c077771SMatthias Ringwald     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
106962c077771SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
106972c077771SMatthias Ringwald     }
106982c077771SMatthias Ringwald     iso_stream->can_send_now_requested = true;
106992c077771SMatthias Ringwald     hci_iso_notify_can_send_now();
107002c077771SMatthias Ringwald     return ERROR_CODE_SUCCESS;
107012c077771SMatthias Ringwald }
107022c077771SMatthias Ringwald 
10703d3a89d91SMatthias Ringwald uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10704d3a89d91SMatthias Ringwald     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10705d3a89d91SMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10706d3a89d91SMatthias Ringwald     }
10707d3a89d91SMatthias Ringwald     if (cig_params->num_cis == 0){
10708d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10709d3a89d91SMatthias Ringwald     }
107103e377057SMatthias Ringwald     if (cig_params->num_cis > MAX_NR_CIS){
10711d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10712d3a89d91SMatthias Ringwald     }
10713d3a89d91SMatthias Ringwald 
10714d3a89d91SMatthias Ringwald     // reserve ISO Streams
10715d3a89d91SMatthias Ringwald     uint8_t i;
10716d3a89d91SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10717d3a89d91SMatthias Ringwald     for (i=0;i<cig_params->num_cis;i++){
10718969d876aSMatthias 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);
1071936468e6fSMatthias Ringwald         if (iso_stream == NULL) {
10720969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10721d3a89d91SMatthias Ringwald             break;
10722d3a89d91SMatthias Ringwald         }
10723d3a89d91SMatthias Ringwald     }
10724d3a89d91SMatthias Ringwald 
10725d3a89d91SMatthias Ringwald     // free structs on error
10726d3a89d91SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10727d3a89d91SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10728d3a89d91SMatthias Ringwald         return status;
10729d3a89d91SMatthias Ringwald     }
10730d3a89d91SMatthias Ringwald 
10731d3a89d91SMatthias Ringwald     le_audio_cig_t * cig = storage;
10732d3a89d91SMatthias Ringwald     cig->cig_id = cig_params->cig_id;
10733d3a89d91SMatthias Ringwald     cig->num_cis = cig_params->num_cis;
10734d3a89d91SMatthias Ringwald     cig->params = cig_params;
10735d3a89d91SMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10736444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10737444e371eSMatthias Ringwald         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10738444e371eSMatthias Ringwald         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
107390f0ba168SMatthias Ringwald         cig->cis_setup_active[i] = false;
107400f0ba168SMatthias Ringwald         cig->cis_established[i] = false;
10741444e371eSMatthias Ringwald     }
10742d3a89d91SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10743d3a89d91SMatthias Ringwald 
10744d3a89d91SMatthias Ringwald     hci_run();
10745d3a89d91SMatthias Ringwald 
10746d3a89d91SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10747d3a89d91SMatthias Ringwald }
10748d3a89d91SMatthias Ringwald 
10749d90722d4SMatthias Ringwald uint8_t gap_cig_remove(uint8_t cig_id){
10750d90722d4SMatthias Ringwald     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10751d90722d4SMatthias Ringwald     if (cig == NULL){
10752d90722d4SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10753d90722d4SMatthias Ringwald     }
10754d90722d4SMatthias Ringwald 
10755d90722d4SMatthias Ringwald     // close active CIS
10756d90722d4SMatthias Ringwald     uint8_t i;
10757d90722d4SMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10758d90722d4SMatthias Ringwald         hci_iso_stream_t * stream = hci_iso_stream_for_con_handle(cig->cis_con_handles[i]);
10759d90722d4SMatthias Ringwald         if (stream != NULL){
10760d90722d4SMatthias Ringwald             stream->state = HCI_ISO_STREAM_STATE_W2_CLOSE;
10761d90722d4SMatthias Ringwald         }
10762d90722d4SMatthias Ringwald     }
10763d90722d4SMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_REMOVE;
10764d90722d4SMatthias Ringwald 
10765d90722d4SMatthias Ringwald     hci_run();
10766d90722d4SMatthias Ringwald 
10767d90722d4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10768d90722d4SMatthias Ringwald }
10769d90722d4SMatthias Ringwald 
10770f2e409f3SMatthias Ringwald uint8_t gap_cis_create(uint8_t cig_id, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10771f2e409f3SMatthias Ringwald     le_audio_cig_t * cig = hci_cig_for_id(cig_id);
10772444e371eSMatthias Ringwald     if (cig == NULL){
10773444e371eSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10774444e371eSMatthias Ringwald     }
10775444e371eSMatthias Ringwald 
10776444e371eSMatthias Ringwald     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10777444e371eSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
10778444e371eSMatthias Ringwald     }
10779444e371eSMatthias Ringwald 
10780444e371eSMatthias Ringwald     // store ACL Connection Handles
10781444e371eSMatthias Ringwald     uint8_t i;
10782444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
1078356bd2ec0SMatthias Ringwald         // check that all con handles exist and store
10784444e371eSMatthias Ringwald         hci_con_handle_t cis_handle = cis_con_handles[i];
1078536468e6fSMatthias Ringwald         if (cis_handle == HCI_CON_HANDLE_INVALID){
1078636468e6fSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1078736468e6fSMatthias Ringwald         }
10788444e371eSMatthias Ringwald         uint8_t j;
10789444e371eSMatthias Ringwald         bool found = false;
10790444e371eSMatthias Ringwald         for (j=0;j<cig->num_cis;j++){
10791444e371eSMatthias Ringwald             if (cig->cis_con_handles[j] == cis_handle){
10792444e371eSMatthias Ringwald                 cig->acl_con_handles[j] = acl_con_handles[j];
1079356bd2ec0SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
1079456bd2ec0SMatthias Ringwald                 btstack_assert(iso_stream != NULL);
1079556bd2ec0SMatthias Ringwald                 iso_stream->acl_handle = acl_con_handles[j];
1079636468e6fSMatthias Ringwald                 found = true;
10797444e371eSMatthias Ringwald                 break;
10798444e371eSMatthias Ringwald             }
10799444e371eSMatthias Ringwald         }
10800444e371eSMatthias Ringwald         if (!found){
10801444e371eSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10802444e371eSMatthias Ringwald         }
10803444e371eSMatthias Ringwald     }
10804444e371eSMatthias Ringwald 
10805444e371eSMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10806444e371eSMatthias Ringwald     hci_run();
10807444e371eSMatthias Ringwald 
10808444e371eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
10809444e371eSMatthias Ringwald }
10810444e371eSMatthias Ringwald 
10811969d876aSMatthias Ringwald static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10812969d876aSMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
108136fd1d2c8SMatthias Ringwald     if (iso_stream == NULL){
108146fd1d2c8SMatthias Ringwald         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10815969d876aSMatthias Ringwald         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1081626b93350SMatthias Ringwald     }
1081726b93350SMatthias Ringwald 
108186fd1d2c8SMatthias Ringwald     // set next state and continue
108196fd1d2c8SMatthias Ringwald     iso_stream->state = state;
1082026b93350SMatthias Ringwald     hci_run();
1082126b93350SMatthias Ringwald     return ERROR_CODE_SUCCESS;
1082226b93350SMatthias Ringwald }
1082326b93350SMatthias Ringwald 
1082426b93350SMatthias Ringwald uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
1082526b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
1082626b93350SMatthias Ringwald }
1082726b93350SMatthias Ringwald 
1082826b93350SMatthias Ringwald uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
1082926b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
1083026b93350SMatthias Ringwald }
1083126b93350SMatthias Ringwald 
10832137a570aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
1083326b93350SMatthias Ringwald 
10834137a570aSMatthias Ringwald // GAP Privacy - notify clients before random address update
10835137a570aSMatthias Ringwald 
10836137a570aSMatthias Ringwald static bool gap_privacy_client_all_ready(void){
10837137a570aSMatthias Ringwald     // check if all ready
10838137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10839137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10840137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10841137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10842137a570aSMatthias Ringwald         if (client->state != GAP_PRIVACY_CLIENT_STATE_READY){
10843137a570aSMatthias Ringwald             return false;
10844137a570aSMatthias Ringwald         }
10845137a570aSMatthias Ringwald     }
10846137a570aSMatthias Ringwald     return true;
10847137a570aSMatthias Ringwald }
10848137a570aSMatthias Ringwald 
10849137a570aSMatthias Ringwald static void gap_privacy_clients_handle_ready(void){
10850137a570aSMatthias Ringwald     // clear 'ready'
10851137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10852137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10853137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10854137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10855137a570aSMatthias Ringwald         client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10856137a570aSMatthias Ringwald     }
10857137a570aSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_PRIVACY_PENDING;
10858137a570aSMatthias Ringwald     hci_run();
10859137a570aSMatthias Ringwald }
10860137a570aSMatthias Ringwald 
10861137a570aSMatthias Ringwald static void gap_privacy_clients_notify(bd_addr_t new_random_address){
10862137a570aSMatthias Ringwald     btstack_linked_list_iterator_t it;
10863137a570aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->gap_privacy_clients);
10864137a570aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
10865137a570aSMatthias Ringwald         gap_privacy_client_t *client = (gap_privacy_client_t *) btstack_linked_list_iterator_next(&it);
10866137a570aSMatthias Ringwald         if (client->state == GAP_PRIVACY_CLIENT_STATE_IDLE){
10867137a570aSMatthias Ringwald             client->state = GAP_PRIVACY_CLIENT_STATE_PENDING;
10868137a570aSMatthias Ringwald             (*client->callback)(client, new_random_address);
10869137a570aSMatthias Ringwald         }
10870137a570aSMatthias Ringwald     }
10871137a570aSMatthias Ringwald     if (gap_privacy_client_all_ready()){
10872137a570aSMatthias Ringwald         gap_privacy_clients_handle_ready();
10873137a570aSMatthias Ringwald     }
10874137a570aSMatthias Ringwald }
10875137a570aSMatthias Ringwald 
10876137a570aSMatthias Ringwald void gap_privacy_client_register(gap_privacy_client_t * client){
10877137a570aSMatthias Ringwald     client->state = GAP_PRIVACY_CLIENT_STATE_IDLE;
10878137a570aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10879137a570aSMatthias Ringwald }
10880137a570aSMatthias Ringwald 
10881137a570aSMatthias Ringwald void gap_privacy_client_ready(gap_privacy_client_t * client){
10882137a570aSMatthias Ringwald     client->state = GAP_PRIVACY_CLIENT_STATE_READY;
10883137a570aSMatthias Ringwald     if (gap_privacy_client_all_ready()){
10884137a570aSMatthias Ringwald         gap_privacy_clients_handle_ready();
10885137a570aSMatthias Ringwald     }
10886137a570aSMatthias Ringwald }
10887137a570aSMatthias Ringwald 
10888137a570aSMatthias Ringwald void gap_privacy_client_unregister(gap_privacy_client_t * client){
10889137a570aSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->gap_privacy_clients, (btstack_linked_item_t *) client);
10890137a570aSMatthias Ringwald }
10891137a570aSMatthias Ringwald 
108924ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
10893f40c73b4SMatthias Ringwald 
10894eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1089518976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
1089618976c74SMatthias Ringwald     hci_connection_t * conn;
1089718976c74SMatthias Ringwald 
1089818976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
1089918976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
1090018976c74SMatthias Ringwald 
109017d33cb26SMilanka Ringwald     // setup Controller info
109027d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
109037d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
109047d33cb26SMilanka Ringwald 
1090518976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
1090618976c74SMatthias Ringwald     addr[5] = 0x01;
1090717ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1090818976c74SMatthias Ringwald     conn->con_handle = addr[5];
1090918976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
109107d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1091118976c74SMatthias Ringwald 
1091218976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
1091318976c74SMatthias Ringwald     addr[5] = 0x02;
1091417ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1091518976c74SMatthias Ringwald     conn->con_handle = addr[5];
1091618976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
109177d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1091818976c74SMatthias Ringwald 
1091918976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
1092018976c74SMatthias Ringwald     addr[5] = 0x03;
1092117ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1092218976c74SMatthias Ringwald     conn->con_handle = addr[5];
1092318976c74SMatthias Ringwald     conn->state = OPEN;
109247d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1092518976c74SMatthias Ringwald 
1092618976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
1092718976c74SMatthias Ringwald     addr[5] = 0x04;
1092817ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1092918976c74SMatthias Ringwald     conn->con_handle = addr[5];
1093018976c74SMatthias Ringwald     conn->state = OPEN;
109317d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1093218976c74SMatthias Ringwald 
1093318976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
1093418976c74SMatthias Ringwald     addr[5] = 0x05;
1093517ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
1093618976c74SMatthias Ringwald     conn->con_handle = addr[5];
1093718976c74SMatthias Ringwald     conn->state = OPEN;
109387d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
109398046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
1094018976c74SMatthias Ringwald }
1094118976c74SMatthias Ringwald 
10942eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
10943eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
10944eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10945eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10946eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10947eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
10948eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
10949eddac615SMatthias Ringwald     }
10950eddac615SMatthias Ringwald }
109511470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
10952b6ffb67fSMatthias Ringwald     hci_stack->le_scanning_param_update = false;
109531470db0cSMatthias Ringwald     hci_init_done();
109541470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
109551470db0cSMatthias Ringwald }
10956eddac615SMatthias Ringwald #endif
10957