xref: /btstack/src/hci.c (revision e938c062fda498bb7e1f80caf014a4004700fa6c)
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 
96aa81e641SMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
97aa81e641SMatthias 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."
98aa81e641SMatthias Ringwald #endif
99aa81e641SMatthias Ringwald 
1001e20a53eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
1011e20a53eSMatthias 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."
1021e20a53eSMatthias Ringwald #endif
1031e20a53eSMatthias Ringwald 
104169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
10562473419SMatthias Ringwald 
10662473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
107659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
10862473419SMatthias Ringwald #endif
109ee091cf1Smatthias.ringwald 
1101cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1111cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1121cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1131cfb383eSMatthias Ringwald #endif
1141cfb383eSMatthias Ringwald 
115f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
116f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN       0x01
117f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX       0x30
11830199e24SMatthias Ringwald #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02
11930199e24SMatthias Ringwald #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03
120beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE         0x00
121beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
122beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE       0x81
123beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
124beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
12530199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_PERIODIC     0x84
12630199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85
127f5875de5SMatthias Ringwald 
128b7f1ee76SMatthias Ringwald // GAP Remote Name Request
129b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
130b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
131b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
132b7f1ee76SMatthias Ringwald 
1330a51f88bSMatthias Ringwald // GAP Pairing
1340a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1350a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1360a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1370a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1380a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1390a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1400a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
141cc15bb2cSMatthias Ringwald #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
1420a51f88bSMatthias Ringwald 
14325e46151SMatthias Ringwald //
1449ce37759SMatthias Ringwald // compact storage of relevant supported HCI Commands.
1459ce37759SMatthias Ringwald // X-Macro below provides enumeration and mapping table into the supported
14625e46151SMatthias Ringwald // commands bitmap (64 bytes) from HCI Read Local Supported Commands
14725e46151SMatthias Ringwald //
14825e46151SMatthias Ringwald 
14925e46151SMatthias Ringwald // format: command name, byte offset, bit nr in 64-byte supported commands
1508c021356SMatthias Ringwald // currently stored in 32-bit variable
15125e46151SMatthias Ringwald #define SUPPORTED_HCI_COMMANDS \
1529ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES         ,  2, 5) \
15325e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \
1549ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE                      , 14, 7) \
15525e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \
1569ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE              , 20, 4) \
157ff7d1758SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2                 , 22, 2) \
1589ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED               , 24, 6) \
1599ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \
1609ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST         , 32, 3) \
1619ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND  , 32, 6) \
16225e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \
16325e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE      , 35, 1) \
164a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH           , 35, 3) \
1659ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY                    , 35, 5) \
16663671e69SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE    , 36, 6) \
16779b7ea2dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2                , 41, 5) \
168a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE           , 45, 7) \
16925e46151SMatthias Ringwald 
17025e46151SMatthias Ringwald // enumerate supported commands
17125e46151SMatthias Ringwald #define X(name, offset, bit) name,
17225e46151SMatthias Ringwald enum {
17325e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS
17425e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS_COUNT
17525e46151SMatthias Ringwald };
17625e46151SMatthias Ringwald #undef X
17725e46151SMatthias Ringwald 
178b83d5eabSMatthias Ringwald // prototypes
17935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
180758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
18171fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable);
18235454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
18320dcdd22SMatthias Ringwald static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
18467aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
18535454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
18635454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
187a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
18835454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
189ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
19096a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
19152db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
1929784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
19352db98b2SMatthias Ringwald #endif
1941cfb383eSMatthias Ringwald 
1957586ee35S[email protected] static int  hci_power_control_on(void);
1967586ee35S[email protected] static void hci_power_control_off(void);
1976da48142SSean Wilson static void hci_state_reset(void);
198685ec254SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds);
199fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
200fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
201b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
202b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
203b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
204b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
205b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
20695d71764SMatthias Ringwald static void hci_run(void);
20795d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
2086a5ffed8SMatthias Ringwald 
2096a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
210f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
211dbe0d85cSMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection);
2126a5ffed8SMatthias Ringwald #endif
2135d509858SMatthias Ringwald 
214a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
215314aa2ccSMatthias Ringwald static void hci_whitelist_free(void);
216e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
21739677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
218384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
219667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
2209c77c9dbSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void);
221c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void);
22273799937SMatthias Ringwald static bool hci_run_general_gap_le(void);
2235d509858SMatthias Ringwald #endif
22425df6c61SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
225ee54aff5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
226f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_free(void);
22725df6c61SMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle);
228ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
229ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
2304ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
231a90016deSMatthias Ringwald static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle);
2324ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream);
23315a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle);
23415a15be3SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t big_handle);
23515a15be3SMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle);
236d39e4f95SMatthias Ringwald static void hci_iso_packet_handler(uint8_t * packet, uint16_t size);
2377aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle);
2385ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void);
2397aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status);
2407aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big);
2412a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status);
2422a6c0f82SMatthias Ringwald static void hci_emit_big_sync_stopped(const le_audio_big_sync_t * big_sync);
2432a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle);
2444ae8623eSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
245ee54aff5SMatthias Ringwald #endif /* ENABLE_BLE */
246758b46ceSmatthias.ringwald 
24706b35ec0Smatthias.ringwald // the STACK is here
2483a9fb326S[email protected] #ifndef HAVE_MALLOC
2493a9fb326S[email protected] static hci_stack_t   hci_stack_static;
2503a9fb326S[email protected] #endif
2513a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
25216833f0aSmatthias.ringwald 
2531c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
25463168530SMatthias Ringwald // default name
25563168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
25663168530SMatthias Ringwald 
25766fb9560S[email protected] // test helper
25866fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
2591c9e5e9dSMatthias Ringwald #endif
26066fb9560S[email protected] 
261aee5d5c1SMatthias Ringwald // reset connection state on create and on reconnect
262aee5d5c1SMatthias Ringwald // don't overwrite addr, con handle, role
263aee5d5c1SMatthias Ringwald static void hci_connection_init(hci_connection_t * conn){
2648daf94bcSMatthias Ringwald     conn->authentication_flags = AUTH_FLAG_NONE;
26596a45072S[email protected]     conn->bonding_flags = 0;
26696a45072S[email protected]     conn->requested_security_level = LEVEL_0;
26752db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
26888a03c8dSMatthias Ringwald     conn->request_role = HCI_ROLE_INVALID;
269140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = 0xffff;
270965a4ccfSMatthias Ringwald     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
271e9f98c4aSMatthias Ringwald     conn->link_key_type = INVALID_LINK_KEY;
27291a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
27391a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
27496a45072S[email protected]     hci_connection_timestamp(conn);
27552db98b2SMatthias Ringwald #endif
27696a45072S[email protected]     conn->acl_recombination_length = 0;
27796a45072S[email protected]     conn->acl_recombination_pos = 0;
278ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
279760b20efSMatthias Ringwald 
280da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
281b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
282b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
283b90f6e0aSMatthias Ringwald #endif
2840f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2850f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
2860f3b27c5SMatthias Ringwald #endif
287cb439cf1SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
288cb439cf1SMatthias Ringwald     conn->classic_oob_c_192 = NULL;
289cb439cf1SMatthias Ringwald     conn->classic_oob_r_192 = NULL;
290cb439cf1SMatthias Ringwald     conn->classic_oob_c_256 = NULL;
291cb439cf1SMatthias Ringwald     conn->classic_oob_r_256 = NULL;
292cb439cf1SMatthias Ringwald #endif
293aee5d5c1SMatthias Ringwald }
294aee5d5c1SMatthias Ringwald 
295aee5d5c1SMatthias Ringwald /**
296aee5d5c1SMatthias Ringwald  * create connection for given address
297aee5d5c1SMatthias Ringwald  *
298aee5d5c1SMatthias Ringwald  * @return connection OR NULL, if no memory left
299aee5d5c1SMatthias Ringwald  */
300aee5d5c1SMatthias Ringwald static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){
301aee5d5c1SMatthias Ringwald     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
302aee5d5c1SMatthias Ringwald 
303aee5d5c1SMatthias Ringwald     hci_connection_t * conn = btstack_memory_hci_connection_get();
304aee5d5c1SMatthias Ringwald     if (!conn) return NULL;
305aee5d5c1SMatthias Ringwald     hci_connection_init(conn);
306aee5d5c1SMatthias Ringwald 
307aee5d5c1SMatthias Ringwald     bd_addr_copy(conn->address, addr);
308aee5d5c1SMatthias Ringwald     conn->address_type = addr_type;
309aee5d5c1SMatthias Ringwald     conn->con_handle = HCI_CON_HANDLE_INVALID;
310aee5d5c1SMatthias Ringwald     conn->role = HCI_ROLE_INVALID;
311aee5d5c1SMatthias Ringwald 
312665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
313aee5d5c1SMatthias Ringwald 
31496a45072S[email protected]     return conn;
31596a45072S[email protected] }
31666fb9560S[email protected] 
317da886c03S[email protected] 
318da886c03S[email protected] /**
319da886c03S[email protected]  * get le connection parameter range
320da886c03S[email protected] *
321da886c03S[email protected]  * @return le connection parameter range struct
322da886c03S[email protected]  */
3234ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
3244ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
325da886c03S[email protected] }
326da886c03S[email protected] 
327da886c03S[email protected] /**
328da886c03S[email protected]  * set le connection parameter range
329da886c03S[email protected]  *
330da886c03S[email protected]  */
331da886c03S[email protected] 
3324ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
3334ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
334da886c03S[email protected] }
335da886c03S[email protected] 
336da886c03S[email protected] /**
33773cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
33873cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
33973cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
34073cd8a2aSMatthias Ringwald  * @param conn_latency
34173cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
3426b65794dSMilanka Ringwald  * @return 1 if included
34373cd8a2aSMatthias Ringwald  */
34473cd8a2aSMatthias 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){
34573cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
34673cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
34773cd8a2aSMatthias Ringwald 
34873cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
34973cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
35073cd8a2aSMatthias Ringwald 
35173cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
35273cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
35373cd8a2aSMatthias Ringwald 
35473cd8a2aSMatthias Ringwald     return 1;
35573cd8a2aSMatthias Ringwald }
35673cd8a2aSMatthias Ringwald 
35773cd8a2aSMatthias Ringwald /**
3582b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
3592b6ab3e6SMatthias Ringwald  * @note: default: 1
3602b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
3612b6ab3e6SMatthias Ringwald  */
362d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3632b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
3642b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
3652b6ab3e6SMatthias Ringwald }
366d4e4907bSMatthias Ringwald #endif
3672b6ab3e6SMatthias Ringwald 
3682b6ab3e6SMatthias Ringwald /**
369da886c03S[email protected]  * get hci connections iterator
370da886c03S[email protected]  *
371da886c03S[email protected]  * @return hci connections iterator
372da886c03S[email protected]  */
373da886c03S[email protected] 
374665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
375665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
376da886c03S[email protected] }
377da886c03S[email protected] 
37897addcc5Smatthias.ringwald /**
379ee091cf1Smatthias.ringwald  * get connection for a given handle
380ee091cf1Smatthias.ringwald  *
381ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
382ee091cf1Smatthias.ringwald  */
3835061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
384665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
385665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
386665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
387665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
3883ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
389da886c03S[email protected]             return item;
390ee091cf1Smatthias.ringwald         }
391ee091cf1Smatthias.ringwald     }
392ee091cf1Smatthias.ringwald     return NULL;
393ee091cf1Smatthias.ringwald }
394ee091cf1Smatthias.ringwald 
39596a45072S[email protected] /**
39696a45072S[email protected]  * get connection for given address
39796a45072S[email protected]  *
39896a45072S[email protected]  * @return connection OR NULL, if not found
39996a45072S[email protected]  */
400667ba9d1SMatthias Ringwald hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
401665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
402665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
403665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
404665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
40596a45072S[email protected]         if (connection->address_type != addr_type)  continue;
40696a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
40762bda3fbS[email protected]         return connection;
40862bda3fbS[email protected]     }
40962bda3fbS[email protected]     return NULL;
41062bda3fbS[email protected] }
41162bda3fbS[email protected] 
412d5f71a7eSMatthias Ringwald #ifdef ENABLE_CLASSIC
413d5f71a7eSMatthias Ringwald 
4143e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
4153e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
4163e5e0926SMatthias Ringwald }
41752db98b2SMatthias Ringwald 
418228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
419228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
420228e430cSMatthias Ringwald }
421228e430cSMatthias Ringwald 
422ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
423ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
424ee752bb8SMatthias Ringwald     int connections = 0;
425ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
426ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
427ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
428ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
429ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
430ee752bb8SMatthias Ringwald         connections++;
431ee752bb8SMatthias Ringwald     }
432ee752bb8SMatthias Ringwald     return connections;
433ee752bb8SMatthias Ringwald }
434ee752bb8SMatthias Ringwald #endif
435ee752bb8SMatthias Ringwald 
436ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
43791a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
438aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
439528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
440c785ef68Smatthias.ringwald         // connections might be timed out
441c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
442c785ef68Smatthias.ringwald     }
443f316a845SMatthias Ringwald #else
444c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
4455f26aadcSMatthias Ringwald         // connections might be timed out
4465f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
4475f26aadcSMatthias Ringwald     }
4485f26aadcSMatthias Ringwald #endif
449c785ef68Smatthias.ringwald }
450ee091cf1Smatthias.ringwald 
451ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
452aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
453528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
454f316a845SMatthias Ringwald #else
455528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
4565f26aadcSMatthias Ringwald #endif
457ee091cf1Smatthias.ringwald }
458ee091cf1Smatthias.ringwald 
45943bfb1bdSmatthias.ringwald /**
46080ca58a0Smatthias.ringwald  * add authentication flags and reset timer
46196a45072S[email protected]  * @note: assumes classic connection
4622e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
4637fde4af9Smatthias.ringwald  */
4647fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
4657fde4af9Smatthias.ringwald     bd_addr_t addr;
466724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
467f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4687fde4af9Smatthias.ringwald     if (conn) {
46928ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
47080ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
4717fde4af9Smatthias.ringwald     }
4727fde4af9Smatthias.ringwald }
4737fde4af9Smatthias.ringwald 
4741714cbbdSMatthias Ringwald static bool hci_pairing_active(hci_connection_t * hci_connection){
4758daf94bcSMatthias Ringwald     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
4761714cbbdSMatthias Ringwald }
4771714cbbdSMatthias Ringwald 
4781714cbbdSMatthias Ringwald static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
4791714cbbdSMatthias Ringwald     if (hci_pairing_active(hci_connection)) return;
4801714cbbdSMatthias Ringwald     if (ssp){
4818daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
4821714cbbdSMatthias Ringwald     } else {
4838daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
4841714cbbdSMatthias Ringwald     }
4851714cbbdSMatthias Ringwald     // if we are initiator, we have sent an HCI Authenticate Request
4861714cbbdSMatthias Ringwald     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
4871714cbbdSMatthias Ringwald 
4885a561920SMatthias Ringwald     // if we are responder, use minimal service security level as required level
4895a561920SMatthias Ringwald     if (!initiator){
490acadfdd0SMatthias 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);
4915a561920SMatthias Ringwald     }
4925a561920SMatthias Ringwald 
4935a561920SMatthias Ringwald     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
49477208d90SMatthias Ringwald 
49577208d90SMatthias Ringwald     uint8_t event[12];
49677208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_STARTED;
49777208d90SMatthias Ringwald     event[1] = 10;
498bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
4994159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
50077208d90SMatthias Ringwald     event[10] = (uint8_t) ssp;
50177208d90SMatthias Ringwald     event[11] = (uint8_t) initiator;
50277208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5031714cbbdSMatthias Ringwald }
5041714cbbdSMatthias Ringwald 
5051714cbbdSMatthias Ringwald static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
5063c439ac4SMatthias Ringwald     hci_connection->requested_security_level = LEVEL_0;
5071714cbbdSMatthias Ringwald     if (!hci_pairing_active(hci_connection)) return;
5088daf94bcSMatthias Ringwald     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
5091e7371deSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
510cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_192 = NULL;
511cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_192 = NULL;
512cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_256 = NULL;
513cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_256 = NULL;
5141e7371deSMatthias Ringwald #endif
5151714cbbdSMatthias Ringwald     log_info("pairing complete, status %02x", status);
51677208d90SMatthias Ringwald 
5173176c896SMatthias Ringwald     uint8_t event[11];
51877208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_COMPLETE;
51977208d90SMatthias Ringwald     event[1] = 9;
520bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
5214159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
52277208d90SMatthias Ringwald     event[10] = status;
52377208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5245999ee11SMatthias Ringwald 
5255999ee11SMatthias Ringwald     // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted
5265999ee11SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){
5275999ee11SMatthias Ringwald         hci_connection->bonding_flags &= ~BONDING_DEDICATED;
5285999ee11SMatthias Ringwald         hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
5295999ee11SMatthias Ringwald         hci_connection->bonding_status = status;
5305999ee11SMatthias Ringwald     }
5311714cbbdSMatthias Ringwald }
5321714cbbdSMatthias Ringwald 
53320dcdd22SMatthias Ringwald bool hci_authentication_active_for_handle(hci_con_handle_t handle){
5345061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
53520dcdd22SMatthias Ringwald     if (!conn) return false;
53620dcdd22SMatthias Ringwald     return hci_pairing_active(conn);
53780ca58a0Smatthias.ringwald }
53880ca58a0Smatthias.ringwald 
53915a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
54055597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5412bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
542a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
543c12e46e7Smatthias.ringwald }
54455597469SMatthias Ringwald 
54555597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
54655597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5472bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
54855597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
549c12e46e7Smatthias.ringwald }
5501b6fb31bSMatthias Ringwald 
551e8ad470fSMatthias Ringwald bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
552e8ad470fSMatthias Ringwald 	if (!hci_stack->link_key_db) return false;
55376b0318eSMatthias Ringwald 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
55476b0318eSMatthias Ringwald 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
55576b0318eSMatthias Ringwald 	return result;
556e8ad470fSMatthias Ringwald }
557e8ad470fSMatthias Ringwald 
558ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
559ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
560ceecb9d9SMatthias Ringwald     link_key_t link_key;
561ceecb9d9SMatthias Ringwald     link_key_type_t type;
562ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
563ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
564ceecb9d9SMatthias Ringwald     if (!ok) {
565ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
566ceecb9d9SMatthias Ringwald         return;
567ceecb9d9SMatthias Ringwald     }
568ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
569ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
570ceecb9d9SMatthias Ringwald     }
571ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
572ceecb9d9SMatthias Ringwald }
573ceecb9d9SMatthias Ringwald 
5741b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
5751b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
5761b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
5771b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
5781b6fb31bSMatthias Ringwald }
5791b6fb31bSMatthias 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){
5801b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
5811b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
5821b6fb31bSMatthias Ringwald }
5831b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
5841b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
5851b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
5861b6fb31bSMatthias Ringwald }
58735454696SMatthias Ringwald #endif
588c12e46e7Smatthias.ringwald 
589eb8076ddSMatthias Ringwald static bool hci_is_le_connection_type(bd_addr_type_t address_type){
590eb8076ddSMatthias Ringwald     switch (address_type){
591ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
592ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
593ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
594ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
595eb8076ddSMatthias Ringwald             return true;
596ce41473eSMatthias Ringwald         default:
597eb8076ddSMatthias Ringwald             return false;
598ce41473eSMatthias Ringwald     }
5990bf6344aS[email protected] }
6000bf6344aS[email protected] 
601eb8076ddSMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
602eb8076ddSMatthias Ringwald     return hci_is_le_connection_type(connection->address_type);
603eb8076ddSMatthias Ringwald }
604eb8076ddSMatthias Ringwald 
6057fde4af9Smatthias.ringwald /**
60643bfb1bdSmatthias.ringwald  * count connections
60743bfb1bdSmatthias.ringwald  */
60840d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
60956c253c9Smatthias.ringwald     int count = 0;
610665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
611a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
61215a27967SMatthias Ringwald         count++;
61315a27967SMatthias Ringwald     }
61443bfb1bdSmatthias.ringwald     return count;
61543bfb1bdSmatthias.ringwald }
616c8e4258aSmatthias.ringwald 
6178f733c6fSMatthias Ringwald uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
618ee303eddS[email protected] 
619f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
620f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
621ee303eddS[email protected] 
622665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
623a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
624998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
625ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
626ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
627ce41473eSMatthias Ringwald         }
628f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
629ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
630ee303eddS[email protected]         }
631ee303eddS[email protected]     }
632d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
633ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
634ee303eddS[email protected]     int free_slots_le = 0;
635ee303eddS[email protected] 
636ee303eddS[email protected]     if (free_slots_classic < 0){
6379da54300S[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);
638998906cdSmatthias.ringwald         return 0;
639998906cdSmatthias.ringwald     }
640ee303eddS[email protected] 
641ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
642ee303eddS[email protected]         // if we have LE slots, they are used
643ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
644ee303eddS[email protected]         if (free_slots_le < 0){
6459da54300S[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);
646ee303eddS[email protected]             return 0;
647998906cdSmatthias.ringwald         }
648ee303eddS[email protected]     } else {
649ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
650ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
651ee303eddS[email protected]         if (free_slots_classic < 0){
6529da54300S[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);
653ee303eddS[email protected]             return 0;
654ee303eddS[email protected]         }
655ee303eddS[email protected]     }
656ee303eddS[email protected] 
657ee303eddS[email protected]     switch (address_type){
658ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
6592125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
660ee303eddS[email protected]             return 0;
661ee303eddS[email protected] 
662f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6638f733c6fSMatthias Ringwald             return (uint16_t) free_slots_classic;
664ee303eddS[email protected] 
665ee303eddS[email protected]         default:
6668f733c6fSMatthias Ringwald            if (hci_stack->le_acl_packets_total_num > 0){
6678f733c6fSMatthias Ringwald                return (uint16_t) free_slots_le;
668ee303eddS[email protected]            }
6698f733c6fSMatthias Ringwald            return (uint16_t) free_slots_classic;
670cb00d3aaS[email protected]     }
671998906cdSmatthias.ringwald }
672998906cdSmatthias.ringwald 
6732125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
6742125de09SMatthias Ringwald     // get connection type
6752125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6762125de09SMatthias Ringwald     if (!connection){
6772125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
6782125de09SMatthias Ringwald         return 0;
6792125de09SMatthias Ringwald     }
6802125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
6812125de09SMatthias Ringwald }
6822125de09SMatthias Ringwald 
68335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
684701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
685f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
686665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
687760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
688760b20efSMatthias Ringwald         // explicit flow control
689665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
690e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
691ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
692ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
693e35edcc1S[email protected]         }
694e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
695701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
69644d0e3d5S[email protected]             return 0;
69744d0e3d5S[email protected]         }
698e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
69949205f5dSMatthias Ringwald     } else {
70049205f5dSMatthias Ringwald         // implicit flow control -- TODO
7016f28d2eeSMatthias Ringwald         int num_ready = 0;
7026f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
7036f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
7046f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
7056f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
7066f28d2eeSMatthias Ringwald             num_ready++;
70749205f5dSMatthias Ringwald         }
7086f28d2eeSMatthias Ringwald         return num_ready;
7096f28d2eeSMatthias Ringwald     }
710e35edcc1S[email protected] }
71135454696SMatthias Ringwald #endif
71244d0e3d5S[email protected] 
7132b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
7142b838201SMatthias Ringwald static int hci_can_send_comand_packet_transport(void){
715ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
716ac928cc2S[email protected] 
717ac928cc2S[email protected]     // check for async hci transport implementations
718ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
719ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
720ac928cc2S[email protected]             return 0;
721ac928cc2S[email protected]         }
722ac928cc2S[email protected]     }
7232b838201SMatthias Ringwald     return 1;
7242b838201SMatthias Ringwald }
725ac928cc2S[email protected] 
7262b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
7271972f31fSMatthias Ringwald bool hci_can_send_command_packet_now(void){
7281972f31fSMatthias Ringwald     if (hci_can_send_comand_packet_transport() == 0) return false;
7294ea43905SMatthias Ringwald     return hci_stack->num_cmd_packets > 0u;
730ac928cc2S[email protected] }
731ac928cc2S[email protected] 
7329d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
733ac928cc2S[email protected]     // check for async hci transport implementations
7341972f31fSMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return true;
7359d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
736ac928cc2S[email protected] }
7379d04d3a7SMatthias Ringwald 
7381972f31fSMatthias Ringwald static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
7391972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
7409d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
741ac928cc2S[email protected] }
7429d04d3a7SMatthias Ringwald 
7431972f31fSMatthias Ringwald bool hci_can_send_acl_le_packet_now(void){
7441972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
7459d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
7469d04d3a7SMatthias Ringwald }
7479d04d3a7SMatthias Ringwald 
7481972f31fSMatthias Ringwald bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
7491972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
750e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
751ac928cc2S[email protected] }
752ac928cc2S[email protected] 
7531972f31fSMatthias Ringwald bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
7541972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
755ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
7566b4af23dS[email protected] }
7576b4af23dS[email protected] 
75835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7591972f31fSMatthias Ringwald bool hci_can_send_acl_classic_packet_now(void){
7601972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
761f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
76235454696SMatthias Ringwald }
76335454696SMatthias Ringwald 
7641972f31fSMatthias Ringwald bool hci_can_send_prepared_sco_packet_now(void){
7651972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
766f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
767f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
768f234b250SMatthias Ringwald     } else {
769701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
77044d0e3d5S[email protected]     }
771f234b250SMatthias Ringwald }
77244d0e3d5S[email protected] 
7731972f31fSMatthias Ringwald bool hci_can_send_sco_packet_now(void){
7741972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
775701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
77644d0e3d5S[email protected] }
77744d0e3d5S[email protected] 
778d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
779d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
780d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
781d057580eSMatthias Ringwald }
78235454696SMatthias Ringwald #endif
783d057580eSMatthias Ringwald 
78495d71764SMatthias Ringwald // used for internal checks in l2cap.c
78502c7fc01SMatthias Ringwald bool hci_is_packet_buffer_reserved(void){
786c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
787c8b9416aS[email protected] }
788c8b9416aS[email protected] 
7896b65794dSMilanka Ringwald // reserves outgoing packet buffer.
7906b65794dSMilanka Ringwald // @return 1 if successful
791cafc12e8SMatthias Ringwald bool hci_reserve_packet_buffer(void){
7929d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
7939d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
794cafc12e8SMatthias Ringwald         return false;
7959d14b626S[email protected]     }
79602c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = true;
797cafc12e8SMatthias Ringwald     return true;
7986b4af23dS[email protected] }
7996b4af23dS[email protected] 
80068a0fcf7S[email protected] void hci_release_packet_buffer(void){
80102c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
80268a0fcf7S[email protected] }
80368a0fcf7S[email protected] 
8046b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
8057f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
8066b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
8076b4af23dS[email protected] }
8086b4af23dS[email protected] 
8098ad9cf99SMatthias Ringwald // used for debugging
8108ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
8118ad9cf99SMatthias Ringwald static void hci_controller_dump_packets(void){
8128ad9cf99SMatthias Ringwald     // format: "{handle:04x}:{count:02d} "
8138ad9cf99SMatthias Ringwald     char summaries[3][7 * 8 + 1];
8148ad9cf99SMatthias Ringwald     uint16_t totals[3];
8158ad9cf99SMatthias Ringwald     uint8_t index;
8168ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8178ad9cf99SMatthias Ringwald         summaries[index][0] = 0;
8188ad9cf99SMatthias Ringwald         totals[index] = 0;
8198ad9cf99SMatthias Ringwald     }
8208ad9cf99SMatthias Ringwald     btstack_linked_item_t *it;
8218ad9cf99SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8228ad9cf99SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
8238ad9cf99SMatthias Ringwald         switch (connection->address_type){
8248ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_ACL:
8258ad9cf99SMatthias Ringwald                 index = 0;
8268ad9cf99SMatthias Ringwald                 break;
8278ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_SCO:
8288ad9cf99SMatthias Ringwald                 index = 2;
8298ad9cf99SMatthias Ringwald                 break;
8308ad9cf99SMatthias Ringwald             default:
8318ad9cf99SMatthias Ringwald                 index = 1;
832ce7ca7c8SMatthias Ringwald                 break;
8338ad9cf99SMatthias Ringwald         }
8348ad9cf99SMatthias Ringwald         totals[index] += connection->num_packets_sent;
8358ad9cf99SMatthias Ringwald         char item_text[10];
8368ad9cf99SMatthias Ringwald         sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent);
8378ad9cf99SMatthias Ringwald         btstack_strcat(summaries[index], sizeof(summaries[0]), item_text);
8388ad9cf99SMatthias Ringwald     }
8398ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8408ad9cf99SMatthias Ringwald         if (summaries[index][0] == 0){
8418ad9cf99SMatthias Ringwald             summaries[index][0] = '-';
8428ad9cf99SMatthias Ringwald             summaries[index][1] = 0;
8438ad9cf99SMatthias Ringwald         }
8448ad9cf99SMatthias Ringwald     }
8458ad9cf99SMatthias 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]);
8468ad9cf99SMatthias Ringwald }
8478ad9cf99SMatthias Ringwald #endif
8488ad9cf99SMatthias Ringwald 
8493e2050f7SMatthias Ringwald static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
850452cf3bbS[email protected] 
851452cf3bbS[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);
852452cf3bbS[email protected] 
853452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
854452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
8554ea43905SMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
856452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
857452cf3bbS[email protected]     }
858452cf3bbS[email protected] 
8590f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
860fcf88f47SMatthias Ringwald     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
8610f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
8620f3b27c5SMatthias Ringwald     }
8630f3b27c5SMatthias Ringwald #endif
864452cf3bbS[email protected] 
865d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
866d999b54eSMatthias Ringwald 
8673e2050f7SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
868452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
869ff3cc4a5SMatthias Ringwald     while (true){
870452cf3bbS[email protected] 
871d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
872d999b54eSMatthias Ringwald 
873452cf3bbS[email protected]         // get current data
8744ea43905SMatthias Ringwald         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
875452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
8761979f09cSMatthias Ringwald         bool more_fragments = false;
877452cf3bbS[email protected] 
878452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
879452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
8801979f09cSMatthias Ringwald             more_fragments = true;
881452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
882452cf3bbS[email protected]         }
883452cf3bbS[email protected] 
884452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
8854ea43905SMatthias Ringwald         if (acl_header_pos > 0u){
886f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
8874ea43905SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
888f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
889452cf3bbS[email protected]         }
890452cf3bbS[email protected] 
891452cf3bbS[email protected]         // update header len
8924ea43905SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
893452cf3bbS[email protected] 
894452cf3bbS[email protected]         // count packet
895ce41473eSMatthias Ringwald         connection->num_packets_sent++;
8961979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
897d999b54eSMatthias Ringwald 
898d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
899d999b54eSMatthias Ringwald         if (more_fragments){
900d999b54eSMatthias Ringwald             // update start of next fragment to send
901d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
902d999b54eSMatthias Ringwald         } else {
903d999b54eSMatthias Ringwald             // done
904d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
905d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
906d999b54eSMatthias Ringwald         }
907452cf3bbS[email protected] 
908452cf3bbS[email protected]         // send packet
909452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
910452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
9115bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
91281d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
9133e2050f7SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
9143e2050f7SMatthias Ringwald         if (err != 0){
9153e2050f7SMatthias Ringwald             // no error from HCI Transport expected
9163e2050f7SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
9173e2050f7SMatthias Ringwald         }
918452cf3bbS[email protected] 
9198ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
9208ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
9218ad9cf99SMatthias Ringwald #endif
9228ad9cf99SMatthias Ringwald 
9231979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
924d999b54eSMatthias Ringwald 
925452cf3bbS[email protected]         // done yet?
926452cf3bbS[email protected]         if (!more_fragments) break;
927452cf3bbS[email protected] 
928452cf3bbS[email protected]         // can send more?
9293e2050f7SMatthias Ringwald         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
930452cf3bbS[email protected]     }
931452cf3bbS[email protected] 
932d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
933452cf3bbS[email protected] 
934d051460cS[email protected]     // release buffer now for synchronous transport
935203bace6S[email protected]     if (hci_transport_synchronous()){
93681d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
937452cf3bbS[email protected]         hci_release_packet_buffer();
938fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
939452cf3bbS[email protected]     }
940452cf3bbS[email protected] 
9413e2050f7SMatthias Ringwald     return status;
942452cf3bbS[email protected] }
943452cf3bbS[email protected] 
944826f7347S[email protected] // pre: caller has reserved the packet buffer
9453e2050f7SMatthias Ringwald uint8_t hci_send_acl_packet_buffer(int size){
9463e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
947826f7347S[email protected] 
948d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
949d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
950d713a683S[email protected] 
951826f7347S[email protected]     // check for free places on Bluetooth module
952d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
953826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
95497b61c7bS[email protected]         hci_release_packet_buffer();
955068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
95697b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
95797b61c7bS[email protected]     }
9586218e6f1Smatthias.ringwald 
9595061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
96097b61c7bS[email protected]     if (!connection) {
9615fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
96297b61c7bS[email protected]         hci_release_packet_buffer();
963068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
9643e2050f7SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
96597b61c7bS[email protected]     }
96652db98b2SMatthias Ringwald 
96752db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
96856cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
96952db98b2SMatthias Ringwald #endif
97056cf178bSmatthias.ringwald 
971452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
9727856c818Smatthias.ringwald 
973452cf3bbS[email protected]     // setup data
974452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
975452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
9766218e6f1Smatthias.ringwald 
977452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
978ee091cf1Smatthias.ringwald }
979ee091cf1Smatthias.ringwald 
98035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
98144d0e3d5S[email protected] // pre: caller has reserved the packet buffer
9823e2050f7SMatthias Ringwald uint8_t hci_send_sco_packet_buffer(int size){
9833e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
98444d0e3d5S[email protected] 
98544d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
9864b3e1e19SMatthias Ringwald 
9874b3e1e19SMatthias Ringwald     // skip checks in loopback mode
9884b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
98944d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
99044d0e3d5S[email protected] 
99144d0e3d5S[email protected]         // check for free places on Bluetooth module
992701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
993cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
99444d0e3d5S[email protected]             hci_release_packet_buffer();
995068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
99644d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
99744d0e3d5S[email protected]         }
99844d0e3d5S[email protected] 
999e35edcc1S[email protected]         // track send packet in connection struct
1000e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
1001e35edcc1S[email protected]         if (!connection) {
1002e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
1003e35edcc1S[email protected]             hci_release_packet_buffer();
1004068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
10053e2050f7SMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1006e35edcc1S[email protected]         }
1007f234b250SMatthias Ringwald 
1008f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
1009f234b250SMatthias Ringwald             // token used
10101972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = false;
1011f234b250SMatthias Ringwald         } else {
1012760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
1013ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
10146f28d2eeSMatthias Ringwald             } else {
1015e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
1016760b20efSMatthias Ringwald             }
10174b3e1e19SMatthias Ringwald         }
1018f234b250SMatthias Ringwald     }
101944d0e3d5S[email protected] 
102044d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
1021543e835cSMatthias Ringwald 
102243149fc9SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
102343149fc9SMatthias Ringwald     hci_stack->sco_transport->send_packet(packet, size);
102443149fc9SMatthias Ringwald     hci_release_packet_buffer();
102543149fc9SMatthias Ringwald     hci_emit_transport_packet_sent();
102643149fc9SMatthias Ringwald 
102743149fc9SMatthias Ringwald     return 0;
102843149fc9SMatthias Ringwald #else
102943149fc9SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
1030543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
1031543e835cSMatthias Ringwald         hci_release_packet_buffer();
1032fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
1033543e835cSMatthias Ringwald     }
1034543e835cSMatthias Ringwald 
10353e2050f7SMatthias Ringwald     if (err != 0){
10363e2050f7SMatthias Ringwald         return ERROR_CODE_HARDWARE_FAILURE;
10373e2050f7SMatthias Ringwald     }
10383e2050f7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
103943149fc9SMatthias Ringwald #endif
104044d0e3d5S[email protected] }
104135454696SMatthias Ringwald #endif
104244d0e3d5S[email protected] 
10430a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
104468ab6207SMatthias Ringwald static uint8_t hci_send_iso_packet_fragments(void){
104568ab6207SMatthias Ringwald 
104668ab6207SMatthias Ringwald     uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length;
104768ab6207SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
104868ab6207SMatthias Ringwald     // multiple packets could be send on a synchronous HCI transport
104968ab6207SMatthias Ringwald     while (true){
105068ab6207SMatthias Ringwald 
105168ab6207SMatthias Ringwald         // get current data
105268ab6207SMatthias Ringwald         const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u;
105368ab6207SMatthias Ringwald         int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos;
105468ab6207SMatthias Ringwald         bool more_fragments = false;
105568ab6207SMatthias Ringwald 
105668ab6207SMatthias Ringwald         // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
105768ab6207SMatthias Ringwald         if (current_iso_data_packet_length > max_iso_data_packet_length){
105868ab6207SMatthias Ringwald             more_fragments = true;
105968ab6207SMatthias Ringwald             current_iso_data_packet_length = max_iso_data_packet_length;
106068ab6207SMatthias Ringwald         }
106168ab6207SMatthias Ringwald 
106268ab6207SMatthias Ringwald         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
106368ab6207SMatthias Ringwald         uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
106468ab6207SMatthias Ringwald         uint8_t pb_flags;
106568ab6207SMatthias Ringwald         if (iso_header_pos == 0u){
106668ab6207SMatthias Ringwald             // first fragment, keep TS field
106768ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x00 : 0x02;
106868ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u);
106968ab6207SMatthias Ringwald         } else {
107068ab6207SMatthias Ringwald             // later fragment, drop TS field
107168ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x01 : 0x03;
107268ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u);
107368ab6207SMatthias Ringwald         }
107468ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags);
107568ab6207SMatthias Ringwald 
107668ab6207SMatthias Ringwald         // update header len
107768ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length);
107868ab6207SMatthias Ringwald 
107968ab6207SMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
108068ab6207SMatthias Ringwald         if (more_fragments){
108168ab6207SMatthias Ringwald             // update start of next fragment to send
108268ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos += current_iso_data_packet_length;
108368ab6207SMatthias Ringwald         } else {
108468ab6207SMatthias Ringwald             // done
108568ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos = 0;
108668ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_total_size = 0;
108768ab6207SMatthias Ringwald         }
108868ab6207SMatthias Ringwald 
108968ab6207SMatthias Ringwald         // send packet
109068ab6207SMatthias Ringwald         uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos];
109168ab6207SMatthias Ringwald         const int size = current_iso_data_packet_length + 4;
109268ab6207SMatthias Ringwald         hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size);
109368ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = true;
109468ab6207SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size);
109568ab6207SMatthias Ringwald         if (err != 0){
109668ab6207SMatthias Ringwald             // no error from HCI Transport expected
109768ab6207SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
109868ab6207SMatthias Ringwald         }
109968ab6207SMatthias Ringwald 
110068ab6207SMatthias Ringwald         // done yet?
110168ab6207SMatthias Ringwald         if (!more_fragments) break;
110268ab6207SMatthias Ringwald 
110368ab6207SMatthias Ringwald         // can send more?
110468ab6207SMatthias Ringwald         if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false;
110568ab6207SMatthias Ringwald     }
110668ab6207SMatthias Ringwald 
110768ab6207SMatthias Ringwald     // release buffer now for synchronous transport
110868ab6207SMatthias Ringwald     if (hci_transport_synchronous()){
110968ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = false;
111068ab6207SMatthias Ringwald         hci_release_packet_buffer();
111168ab6207SMatthias Ringwald         hci_emit_transport_packet_sent();
111268ab6207SMatthias Ringwald     }
111368ab6207SMatthias Ringwald 
111468ab6207SMatthias Ringwald     return status;
111568ab6207SMatthias Ringwald }
111668ab6207SMatthias Ringwald 
1117ace08712SMatthias Ringwald uint8_t hci_send_iso_packet_buffer(uint16_t size){
1118ace08712SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1119ace08712SMatthias Ringwald 
1120e5413aa0SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff;
1121e5413aa0SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle);
1122e5413aa0SMatthias Ringwald     if (iso_stream == NULL){
1123e5413aa0SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1124e5413aa0SMatthias Ringwald     }
1125e5413aa0SMatthias Ringwald 
1126e5413aa0SMatthias Ringwald     // TODO: check for space on controller
1127e5413aa0SMatthias Ringwald 
1128e5413aa0SMatthias Ringwald     // track outgoing packet sent
1129e5413aa0SMatthias Ringwald     log_info("Outgoing ISO packet for con handle 0x%04x", con_handle);
1130e5413aa0SMatthias Ringwald     iso_stream->num_packets_sent++;
1131e5413aa0SMatthias Ringwald 
113268ab6207SMatthias Ringwald     // setup data
113368ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_total_size = size;
113468ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_pos = 4;   // start of L2CAP packet
113568ab6207SMatthias Ringwald 
113668ab6207SMatthias Ringwald     return hci_send_iso_packet_fragments();
1137ace08712SMatthias Ringwald }
1138ace08712SMatthias Ringwald #endif
1139ace08712SMatthias Ringwald 
1140c3b46f5aSMatthias Ringwald static void acl_handler(uint8_t *packet, uint16_t size){
1141e76a89eeS[email protected] 
11427856c818Smatthias.ringwald     // get info
11437856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
11445061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
11457856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
11467856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
11477856c818Smatthias.ringwald 
11487856c818Smatthias.ringwald     // ignore non-registered handle
11497856c818Smatthias.ringwald     if (!conn){
1150c3b46f5aSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , con_handle);
11517856c818Smatthias.ringwald         return;
11527856c818Smatthias.ringwald     }
11537856c818Smatthias.ringwald 
1154e76a89eeS[email protected]     // assert packet is complete
11554ea43905SMatthias Ringwald     if ((acl_length + 4u) != size){
1156c3b46f5aSMatthias Ringwald         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
1157e76a89eeS[email protected]         return;
1158e76a89eeS[email protected]     }
1159e76a89eeS[email protected] 
116052db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
11617856c818Smatthias.ringwald     // update idle timestamp
11627856c818Smatthias.ringwald     hci_connection_timestamp(conn);
116352db98b2SMatthias Ringwald #endif
11647856c818Smatthias.ringwald 
11652b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
11662b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
11672b838201SMatthias Ringwald     conn->num_packets_completed++;
11682b838201SMatthias Ringwald #endif
11692b838201SMatthias Ringwald 
11707856c818Smatthias.ringwald     // handle different packet types
11714ea43905SMatthias Ringwald     switch (acl_flags & 0x03u) {
11727856c818Smatthias.ringwald 
11737856c818Smatthias.ringwald         case 0x01: // continuation fragment
11747856c818Smatthias.ringwald 
11750ca847afS[email protected]             // sanity checks
11764ea43905SMatthias Ringwald             if (conn->acl_recombination_pos == 0u) {
11779da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
11787856c818Smatthias.ringwald                 return;
11797856c818Smatthias.ringwald             }
11804ea43905SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
11810ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
11820ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
11830ca847afS[email protected]                 conn->acl_recombination_pos = 0;
11840ca847afS[email protected]                 return;
11850ca847afS[email protected]             }
11867856c818Smatthias.ringwald 
11877856c818Smatthias.ringwald             // append fragment payload (header already stored)
11886535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
11896535961aSMatthias Ringwald                          &packet[4], acl_length);
11907856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
11917856c818Smatthias.ringwald 
11927856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
11934ea43905SMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
1194d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
11957856c818Smatthias.ringwald                 // reset recombination buffer
11967856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
11977856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
11987856c818Smatthias.ringwald             }
11997856c818Smatthias.ringwald             break;
12007856c818Smatthias.ringwald 
12017856c818Smatthias.ringwald         case 0x02: { // first fragment
12027856c818Smatthias.ringwald 
120323a77e1aS[email protected]             // sanity check
120423a77e1aS[email protected]             if (conn->acl_recombination_pos) {
120523a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
120623a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
120723a77e1aS[email protected]             }
120823a77e1aS[email protected] 
12097856c818Smatthias.ringwald             // peek into L2CAP packet!
12107856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
12117856c818Smatthias.ringwald 
12127856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
12134ea43905SMatthias Ringwald             if (acl_length >= (l2cap_length + 4u)){
12147856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
12154ea43905SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4u);
12167856c818Smatthias.ringwald             } else {
12170ca847afS[email protected] 
12180ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
12190ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
12200ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
12210ca847afS[email protected]                     return;
12220ca847afS[email protected]                 }
12230ca847afS[email protected] 
12247856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
12256535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
12264ea43905SMatthias Ringwald                              packet, acl_length + 4u);
12274ea43905SMatthias Ringwald                 conn->acl_recombination_pos    = acl_length + 4u;
12287856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
12294ea43905SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
12307856c818Smatthias.ringwald             }
12317856c818Smatthias.ringwald             break;
12327856c818Smatthias.ringwald 
12337856c818Smatthias.ringwald         }
12347856c818Smatthias.ringwald         default:
1235c3b46f5aSMatthias Ringwald             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
12367856c818Smatthias.ringwald             return;
12377856c818Smatthias.ringwald     }
123894ab26f8Smatthias.ringwald 
123994ab26f8Smatthias.ringwald     // execute main loop
124094ab26f8Smatthias.ringwald     hci_run();
124116833f0aSmatthias.ringwald }
124222909952Smatthias.ringwald 
12431ab2dc58SMatthias Ringwald static void hci_connection_stop_timer(hci_connection_t * conn){
12441ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
12451ab2dc58SMatthias Ringwald #ifdef ENABLE_CLASSIC
12461ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout_sco);
12471ab2dc58SMatthias Ringwald #endif
12481ab2dc58SMatthias Ringwald }
12491ab2dc58SMatthias Ringwald 
125067a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
12519da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
12523c4d4b90Smatthias.ringwald 
1253b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1254cb70c5abSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1255cb70c5abSMatthias Ringwald     bd_addr_type_t addr_type = conn->address_type;
1256cb70c5abSMatthias Ringwald #endif
1257cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1258cb70c5abSMatthias Ringwald     hci_con_handle_t con_handle = conn->con_handle;
1259ee752bb8SMatthias Ringwald #endif
1260b3264428SMatthias Ringwald #endif
1261ee752bb8SMatthias Ringwald 
12621ab2dc58SMatthias Ringwald     hci_connection_stop_timer(conn);
1263c785ef68Smatthias.ringwald 
1264665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1265a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
12663c4d4b90Smatthias.ringwald 
12673c4d4b90Smatthias.ringwald     // now it's gone
1268c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
1269ee752bb8SMatthias Ringwald 
1270b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1271034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1272ee752bb8SMatthias Ringwald     // update SCO
1273cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1274ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1275ee752bb8SMatthias Ringwald     }
1276034e9b53SMatthias Ringwald #endif
1277cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1278cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1279cb70c5abSMatthias Ringwald         hci_stack->sco_transport->close(con_handle);
1280cb70c5abSMatthias Ringwald     }
1281cb70c5abSMatthias Ringwald #endif
1282b3264428SMatthias Ringwald #endif
1283c7e0c5f6Smatthias.ringwald }
1284c7e0c5f6Smatthias.ringwald 
128535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
128635454696SMatthias Ringwald 
12870c042179S[email protected] static const uint16_t packet_type_sizes[] = {
12888f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
12898f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
12908f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
12918f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
12928f8108aaSmatthias.ringwald };
129365389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
129465389bfcS[email protected]      0, // 3 slot packets
129565389bfcS[email protected]      1, // 5 slot packets
129665389bfcS[email protected]     25, // EDR 2 mpbs
129765389bfcS[email protected]     26, // EDR 3 mbps
129865389bfcS[email protected]     39, // 3 slot EDR packts
129965389bfcS[email protected]     40, // 5 slot EDR packet
130065389bfcS[email protected] };
130165389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
130265389bfcS[email protected]     0x0f00, // 3 slot packets
130365389bfcS[email protected]     0xf000, // 5 slot packets
130465389bfcS[email protected]     0x1102, // EDR 2 mpbs
130565389bfcS[email protected]     0x2204, // EDR 3 mbps
130665389bfcS[email protected]     0x0300, // 3 slot EDR packts
130765389bfcS[email protected]     0x3000, // 5 slot EDR packet
130865389bfcS[email protected] };
13098f8108aaSmatthias.ringwald 
131065389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
131165389bfcS[email protected]     // enable packet types based on size
13128f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
1313f16a69bbS[email protected]     unsigned int i;
13148f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
13158f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
13168f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
13178f8108aaSmatthias.ringwald             packet_types |= 1 << i;
13188f8108aaSmatthias.ringwald         }
13198f8108aaSmatthias.ringwald     }
132065389bfcS[email protected]     // disable packet types due to missing local supported features
132165389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1322f04a0c31SMatthias Ringwald         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
132365389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
132465389bfcS[email protected]         if (feature_set) continue;
132565389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
132665389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
132765389bfcS[email protected]     }
13288f8108aaSmatthias.ringwald     // flip bits for "may not be used"
13298f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
13308f8108aaSmatthias.ringwald     return packet_types;
13318f8108aaSmatthias.ringwald }
13328f8108aaSmatthias.ringwald 
13338f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
13343a9fb326S[email protected]     return hci_stack->packet_types;
13358f8108aaSmatthias.ringwald }
133635454696SMatthias Ringwald #endif
13378f8108aaSmatthias.ringwald 
1338facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
13397dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
13403a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
13417dc17943Smatthias.ringwald }
13427dc17943Smatthias.ringwald 
1343f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
13443a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
13457dc17943Smatthias.ringwald }
13467dc17943Smatthias.ringwald 
134706b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
134820dcdd22SMatthias Ringwald bool hci_extended_sco_link_supported(void){
13493e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
13503e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
13513e68d23dSMatthias Ringwald }
135206b9e820SMatthias Ringwald #endif
13533e68d23dSMatthias Ringwald 
135420dcdd22SMatthias Ringwald bool hci_non_flushable_packet_boundary_flag_supported(void){
13556ac9a97eS[email protected]     // No. 54, byte 6, bit 6
13564ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
13576ac9a97eS[email protected] }
13586ac9a97eS[email protected] 
13599885fb2dSMatthias Ringwald #ifdef ENABLE_CLASSIC
136015a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
13616ac9a97eS[email protected]     // No. 51, byte 6, bit 3
13624ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1363f5d8d141S[email protected] }
13649885fb2dSMatthias Ringwald #endif
1365f5d8d141S[email protected] 
13667f02f414SMatthias Ringwald static int hci_classic_supported(void){
136735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
13686ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
13693a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
137035454696SMatthias Ringwald #else
137135454696SMatthias Ringwald     return 0;
137235454696SMatthias Ringwald #endif
1373f5d8d141S[email protected] }
1374f5d8d141S[email protected] 
13757f02f414SMatthias Ringwald static int hci_le_supported(void){
1376a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
13776ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
13784ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1379f5d8d141S[email protected] #else
1380f5d8d141S[email protected]     return 0;
1381f5d8d141S[email protected] #endif
1382f5d8d141S[email protected] }
1383f5d8d141S[email protected] 
13841ffa425cSMatthias Ringwald static bool hci_command_supported(uint8_t command_index){
13851ffa425cSMatthias Ringwald     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
13861ffa425cSMatthias Ringwald }
13871ffa425cSMatthias Ringwald 
1388b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1389b95a5a35SMatthias Ringwald 
139063671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
139163671e69SMatthias Ringwald static bool hci_extended_advertising_supported(void){
139263671e69SMatthias Ringwald     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
139363671e69SMatthias Ringwald }
139463671e69SMatthias Ringwald #endif
139563671e69SMatthias Ringwald 
1396f5873674SMatthias Ringwald static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
13976bcfa632SMatthias Ringwald     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
13986bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
139969a97523S[email protected]     } else {
14006bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
140169a97523S[email protected]     }
140269a97523S[email protected] }
140369a97523S[email protected] 
14046bcfa632SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
14056bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
14066bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
14076bcfa632SMatthias Ringwald }
14086bcfa632SMatthias Ringwald 
14096bcfa632SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
14106bcfa632SMatthias Ringwald void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
14116bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_advertisements_own_addr_type;
14126bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
14136bcfa632SMatthias Ringwald };
14146bcfa632SMatthias Ringwald #endif
14156bcfa632SMatthias Ringwald 
1416e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
14176bcfa632SMatthias Ringwald 
14186bcfa632SMatthias Ringwald /**
14196bcfa632SMatthias Ringwald  * @brief Get own addr type and address used for LE connections (Central)
14206bcfa632SMatthias Ringwald  */
14216bcfa632SMatthias Ringwald void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
14226bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_connection_own_addr_type;
14236bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
14246bcfa632SMatthias Ringwald }
14256bcfa632SMatthias Ringwald 
1426384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
14279ec2630cSMatthias Ringwald 
1428a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1429a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset];
1430d1dc057bS[email protected]     offset += 1;
1431d1dc057bS[email protected] 
1432a0698cb4SMatthias Ringwald     uint16_t i;
143303fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1434a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
143533e6948bSMatthias Ringwald         // sanity checks on data_length:
143633e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
143733e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
14384ea43905SMatthias Ringwald         if ((offset + 9u + data_length + 1u) > size)    return;
143933e6948bSMatthias Ringwald         // setup event
14404ea43905SMatthias Ringwald         uint8_t event_size = 10u + data_length;
1441a0698cb4SMatthias Ringwald         uint16_t pos = 0;
1442045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
144357c9da5bS[email protected]         event[pos++] = event_size;
14446535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1445d1dc057bS[email protected]         offset += 8;
1446d1dc057bS[email protected]         pos += 8;
1447d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
144833e6948bSMatthias Ringwald         event[pos++] = data_length;
144933e6948bSMatthias Ringwald         offset++;
14506535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
145157c9da5bS[email protected]         pos +=    data_length;
14524ea43905SMatthias Ringwald         offset += data_length + 1u; // rssi
1453d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
145457c9da5bS[email protected]     }
145557c9da5bS[email protected] }
1456a0698cb4SMatthias Ringwald 
1457a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1458a0698cb4SMatthias Ringwald void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1459a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1460a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset++];
1461c95a0fc7SMatthias Ringwald     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1462a0698cb4SMatthias Ringwald     uint8_t i;
1463a0698cb4SMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
1464a0698cb4SMatthias Ringwald         // sanity checks on data_length:
1465a0698cb4SMatthias Ringwald         uint16_t data_length = packet[offset + 23];
1466a0698cb4SMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1467a0698cb4SMatthias Ringwald         if ((offset + 24u + data_length) > size)    return;
1468a0698cb4SMatthias Ringwald         uint16_t event_type = little_endian_read_16(packet, offset);
1469a0698cb4SMatthias Ringwald         offset += 2;
1470a0698cb4SMatthias Ringwald         if ((event_type & 0x10) != 0) {
1471a0698cb4SMatthias Ringwald            // setup legacy event
1472a0698cb4SMatthias Ringwald             uint8_t legacy_event_type;
1473a0698cb4SMatthias Ringwald             switch (event_type){
1474a0698cb4SMatthias Ringwald                 case 0b0010011:
1475a0698cb4SMatthias Ringwald                     // ADV_IND
1476a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1477a0698cb4SMatthias Ringwald                     break;
1478a0698cb4SMatthias Ringwald                 case 0b0010101:
1479a0698cb4SMatthias Ringwald                     // ADV_DIRECT_IND
1480a0698cb4SMatthias Ringwald                     legacy_event_type = 1;
1481a0698cb4SMatthias Ringwald                     break;
1482a0698cb4SMatthias Ringwald                 case 0b0010010:
1483a0698cb4SMatthias Ringwald                     // ADV_SCAN_IND
1484a0698cb4SMatthias Ringwald                     legacy_event_type = 2;
1485a0698cb4SMatthias Ringwald                     break;
1486a0698cb4SMatthias Ringwald                 case 0b0010000:
1487a0698cb4SMatthias Ringwald                     // ADV_NONCONN_IND
1488a0698cb4SMatthias Ringwald                     legacy_event_type = 3;
1489a0698cb4SMatthias Ringwald                     break;
1490a0698cb4SMatthias Ringwald                 case 0b0011011:
1491a0698cb4SMatthias Ringwald                 case 0b0011010:
1492a0698cb4SMatthias Ringwald                     // SCAN_RSP
1493a0698cb4SMatthias Ringwald                     legacy_event_type = 4;
1494a0698cb4SMatthias Ringwald                     break;
1495a0698cb4SMatthias Ringwald                 default:
1496a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1497a0698cb4SMatthias Ringwald                     break;
1498a0698cb4SMatthias Ringwald             }
1499a0698cb4SMatthias Ringwald             uint16_t pos = 0;
1500a0698cb4SMatthias Ringwald             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1501a0698cb4SMatthias Ringwald             event[pos++] = 10u + data_length;
1502a0698cb4SMatthias Ringwald             event[pos++] = legacy_event_type;
1503a0698cb4SMatthias Ringwald             // copy address type + address
1504a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1505a0698cb4SMatthias Ringwald             offset += 7;
1506a0698cb4SMatthias Ringwald             pos += 7;
1507a0698cb4SMatthias Ringwald             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1508a0698cb4SMatthias Ringwald             offset += 4;
1509a0698cb4SMatthias Ringwald             // copy rssi
1510a0698cb4SMatthias Ringwald             event[pos++] = packet[offset++];
1511a0698cb4SMatthias Ringwald             // skip periodic advertising interval and direct address
1512a0698cb4SMatthias Ringwald             offset += 9;
1513a0698cb4SMatthias Ringwald             // copy data len + data;
1514a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1515a0698cb4SMatthias Ringwald             pos    += 1 +data_length;
1516a0698cb4SMatthias Ringwald             offset += 1+ data_length;
1517a0698cb4SMatthias Ringwald             hci_emit_event(event, pos, 1);
1518a0698cb4SMatthias Ringwald         } else {
1519c95a0fc7SMatthias Ringwald             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1520c95a0fc7SMatthias Ringwald             uint8_t report_len = 24 + data_length;
1521c95a0fc7SMatthias Ringwald             event[1] = report_len;
15220f7610adSMatthias Ringwald             little_endian_store_16(event, 2, event_type);
15230f7610adSMatthias Ringwald             memcpy(&event[4], &packet[offset], report_len);
1524c95a0fc7SMatthias Ringwald             offset += report_len;
1525c95a0fc7SMatthias Ringwald             hci_emit_event(event, 2 + report_len, 1);
1526a0698cb4SMatthias Ringwald         }
1527a0698cb4SMatthias Ringwald     }
1528a0698cb4SMatthias Ringwald }
1529a0698cb4SMatthias Ringwald #endif
1530a0698cb4SMatthias Ringwald 
1531b2f949feS[email protected] #endif
1532e8c8828eSMatthias Ringwald #endif
153357c9da5bS[email protected] 
15342b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
15352b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1536bbc366e6SMatthias Ringwald static void hci_update_advertisements_enabled_for_current_roles(void){
1537a408e724SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
15382b6ab3e6SMatthias Ringwald         // get number of active le slave connections
15392b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
15402b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
15412b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
15422b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
15432b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
15442b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
15452b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
15462b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
15472b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
15482b6ab3e6SMatthias Ringwald             num_slave_connections++;
15492b6ab3e6SMatthias Ringwald         }
15502b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1551bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1552bbc366e6SMatthias Ringwald     } else {
1553bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = false;
15542b6ab3e6SMatthias Ringwald     }
15552b6ab3e6SMatthias Ringwald }
15562b6ab3e6SMatthias Ringwald #endif
15572b6ab3e6SMatthias Ringwald #endif
15582b6ab3e6SMatthias Ringwald 
155959d59ecfSMatthias Ringwald #ifdef ENABLE_CLASSIC
156059d59ecfSMatthias Ringwald static void gap_run_set_local_name(void){
156159d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
156259d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
156359d59ecfSMatthias Ringwald     // construct HCI Command and send
156459d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_local_name.opcode;
156559d59ecfSMatthias Ringwald     hci_stack->last_cmd_opcode = opcode;
156659d59ecfSMatthias Ringwald     packet[0] = opcode & 0xff;
156759d59ecfSMatthias Ringwald     packet[1] = opcode >> 8;
156859d59ecfSMatthias Ringwald     packet[2] = DEVICE_NAME_LEN;
156959d59ecfSMatthias Ringwald     memset(&packet[3], 0, DEVICE_NAME_LEN);
157059d59ecfSMatthias Ringwald     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
157159d59ecfSMatthias Ringwald     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
157259d59ecfSMatthias Ringwald     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
157359d59ecfSMatthias Ringwald     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
157459d59ecfSMatthias Ringwald     // expand '00:00:00:00:00:00' in name with bd_addr
157559d59ecfSMatthias Ringwald     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
157659d59ecfSMatthias Ringwald     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
157759d59ecfSMatthias Ringwald }
157859d59ecfSMatthias Ringwald 
157959d59ecfSMatthias Ringwald static void gap_run_set_eir_data(void){
158059d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
158159d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
158259d59ecfSMatthias Ringwald     // construct HCI Command in-place and send
158359d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
158459d59ecfSMatthias Ringwald     hci_stack->last_cmd_opcode = opcode;
158559d59ecfSMatthias Ringwald     uint16_t offset = 0;
158659d59ecfSMatthias Ringwald     packet[offset++] = opcode & 0xff;
158759d59ecfSMatthias Ringwald     packet[offset++] = opcode >> 8;
158859d59ecfSMatthias Ringwald     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
158959d59ecfSMatthias Ringwald     packet[offset++] = 0;  // FEC not required
159059d59ecfSMatthias Ringwald     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
159159d59ecfSMatthias Ringwald     if (hci_stack->eir_data){
159259d59ecfSMatthias Ringwald         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
159359d59ecfSMatthias Ringwald         ad_context_t context;
159459d59ecfSMatthias Ringwald         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
159559d59ecfSMatthias Ringwald             uint8_t data_type   = ad_iterator_get_data_type(&context);
159659d59ecfSMatthias Ringwald             uint8_t size        = ad_iterator_get_data_len(&context);
159759d59ecfSMatthias Ringwald             const uint8_t *data = ad_iterator_get_data(&context);
159859d59ecfSMatthias Ringwald             // copy item
159959d59ecfSMatthias Ringwald             packet[offset++] = size + 1;
160059d59ecfSMatthias Ringwald             packet[offset++] = data_type;
160159d59ecfSMatthias Ringwald             memcpy(&packet[offset], data, size);
160259d59ecfSMatthias Ringwald             // update name item
160359d59ecfSMatthias Ringwald             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
160459d59ecfSMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
160559d59ecfSMatthias Ringwald             }
160659d59ecfSMatthias Ringwald             offset += size;
160759d59ecfSMatthias Ringwald         }
160859d59ecfSMatthias Ringwald     } else {
160959d59ecfSMatthias Ringwald         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
161059d59ecfSMatthias Ringwald         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
161159d59ecfSMatthias Ringwald         packet[offset++] = bytes_to_copy + 1;
161259d59ecfSMatthias Ringwald         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
161359d59ecfSMatthias Ringwald         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
161459d59ecfSMatthias Ringwald         // expand '00:00:00:00:00:00' in name with bd_addr
161559d59ecfSMatthias Ringwald         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
161659d59ecfSMatthias Ringwald     }
161759d59ecfSMatthias Ringwald     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
161859d59ecfSMatthias Ringwald }
1619ab4831a3SMatthias Ringwald 
1620ab4831a3SMatthias Ringwald static void hci_run_gap_tasks_classic(void){
1621baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1622baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1623ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1624ab4831a3SMatthias Ringwald         return;
1625ab4831a3SMatthias Ringwald     }
1626baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1627baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1628ab4831a3SMatthias Ringwald         gap_run_set_local_name();
1629ab4831a3SMatthias Ringwald         return;
1630ab4831a3SMatthias Ringwald     }
1631baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1632baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1633ab4831a3SMatthias Ringwald         gap_run_set_eir_data();
1634ab4831a3SMatthias Ringwald         return;
1635ab4831a3SMatthias Ringwald     }
1636baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1637baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1638ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1639ab4831a3SMatthias Ringwald         return;
1640ab4831a3SMatthias Ringwald     }
1641ab4831a3SMatthias Ringwald     // write page scan activity
1642baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1643baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1644ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1645ab4831a3SMatthias Ringwald         return;
1646ab4831a3SMatthias Ringwald     }
1647ab4831a3SMatthias Ringwald     // write page scan type
1648baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1649baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1650ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1651ab4831a3SMatthias Ringwald         return;
1652ab4831a3SMatthias Ringwald     }
165332a12730SMatthias Ringwald     // write page timeout
1654baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1655baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
165632a12730SMatthias Ringwald         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
165732a12730SMatthias Ringwald         return;
165832a12730SMatthias Ringwald     }
1659ab4831a3SMatthias Ringwald     // send scan enable
1660baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1661baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1662ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1663ab4831a3SMatthias Ringwald         return;
1664ab4831a3SMatthias Ringwald     }
1665c0c8a829SMatthias Ringwald     // send write scan activity
1666baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1667baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1668c0c8a829SMatthias Ringwald         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1669c0c8a829SMatthias Ringwald         return;
1670c0c8a829SMatthias Ringwald     }
1671ab4831a3SMatthias Ringwald }
167259d59ecfSMatthias Ringwald #endif
167359d59ecfSMatthias Ringwald 
16746fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
167506b9e820SMatthias Ringwald 
167696b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
167796b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
16789796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
167996b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
1680a1df452eSMatthias Ringwald     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
168196b53536SMatthias Ringwald         baud_rate = 3000000;
168296b53536SMatthias Ringwald     }
168396b53536SMatthias Ringwald     return baud_rate;
168496b53536SMatthias Ringwald }
168596b53536SMatthias Ringwald 
1686ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
16879ec2630cSMatthias Ringwald     UNUSED(ds);
16889ec2630cSMatthias Ringwald 
16890305bdeaSMatthias Ringwald     switch (hci_stack->substate){
16900305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
16917b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
16920305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
16937b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
16940305bdeaSMatthias Ringwald             hci_run();
16950305bdeaSMatthias Ringwald             break;
16969f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
16979f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
16989f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
16999f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
17009f007422SMatthias Ringwald             }
1701cf373d3aSMatthias Ringwald 
1702cf373d3aSMatthias Ringwald             /* fall through */
1703cf373d3aSMatthias Ringwald 
1704e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1705e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1706e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1707e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1708e47e68c7SMatthias Ringwald             hci_run();
1709688c2635SMatthias Ringwald             break;
17107224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
17117224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
171296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1713cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
17147dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
17157224be7eSMatthias Ringwald             }
1716834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
171761f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1718834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1719834bce8cSMatthias Ringwald                     log_info("Link Reset");
1720834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1721834bce8cSMatthias Ringwald                 }
1722772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1723772a36d3SMatthias Ringwald                 hci_run();
1724772a36d3SMatthias Ringwald             }
17254696bddbSMatthias Ringwald             break;
1726559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1727559961d0SMatthias Ringwald             // otherwise continue
1728559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1729559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1730559961d0SMatthias Ringwald             break;
17310305bdeaSMatthias Ringwald         default:
17320305bdeaSMatthias Ringwald             break;
17330305bdeaSMatthias Ringwald     }
17340305bdeaSMatthias Ringwald }
173506b9e820SMatthias Ringwald #endif
17360305bdeaSMatthias Ringwald 
173771de195eSMatthias Ringwald static void hci_initializing_next_state(void){
173874b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
173974b323a9SMatthias Ringwald }
174074b323a9SMatthias Ringwald 
1741f795c86eSMatthias Ringwald static void hci_init_done(void){
1742f795c86eSMatthias Ringwald     // done. tell the app
1743f795c86eSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1744f795c86eSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1745f795c86eSMatthias Ringwald     hci_emit_state();
1746f795c86eSMatthias Ringwald }
1747f795c86eSMatthias Ringwald 
174874b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
174971de195eSMatthias Ringwald static void hci_initializing_run(void){
1750148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1751f4c579d4SMatthias Ringwald 
17520d37aff3SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
17530d37aff3SMatthias Ringwald 
1754f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1755f9fd20c2SMatthias Ringwald     bool need_baud_change = hci_stack->config
1756f4c579d4SMatthias Ringwald             && hci_stack->chipset
1757f4c579d4SMatthias Ringwald             && hci_stack->chipset->set_baudrate_command
1758f4c579d4SMatthias Ringwald             && hci_stack->hci_transport->set_baudrate
1759f4c579d4SMatthias Ringwald             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1760f4c579d4SMatthias Ringwald #endif
1761f4c579d4SMatthias Ringwald 
176274b323a9SMatthias Ringwald     switch (hci_stack->substate){
176374b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
176474b323a9SMatthias Ringwald             hci_state_reset();
1765a0cf2f3fSMatthias Ringwald 
17666fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
17670305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1768659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1769528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1770528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1771a0cf2f3fSMatthias Ringwald #endif
17720305bdeaSMatthias Ringwald             // send command
177374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
17740305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
177574b323a9SMatthias Ringwald             break;
177676fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
177776fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
177876fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
177976fcb19bSMatthias Ringwald             break;
1780e28e41c0SMatthias Ringwald 
1781e28e41c0SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1782e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1783e47e68c7SMatthias Ringwald             hci_state_reset();
1784e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1785659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1786528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1787528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1788e47e68c7SMatthias Ringwald             // send command
1789e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1790e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1791e47e68c7SMatthias Ringwald             break;
17928d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
17938d29070eSMatthias Ringwald             hci_state_reset();
17948d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
17958d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
17968d29070eSMatthias Ringwald             break;
1797f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1798f4c579d4SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1799f4c579d4SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1800f4c579d4SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1801f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1802f4c579d4SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1803f4c579d4SMatthias Ringwald             break;
1804f4c579d4SMatthias Ringwald         }
1805c97af506SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
1806c97af506SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1807c97af506SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1808c97af506SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1809c97af506SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1810c97af506SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1811c97af506SMatthias Ringwald             break;
18128250c242SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
18138250c242SMatthias Ringwald #ifdef ENABLE_CLASSIC
18148250c242SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
18158250c242SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
18168250c242SMatthias Ringwald             break;
18178250c242SMatthias Ringwald #endif
18188250c242SMatthias Ringwald             /* fall through */
18198250c242SMatthias Ringwald 
1820f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE:
1821f4c579d4SMatthias Ringwald             if (need_baud_change) {
182296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
18233fb36a29SMatthias Ringwald                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1824f8fbdce0SMatthias Ringwald                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
182574b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
18264ea43905SMatthias Ringwald                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
18274696bddbSMatthias Ringwald                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
18284696bddbSMatthias Ringwald                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
182961f37892SMatthias Ringwald                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1830659d758cSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1831528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
18324696bddbSMatthias Ringwald                }
183374b323a9SMatthias Ringwald                break;
1834fab26ab3SMatthias Ringwald             }
1835f4c579d4SMatthias Ringwald 
1836f4c579d4SMatthias Ringwald             /* fall through */
1837f4c579d4SMatthias Ringwald 
183874b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
183974b323a9SMatthias Ringwald             // Custom initialization
18403fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1841ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
18421979f09cSMatthias Ringwald                 bool send_cmd = false;
1843ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1844f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
18451979f09cSMatthias Ringwald                         send_cmd = true;
1846e47e68c7SMatthias Ringwald                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1847e47e68c7SMatthias Ringwald                         break;
1848f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
18491979f09cSMatthias Ringwald                         send_cmd = true;
1850f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1851e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1852659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1853528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1854528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
1855a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1856772a36d3SMatthias Ringwald                             && hci_stack->config
18573fb36a29SMatthias Ringwald                             && hci_stack->chipset
18583fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1859772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
18602caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
1861772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1862772a36d3SMatthias Ringwald                         } else {
18639f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1864772a36d3SMatthias Ringwald                         }
1865e47e68c7SMatthias Ringwald                         break;
1866f41911edSMatthias Ringwald                     default:
1867f41911edSMatthias Ringwald                         break;
1868e47e68c7SMatthias Ringwald                 }
1869ee720f3aSMatthias Ringwald 
1870ee720f3aSMatthias Ringwald                 if (send_cmd){
18714ea43905SMatthias Ringwald                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1872ee720f3aSMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1873ee720f3aSMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
18740305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
187574b323a9SMatthias Ringwald                     break;
187674b323a9SMatthias Ringwald                 }
1877148ca237SMatthias Ringwald                 log_info("Init script done");
187892a0d36dSMatthias Ringwald 
1879559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1880ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1881a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1882a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1883e021ff1eSMatthias Ringwald 
1884559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
188592a0d36dSMatthias Ringwald                     if (need_baud_change) {
18869796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1887cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
188892a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
188992a0d36dSMatthias Ringwald                     }
1890559961d0SMatthias Ringwald 
1891f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
1892f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1893f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
1894f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1895559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1896f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1897559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1898559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
1899559961d0SMatthias Ringwald                     break;
190092a0d36dSMatthias Ringwald                 }
190174b323a9SMatthias Ringwald             }
190206b9e820SMatthias Ringwald #endif
1903521bd5ffSMatthias Ringwald             /* fall through */
190406b9e820SMatthias Ringwald 
190506b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
190606b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
190706b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
190806b9e820SMatthias Ringwald             break;
190953860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
191053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
191153860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
191253860077SMatthias Ringwald             break;
191374b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
19145ffe9d0bSMatthias Ringwald             // only read buffer size if supported
19151ffa425cSMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
191674b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
19170305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_read_buffer_size);
191874b323a9SMatthias Ringwald                 break;
19195ffe9d0bSMatthias Ringwald             }
1920521bd5ffSMatthias Ringwald 
19215ffe9d0bSMatthias Ringwald             /* fall through */
19225ffe9d0bSMatthias Ringwald 
192353860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
192453860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
19250305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
192674b323a9SMatthias Ringwald             break;
19272b838201SMatthias Ringwald 
19282b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
19292b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
19302b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
19312b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
19322b838201SMatthias Ringwald             break;
19332b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
19342b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
19352b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
19362b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
19372b838201SMatthias Ringwald             break;
19382b838201SMatthias Ringwald #endif
19392b838201SMatthias Ringwald 
194074b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
19410305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
194274b323a9SMatthias Ringwald             if (hci_le_supported()){
19435ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
194474b323a9SMatthias Ringwald             } else {
194574b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
19465ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
194774b323a9SMatthias Ringwald             }
194874b323a9SMatthias Ringwald             break;
19492b838201SMatthias Ringwald 
1950ff7d1758SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK_2:
19518254e329SMatthias Ringwald             // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
19528254e329SMatthias Ringwald             // setting Event Mask 2 causes Controller to drop Encryption Change events.
19538254e329SMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
19548254e329SMatthias Ringwald             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
1955ff7d1758SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
1956ff7d1758SMatthias Ringwald                 // Encryption Change Event v2 - bit 25
1957ff7d1758SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
1958ff7d1758SMatthias Ringwald                 break;
1959ff7d1758SMatthias Ringwald             }
1960ff7d1758SMatthias Ringwald 
196135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
1962ff7d1758SMatthias Ringwald             /* fall through */
1963ff7d1758SMatthias Ringwald 
196474b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1965f795c86eSMatthias Ringwald             if (hci_classic_supported() && gap_ssp_supported()){
196674b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
19670305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
196874b323a9SMatthias Ringwald                 break;
1969e7c662faSMatthias Ringwald             }
1970521bd5ffSMatthias Ringwald 
1971e7c662faSMatthias Ringwald             /* fall through */
1972e7c662faSMatthias Ringwald 
1973f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
1974f795c86eSMatthias Ringwald             if (hci_classic_supported()){
1975f6858d14SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
19768a114470SMatthias Ringwald                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1977f6858d14SMatthias Ringwald                 break;
1978f795c86eSMatthias Ringwald             }
1979521bd5ffSMatthias Ringwald 
1980f795c86eSMatthias Ringwald             /* fall through */
1981f795c86eSMatthias Ringwald 
19825d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
1983f3052906SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
19841ffa425cSMatthias Ringwald             if (hci_classic_supported() && hci_stack->secure_connections_enable
19851ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
1986c214d65bSMatthias Ringwald                 hci_stack->secure_connections_active = true;
19875d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
19881ffa425cSMatthias Ringwald                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
19895d23aae8SMatthias Ringwald                 break;
1990f3052906SMatthias Ringwald             }
1991521bd5ffSMatthias Ringwald 
1992a391128dSMatthias Ringwald             /* fall through */
1993a391128dSMatthias Ringwald 
1994a391128dSMatthias Ringwald         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
1995a391128dSMatthias Ringwald             // skip set min encryption key size
1996a391128dSMatthias Ringwald             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
1997a391128dSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
1998a391128dSMatthias Ringwald                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
1999a391128dSMatthias Ringwald                 break;
2000a391128dSMatthias Ringwald             }
2001a391128dSMatthias Ringwald 
2002e4c6114dSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2003521bd5ffSMatthias Ringwald             /* fall through */
2004521bd5ffSMatthias Ringwald 
2005483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
2006729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2007e4c6114dSMatthias Ringwald             // skip write synchronous flow control if not supported
20081ffa425cSMatthias Ringwald             if (hci_classic_supported()
20091ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2010729ed62eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2011729ed62eSMatthias Ringwald                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2012729ed62eSMatthias Ringwald                 break;
2013f795c86eSMatthias Ringwald             }
2014f795c86eSMatthias Ringwald             /* fall through */
2015f795c86eSMatthias Ringwald 
2016483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2017e4c6114dSMatthias Ringwald             // skip write default erroneous data reporting if not supported
20181ffa425cSMatthias Ringwald             if (hci_classic_supported()
20191ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2020483c5078SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2021483c5078SMatthias Ringwald                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2022483c5078SMatthias Ringwald                 break;
2023f795c86eSMatthias Ringwald             }
2024e4c6114dSMatthias Ringwald #endif
2025f795c86eSMatthias Ringwald 
2026f795c86eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2027521bd5ffSMatthias Ringwald             /* fall through */
2028521bd5ffSMatthias Ringwald 
20298051253fSMatthias Ringwald         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2030a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2031e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2032a42798c3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
20338051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2034a42798c3SMatthias Ringwald                 log_info("BCM: Route SCO data via HCI transport");
2035a42798c3SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
20368051253fSMatthias Ringwald #endif
20378051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
20388051253fSMatthias Ringwald                 log_info("BCM: Route SCO data via PCM interface");
20391d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
2040f795c86eSMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
20411d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
20421d2bbd54SMatthias Ringwald #else
20431d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
20441d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
20451d2bbd54SMatthias Ringwald #endif
20468051253fSMatthias Ringwald #endif
2047a42798c3SMatthias Ringwald                 break;
2048f795c86eSMatthias Ringwald             }
2049f795c86eSMatthias Ringwald #endif
2050f795c86eSMatthias Ringwald 
20514e821764SMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
2052521bd5ffSMatthias Ringwald             /* fall through */
2053521bd5ffSMatthias Ringwald 
20544e821764SMatthias Ringwald         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2055e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
20564e821764SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
20574e821764SMatthias Ringwald                 log_info("BCM: Config PCM interface for I2S");
20581d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
20591d2bbd54SMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
20601d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
20611d2bbd54SMatthias Ringwald #else
20621d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
20631d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
20641d2bbd54SMatthias Ringwald #endif
20654e821764SMatthias Ringwald                 break;
2066f795c86eSMatthias Ringwald             }
206735454696SMatthias Ringwald #endif
20684e821764SMatthias Ringwald #endif
20694e821764SMatthias Ringwald 
2070a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2071521bd5ffSMatthias Ringwald             /* fall through */
2072521bd5ffSMatthias Ringwald 
207374b323a9SMatthias Ringwald         // LE INIT
207474b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
2075f795c86eSMatthias Ringwald             if (hci_le_supported()){
207674b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
207779b7ea2dSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
207879b7ea2dSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size_v2);
207979b7ea2dSMatthias Ringwald                 } else {
20800305bdeaSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size);
208179b7ea2dSMatthias Ringwald                 }
208274b323a9SMatthias Ringwald                 break;
2083f795c86eSMatthias Ringwald             }
2084521bd5ffSMatthias Ringwald 
2085f795c86eSMatthias Ringwald             /* fall through */
2086f795c86eSMatthias Ringwald 
2087699a5fcaSMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2088699a5fcaSMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
20891ffa425cSMatthias Ringwald             if (hci_le_supported()
20901ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2091699a5fcaSMatthias Ringwald                 // LE Supported Host = 1, Simultaneous Host = 0
2092699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2093699a5fcaSMatthias Ringwald                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2094daabb8b8SMatthias Ringwald                 break;
2095f795c86eSMatthias Ringwald             }
2096521bd5ffSMatthias Ringwald 
2097f795c86eSMatthias Ringwald             /* fall through */
2098f795c86eSMatthias Ringwald 
2099699a5fcaSMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
2100f795c86eSMatthias Ringwald             if (hci_le_supported()){
2101699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
210291d9e5d0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x07); // all events from core v5.3 without LE Enhanced Connection Complete
210374b323a9SMatthias Ringwald                 break;
2104f795c86eSMatthias Ringwald             }
2105b435e062SMatthias Ringwald #endif
2106b435e062SMatthias Ringwald 
2107b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2108521bd5ffSMatthias Ringwald             /* fall through */
2109521bd5ffSMatthias Ringwald 
2110dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
21111ffa425cSMatthias Ringwald             if (hci_le_supported()
21121ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2113dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2114dcd678baSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_data_length);
2115dcd678baSMatthias Ringwald                 break;
2116f795c86eSMatthias Ringwald             }
2117521bd5ffSMatthias Ringwald 
2118f795c86eSMatthias Ringwald             /* fall through */
2119f795c86eSMatthias Ringwald 
2120dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
21211ffa425cSMatthias Ringwald             if (hci_le_supported()
21221ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2123dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2124b435e062SMatthias 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);
2125dcd678baSMatthias Ringwald                 break;
2126f795c86eSMatthias Ringwald             }
2127b435e062SMatthias Ringwald #endif
2128b435e062SMatthias Ringwald 
2129b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2130521bd5ffSMatthias Ringwald             /* fall through */
2131521bd5ffSMatthias Ringwald 
21323b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
2133f795c86eSMatthias Ringwald             if (hci_le_supported()){
21343b6d4121SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
21353b6d4121SMatthias Ringwald                 hci_send_cmd(&hci_le_read_white_list_size);
21363b6d4121SMatthias Ringwald                 break;
2137f795c86eSMatthias Ringwald             }
2138521bd5ffSMatthias Ringwald 
213974b323a9SMatthias Ringwald #endif
21404f982f31SMatthias Ringwald 
21413a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
21423a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
21433a74541eSMatthias Ringwald             /* fall through */
21443a74541eSMatthias Ringwald 
21453a74541eSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
21463a74541eSMatthias Ringwald             if (hci_extended_advertising_supported()){
21473a74541eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
21483a74541eSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
21493a74541eSMatthias Ringwald                 break;
21503a74541eSMatthias Ringwald             }
21513a74541eSMatthias Ringwald #endif
21523a74541eSMatthias Ringwald #endif
2153521bd5ffSMatthias Ringwald             /* fall through */
2154521bd5ffSMatthias Ringwald 
2155c63ee49aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2156c63ee49aSMatthias Ringwald     case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2157c63ee49aSMatthias Ringwald             if (hci_le_supported()) {
2158c63ee49aSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2159c63ee49aSMatthias Ringwald                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2160c63ee49aSMatthias Ringwald                 break;
2161c63ee49aSMatthias Ringwald             }
2162c63ee49aSMatthias Ringwald #endif
2163c63ee49aSMatthias Ringwald 
2164c63ee49aSMatthias Ringwald             /* fall through */
2165c63ee49aSMatthias Ringwald 
2166f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
21674f982f31SMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
216873799937SMatthias Ringwald             // main init sequence complete
21694f982f31SMatthias Ringwald #ifdef ENABLE_CLASSIC
217073799937SMatthias Ringwald             // check if initial Classic GAP Tasks are completed
2171baa4881eSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
21724f982f31SMatthias Ringwald                 hci_run_gap_tasks_classic();
21734f982f31SMatthias Ringwald                 break;
21744f982f31SMatthias Ringwald             }
21754f982f31SMatthias Ringwald #endif
217673799937SMatthias Ringwald #ifdef ENABLE_BLE
217773799937SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
217873799937SMatthias Ringwald             // check if initial LE GAP Tasks are completed
217973799937SMatthias Ringwald             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
218073799937SMatthias Ringwald                 hci_run_general_gap_le();
218173799937SMatthias Ringwald                 break;
218273799937SMatthias Ringwald             }
218373799937SMatthias Ringwald #endif
218473799937SMatthias Ringwald #endif
2185f795c86eSMatthias Ringwald             hci_init_done();
2186f795c86eSMatthias Ringwald             break;
2187f795c86eSMatthias Ringwald 
218874b323a9SMatthias Ringwald         default:
218974b323a9SMatthias Ringwald             return;
219074b323a9SMatthias Ringwald     }
219155975f88SMatthias Ringwald }
219255975f88SMatthias Ringwald 
219307fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
219407fd2f31SMatthias Ringwald     bool command_completed = false;
21950e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2196f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
21976155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
219807fd2f31SMatthias Ringwald             command_completed = true;
2199148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
22006155b3d3S[email protected]         } else {
2201d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
22026155b3d3S[email protected]         }
22036155b3d3S[email protected]     }
22040f97eae7SMatthias Ringwald 
22050e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
22066155b3d3S[email protected]         uint8_t  status = packet[2];
2207f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
22086155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
22096155b3d3S[email protected]             if (status){
221007fd2f31SMatthias Ringwald                 command_completed = true;
2211148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
22126155b3d3S[email protected]             } else {
22136155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
22146155b3d3S[email protected]             }
22156155b3d3S[email protected]         } else {
2216148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
22176155b3d3S[email protected]         }
22186155b3d3S[email protected]     }
22196fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2220e47e68c7SMatthias Ringwald     // Vendor == CSR
22210e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2222e47e68c7SMatthias Ringwald         // TODO: track actual command
222307fd2f31SMatthias Ringwald         command_completed = true;
2224e47e68c7SMatthias Ringwald     }
2225a2481739S[email protected] 
22264e9daa6fSMatthias Ringwald     // Vendor == Toshiba
22270e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
22284e9daa6fSMatthias Ringwald         // TODO: track actual command
222907fd2f31SMatthias Ringwald         command_completed = true;
2230004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2231004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
22324e9daa6fSMatthias Ringwald     }
223307fd2f31SMatthias Ringwald #endif
223407fd2f31SMatthias Ringwald 
223507fd2f31SMatthias Ringwald     return command_completed;
223607fd2f31SMatthias Ringwald }
223707fd2f31SMatthias Ringwald 
223807fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
223907fd2f31SMatthias Ringwald 
224007fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
224107fd2f31SMatthias Ringwald 
224207fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
224307fd2f31SMatthias Ringwald 
22446fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
22454e9daa6fSMatthias Ringwald 
22460f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
22470f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
22480f97eae7SMatthias Ringwald     //
22490f97eae7SMatthias Ringwald     // HCI Reset
22500f97eae7SMatthias Ringwald     // Timeout 100 ms
22510f97eae7SMatthias Ringwald     // HCI Reset
22520f97eae7SMatthias Ringwald     // Command Complete Reset
22530f97eae7SMatthias Ringwald     // HCI Read Local Version Information
22540f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
22550f97eae7SMatthias Ringwald     // hang...
22560f97eae7SMatthias Ringwald     //
22570f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
22580f97eae7SMatthias Ringwald     if (!command_completed
2259a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
22600e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
22610f97eae7SMatthias Ringwald 
2262f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
22630f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
22640f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
22650f97eae7SMatthias Ringwald             return;
22660f97eae7SMatthias Ringwald         }
22670f97eae7SMatthias Ringwald     }
22680f97eae7SMatthias Ringwald 
22699f007422SMatthias Ringwald     // CSR & H5
22709f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
22719f007422SMatthias Ringwald     if (!command_completed
2272a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
22730e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
22749f007422SMatthias Ringwald 
22759f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
22769f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
22779f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
22789f007422SMatthias Ringwald             return;
22799f007422SMatthias Ringwald         }
22809f007422SMatthias Ringwald     }
22819f007422SMatthias Ringwald 
22829f007422SMatthias 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
22839f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
22849f007422SMatthias Ringwald     if (command_completed){
22859f007422SMatthias Ringwald         switch (hci_stack->substate){
22869f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
22879f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
22889f007422SMatthias Ringwald                 break;
22899f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
22909f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
22919f007422SMatthias Ringwald                 break;
22929f007422SMatthias Ringwald             default:
22939f007422SMatthias Ringwald                 break;
22949f007422SMatthias Ringwald         }
22959f007422SMatthias Ringwald     }
22960f97eae7SMatthias Ringwald 
229706b9e820SMatthias Ringwald #endif
22980f97eae7SMatthias Ringwald 
2299a2481739S[email protected]     if (!command_completed) return;
2300a2481739S[email protected] 
230107fd2f31SMatthias Ringwald     bool need_baud_change = false;
230207fd2f31SMatthias Ringwald     bool need_addr_change = false;
230306b9e820SMatthias Ringwald 
23046fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
230506b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
23063fb36a29SMatthias Ringwald                         && hci_stack->chipset
23073fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
2308db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
23099796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2310db8bc6ffSMatthias Ringwald 
231106b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
23123fb36a29SMatthias Ringwald                         && hci_stack->chipset
23133fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
231406b9e820SMatthias Ringwald #endif
2315a80162e9SMatthias Ringwald 
23165c363727SMatthias Ringwald     switch(hci_stack->substate){
231706b9e820SMatthias Ringwald 
23186fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
23199f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
2320d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
23219f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
2322f4c579d4SMatthias Ringwald 
2323f4c579d4SMatthias Ringwald             /* fall through */
2324f4c579d4SMatthias Ringwald #endif
2325f4c579d4SMatthias Ringwald 
232674b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
2327528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2328f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
23292f48d920SMatthias Ringwald             return;
2330f4c579d4SMatthias Ringwald 
2331f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2332a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
23334696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
2334fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
233561f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
233696b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2337cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2338fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
23394696bddbSMatthias Ringwald             }
234074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
234174b323a9SMatthias Ringwald             return;
2342a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2343528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2344a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2345a80162e9SMatthias Ringwald             return;
234674b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
234774b323a9SMatthias Ringwald             // repeat custom init
234874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
234974b323a9SMatthias Ringwald             return;
235006b9e820SMatthias Ringwald #endif
235106b9e820SMatthias Ringwald 
2352a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
23530e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2354efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2355efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2356eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2357eb3a5314SMatthias Ringwald                 return;
2358eb3a5314SMatthias Ringwald             }
235953860077SMatthias Ringwald             if (need_addr_change){
236053860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
236153860077SMatthias Ringwald                 return;
236253860077SMatthias Ringwald             }
236353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
236453860077SMatthias Ringwald             return;
23656fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
23667224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
23677224be7eSMatthias Ringwald             if (need_baud_change){
236896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2369cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2370fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
23717224be7eSMatthias Ringwald             }
2372eb3a5314SMatthias Ringwald             if (need_addr_change){
2373eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2374eb3a5314SMatthias Ringwald                 return;
2375eb3a5314SMatthias Ringwald             }
2376eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2377eb3a5314SMatthias Ringwald             return;
237853860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
23796ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
23806ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
23816ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
238253860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
238353860077SMatthias Ringwald                 return;
238453860077SMatthias Ringwald             }
238553860077SMatthias Ringwald             // skipping st warm boot
238653860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
238753860077SMatthias Ringwald             return;
238853860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
238953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
239053860077SMatthias Ringwald             return;
239106b9e820SMatthias Ringwald #endif
2392e7c662faSMatthias Ringwald 
2393f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
2394eb8d95caSMatthias Ringwald             // set state if we came here by fall through
2395eb8d95caSMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
2396f795c86eSMatthias Ringwald             return;
2397a650ba4dSMatthias Ringwald 
23986155b3d3S[email protected]         default:
239974b323a9SMatthias Ringwald             break;
24006155b3d3S[email protected]     }
240155975f88SMatthias Ringwald     hci_initializing_next_state();
24026155b3d3S[email protected] }
24036155b3d3S[email protected] 
24040bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
24053bb5ff27SMatthias Ringwald     // CC2564C might emit Connection Complete for rejected incoming SCO connection
24061a4fdac4SMatthias Ringwald     // To prevent accidentally free'ing the HCI connection for the ACL connection,
24071a4fdac4SMatthias Ringwald     // check if we have been aware of the HCI connection
24081f34df2cSMatthias Ringwald     switch (conn->state){
24091a4fdac4SMatthias Ringwald         case SENT_CREATE_CONNECTION:
24101f34df2cSMatthias Ringwald         case RECEIVED_CONNECTION_REQUEST:
24111f34df2cSMatthias Ringwald             break;
24121f34df2cSMatthias Ringwald         default:
24131f34df2cSMatthias Ringwald             return;
24141f34df2cSMatthias Ringwald     }
24153bb5ff27SMatthias Ringwald 
2416229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
24170bbba85bSMatthias Ringwald     bd_addr_t bd_address;
24186535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
24190bbba85bSMatthias Ringwald 
24206bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
24216bc9fa5eSMatthias Ringwald     // cache needed data
24226bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
24236bc9fa5eSMatthias Ringwald #endif
24246bc9fa5eSMatthias Ringwald 
24250bbba85bSMatthias Ringwald     // connection failed, remove entry
24260bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
24270bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
24280bbba85bSMatthias Ringwald 
24296bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
24300bbba85bSMatthias Ringwald     // notify client if dedicated bonding
24310bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
24320bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
24330bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
24340bbba85bSMatthias Ringwald     }
24350bbba85bSMatthias Ringwald 
24360bbba85bSMatthias Ringwald     // if authentication error, also delete link key
24370bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
24380bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
24390bbba85bSMatthias Ringwald     }
24401c79b5e3SMatthias Ringwald #else
24411c79b5e3SMatthias Ringwald     UNUSED(status);
24426bc9fa5eSMatthias Ringwald #endif
24430bbba85bSMatthias Ringwald }
24440bbba85bSMatthias Ringwald 
2445be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
24462f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
24472f5c44baSMatthias Ringwald     // SSP Controller
24482f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
24492f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
24502f5c44baSMatthias Ringwald     }
24512f5c44baSMatthias Ringwald     // eSCO
24522f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
24532f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
24542f5c44baSMatthias Ringwald     }
24552f5c44baSMatthias Ringwald     // Extended features
24562f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
24572f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
24582f5c44baSMatthias Ringwald     }
24592f5c44baSMatthias Ringwald }
24602f5c44baSMatthias Ringwald 
24612f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
24622f5c44baSMatthias Ringwald     // SSP Host
24632f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
24642f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
24652f5c44baSMatthias Ringwald     }
246650c51a77SMatthias Ringwald     // SC Host
246750c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
246850c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
246950c51a77SMatthias Ringwald     }
247050c51a77SMatthias Ringwald }
247150c51a77SMatthias Ringwald 
247250c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
247350c51a77SMatthias Ringwald     // SC Controller
247450c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
247550c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
247650c51a77SMatthias Ringwald     }
24772f5c44baSMatthias Ringwald }
24782f5c44baSMatthias Ringwald 
2479de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
2480461a2bc4SMatthias Ringwald     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2481de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
248249bafb5eSMatthias Ringwald     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2483de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
2484de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2485de0df013SMatthias Ringwald     }
2486de0df013SMatthias Ringwald }
2487128825c3SMatthias Ringwald static bool hci_remote_sc_enabled(hci_connection_t * connection){
2488128825c3SMatthias Ringwald     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2489128825c3SMatthias Ringwald     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2490128825c3SMatthias Ringwald }
2491128825c3SMatthias Ringwald 
2492be500194SMatthias Ringwald #endif
2493de0df013SMatthias Ringwald 
249467c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
249567c6c9dcSMatthias Ringwald     // handle BT initialization
249667c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
249767c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
249867c6c9dcSMatthias Ringwald     }
249967c6c9dcSMatthias Ringwald 
250067c6c9dcSMatthias Ringwald     // help with BT sleep
250167c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
250267c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
250372a2585aSMatthias Ringwald         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
250472a2585aSMatthias Ringwald         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
250567c6c9dcSMatthias Ringwald         hci_initializing_next_state();
250667c6c9dcSMatthias Ringwald     }
250767c6c9dcSMatthias Ringwald }
250867c6c9dcSMatthias Ringwald 
25099866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
25109866fdc7SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
25118daf94bcSMatthias Ringwald     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
25129866fdc7SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
2513de9f0299SMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_connection(conn);
2514de9f0299SMatthias Ringwald 
2515de9f0299SMatthias Ringwald     // trigger disconnect for dedicated bonding, skip emit security level as disconnect is pending
2516de9f0299SMatthias Ringwald     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2517de9f0299SMatthias Ringwald         conn->bonding_flags &= ~BONDING_DEDICATED;
2518de9f0299SMatthias Ringwald         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2519de9f0299SMatthias Ringwald         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2520de9f0299SMatthias Ringwald         return;
2521de9f0299SMatthias Ringwald     }
2522abdad579SMatthias Ringwald 
25238daf94bcSMatthias Ringwald     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
25241cf0a6c8SMatthias Ringwald         conn->requested_security_level = LEVEL_0;
2525de9f0299SMatthias Ringwald         hci_emit_security_level(conn->con_handle, security_level);
2526abdad579SMatthias Ringwald         return;
2527abdad579SMatthias Ringwald     }
2528abdad579SMatthias Ringwald 
2529d54424c3SMatthias Ringwald     // Request remote features if not already done
2530dbe0d85cSMatthias Ringwald     hci_trigger_remote_features_for_connection(conn);
2531d54424c3SMatthias Ringwald 
2532abdad579SMatthias Ringwald     // Request Authentication if not already done
2533abdad579SMatthias Ringwald     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2534abdad579SMatthias Ringwald     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
25359866fdc7SMatthias Ringwald }
25369866fdc7SMatthias Ringwald #endif
25379866fdc7SMatthias Ringwald 
25383b631737SMatthias Ringwald static void hci_store_local_supported_commands(const uint8_t * packet){
253925e46151SMatthias Ringwald     // create mapping table
254025e46151SMatthias Ringwald #define X(name, offset, bit) { offset, bit },
254125e46151SMatthias Ringwald     static struct {
254225e46151SMatthias Ringwald         uint8_t byte_offset;
254325e46151SMatthias Ringwald         uint8_t bit_position;
254425e46151SMatthias Ringwald     } supported_hci_commands_map [] = {
254525e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
254625e46151SMatthias Ringwald     };
254725e46151SMatthias Ringwald #undef X
254825e46151SMatthias Ringwald 
254925e46151SMatthias Ringwald     // create names for debug purposes
255025e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
255125e46151SMatthias Ringwald #define X(name, offset, bit) #name,
255225e46151SMatthias Ringwald     static const char * command_names[] = {
255325e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
255425e46151SMatthias Ringwald     };
255525e46151SMatthias Ringwald #undef X
255625e46151SMatthias Ringwald #endif
255725e46151SMatthias Ringwald 
25581ffa425cSMatthias Ringwald     hci_stack->local_supported_commands = 0;
255925e46151SMatthias Ringwald     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
256025e46151SMatthias Ringwald     uint16_t i;
256125e46151SMatthias Ringwald     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
256225e46151SMatthias Ringwald         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
256325e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
256425e46151SMatthias Ringwald             log_info("Command %s (%u) supported %u/%u", command_names[i], i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
256525e46151SMatthias Ringwald #else
25661ffa425cSMatthias Ringwald             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
256725e46151SMatthias Ringwald #endif
25681ffa425cSMatthias Ringwald             hci_stack->local_supported_commands |= (1LU << i);
256925e46151SMatthias Ringwald         }
257025e46151SMatthias Ringwald     }
25711ffa425cSMatthias Ringwald     log_info("Local supported commands summary %04x", hci_stack->local_supported_commands);
25723b631737SMatthias Ringwald }
25733b631737SMatthias Ringwald 
25744f781026SMatthias Ringwald static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2575b08371a9SMilanka Ringwald     UNUSED(size);
2576e76a89eeS[email protected] 
25779cbd2215SMatthias Ringwald     uint16_t manufacturer;
25789cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
2579fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
25801f7b95a1Smatthias.ringwald     hci_connection_t * conn;
2581c7a108afSMatthias Ringwald #endif
2582c7a108afSMatthias Ringwald #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
2583645b7c25SMatthias Ringwald     uint8_t status;
25849cbd2215SMatthias Ringwald #endif
25856bef4003SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
25866bef4003SMatthias Ringwald     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
25877ec5eeaaSmatthias.ringwald 
2588645b7c25SMatthias Ringwald     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2589645b7c25SMatthias Ringwald     switch (opcode){
2590645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2591645b7c25SMatthias Ringwald             if (packet[5]) break;
25929e263bd7SMatthias Ringwald             // terminate, name 248 chars
25939e263bd7SMatthias Ringwald             packet[6+248] = 0;
25949e263bd7SMatthias Ringwald             log_info("local name: %s", &packet[6]);
2595645b7c25SMatthias Ringwald             break;
2596645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
25971d279b20Smatthias.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"
2598c3b46f5aSMatthias Ringwald             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2599429122ccSMatthias Ringwald                 uint16_t acl_len = little_endian_read_16(packet, 6);
2600429122ccSMatthias Ringwald                 uint16_t sco_len = packet[8];
2601429122ccSMatthias Ringwald 
2602429122ccSMatthias Ringwald                 // determine usable ACL/SCO payload size
2603429122ccSMatthias Ringwald                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2604429122ccSMatthias Ringwald                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2605429122ccSMatthias Ringwald 
2606b1c141dbSMatthias Ringwald                 hci_stack->acl_packets_total_num = (uint8_t) little_endian_read_16(packet, 9);
2607b1c141dbSMatthias Ringwald                 hci_stack->sco_packets_total_num = (uint8_t) little_endian_read_16(packet, 11);
2608a8b12447S[email protected] 
2609429122ccSMatthias Ringwald                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2610429122ccSMatthias Ringwald                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
26111a06f663S[email protected]                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2612c3b46f5aSMatthias Ringwald             }
2613645b7c25SMatthias Ringwald             break;
2614645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_RSSI:
2615645b7c25SMatthias Ringwald             if (packet[5] == ERROR_CODE_SUCCESS){
2616891b9fc2SMatthias Ringwald                 uint8_t event[5];
2617891b9fc2SMatthias Ringwald                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2618891b9fc2SMatthias Ringwald                 event[1] = 3;
26196535961aSMatthias Ringwald                 (void)memcpy(&event[2], &packet[6], 3);
2620891b9fc2SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2621891b9fc2SMatthias Ringwald             }
2622645b7c25SMatthias Ringwald             break;
2623a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
262479b7ea2dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
262579b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
262679b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_total_num = packet[11];
262779b7ea2dSMatthias Ringwald             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
262879b7ea2dSMatthias Ringwald                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
262979b7ea2dSMatthias Ringwald 
263079b7ea2dSMatthias Ringwald             /* fall through */
263179b7ea2dSMatthias Ringwald 
2632645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2633f8fbdce0SMatthias Ringwald             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2634ee303eddS[email protected]             hci_stack->le_acl_packets_total_num = packet[8];
26356c26b087S[email protected]             // determine usable ACL payload size
26366c26b087S[email protected]             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
26376c26b087S[email protected]                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
26386c26b087S[email protected]             }
263979b7ea2dSMatthias 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);
2640645b7c25SMatthias Ringwald             break;
2641b435e062SMatthias Ringwald #endif
2642b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2643645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2644dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2645dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2646dcd678baSMatthias 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);
2647645b7c25SMatthias Ringwald             break;
2648b435e062SMatthias Ringwald #endif
2649d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2650645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2651e691bb38SMatthias Ringwald             hci_stack->le_whitelist_capacity = packet[6];
265215d0a15bSMatthias Ringwald             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2653645b7c25SMatthias Ringwald             break;
265465a46ef3S[email protected] #endif
26553a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
26563a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
26573a74541eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
26583a74541eSMatthias Ringwald             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
26593a74541eSMatthias Ringwald             break;
266025df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
266125df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
266225df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
266325df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
266425df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
266525df6c61SMatthias Ringwald                 uint8_t adv_status = packet[6];
266625df6c61SMatthias Ringwald                 uint8_t tx_power   = packet[7];
266725df6c61SMatthias 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 };
266825df6c61SMatthias Ringwald                 if (adv_status == 0){
266925df6c61SMatthias Ringwald                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
267025df6c61SMatthias Ringwald                 }
267125df6c61SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
267225df6c61SMatthias Ringwald             }
267325df6c61SMatthias Ringwald             break;
267425df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
267525df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
267625df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
267725df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
267825df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
267925df6c61SMatthias Ringwald                 uint8_t adv_status = packet[5];
268025df6c61SMatthias Ringwald                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status };
268125df6c61SMatthias Ringwald                 if (adv_status == 0){
268225df6c61SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
268325df6c61SMatthias Ringwald                 }
268425df6c61SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
268525df6c61SMatthias Ringwald             }
268625df6c61SMatthias Ringwald             break;
26873a74541eSMatthias Ringwald #endif
26883a74541eSMatthias Ringwald #endif
2689645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BD_ADDR:
2690645b7c25SMatthias Ringwald             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2691645b7c25SMatthias Ringwald             log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
269233373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
26931624665aSMatthias Ringwald             if (hci_stack->link_key_db){
26941624665aSMatthias Ringwald                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
26951624665aSMatthias Ringwald             }
269633373e40SMatthias Ringwald #endif
2697645b7c25SMatthias Ringwald             break;
269835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2699645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
270071fd255dSMatthias Ringwald             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2701645b7c25SMatthias Ringwald             break;
27023d1f2d24SMatthias Ringwald         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
27033d1f2d24SMatthias Ringwald             status = hci_event_command_complete_get_return_parameters(packet)[0];
27043d1f2d24SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
27053d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
27063d1f2d24SMatthias Ringwald             } else {
27073d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
27083d1f2d24SMatthias Ringwald             }
27093d1f2d24SMatthias Ringwald             break;
2710645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
271130199e24SMatthias Ringwald         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2712f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2713f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2714f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2715f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2716f5875de5SMatthias Ringwald             }
2717645b7c25SMatthias Ringwald             break;
271835454696SMatthias Ringwald #endif
2719645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
27204f781026SMatthias Ringwald             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
272165389bfcS[email protected] 
272235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2723a5a23fc2S[email protected]             // determine usable ACL packet types based on host buffer size and supported features
2724a5a23fc2S[email protected]             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
27258b96126aSMatthias Ringwald             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
272635454696SMatthias Ringwald #endif
2727f5d8d141S[email protected]             // Classic/LE
2728f5d8d141S[email protected]             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2729645b7c25SMatthias Ringwald             break;
2730645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2731645b7c25SMatthias Ringwald             manufacturer = little_endian_read_16(packet, 10);
2732c21d89f3SMatthias Ringwald             // map Cypress to Broadcom
2733c21d89f3SMatthias Ringwald             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2734c21d89f3SMatthias Ringwald                 log_info("Treat Cypress as Broadcom");
2735c21d89f3SMatthias Ringwald                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2736c21d89f3SMatthias Ringwald                 little_endian_store_16(packet, 10, manufacturer);
2737c21d89f3SMatthias Ringwald             }
2738c21d89f3SMatthias Ringwald             hci_stack->manufacturer = manufacturer;
27394696bddbSMatthias Ringwald             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2740645b7c25SMatthias Ringwald             break;
2741645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
27423b631737SMatthias Ringwald             hci_store_local_supported_commands(packet);
2743645b7c25SMatthias Ringwald             break;
2744e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
2745645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
27464f781026SMatthias Ringwald             if (packet[5]) return;
27475b9b590fSMatthias Ringwald             hci_stack->synchronous_flow_control_enabled = 1;
2748645b7c25SMatthias Ringwald             break;
2749645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2750645b7c25SMatthias Ringwald             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2751573897a0SMatthias Ringwald             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2752573897a0SMatthias Ringwald             conn   = hci_connection_for_handle(handle);
2753c3b46f5aSMatthias Ringwald             if (conn != NULL) {
27549866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
2755573897a0SMatthias Ringwald                 if (status == 0){
27569866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
27574a659b0eSMatthias Ringwald                     log_info("Handle %04x key Size: %u", handle, key_size);
2758170fafaeSMatthias Ringwald                 } else {
2759e9f98c4aSMatthias Ringwald                     key_size = 1;
27609866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2761573897a0SMatthias Ringwald                 }
27629866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2763c3b46f5aSMatthias Ringwald             }
2764645b7c25SMatthias Ringwald             break;
2765cc15bb2cSMatthias Ringwald         // assert pairing complete event is emitted.
2766cc15bb2cSMatthias Ringwald         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2767cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2768cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2769cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
27708cc1507eSMatthias Ringwald             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2771cc15bb2cSMatthias Ringwald             // lookup connection by gap pairing addr
2772cc15bb2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2773cc15bb2cSMatthias Ringwald             if (conn == NULL) break;
2774cc15bb2cSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2775cc15bb2cSMatthias Ringwald             break;
2776cc15bb2cSMatthias Ringwald 
277775a8e4faSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
277875a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
277975a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
278075a8e4faSMatthias Ringwald             uint8_t event[67];
278175a8e4faSMatthias Ringwald             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
278275a8e4faSMatthias Ringwald             event[1] = 65;
278375a8e4faSMatthias Ringwald             (void)memset(&event[2], 0, 65);
278475a8e4faSMatthias Ringwald             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
278575a8e4faSMatthias Ringwald                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
278675a8e4faSMatthias Ringwald                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
278775a8e4faSMatthias Ringwald                     event[2] = 3;
278875a8e4faSMatthias Ringwald                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
278975a8e4faSMatthias Ringwald                 } else {
279075a8e4faSMatthias Ringwald                     event[2] = 1;
279175a8e4faSMatthias Ringwald                 }
279275a8e4faSMatthias Ringwald             }
279375a8e4faSMatthias Ringwald             hci_emit_event(event, sizeof(event), 0);
279475a8e4faSMatthias Ringwald             break;
279575a8e4faSMatthias Ringwald         }
27961ae74bf3SMatthias Ringwald 
27971ae74bf3SMatthias Ringwald         // note: only needed if user does not provide OOB data
27981ae74bf3SMatthias Ringwald         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
27991ae74bf3SMatthias Ringwald             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
28001ae74bf3SMatthias Ringwald             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
28011ae74bf3SMatthias Ringwald             if (conn == NULL) break;
28021ae74bf3SMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
28031ae74bf3SMatthias Ringwald             break;
2804e8c8828eSMatthias Ringwald #endif
280575a8e4faSMatthias Ringwald #endif
28064ae8623eSMatthias Ringwald #ifdef ENABLE_BLE
28074ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
28084ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
28094ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
28104ae8623eSMatthias Ringwald             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
28114ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
2812a90016deSMatthias Ringwald                 hci_iso_stream_requested_finalize(0xff);
28134ae8623eSMatthias Ringwald             }
28144ae8623eSMatthias Ringwald             break;
28157aa35f6aSMatthias Ringwald         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
28167aa35f6aSMatthias Ringwald             // lookup BIG by state
28177aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_t it;
28187aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
28197aa35f6aSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
28207aa35f6aSMatthias Ringwald                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
28217aa35f6aSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
28227aa35f6aSMatthias Ringwald                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
28237aa35f6aSMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
28247aa35f6aSMatthias Ringwald                         big->state_vars.next_bis++;
28257aa35f6aSMatthias Ringwald                         if (big->state_vars.next_bis == big->num_bis){
28267aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
28277aa35f6aSMatthias Ringwald                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
28287aa35f6aSMatthias Ringwald                         } else {
28297aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
28307aa35f6aSMatthias Ringwald                         }
28317aa35f6aSMatthias Ringwald                     } else {
28327aa35f6aSMatthias Ringwald                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
28337aa35f6aSMatthias Ringwald                         big->state_vars.status = status;
28342a6c0f82SMatthias Ringwald                     }
28352a6c0f82SMatthias Ringwald                     return;
28362a6c0f82SMatthias Ringwald                 }
28372a6c0f82SMatthias Ringwald             }
28382a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
28392a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
28402a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
28412a6c0f82SMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
28422a6c0f82SMatthias Ringwald                     status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
28432a6c0f82SMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
28442a6c0f82SMatthias Ringwald                         big_sync->state_vars.next_bis++;
28452a6c0f82SMatthias Ringwald                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
28462a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
28472a6c0f82SMatthias Ringwald                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
28482a6c0f82SMatthias Ringwald                         } else {
28492a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
28502a6c0f82SMatthias Ringwald                         }
28512a6c0f82SMatthias Ringwald                     } else {
28522a6c0f82SMatthias Ringwald                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
28532a6c0f82SMatthias Ringwald                         big_sync->state_vars.status = status;
28542a6c0f82SMatthias Ringwald                     }
28552a6c0f82SMatthias Ringwald                     return;
28562a6c0f82SMatthias Ringwald                 }
28572a6c0f82SMatthias Ringwald             }
28582a6c0f82SMatthias Ringwald             break;
28592a6c0f82SMatthias Ringwald         }
28602a6c0f82SMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
28612a6c0f82SMatthias Ringwald             // lookup BIG by state
28622a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_t it;
28632a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
28642a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
28652a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
28662a6c0f82SMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED){
28672a6c0f82SMatthias Ringwald                     btstack_linked_list_iterator_remove(&it);
28682a6c0f82SMatthias Ringwald                     switch (big_sync->state){
28692a6c0f82SMatthias Ringwald                         case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
28702a6c0f82SMatthias Ringwald                             hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
28712a6c0f82SMatthias Ringwald                             break;
28722a6c0f82SMatthias Ringwald                         default:
28732a6c0f82SMatthias Ringwald                             hci_emit_big_sync_stopped(big_sync);
28747aa35f6aSMatthias Ringwald                             break;
28757aa35f6aSMatthias Ringwald                     }
28767aa35f6aSMatthias Ringwald                     return;
28777aa35f6aSMatthias Ringwald                 }
28787aa35f6aSMatthias Ringwald             }
28797aa35f6aSMatthias Ringwald             break;
28807aa35f6aSMatthias Ringwald         }
28814ae8623eSMatthias Ringwald #endif
28824ae8623eSMatthias Ringwald #endif
28836f35bb46SMatthias Ringwald         default:
28846f35bb46SMatthias Ringwald             break;
28854f781026SMatthias Ringwald     }
2886645b7c25SMatthias Ringwald }
28874f781026SMatthias Ringwald 
2888afbf1cd7SMatthias Ringwald static void handle_command_status_event(uint8_t * packet, uint16_t size) {
2889afbf1cd7SMatthias Ringwald     UNUSED(size);
2890afbf1cd7SMatthias Ringwald 
2891afbf1cd7SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
2892afbf1cd7SMatthias Ringwald     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2893afbf1cd7SMatthias Ringwald 
2894c70df5f8SMatthias Ringwald     // get opcode and command status
2895c70df5f8SMatthias Ringwald     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
2896c70df5f8SMatthias Ringwald 
2897c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
2898c70df5f8SMatthias Ringwald     uint8_t status = hci_event_command_status_get_status(packet);
2899c70df5f8SMatthias Ringwald #endif
2900c70df5f8SMatthias Ringwald 
2901c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2902c70df5f8SMatthias Ringwald     bd_addr_type_t addr_type;
2903c70df5f8SMatthias Ringwald #endif
2904c70df5f8SMatthias Ringwald 
2905c70df5f8SMatthias Ringwald     switch (opcode){
2906afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
2907c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
2908c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
2909afbf1cd7SMatthias Ringwald #endif
2910afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2911c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
2912afbf1cd7SMatthias Ringwald #endif
2913c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
2914afbf1cd7SMatthias Ringwald             addr_type = hci_stack->outgoing_addr_type;
2915afbf1cd7SMatthias Ringwald 
2916afbf1cd7SMatthias Ringwald             // reset outgoing address info
2917afbf1cd7SMatthias Ringwald             memset(hci_stack->outgoing_addr, 0, 6);
2918afbf1cd7SMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2919afbf1cd7SMatthias Ringwald 
2920afbf1cd7SMatthias Ringwald             // on error
2921afbf1cd7SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
2922afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2923afbf1cd7SMatthias Ringwald                 if (hci_is_le_connection_type(addr_type)){
2924afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2925afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
2926afbf1cd7SMatthias Ringwald                 }
2927afbf1cd7SMatthias Ringwald #endif
2928afbf1cd7SMatthias Ringwald                 // error => outgoing connection failed
2929c70df5f8SMatthias Ringwald                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
2930afbf1cd7SMatthias Ringwald                 if (conn != NULL){
2931afbf1cd7SMatthias Ringwald                     hci_handle_connection_failed(conn, status);
2932afbf1cd7SMatthias Ringwald                 }
2933afbf1cd7SMatthias Ringwald             }
2934c70df5f8SMatthias Ringwald             break;
2935c70df5f8SMatthias Ringwald #endif
2936afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
2937c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY:
2938afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
2939afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2940afbf1cd7SMatthias Ringwald             } else {
2941afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2942afbf1cd7SMatthias Ringwald             }
2943c70df5f8SMatthias Ringwald             break;
2944c70df5f8SMatthias Ringwald #endif
2945afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2946c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
2947c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
2948afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS){
2949a90016deSMatthias Ringwald                 hci_iso_stream_requested_confirm(0xff);
2950afbf1cd7SMatthias Ringwald             } else {
2951a90016deSMatthias Ringwald                 hci_iso_stream_requested_finalize(0xff);
2952afbf1cd7SMatthias Ringwald             }
2953c70df5f8SMatthias Ringwald             break;
2954afbf1cd7SMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
2955c70df5f8SMatthias Ringwald         default:
2956c70df5f8SMatthias Ringwald             break;
2957c70df5f8SMatthias Ringwald     }
2958afbf1cd7SMatthias Ringwald }
2959afbf1cd7SMatthias Ringwald 
29600ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
29610ce3f217SMatthias Ringwald static void event_handle_le_connection_complete(const uint8_t * packet){
29620ce3f217SMatthias Ringwald 	bd_addr_t addr;
29630ce3f217SMatthias Ringwald 	bd_addr_type_t addr_type;
29640ce3f217SMatthias Ringwald 	hci_connection_t * conn;
29650ce3f217SMatthias Ringwald 
29660ce3f217SMatthias Ringwald 	// Connection management
29670ce3f217SMatthias Ringwald 	reverse_bd_addr(&packet[8], addr);
29680ce3f217SMatthias Ringwald 	addr_type = (bd_addr_type_t)packet[7];
29690ce3f217SMatthias Ringwald 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
29700ce3f217SMatthias Ringwald 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
29710ce3f217SMatthias Ringwald 
29720ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
29730ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
29740ce3f217SMatthias Ringwald 	if (packet[3]){
29750ce3f217SMatthias Ringwald 
29760ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
29770ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
29780ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
29790ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
29800ce3f217SMatthias Ringwald 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
29811f468175SMatthias Ringwald 		    // reset state
29820ce3f217SMatthias Ringwald             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
29831f468175SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
29840ce3f217SMatthias Ringwald 			// get outgoing connection conn struct for direct connect
29850ce3f217SMatthias Ringwald 			conn = gap_get_outgoing_connection();
29860ce3f217SMatthias Ringwald 		}
29870ce3f217SMatthias Ringwald 
29880ce3f217SMatthias Ringwald 		// outgoing le connection establishment is done
29890ce3f217SMatthias Ringwald 		if (conn){
29900ce3f217SMatthias Ringwald 			// remove entry
29910ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
29920ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
29930ce3f217SMatthias Ringwald 		}
29940ce3f217SMatthias Ringwald 		return;
29950ce3f217SMatthias Ringwald 	}
29960ce3f217SMatthias Ringwald #endif
29970ce3f217SMatthias Ringwald 
29980ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
29990ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_MASTER){
30000ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
30010ce3f217SMatthias Ringwald 		// if we're master on an le connection, it was an outgoing connection and we're done with it
30020ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
30030ce3f217SMatthias Ringwald 		if (hci_is_le_connection_type(addr_type)){
30040ce3f217SMatthias Ringwald 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
30050ce3f217SMatthias Ringwald 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
30060ce3f217SMatthias Ringwald 		}
30070ce3f217SMatthias Ringwald #endif
30080ce3f217SMatthias Ringwald 	} else {
30090ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30100ce3f217SMatthias Ringwald 		// if we're slave, it was an incoming connection, advertisements have stopped
3011935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
30120ce3f217SMatthias Ringwald #endif
30130ce3f217SMatthias Ringwald 	}
30140ce3f217SMatthias Ringwald 
30150ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
30160ce3f217SMatthias Ringwald 	if (!conn){
30170ce3f217SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
30180ce3f217SMatthias Ringwald 	}
30190ce3f217SMatthias Ringwald 
30200ce3f217SMatthias Ringwald 	// no memory, sorry.
30210ce3f217SMatthias Ringwald 	if (!conn){
30220ce3f217SMatthias Ringwald 		return;
30230ce3f217SMatthias Ringwald 	}
30240ce3f217SMatthias Ringwald 
30250ce3f217SMatthias Ringwald 	conn->state = OPEN;
30260ce3f217SMatthias Ringwald 	conn->role  = packet[6];
30270ce3f217SMatthias Ringwald 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
30280ce3f217SMatthias Ringwald 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
30290ce3f217SMatthias Ringwald 
30300ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30310ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_SLAVE){
30320ce3f217SMatthias Ringwald 		hci_update_advertisements_enabled_for_current_roles();
30330ce3f217SMatthias Ringwald 	}
30340ce3f217SMatthias Ringwald #endif
30350ce3f217SMatthias Ringwald 
3036dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
3037dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3038dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
3039dde9ff1eSMatthias Ringwald 
30400ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
30410ce3f217SMatthias Ringwald 
30420ce3f217SMatthias Ringwald 	// restart timer
30430ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
30440ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
30450ce3f217SMatthias Ringwald 
30460ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
30470ce3f217SMatthias Ringwald 
30480ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
30490ce3f217SMatthias Ringwald }
30500ce3f217SMatthias Ringwald #endif
30510ce3f217SMatthias Ringwald 
305217c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
305317c6fe5cSMatthias 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){
305417c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
305517c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
30569a8f78c1SMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
30579a8f78c1SMatthias Ringwald     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
305817c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
30599a8f78c1SMatthias Ringwald         // MITM not possible without keyboard or display
306017c6fe5cSMatthias Ringwald         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
306117c6fe5cSMatthias Ringwald         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
30629a8f78c1SMatthias Ringwald 
30639a8f78c1SMatthias Ringwald         // MITM possible if one side has keyboard and the other has keyboard or display
30649a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
30659a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
30669a8f78c1SMatthias Ringwald 
30679a8f78c1SMatthias Ringwald         // MITM not possible if one side has only display and other side has no keyboard
30689a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
30699a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
307017c6fe5cSMatthias Ringwald     }
307117c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
307217c6fe5cSMatthias Ringwald     return true;
307317c6fe5cSMatthias Ringwald }
30743817f9dfSMatthias Ringwald 
30753817f9dfSMatthias Ringwald static bool btstack_is_null(uint8_t * data, uint16_t size){
30763817f9dfSMatthias Ringwald     uint16_t i;
30773817f9dfSMatthias Ringwald     for (i=0; i < size ; i++){
30783817f9dfSMatthias Ringwald         if (data[i] != 0) {
30793817f9dfSMatthias Ringwald             return false;
30803817f9dfSMatthias Ringwald         }
30813817f9dfSMatthias Ringwald     }
30823817f9dfSMatthias Ringwald     return true;
30833817f9dfSMatthias Ringwald }
30843817f9dfSMatthias Ringwald 
3085b3c4163bSMatthias Ringwald static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
30862dd8985bSMatthias Ringwald     // get requested security level
30872dd8985bSMatthias Ringwald     gap_security_level_t requested_security_level = conn->requested_security_level;
30882dd8985bSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
30892dd8985bSMatthias Ringwald         requested_security_level = LEVEL_4;
30902dd8985bSMatthias Ringwald     }
30912dd8985bSMatthias Ringwald 
3092b3c4163bSMatthias Ringwald     // assess security: LEVEL 4 requires SC
30932dd8985bSMatthias Ringwald     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
30942dd8985bSMatthias Ringwald     if ((requested_security_level == LEVEL_4) &&
30952dd8985bSMatthias Ringwald         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
30962dd8985bSMatthias Ringwald         !hci_remote_sc_enabled(conn)){
3097b3c4163bSMatthias Ringwald         log_info("Level 4 required, but SC not supported -> abort");
3098b3c4163bSMatthias Ringwald         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3099b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3100b3c4163bSMatthias Ringwald         return;
3101b3c4163bSMatthias Ringwald     }
3102b3c4163bSMatthias Ringwald 
3103b3c4163bSMatthias Ringwald     // assess security based on io capabilities
3104b3c4163bSMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3105b3c4163bSMatthias Ringwald         // responder: fully validate io caps of both sides as well as OOB data
3106b3c4163bSMatthias Ringwald         bool security_possible = false;
3107b3c4163bSMatthias Ringwald         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3108b3c4163bSMatthias Ringwald 
3109b3c4163bSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3110b3c4163bSMatthias Ringwald         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3111b3c4163bSMatthias Ringwald         // so we merge the OOB data availability
3112b3c4163bSMatthias Ringwald         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3113b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_192 != NULL){
3114b3c4163bSMatthias Ringwald             have_oob_data |= 1;
3115b3c4163bSMatthias Ringwald         }
3116b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_256 != NULL){
3117b3c4163bSMatthias Ringwald             have_oob_data |= 2;
3118b3c4163bSMatthias Ringwald         }
3119b3c4163bSMatthias Ringwald         // for up to Level 3, either P-192 as well as P-256 will do
3120b3c4163bSMatthias 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
3121b3c4163bSMatthias Ringwald         // if remote does not SC, we should not receive P-256 data either
3122b3c4163bSMatthias Ringwald         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3123b3c4163bSMatthias Ringwald             security_possible = true;
3124b3c4163bSMatthias Ringwald         }
3125b3c4163bSMatthias Ringwald         // for Level 4, P-256 is needed
3126b3c4163bSMatthias Ringwald         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3127b3c4163bSMatthias Ringwald             security_possible = true;
3128b3c4163bSMatthias Ringwald         }
3129b3c4163bSMatthias Ringwald #endif
3130b3c4163bSMatthias Ringwald 
3131b3c4163bSMatthias Ringwald         if (security_possible == false){
31322dd8985bSMatthias Ringwald             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3133b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3134b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3135b3c4163bSMatthias Ringwald             return;
3136b3c4163bSMatthias Ringwald         }
3137b3c4163bSMatthias Ringwald     } else {
3138b3c4163bSMatthias Ringwald         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
31391fe968f5SMatthias Ringwald #ifndef ENABLE_CLASSIC_PAIRING_OOB
31401fe968f5SMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3141b3c4163bSMatthias Ringwald         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3142b3c4163bSMatthias Ringwald             log_info("Level 3+ required, but no input/output -> abort");
3143b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3144b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3145b3c4163bSMatthias Ringwald             return;
3146b3c4163bSMatthias Ringwald         }
3147b3c4163bSMatthias Ringwald #endif
31481fe968f5SMatthias Ringwald #endif
3149b3c4163bSMatthias Ringwald     }
3150b3c4163bSMatthias Ringwald 
3151b3c4163bSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3152b3c4163bSMatthias Ringwald     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3153b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3154b3c4163bSMatthias Ringwald     } else {
3155b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3156b3c4163bSMatthias Ringwald     }
3157b3c4163bSMatthias Ringwald #endif
3158b3c4163bSMatthias Ringwald }
3159b3c4163bSMatthias Ringwald 
316017c6fe5cSMatthias Ringwald #endif
316117c6fe5cSMatthias Ringwald 
3162c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
31634f781026SMatthias Ringwald 
31644f781026SMatthias Ringwald     uint16_t event_length = packet[1];
31654f781026SMatthias Ringwald 
31664f781026SMatthias Ringwald     // assert packet is complete
31674ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
31684f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
31694f781026SMatthias Ringwald         return;
31704f781026SMatthias Ringwald     }
31714f781026SMatthias Ringwald 
31724f781026SMatthias Ringwald     hci_con_handle_t handle;
31734f781026SMatthias Ringwald     hci_connection_t * conn;
31744f781026SMatthias Ringwald     int i;
31754f781026SMatthias Ringwald 
31764f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
31775e91d96cSMatthias Ringwald     hci_link_type_t link_type;
317848f33f37SMatthias Ringwald     bd_addr_t addr;
3179cef94710SMatthias Ringwald     bd_addr_type_t addr_type;
31804f781026SMatthias Ringwald #endif
31814ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
31824ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream;
31837aa35f6aSMatthias Ringwald     le_audio_big_t   * big;
31842a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync;
31854ae8623eSMatthias Ringwald #endif
31864f781026SMatthias Ringwald 
31874f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
31884f781026SMatthias Ringwald 
31894f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
31904f781026SMatthias Ringwald 
31914f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
31924f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
319356cf178bSmatthias.ringwald             break;
319456cf178bSmatthias.ringwald 
31957ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
3196afbf1cd7SMatthias Ringwald             handle_command_status_event(packet, size);
31977ec5eeaaSmatthias.ringwald             break;
31987ec5eeaaSmatthias.ringwald 
31992e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
32009784dac1SMatthias Ringwald             if (size < 3) return;
32019784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
32024ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
32039784dac1SMatthias Ringwald             uint16_t offset = 3;
32049784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
32054ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
32064ea43905SMatthias Ringwald                 offset += 2u;
3207f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
32084ea43905SMatthias Ringwald                 offset += 2u;
32092e440c8aS[email protected] 
32105061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
3211e5413aa0SMatthias Ringwald                 if (conn != NULL) {
321223bed257S[email protected] 
3213ce41473eSMatthias Ringwald                     if (conn->num_packets_sent >= num_packets) {
3214ce41473eSMatthias Ringwald                         conn->num_packets_sent -= num_packets;
3215e35edcc1S[email protected]                     } else {
3216ce41473eSMatthias Ringwald                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3217ce41473eSMatthias Ringwald                         conn->num_packets_sent = 0;
3218e35edcc1S[email protected]                     }
3219ce41473eSMatthias Ringwald                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3220e5413aa0SMatthias Ringwald                 }
3221e5413aa0SMatthias Ringwald 
32228ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
32238ad9cf99SMatthias Ringwald                 hci_controller_dump_packets();
32248ad9cf99SMatthias Ringwald #endif
32258ad9cf99SMatthias Ringwald 
3226e5413aa0SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3227e5413aa0SMatthias Ringwald                 if (conn == NULL){
3228e5413aa0SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3229e5413aa0SMatthias Ringwald                     if (iso_stream != NULL){
3230e5413aa0SMatthias Ringwald                         if (iso_stream->num_packets_sent >= num_packets) {
3231e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent -= num_packets;
3232e5413aa0SMatthias Ringwald                         } else {
3233e5413aa0SMatthias Ringwald                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3234e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent = 0;
3235e5413aa0SMatthias Ringwald                         }
3236e5413aa0SMatthias Ringwald                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3237e5413aa0SMatthias Ringwald                                  num_packets, handle, iso_stream->num_packets_sent);
3238e5413aa0SMatthias Ringwald                     }
32395ade6657SMatthias Ringwald                     hci_iso_notify_can_send_now();
3240e5413aa0SMatthias Ringwald                 }
3241e5413aa0SMatthias Ringwald #endif
3242760b20efSMatthias Ringwald 
3243760b20efSMatthias Ringwald #ifdef ENABLE_CLASSIC
3244760b20efSMatthias Ringwald                 // For SCO, we do the can_send_now_check here
3245760b20efSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
3246760b20efSMatthias Ringwald #endif
324756cf178bSmatthias.ringwald             }
32486772a24cSmatthias.ringwald             break;
32492e440c8aS[email protected]         }
325035454696SMatthias Ringwald 
325135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
32529afaa4d4SMatthias Ringwald         case HCI_EVENT_FLUSH_OCCURRED:
32539afaa4d4SMatthias Ringwald             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
32549afaa4d4SMatthias Ringwald             handle = hci_event_flush_occurred_get_handle(packet);
32559afaa4d4SMatthias Ringwald             conn = hci_connection_for_handle(handle);
32569afaa4d4SMatthias Ringwald             if (conn) {
32579afaa4d4SMatthias Ringwald                 log_info("Flush occurred, disconnect 0x%04x", handle);
32589afaa4d4SMatthias Ringwald                 conn->state = SEND_DISCONNECT;
32599afaa4d4SMatthias Ringwald             }
32609afaa4d4SMatthias Ringwald             break;
32619afaa4d4SMatthias Ringwald 
3262f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
3263f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3264f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3265f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3266f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
3267f5875de5SMatthias Ringwald             }
3268f5875de5SMatthias Ringwald             break;
3269b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3270b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3271b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3272b7f1ee76SMatthias Ringwald             }
3273b7f1ee76SMatthias Ringwald             break;
32741f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
3275724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
32765e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
327772cf8859SMatthias Ringwald 
327872cf8859SMatthias Ringwald             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
327972cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
328072cf8859SMatthias Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
328172cf8859SMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
328272cf8859SMatthias Ringwald                 break;
328372cf8859SMatthias Ringwald             }
328472cf8859SMatthias Ringwald 
328507e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
32865e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3287d152b6c6SMatthias Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
328807e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
328907e010b6SMilanka Ringwald                     break;
329007e010b6SMilanka Ringwald                 }
329107e010b6SMilanka Ringwald             }
329207e010b6SMilanka Ringwald 
329337eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
32945e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
32955e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
32962e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
32971f7b95a1Smatthias.ringwald             if (!conn) {
32985293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
32991f7b95a1Smatthias.ringwald             }
3300ce4c8fabSmatthias.ringwald             if (!conn) {
3301ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
33024536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3303058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
3304f23819bcSMatthias Ringwald                 hci_run();
3305f23819bcSMatthias Ringwald                 // avoid event to higher layer
3306f23819bcSMatthias Ringwald                 return;
3307ce4c8fabSmatthias.ringwald             }
33085cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
330932ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
3310f3a16b9aSMatthias Ringwald             // store info about eSCO
33115e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
331276ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
3313f3a16b9aSMatthias Ringwald             }
331432ab9390Smatthias.ringwald             hci_run();
33151f7b95a1Smatthias.ringwald             break;
33161f7b95a1Smatthias.ringwald 
33176772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
3318fe1ed1b8Smatthias.ringwald             // Connection management
3319724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
33209da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3321f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
33222e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3323fe1ed1b8Smatthias.ringwald             if (conn) {
3324b448a0e7Smatthias.ringwald                 if (!packet[2]){
3325c8e4258aSmatthias.ringwald                     conn->state = OPEN;
3326f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
33276909f064SMatthias Ringwald 
332822df2fe2SMatthias Ringwald                     // trigger write supervision timeout if we're master
3329d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
333022df2fe2SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
33316909f064SMatthias Ringwald                     }
33326909f064SMatthias Ringwald 
333322df2fe2SMatthias Ringwald                     // trigger write automatic flush timeout
33349afaa4d4SMatthias Ringwald                     if (hci_stack->automatic_flush_timeout != 0){
33359afaa4d4SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
33369afaa4d4SMatthias Ringwald                     }
33379afaa4d4SMatthias Ringwald 
3338c785ef68Smatthias.ringwald                     // restart timer
3339528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3340528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
3341c785ef68Smatthias.ringwald 
334218c4a0a3SMatthias Ringwald                     // trigger remote features for dedicated bonding
334318c4a0a3SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
334418c4a0a3SMatthias Ringwald                         hci_trigger_remote_features_for_connection(conn);
334518c4a0a3SMatthias Ringwald                     }
334618c4a0a3SMatthias Ringwald 
33479da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
334843bfb1bdSmatthias.ringwald 
334943bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
3350b448a0e7Smatthias.ringwald                 } else {
33510bbba85bSMatthias Ringwald                     // connection failed
33520bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
3353fe1ed1b8Smatthias.ringwald                 }
3354fe1ed1b8Smatthias.ringwald             }
33556772a24cSmatthias.ringwald             break;
3356fe1ed1b8Smatthias.ringwald 
335744d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3358724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
33591f34df2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
33601f34df2cSMatthias Ringwald             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
33611a06f663S[email protected]             if (packet[2]){
336244d0e3d5S[email protected]                 // connection failed
33631f34df2cSMatthias Ringwald                 if (conn){
33641f34df2cSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
33651f34df2cSMatthias Ringwald                 }
336644d0e3d5S[email protected]                 break;
336744d0e3d5S[email protected]             }
3368e35edcc1S[email protected]             if (!conn) {
3369e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
3370e35edcc1S[email protected]             }
3371e35edcc1S[email protected]             if (!conn) {
3372e35edcc1S[email protected]                 break;
3373e35edcc1S[email protected]             }
33741a06f663S[email protected]             conn->state = OPEN;
3375f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
3376ee752bb8SMatthias Ringwald 
3377ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3378ee752bb8SMatthias Ringwald             // update SCO
3379ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3380ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3381ee752bb8SMatthias Ringwald             }
3382f234b250SMatthias Ringwald             // trigger can send now
3383f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
33841972f31fSMatthias Ringwald                 hci_stack->sco_can_send_now = true;
3385f234b250SMatthias Ringwald             }
3386ee752bb8SMatthias Ringwald #endif
3387cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3388cb70c5abSMatthias Ringwald             // configure sco transport
3389cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
3390cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3391cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3392cb70c5abSMatthias Ringwald             }
3393cb70c5abSMatthias Ringwald #endif
339444d0e3d5S[email protected]             break;
339544d0e3d5S[email protected] 
3396afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3397f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
3398afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
3399afd4e962S[email protected]             if (!conn) break;
3400afd4e962S[email protected]             if (!packet[2]){
34012f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
34022f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
34032f5c44baSMatthias Ringwald 
34045ccef624SMatthias Ringwald                 // read extended features if possible
34051ffa425cSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
34061ffa425cSMatthias Ringwald                 && ((conn->remote_supported_features[0] & 2) != 0)) {
34075ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
34085ccef624SMatthias Ringwald                     break;
34095ccef624SMatthias Ringwald                 }
34105ccef624SMatthias Ringwald             }
34115ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
34125ccef624SMatthias Ringwald             break;
34135ccef624SMatthias Ringwald 
34145ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
34155ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
34165ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
34175ccef624SMatthias Ringwald             if (!conn) break;
34185ccef624SMatthias Ringwald             // status = ok, page = 1
341950c51a77SMatthias Ringwald             if (!packet[2]) {
342050c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
342150c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
34225ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
342350c51a77SMatthias Ringwald                 bool done = false;
342450c51a77SMatthias Ringwald                 switch (page_number){
342550c51a77SMatthias Ringwald                     case 1:
34262f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
342750c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
342850c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
342950c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
343050c51a77SMatthias Ringwald                         } else {
343150c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
343250c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
343350c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
343450c51a77SMatthias Ringwald                             }
343550c51a77SMatthias Ringwald                             done = true;
343650c51a77SMatthias Ringwald                         }
343750c51a77SMatthias Ringwald                         break;
343850c51a77SMatthias Ringwald                     case 2:
343950c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
344050c51a77SMatthias Ringwald                         done = true;
344150c51a77SMatthias Ringwald                         break;
344250c51a77SMatthias Ringwald                     default:
344350c51a77SMatthias Ringwald                         break;
344450c51a77SMatthias Ringwald                 }
344550c51a77SMatthias Ringwald                 if (!done) break;
3446afd4e962S[email protected]             }
3447de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
3448afd4e962S[email protected]             break;
3449afd4e962S[email protected] 
34507fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
3451308eeaffSMatthias Ringwald #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
345263c0b2fdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
345363c0b2fdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
345463c0b2fdSMatthias Ringwald             if (!conn) break;
345563c0b2fdSMatthias Ringwald 
345663c0b2fdSMatthias Ringwald             // lookup link key in db if not cached
345763c0b2fdSMatthias Ringwald             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
345863c0b2fdSMatthias Ringwald                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
345963c0b2fdSMatthias Ringwald             }
346063c0b2fdSMatthias Ringwald 
346163c0b2fdSMatthias Ringwald             // response sent by hci_run()
346263c0b2fdSMatthias Ringwald             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
346363c0b2fdSMatthias Ringwald #endif
3464608f51bbSMatthias Ringwald             break;
34657fde4af9Smatthias.ringwald 
34669ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
34671714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
3468f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
34699ab95c90S[email protected]             if (!conn) break;
34701714cbbdSMatthias Ringwald 
34711714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
34721714cbbdSMatthias Ringwald 
34733817f9dfSMatthias Ringwald             // CVE-2020-26555: ignore NULL link key
34743817f9dfSMatthias Ringwald             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
34753817f9dfSMatthias Ringwald             if (btstack_is_null(&packet[8], 16)) break;
34763817f9dfSMatthias Ringwald 
34777bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
34789ab95c90S[email protected]             // Change Connection Encryption keeps link key type
34799ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
34809ab95c90S[email protected]                 conn->link_key_type = link_key_type;
34819ab95c90S[email protected]             }
34823817f9dfSMatthias Ringwald 
3483e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
3484e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
3485e9f98c4aSMatthias Ringwald 
3486bec5f683SMatthias Ringwald             // only store link key:
3487bec5f683SMatthias Ringwald             // - if bondable enabled
3488bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
34896edaed7fSMatthias Ringwald             // - if security level sufficient
34906edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
3491bec5f683SMatthias Ringwald             // - for SSP, also check if remote side requested bonding as well
3492bec5f683SMatthias Ringwald             if (conn->link_key_type != COMBINATION_KEY){
3493532454f9SMatthias Ringwald                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3494532454f9SMatthias Ringwald                 if (!remote_bonding){
3495bec5f683SMatthias Ringwald                     break;
3496bec5f683SMatthias Ringwald                 }
3497bec5f683SMatthias Ringwald             }
349855597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
34997fde4af9Smatthias.ringwald             break;
35009ab95c90S[email protected]         }
35017fde4af9Smatthias.ringwald 
35027fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
35031714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
35041714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
35051714cbbdSMatthias Ringwald             if (!conn) break;
35061714cbbdSMatthias Ringwald 
35071714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
3508a800d95eSMatthias Ringwald             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
35093a9fb326S[email protected]             if (!hci_stack->bondable ){
35108daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
35111714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3512f8fb5f6eS[email protected]                 hci_run();
3513f8fb5f6eS[email protected]                 return;
35144c57c146S[email protected]             }
3515a800d95eSMatthias Ringwald             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3516a800d95eSMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3517a800d95eSMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
351850dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
351950dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
352050dcc63cSMatthias Ringwald                 hci_run();
352150dcc63cSMatthias Ringwald                 return;
352250dcc63cSMatthias Ringwald             }
35237fde4af9Smatthias.ringwald             break;
35247fde4af9Smatthias.ringwald 
352550d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
352650d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
352750d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
352850d7398cSMatthias Ringwald             if (!conn) break;
35291714cbbdSMatthias Ringwald 
35308daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
35311714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
353250d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3533e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3534d22b82d6SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3535d22b82d6SMatthias Ringwald             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3536d22b82d6SMatthias Ringwald #endif
353750d7398cSMatthias Ringwald             break;
353850d7398cSMatthias Ringwald 
35391d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
35401714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
35411714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
35421714cbbdSMatthias Ringwald             if (!conn) break;
35431714cbbdSMatthias Ringwald 
3544c950c316SMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
35459671e615SMatthias Ringwald             hci_connection_timestamp(conn);
35461714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
3547dbe1a790S[email protected]             break;
3548dbe1a790S[email protected] 
35491849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
35501849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
35517ca4a7edSMatthias Ringwald             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
35527ca4a7edSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
35537ca4a7edSMatthias Ringwald             if (!conn) break;
35547ca4a7edSMatthias Ringwald 
35557ca4a7edSMatthias Ringwald             hci_connection_timestamp(conn);
35567ca4a7edSMatthias Ringwald 
35577ca4a7edSMatthias Ringwald             hci_pairing_started(conn, true);
35587ca4a7edSMatthias Ringwald 
35597ca4a7edSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
35601849becdSMatthias Ringwald             break;
35611849becdSMatthias Ringwald #endif
35621849becdSMatthias Ringwald 
3563dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
356417c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3565367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3566367aedc0SMatthias Ringwald             if (!conn) break;
3567367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3568367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
35698daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3570367aedc0SMatthias Ringwald                 };
3571367aedc0SMatthias Ringwald             } else {
3572367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3573367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3574367aedc0SMatthias Ringwald                 // don't forward event to app
3575367aedc0SMatthias Ringwald                 hci_run();
3576367aedc0SMatthias Ringwald                 return;
3577367aedc0SMatthias Ringwald             }
3578dbe1a790S[email protected]             break;
3579dbe1a790S[email protected] 
3580dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
3581367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3582367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
35838daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3584367aedc0SMatthias Ringwald             };
35851d6b20aeS[email protected]             break;
35861849becdSMatthias Ringwald 
35873dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
35883dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
35893dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
35903dce6128SMatthias Ringwald             if (!conn) break;
35913dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
35923dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
35933dce6128SMatthias Ringwald             break;
359435454696SMatthias Ringwald #endif
35951d6b20aeS[email protected] 
3596f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
3597a355334eSMatthias Ringwald         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3598254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
3599f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
3600f0944df2S[email protected]             if (!conn) break;
36014ea43905SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == 0u) {
3602254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3603254b78eeSMatthias Ringwald                 if (encryption_enabled){
3604573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
3605573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
36068daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3607573897a0SMatthias Ringwald                     }
3608573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
3609573897a0SMatthias Ringwald                     else {
3610fcaf38b9SMatthias Ringwald 
3611254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
361236c3546bSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3613254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3614edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3615254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
36169ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3617254b78eeSMatthias Ringwald                             break;
3618254b78eeSMatthias Ringwald                         }
3619254b78eeSMatthias Ringwald 
3620aa2fe986SMatthias Ringwald                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3621aa2fe986SMatthias Ringwald                         if (connected_uses_aes_ccm){
3622aa2fe986SMatthias Ringwald                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3623aa2fe986SMatthias Ringwald                         }
3624aa2fe986SMatthias Ringwald 
3625aa2fe986SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
3626aa2fe986SMatthias Ringwald                         // work around for issue with PTS dongle
3627aa2fe986SMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3628aa2fe986SMatthias Ringwald #endif
3629a355334eSMatthias Ringwald                         // validate encryption key size
3630a355334eSMatthias Ringwald                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3631a355334eSMatthias Ringwald                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3632a355334eSMatthias Ringwald                             // already got encryption key size
3633a355334eSMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3634a355334eSMatthias Ringwald                         } else {
36351ffa425cSMatthias Ringwald                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
36366e058d3fSMatthias Ringwald                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3637573897a0SMatthias Ringwald                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
36386e058d3fSMatthias Ringwald                             } else {
36396e058d3fSMatthias Ringwald                                 // if not, pretend everything is perfect
36409866fdc7SMatthias Ringwald                                 hci_handle_read_encryption_key_size_complete(conn, 16);
36416e058d3fSMatthias Ringwald                             }
3642573897a0SMatthias Ringwald                         }
3643a355334eSMatthias Ringwald                     }
3644573897a0SMatthias Ringwald #endif
3645f0944df2S[email protected]                 } else {
36468daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3647f0944df2S[email protected]                 }
36485999ee11SMatthias Ringwald             } else {
36495999ee11SMatthias Ringwald                 uint8_t status = hci_event_encryption_change_get_status(packet);
36505999ee11SMatthias Ringwald                 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
36515999ee11SMatthias Ringwald                     conn->bonding_flags &= ~BONDING_DEDICATED;
36525999ee11SMatthias Ringwald                     conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
36535999ee11SMatthias Ringwald                     conn->bonding_status = status;
36545999ee11SMatthias Ringwald                 }
3655ad83dc6aS[email protected]             }
3656573897a0SMatthias Ringwald 
3657f0944df2S[email protected]             break;
3658f0944df2S[email protected] 
365935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
36601eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
3661abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
36621eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
36631eb2563eS[email protected]             if (!conn) break;
3664ad83dc6aS[email protected] 
3665dbd5dcc3SMatthias Ringwald             // clear authentication active flag
3666dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
36671714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
3668dbd5dcc3SMatthias Ringwald 
3669abdad579SMatthias Ringwald             // authenticated only if auth status == 0
3670abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
3671abdad579SMatthias Ringwald                 // authenticated
36728daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3673abdad579SMatthias Ringwald 
3674131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
36758daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
36761eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3677ad83dc6aS[email protected]                     break;
3678ad83dc6aS[email protected]                 }
3679abdad579SMatthias Ringwald             }
3680abdad579SMatthias Ringwald 
3681abdad579SMatthias Ringwald             // emit updated security level
36821eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
36831eb2563eS[email protected]             break;
36841714cbbdSMatthias Ringwald 
36851714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
36861714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
36871714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
36881714cbbdSMatthias Ringwald             if (!conn) break;
36891714cbbdSMatthias Ringwald 
3690aa2fe986SMatthias Ringwald             // treat successfully paired connection as authenticated
3691aa2fe986SMatthias Ringwald             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
3692f3aafff1SMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3693aa2fe986SMatthias Ringwald             }
3694aa2fe986SMatthias Ringwald 
36951714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
36961714cbbdSMatthias Ringwald             break;
369735454696SMatthias Ringwald #endif
369834d2123cS[email protected] 
369986805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
3700ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
3701ccda6e14S[email protected]         // see end of function, too.
3702a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
3703a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
3704f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
370581d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
37064ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
3707c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
37084ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
370981d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
3710c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
3711c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
371281d2bdb2SMatthias Ringwald                     if (release_buffer){
371381d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
371481d2bdb2SMatthias Ringwald                     }
3715c6a37cfdSMatthias Ringwald                 }
3716c6a37cfdSMatthias Ringwald             }
371735454696SMatthias Ringwald 
37184ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3719098c2716SMatthias Ringwald             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
3720098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size > 0u) {
3721098c2716SMatthias Ringwald                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
3722098c2716SMatthias Ringwald                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
3723098c2716SMatthias Ringwald                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
3724098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_total_size = 0;
3725098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_pos = 0;
3726098c2716SMatthias Ringwald                     if (release_buffer){
3727098c2716SMatthias Ringwald                         hci_release_packet_buffer();
3728098c2716SMatthias Ringwald                     }
3729098c2716SMatthias Ringwald                 }
3730098c2716SMatthias Ringwald             }
3731098c2716SMatthias Ringwald 
37324ae8623eSMatthias Ringwald             // finalize iso stream if handle matches
373315a15be3SMatthias Ringwald             iso_stream = hci_iso_stream_for_con_handle(handle);
37344ae8623eSMatthias Ringwald             if (iso_stream != NULL){
37354ae8623eSMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
37364ae8623eSMatthias Ringwald                 break;
37374ae8623eSMatthias Ringwald             }
37384ae8623eSMatthias Ringwald #endif
37394ae8623eSMatthias Ringwald 
3740c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
3741c6a37cfdSMatthias Ringwald             if (!conn) break;
37421714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
37431714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
37441714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37451714cbbdSMatthias Ringwald #endif
3746046ec007SMatthias Ringwald 
3747046ec007SMatthias Ringwald             // emit dedicatd bonding event
3748046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
3749046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
3750046ec007SMatthias Ringwald             }
3751046ec007SMatthias Ringwald 
3752459d27b9SMatthias Ringwald             // mark connection for shutdown, stop timers, reset state
3753459d27b9SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
3754459d27b9SMatthias Ringwald             hci_connection_stop_timer(conn);
3755459d27b9SMatthias Ringwald             hci_connection_init(conn);
3756459d27b9SMatthias Ringwald 
375735454696SMatthias Ringwald #ifdef ENABLE_BLE
3758d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3759046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
37602b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
3761bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
37629a2e4658SMatthias Ringwald             }
376335454696SMatthias Ringwald #endif
3764d70217a2SMatthias Ringwald #endif
3765ccda6e14S[email protected]             break;
37666772a24cSmatthias.ringwald 
3767c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
3768313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
3769d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
3770c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
37717586ee35S[email protected]             } else {
37727586ee35S[email protected]                 // if no special requests, just reboot stack
37737586ee35S[email protected]                 hci_power_control_off();
37747586ee35S[email protected]                 hci_power_control_on();
3775c68bdf90Smatthias.ringwald             }
3776c68bdf90Smatthias.ringwald             break;
3777c68bdf90Smatthias.ringwald 
37780e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
37795cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
37805cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
3781c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
3782f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
3783c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3784c4c88f1bSJakob Krantz             if (!conn) break;
37855cf766e8SMatthias Ringwald             conn->role = packet[9];
37865cf766e8SMatthias Ringwald             break;
37870e6f3837SMatthias Ringwald #endif
37885cf766e8SMatthias Ringwald 
378963fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3790098c2716SMatthias Ringwald             // release packet buffer only for asynchronous transport and if there are not further fragments
37914fa24b5fS[email protected]             if (hci_transport_synchronous()) {
379263fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
37934fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
37944fa24b5fS[email protected]             }
379581d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
3796098c2716SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3797098c2716SMatthias Ringwald             hci_stack->iso_fragmentation_tx_active = 0;
3798098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size) break;
3799098c2716SMatthias Ringwald #endif
3800d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
3801d051460cS[email protected]             hci_release_packet_buffer();
3802701e3307SMatthias Ringwald 
38035ade6657SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
38045ade6657SMatthias Ringwald             hci_iso_notify_can_send_now();
38055ade6657SMatthias Ringwald #endif
380663fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
380763fa3374SMatthias Ringwald 
380835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
380963fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
3810701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
381135454696SMatthias Ringwald #endif
38126b4af23dS[email protected]             break;
38136b4af23dS[email protected] 
381435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
381563fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
381663fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
38171972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = true;
381863fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
381963fa3374SMatthias Ringwald             return;
38201cfb383eSMatthias Ringwald 
38211cfb383eSMatthias Ringwald         // explode inquriy results for easier consumption
38221cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
38231cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
38241cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
38259784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
38261cfb383eSMatthias Ringwald             break;
382735454696SMatthias Ringwald #endif
382863fa3374SMatthias Ringwald 
3829a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
38305909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
38315909f7f2Smatthias.ringwald             switch (packet[2]){
3832d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
383357c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
38346fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
383557c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
38367bdc6798S[email protected]                     break;
3837a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3838a0698cb4SMatthias Ringwald                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
3839a0698cb4SMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
3840a0698cb4SMatthias Ringwald                     le_handle_extended_advertisement_report(packet, size);
3841a0698cb4SMatthias Ringwald                     break;
3842a0698cb4SMatthias Ringwald #endif
3843d70217a2SMatthias Ringwald #endif
38445909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
38450ce3f217SMatthias Ringwald 					event_handle_le_connection_complete(packet);
38465909f7f2Smatthias.ringwald                     break;
38475909f7f2Smatthias.ringwald 
3848f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3849c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3850c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3851c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
3852c9db5c21SMilanka Ringwald                     if (!conn) break;
3853c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3854c9db5c21SMilanka Ringwald                     break;
385565a46ef3S[email protected] 
385673cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
385773cd8a2aSMatthias Ringwald                     // connection
385873cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
385973cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
386073cd8a2aSMatthias Ringwald                     if (conn) {
386173cd8a2aSMatthias Ringwald                         // read arguments
386273cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
386373cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
386473cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
386573cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
386673cd8a2aSMatthias Ringwald 
386773cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
386873cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
386973cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
387073cd8a2aSMatthias 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);
387173cd8a2aSMatthias Ringwald                         if (update_parameter){
387273cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
387373cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
387473cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
387573cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
387673cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
387773cd8a2aSMatthias Ringwald                         } else {
3878c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
387973cd8a2aSMatthias Ringwald                         }
388073cd8a2aSMatthias Ringwald                     }
388173cd8a2aSMatthias Ringwald                     break;
38820f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
38830f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
38840f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
38850f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
38860f3b27c5SMatthias Ringwald                     if (conn) {
38870f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
38880f3b27c5SMatthias Ringwald                     }
38890f3b27c5SMatthias Ringwald                     break;
38900f3b27c5SMatthias Ringwald #endif
38914ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
38924ae8623eSMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
38934ae8623eSMatthias Ringwald                     handle = hci_subevent_le_cis_established_get_connection_handle(packet);
389415a15be3SMatthias Ringwald                     iso_stream = hci_iso_stream_for_con_handle(handle);
38954ae8623eSMatthias Ringwald                     if (iso_stream){
38964ae8623eSMatthias Ringwald                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
38974ae8623eSMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
38984ae8623eSMatthias Ringwald                             iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
38994ae8623eSMatthias Ringwald                         } else {
39004ae8623eSMatthias Ringwald                             hci_iso_stream_finalize(iso_stream);
39014ae8623eSMatthias Ringwald                         }
39024ae8623eSMatthias Ringwald                     }
39037aa35f6aSMatthias Ringwald                     break;
39047aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
39057aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(packet[4]);
39067aa35f6aSMatthias Ringwald                     if (big != NULL){
39077aa35f6aSMatthias Ringwald                         uint8_t status = packet[3];
39087aa35f6aSMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
39097aa35f6aSMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
39107aa35f6aSMatthias Ringwald                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
39117aa35f6aSMatthias Ringwald                             uint8_t i;
39127aa35f6aSMatthias Ringwald                             for (i=0;i<num_bis;i++){
3913fb16346aSMatthias Ringwald                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
3914fb16346aSMatthias Ringwald                                 big->bis_con_handles[i] = bis_handle;
3915fb16346aSMatthias Ringwald                                 // assign bis handle
3916fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_t it;
3917fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3918fb16346aSMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
3919fb16346aSMatthias Ringwald                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3920fb16346aSMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
3921fb16346aSMatthias Ringwald                                         (iso_stream->big_handle == big->big_handle)){
3922fb16346aSMatthias Ringwald                                         iso_stream->con_handle = bis_handle;
3923fb16346aSMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
3924cd1139aaSMatthias Ringwald                                         break;
3925fb16346aSMatthias Ringwald                                     }
3926fb16346aSMatthias Ringwald                                 }
39277aa35f6aSMatthias Ringwald                             }
39282a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
39297aa35f6aSMatthias Ringwald                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
39307aa35f6aSMatthias Ringwald                                 big->state_vars.next_bis = 0;
39312a6c0f82SMatthias Ringwald                             }
39327aa35f6aSMatthias Ringwald                         } else {
39332a6c0f82SMatthias Ringwald                             // create BIG failed or has been stopped by us
3934fb16346aSMatthias Ringwald                             hci_iso_stream_requested_finalize(big->big_handle);
39357aa35f6aSMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
39362a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
39377aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, status);
39382a6c0f82SMatthias Ringwald                             } else {
39392a6c0f82SMatthias Ringwald                                 hci_emit_big_terminated(big);
39402a6c0f82SMatthias Ringwald                             }
39417aa35f6aSMatthias Ringwald                         }
39427aa35f6aSMatthias Ringwald                     }
39437aa35f6aSMatthias Ringwald                     break;
39447aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
39457aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
39467aa35f6aSMatthias Ringwald                     if (big != NULL){
3947fb16346aSMatthias Ringwald                         // finalize associated ISO streams
3948fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_t it;
3949fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3950fb16346aSMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)){
3951fb16346aSMatthias Ringwald                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3952fb16346aSMatthias Ringwald                             if (iso_stream->big_handle == big->big_handle){
3953346f8c2cSMatthias Ringwald                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->big_handle, iso_stream->con_handle);
3954fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_remove(&it);
3955fb16346aSMatthias Ringwald                                 btstack_memory_hci_iso_stream_free(iso_stream);
3956fb16346aSMatthias Ringwald                             }
3957fb16346aSMatthias Ringwald                         }
39587aa35f6aSMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
39597aa35f6aSMatthias Ringwald                         switch (big->state){
39607aa35f6aSMatthias Ringwald                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
39617aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, big->state_vars.status);
39627aa35f6aSMatthias Ringwald                                 break;
39637aa35f6aSMatthias Ringwald                             default:
39647aa35f6aSMatthias Ringwald                                 hci_emit_big_terminated(big);
39657aa35f6aSMatthias Ringwald                                 break;
39667aa35f6aSMatthias Ringwald                         }
39677aa35f6aSMatthias Ringwald                     }
39687aa35f6aSMatthias Ringwald                     break;
39692a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
39702a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
39712a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
39722a6c0f82SMatthias Ringwald                         uint8_t status = packet[3];
39732a6c0f82SMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
39742a6c0f82SMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
39752a6c0f82SMatthias Ringwald                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
39762a6c0f82SMatthias Ringwald                             uint8_t i;
39772a6c0f82SMatthias Ringwald                             for (i=0;i<num_bis;i++){
39782a6c0f82SMatthias Ringwald                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
39792a6c0f82SMatthias Ringwald                             }
39802a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
39812a6c0f82SMatthias Ringwald                                 // trigger iso path setup
39822a6c0f82SMatthias Ringwald                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
39832a6c0f82SMatthias Ringwald                                 big_sync->state_vars.next_bis = 0;
39842a6c0f82SMatthias Ringwald                             }
39852a6c0f82SMatthias Ringwald                         } else {
39862a6c0f82SMatthias Ringwald                             // create BIG Sync failed or has been stopped by us
39872a6c0f82SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
39882a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
39892a6c0f82SMatthias Ringwald                                 hci_emit_big_sync_created(big_sync, status);
39902a6c0f82SMatthias Ringwald                             } else {
39912a6c0f82SMatthias Ringwald                                 hci_emit_big_sync_stopped(big_sync);
39922a6c0f82SMatthias Ringwald                             }
39932a6c0f82SMatthias Ringwald                         }
39942a6c0f82SMatthias Ringwald                     }
39952a6c0f82SMatthias Ringwald                     break;
39962a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
39972a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
39982a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
39992a6c0f82SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
40002a6c0f82SMatthias Ringwald                         hci_emit_big_sync_stopped(big_sync);
40012a6c0f82SMatthias Ringwald                     }
40022a6c0f82SMatthias Ringwald                     break;
40034ae8623eSMatthias Ringwald #endif
40045909f7f2Smatthias.ringwald                 default:
40055909f7f2Smatthias.ringwald                     break;
40065909f7f2Smatthias.ringwald             }
40075909f7f2Smatthias.ringwald             break;
40085909f7f2Smatthias.ringwald #endif
40090b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
40100b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
40110b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
40120b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
40130b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
40140b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
40150b36101dSMatthias Ringwald                     break;
40160b36101dSMatthias Ringwald                 default:
40170b36101dSMatthias Ringwald                     break;
40180b36101dSMatthias Ringwald             }
40190b36101dSMatthias Ringwald             break;
40206772a24cSmatthias.ringwald         default:
40216772a24cSmatthias.ringwald             break;
4022fe1ed1b8Smatthias.ringwald     }
4023fe1ed1b8Smatthias.ringwald 
402467c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
402589db417bSmatthias.ringwald 
402686805605S[email protected]     // notify upper stack
4027d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
402894ab26f8Smatthias.ringwald 
402986805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4030797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4031f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
403205ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4033046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
4034797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
403505ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
4036b0136355SMatthias Ringwald 		}
40378ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
40388ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
40398ad9cf99SMatthias Ringwald #endif
404086805605S[email protected]     }
404186805605S[email protected] 
404294ab26f8Smatthias.ringwald 	// execute main loop
404394ab26f8Smatthias.ringwald 	hci_run();
404416833f0aSmatthias.ringwald }
404516833f0aSmatthias.ringwald 
404635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
40476f28d2eeSMatthias Ringwald 
40486be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
40496f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
40506f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn);
40516f28d2eeSMatthias Ringwald 
40526f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
405359c33575SMatthias Ringwald     log_debug("SCO TX Timeout");
40545a6b2dbdSMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
40556f28d2eeSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
40566f28d2eeSMatthias Ringwald     if (!conn) return;
40576f28d2eeSMatthias Ringwald 
4058afaddd67SMatthias Ringwald     // trigger send
4059afaddd67SMatthias Ringwald     conn->sco_tx_ready = 1;
4060e4157653SMatthias Ringwald     // extra packet if CVSD but SCO buffer is too short
4061a1df452eSMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
4062e4157653SMatthias Ringwald         conn->sco_tx_ready++;
4063e4157653SMatthias Ringwald     }
4064afaddd67SMatthias Ringwald     hci_notify_if_sco_can_send_now();
40656f28d2eeSMatthias Ringwald }
40666f28d2eeSMatthias Ringwald 
406759c33575SMatthias Ringwald 
406859c33575SMatthias Ringwald #define SCO_TX_AFTER_RX_MS (6)
406959c33575SMatthias Ringwald 
40706f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn){
407159c33575SMatthias Ringwald 
40726f28d2eeSMatthias Ringwald     uint32_t now = btstack_run_loop_get_time_ms();
407359c33575SMatthias Ringwald     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
407459c33575SMatthias Ringwald     int time_delta_ms = sco_tx_ms - now;
407559c33575SMatthias Ringwald 
407659c33575SMatthias Ringwald     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
407759c33575SMatthias Ringwald 
407859c33575SMatthias Ringwald     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
4079ddbec4ceSMatthias Ringwald     btstack_run_loop_remove_timer(timer);
408059c33575SMatthias Ringwald     btstack_run_loop_set_timer(timer, time_delta_ms);
408159c33575SMatthias Ringwald     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
408259c33575SMatthias Ringwald     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
408359c33575SMatthias Ringwald     btstack_run_loop_add_timer(timer);
40846f28d2eeSMatthias Ringwald }
40856be3cf7fSMatthias Ringwald #endif
40866f28d2eeSMatthias Ringwald 
4087c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
40880b3f95dfSMatthias Ringwald     // lookup connection struct
40892b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
40902b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
40910b3f95dfSMatthias Ringwald     if (!conn) return;
40920b3f95dfSMatthias Ringwald 
40936be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
4094760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4095760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4096a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4097760b20efSMatthias Ringwald             packet[2] = 0x3c;
4098760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
4099760b20efSMatthias Ringwald             size = 63;
41000b3f95dfSMatthias Ringwald         }
41010b3f95dfSMatthias Ringwald     }
4102760b20efSMatthias Ringwald 
4103f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
4104f234b250SMatthias Ringwald         // Nothing to do
4105f234b250SMatthias Ringwald     } else {
410649205f5dSMatthias 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);
4107760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
41086f28d2eeSMatthias Ringwald             uint32_t now = btstack_run_loop_get_time_ms();
410959c33575SMatthias Ringwald 
411059c33575SMatthias Ringwald             if (!conn->sco_rx_valid){
411159c33575SMatthias Ringwald                 // ignore first 10 packets
41126f28d2eeSMatthias Ringwald                 conn->sco_rx_count++;
411359c33575SMatthias Ringwald                 // log_debug("sco rx count %u", conn->sco_rx_count);
411459c33575SMatthias Ringwald                 if (conn->sco_rx_count == 10) {
411559c33575SMatthias Ringwald                     // use first timestamp as is and pretent it just started
41166f28d2eeSMatthias Ringwald                     conn->sco_rx_ms = now;
41176f28d2eeSMatthias Ringwald                     conn->sco_rx_valid = 1;
411859c33575SMatthias Ringwald                     conn->sco_rx_count = 0;
411959c33575SMatthias Ringwald                     sco_schedule_tx(conn);
412059c33575SMatthias Ringwald                 }
412159c33575SMatthias Ringwald             } else {
412259c33575SMatthias Ringwald                 // track expected arrival timme
412359c33575SMatthias Ringwald                 conn->sco_rx_count++;
412459c33575SMatthias Ringwald                 conn->sco_rx_ms += 7;
412559c33575SMatthias Ringwald                 int delta = (int32_t) (now - conn->sco_rx_ms);
412659c33575SMatthias Ringwald                 if (delta > 0){
412759c33575SMatthias Ringwald                     conn->sco_rx_ms++;
412859c33575SMatthias Ringwald                 }
412959c33575SMatthias Ringwald                 // log_debug("sco rx %u", conn->sco_rx_ms);
41306f28d2eeSMatthias Ringwald                 sco_schedule_tx(conn);
41316f28d2eeSMatthias Ringwald             }
4132760b20efSMatthias Ringwald         }
4133f234b250SMatthias Ringwald     }
41346be3cf7fSMatthias Ringwald #endif
41356be3cf7fSMatthias Ringwald 
41360b3f95dfSMatthias Ringwald     // deliver to app
41370b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
41380b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
41390b3f95dfSMatthias Ringwald     }
41400b3f95dfSMatthias Ringwald 
4141ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4142ed325439SMatthias Ringwald     // We can send one packet for each received packet
4143ed325439SMatthias Ringwald     conn->sco_tx_ready++;
4144ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
4145ed325439SMatthias Ringwald #endif
4146ed325439SMatthias Ringwald 
41470b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
41482b838201SMatthias Ringwald     conn->num_packets_completed++;
41492b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
41502b838201SMatthias Ringwald     hci_run();
41512b838201SMatthias Ringwald #endif
4152c91d150bS[email protected] }
415335454696SMatthias Ringwald #endif
4154c91d150bS[email protected] 
41550a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
41565bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
415710e830c9Smatthias.ringwald     switch (packet_type) {
415810e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
415910e830c9Smatthias.ringwald             event_handler(packet, size);
416010e830c9Smatthias.ringwald             break;
416110e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
416210e830c9Smatthias.ringwald             acl_handler(packet, size);
416310e830c9Smatthias.ringwald             break;
416435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4165c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
4166c91d150bS[email protected]             sco_handler(packet, size);
4167202c8a4cSMatthias Ringwald             break;
416835454696SMatthias Ringwald #endif
41690a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
41705027c498SMatthias Ringwald         case HCI_ISO_DATA_PACKET:
4171d39e4f95SMatthias Ringwald             hci_iso_packet_handler(packet, size);
41725027c498SMatthias Ringwald             break;
41735027c498SMatthias Ringwald #endif
417410e830c9Smatthias.ringwald         default:
417510e830c9Smatthias.ringwald             break;
417610e830c9Smatthias.ringwald     }
417710e830c9Smatthias.ringwald }
417810e830c9Smatthias.ringwald 
4179d6b06661SMatthias Ringwald /**
4180d6b06661SMatthias Ringwald  * @brief Add event packet handler.
4181d6b06661SMatthias Ringwald  */
4182d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4183d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4184d6b06661SMatthias Ringwald }
4185d6b06661SMatthias Ringwald 
418667f708e0SMatthias Ringwald /**
418767f708e0SMatthias Ringwald  * @brief Remove event packet handler.
418867f708e0SMatthias Ringwald  */
418967f708e0SMatthias Ringwald void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
419067f708e0SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
419167f708e0SMatthias Ringwald }
4192d6b06661SMatthias Ringwald 
4193fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
41943d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4195fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
419616833f0aSmatthias.ringwald }
419716833f0aSmatthias.ringwald 
419835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
41998abbe8b5SMatthias Ringwald /**
42008abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
42018abbe8b5SMatthias Ringwald  */
42023d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
42038abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
42048abbe8b5SMatthias Ringwald }
420535454696SMatthias Ringwald #endif
42068abbe8b5SMatthias Ringwald 
42070a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
42085027c498SMatthias Ringwald void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
42095027c498SMatthias Ringwald     hci_stack->iso_packet_handler = handler;
42105027c498SMatthias Ringwald }
42115027c498SMatthias Ringwald #endif
42125027c498SMatthias Ringwald 
421371de195eSMatthias Ringwald static void hci_state_reset(void){
4214595bdbfbS[email protected]     // no connections yet
4215595bdbfbS[email protected]     hci_stack->connections = NULL;
421674308b23Smatthias.ringwald 
421774308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
421874308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
421974308b23Smatthias.ringwald     // hci_stack->connectable = 0;
422074308b23Smatthias.ringwald     // hci_stack->bondable = 1;
4221b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
4222595bdbfbS[email protected] 
422344935e40S[email protected]     // buffer is free
422402c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
422544935e40S[email protected] 
4226595bdbfbS[email protected]     // no pending cmds
4227595bdbfbS[email protected]     hci_stack->decline_reason = 0;
4228595bdbfbS[email protected] 
4229c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
4230c214d65bSMatthias Ringwald 
4231bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
4232496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
423332a12730SMatthias Ringwald     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
423432a12730SMatthias Ringwald 
4235baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic =
423659d59ecfSMatthias Ringwald             GAP_TASK_SET_DEFAULT_LINK_POLICY |
423759d59ecfSMatthias Ringwald             GAP_TASK_SET_CLASS_OF_DEVICE |
423859d59ecfSMatthias Ringwald             GAP_TASK_SET_LOCAL_NAME |
4239bc2dcc03SMatthias Ringwald             GAP_TASK_SET_EIR_DATA |
424032a12730SMatthias Ringwald             GAP_TASK_WRITE_SCAN_ENABLE |
424132a12730SMatthias Ringwald             GAP_TASK_WRITE_PAGE_TIMEOUT;
4242bea424a5SMatthias Ringwald #endif
4243bea424a5SMatthias Ringwald 
4244cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
42458d5f0979SMatthias Ringwald     hci_stack->classic_read_local_oob_data = false;
42461ae74bf3SMatthias Ringwald     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4247cf01e888SMatthias Ringwald #endif
4248cf01e888SMatthias Ringwald 
4249595bdbfbS[email protected]     // LE
4250b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
4251b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
4252b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
4253d70217a2SMatthias Ringwald #endif
4254d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4255a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
425673799937SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
4257b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4258d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4259e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
42604bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
42614bafedd5SMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
42624bafedd5SMatthias Ringwald #endif
4263d70217a2SMatthias Ringwald #endif
4264a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4265935aa76eSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
42666bf435a6SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4267a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4268a61834b6SMatthias Ringwald     }
4269a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
4270a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4271a61834b6SMatthias Ringwald     }
4272a61834b6SMatthias Ringwald #endif
4273595bdbfbS[email protected] }
4274595bdbfbS[email protected] 
427535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
42762d5e09d6SMatthias Ringwald /**
42772d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
42782d5e09d6SMatthias Ringwald  */
42792d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
42802d5e09d6SMatthias Ringwald     // store and open remote device db
42812d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
42822d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
42832d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
42842d5e09d6SMatthias Ringwald     }
42852d5e09d6SMatthias Ringwald }
428635454696SMatthias Ringwald #endif
42872d5e09d6SMatthias Ringwald 
42882d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
4289475c8125Smatthias.ringwald 
42903a9fb326S[email protected] #ifdef HAVE_MALLOC
42913a9fb326S[email protected]     if (!hci_stack) {
42923a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
42933a9fb326S[email protected]     }
42943a9fb326S[email protected] #else
42953a9fb326S[email protected]     hci_stack = &hci_stack_static;
42963a9fb326S[email protected] #endif
429766fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
42983a9fb326S[email protected] 
4299475c8125Smatthias.ringwald     // reference to use transport layer implementation
43003a9fb326S[email protected]     hci_stack->hci_transport = transport;
4301475c8125Smatthias.ringwald 
430211e23e5fSmatthias.ringwald     // reference to used config
43033a9fb326S[email protected]     hci_stack->config = config;
430411e23e5fSmatthias.ringwald 
430526a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
430626a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
430726a9b6daSMatthias Ringwald 
43088fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
43093a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
43108fcba05dSmatthias.ringwald 
431116833f0aSmatthias.ringwald     // register packet handlers with transport
431210e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
4313f5454fc6Smatthias.ringwald 
43143a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
4315e2386ba1S[email protected] 
4316e2386ba1S[email protected]     // class of device
43173a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
4318a45d6b9fS[email protected] 
4319f20168b8Smatthias.ringwald     // bondable by default
4320f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
4321f20168b8Smatthias.ringwald 
4322e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
432363168530SMatthias Ringwald     // classic name
432463168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
4325c4c88f1bSJakob Krantz 
4326c4c88f1bSJakob Krantz     // Master slave policy
4327c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
4328170fafaeSMatthias Ringwald 
4329b4eb4420SMatthias Ringwald     // Allow Role Switch
4330b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
4331b4eb4420SMatthias Ringwald 
433278315a58SMatthias Ringwald     // Default / minimum security level = 2
433378315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
433478315a58SMatthias Ringwald 
43355dbec6b3SMatthias Ringwald     // Default Security Mode 4
43365dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
43375dbec6b3SMatthias Ringwald 
4338cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4339cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
4340d821984bSMatthias Ringwald 
4341d821984bSMatthias Ringwald     // Link Supervision Timeout
4342d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4343d821984bSMatthias Ringwald 
4344e9f343c8SMatthias Ringwald #endif
434563168530SMatthias Ringwald 
434663048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
43473a9fb326S[email protected]     hci_stack->ssp_enable = 1;
43483a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
43493a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
43503a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
435169a97523S[email protected] 
43525d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
43535d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
43545d23aae8SMatthias Ringwald 
4355fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
4356fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
4357d950d659SMatthias Ringwald 
4358831711daSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4359831711daSMatthias Ringwald     // connection parameter to use for outgoing connections
4360cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
4361cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
4362831711daSMatthias Ringwald     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
4363831711daSMatthias Ringwald     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
4364831711daSMatthias Ringwald     hci_stack->le_connection_latency      = 4;         // 4
4365831711daSMatthias Ringwald     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
4366831711daSMatthias Ringwald     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
4367831711daSMatthias Ringwald     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
43687261e5d8SMatthias Ringwald 
43697261e5d8SMatthias Ringwald     // default LE Scanning
43708b69e4c7SMatthias Ringwald     hci_stack->le_scan_type     =   0x1; // active
43718b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
43728b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
4373831711daSMatthias Ringwald #endif
4374831711daSMatthias Ringwald 
43752b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43762b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
43772b6ab3e6SMatthias Ringwald #endif
43782b6ab3e6SMatthias Ringwald 
4379831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
4380831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4381831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4382831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4383831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4384831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4385831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4386831711daSMatthias Ringwald 
438701d4f05fSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
438801d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = 1;
438901d4f05fSMatthias Ringwald #endif
439001d4f05fSMatthias Ringwald 
4391595bdbfbS[email protected]     hci_state_reset();
4392475c8125Smatthias.ringwald }
4393475c8125Smatthias.ringwald 
43944688f216SMatthias Ringwald void hci_deinit(void){
4395b02cfc15SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
43964688f216SMatthias Ringwald #ifdef HAVE_MALLOC
43974688f216SMatthias Ringwald     if (hci_stack) {
43984688f216SMatthias Ringwald         free(hci_stack);
43994688f216SMatthias Ringwald     }
44004688f216SMatthias Ringwald #endif
44014688f216SMatthias Ringwald     hci_stack = NULL;
4402b5bbcbf4SMatthias Ringwald 
4403b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
44044688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
4405b5bbcbf4SMatthias Ringwald #endif
44064688f216SMatthias Ringwald }
44074688f216SMatthias Ringwald 
44083fb36a29SMatthias Ringwald /**
44093fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
44103fb36a29SMatthias Ringwald  */
44113fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
44123fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
44133fb36a29SMatthias Ringwald 
44143fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
44153fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
44163fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
44173fb36a29SMatthias Ringwald     }
44183fb36a29SMatthias Ringwald }
44193fb36a29SMatthias Ringwald 
4420fb55bd0aSMatthias Ringwald /**
4421d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4422fb55bd0aSMatthias Ringwald  */
4423fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
4424fb55bd0aSMatthias Ringwald     // references to used control implementation
4425fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
4426d0b87befSMatthias Ringwald     // init with transport config
4427d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
4428fb55bd0aSMatthias Ringwald }
4429fb55bd0aSMatthias Ringwald 
44301f9eb2ccSMatthias Ringwald static void hci_discard_connections(void){
4431346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_t it;
4432346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4433346f8c2cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
44341f9eb2ccSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4435346f8c2cSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
44361f9eb2ccSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
44371f9eb2ccSMatthias Ringwald         hci_shutdown_connection(connection);
44381f9eb2ccSMatthias Ringwald     }
4439346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4440346f8c2cSMatthias Ringwald     while (hci_stack->iso_streams != NULL){
4441346f8c2cSMatthias Ringwald         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4442346f8c2cSMatthias Ringwald     }
4443346f8c2cSMatthias Ringwald #endif
44441f9eb2ccSMatthias Ringwald }
44451f9eb2ccSMatthias Ringwald 
444671de195eSMatthias Ringwald void hci_close(void){
4447e6d6524dSMatthias Ringwald 
4448e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
4449404843c1Smatthias.ringwald     // close remote device db
4450a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
4451a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
4452404843c1Smatthias.ringwald     }
4453e6d6524dSMatthias Ringwald #endif
44547224be7eSMatthias Ringwald 
44551f9eb2ccSMatthias Ringwald     hci_discard_connections();
44567224be7eSMatthias Ringwald 
4457f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
44583a9fb326S[email protected] 
44593a9fb326S[email protected] #ifdef HAVE_MALLOC
44603a9fb326S[email protected]     free(hci_stack);
44613a9fb326S[email protected] #endif
44623a9fb326S[email protected]     hci_stack = NULL;
4463404843c1Smatthias.ringwald }
4464404843c1Smatthias.ringwald 
4465cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4466cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4467cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
4468cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
4469cb70c5abSMatthias Ringwald }
4470cb70c5abSMatthias Ringwald #endif
4471cb70c5abSMatthias Ringwald 
447235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4473170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4474170fafaeSMatthias Ringwald     // validate ranage and set
4475170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
4476170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
4477170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4478170fafaeSMatthias Ringwald }
447978315a58SMatthias Ringwald 
4480137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4481137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
44825dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
4483137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
4484137715ebSMatthias Ringwald     } else {
4485137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4486137715ebSMatthias Ringwald     }
44875dbec6b3SMatthias Ringwald }
44885dbec6b3SMatthias Ringwald 
44895dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
44905dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
44915dbec6b3SMatthias Ringwald }
44925dbec6b3SMatthias Ringwald 
449378315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
449478315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
449578315a58SMatthias Ringwald }
449678315a58SMatthias Ringwald 
449778315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
4498d7387af3SMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
4499d7387af3SMatthias Ringwald         return LEVEL_4;
4500d7387af3SMatthias Ringwald     }
450178315a58SMatthias Ringwald     return hci_stack->gap_security_level;
450278315a58SMatthias Ringwald }
450330cdf3c6SMatthias Ringwald 
45048ad4dfffSMatthias Ringwald void gap_set_minimal_service_security_level(gap_security_level_t security_level){
45058ad4dfffSMatthias Ringwald     hci_stack->gap_minimal_service_security_level = security_level;
45068ad4dfffSMatthias Ringwald }
45078ad4dfffSMatthias Ringwald 
450830cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
450930cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
451030cdf3c6SMatthias Ringwald }
451130cdf3c6SMatthias Ringwald 
451230cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
451330cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
451430cdf3c6SMatthias Ringwald }
4515170fafaeSMatthias Ringwald #endif
4516170fafaeSMatthias Ringwald 
4517170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
451860b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
45199e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
4520baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
452159d59ecfSMatthias Ringwald     hci_run();
45229e61646fS[email protected] }
452376f27cffSMatthias Ringwald 
4524c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4525c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
4526baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
452759d59ecfSMatthias Ringwald     hci_run();
4528c33e56d3SMatthias Ringwald }
4529c33e56d3SMatthias Ringwald 
4530b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
4531b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4532b4eb4420SMatthias Ringwald }
4533b4eb4420SMatthias Ringwald 
4534b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
4535b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
4536b4eb4420SMatthias Ringwald }
4537b4eb4420SMatthias Ringwald 
45380c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
45390c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
45400c3eb48dSMatthias Ringwald }
45410c3eb48dSMatthias Ringwald 
45429afaa4d4SMatthias Ringwald void gap_enable_link_watchdog(uint16_t timeout_ms){
45439afaa4d4SMatthias Ringwald     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
45449afaa4d4SMatthias Ringwald }
45459afaa4d4SMatthias Ringwald 
45469afaa4d4SMatthias Ringwald uint16_t hci_automatic_flush_timeout(void){
45479afaa4d4SMatthias Ringwald     return hci_stack->automatic_flush_timeout;
45489afaa4d4SMatthias Ringwald }
45499afaa4d4SMatthias Ringwald 
455076f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
455176f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
455276f27cffSMatthias Ringwald }
455335454696SMatthias Ringwald #endif
45549e61646fS[email protected] 
45556fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
4556f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4557f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
45586535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4559f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
4560f456b2d0S[email protected] }
456176f27cffSMatthias Ringwald #endif
4562f456b2d0S[email protected] 
45638d213e1aSmatthias.ringwald // State-Module-Driver overview
45648d213e1aSmatthias.ringwald // state                    module  low-level
45658d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
45668d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
45678d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
45688d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
4569d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
4570d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
4571c7e0c5f6Smatthias.ringwald 
457240d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
45737301ad89Smatthias.ringwald 
4574038bc64cSmatthias.ringwald     // power on
4575f9a30166Smatthias.ringwald     int err = 0;
45763a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
4577d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
4578f9a30166Smatthias.ringwald     }
4579038bc64cSmatthias.ringwald     if (err){
45809da54300S[email protected]         log_error( "POWER_ON failed");
4581038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
4582038bc64cSmatthias.ringwald         return err;
4583038bc64cSmatthias.ringwald     }
4584038bc64cSmatthias.ringwald 
458524b3c629SMatthias Ringwald     // int chipset driver
45863fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
45873fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
45883fb36a29SMatthias Ringwald     }
45893fb36a29SMatthias Ringwald 
459024b3c629SMatthias Ringwald     // init transport
459124b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
459224b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
459324b3c629SMatthias Ringwald     }
459424b3c629SMatthias Ringwald 
459524b3c629SMatthias Ringwald     // open transport
459624b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
4597038bc64cSmatthias.ringwald     if (err){
45989da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
45993a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
4600d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
4601f9a30166Smatthias.ringwald         }
4602038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
4603038bc64cSmatthias.ringwald         return err;
4604038bc64cSmatthias.ringwald     }
46058d213e1aSmatthias.ringwald     return 0;
46068d213e1aSmatthias.ringwald }
4607038bc64cSmatthias.ringwald 
460840d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
46098d213e1aSmatthias.ringwald 
46109da54300S[email protected]     log_info("hci_power_control_off");
46119418f9c9Smatthias.ringwald 
46128d213e1aSmatthias.ringwald     // close low-level device
461324b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
46148d213e1aSmatthias.ringwald 
46159da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
46169418f9c9Smatthias.ringwald 
46178d213e1aSmatthias.ringwald     // power off
46183a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
4619d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
46208d213e1aSmatthias.ringwald     }
46219418f9c9Smatthias.ringwald 
46229da54300S[email protected]     log_info("hci_power_control_off - control closed");
46239418f9c9Smatthias.ringwald 
46243a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
462572ea5239Smatthias.ringwald }
462672ea5239Smatthias.ringwald 
462740d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
462872ea5239Smatthias.ringwald 
46299da54300S[email protected]     log_info("hci_power_control_sleep");
46303144bce4Smatthias.ringwald 
4631b429b9b7Smatthias.ringwald #if 0
4632b429b9b7Smatthias.ringwald     // don't close serial port during sleep
4633b429b9b7Smatthias.ringwald 
463472ea5239Smatthias.ringwald     // close low-level device
46353a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
4636b429b9b7Smatthias.ringwald #endif
463772ea5239Smatthias.ringwald 
463872ea5239Smatthias.ringwald     // sleep mode
46393a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
4640d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
464172ea5239Smatthias.ringwald     }
4642b429b9b7Smatthias.ringwald 
46433a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
46448d213e1aSmatthias.ringwald }
46458d213e1aSmatthias.ringwald 
464640d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
4647b429b9b7Smatthias.ringwald 
46489da54300S[email protected]     log_info("hci_power_control_wake");
4649b429b9b7Smatthias.ringwald 
4650b429b9b7Smatthias.ringwald     // wake on
46513a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
4652d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
4653b429b9b7Smatthias.ringwald     }
4654b429b9b7Smatthias.ringwald 
4655b429b9b7Smatthias.ringwald #if 0
4656b429b9b7Smatthias.ringwald     // open low-level device
46573a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
4658b429b9b7Smatthias.ringwald     if (err){
46599da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
46603a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
4661d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
4662b429b9b7Smatthias.ringwald         }
4663b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
4664b429b9b7Smatthias.ringwald         return err;
4665b429b9b7Smatthias.ringwald     }
4666b429b9b7Smatthias.ringwald #endif
4667b429b9b7Smatthias.ringwald 
4668b429b9b7Smatthias.ringwald     return 0;
4669b429b9b7Smatthias.ringwald }
4670b429b9b7Smatthias.ringwald 
46710c88d5efSMatthias Ringwald static void hci_power_enter_initializing_state(void){
467244935e40S[email protected]     // set up state machine
467344935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
467402c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
467544935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
46765c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
467744935e40S[email protected] }
4678b429b9b7Smatthias.ringwald 
46790c88d5efSMatthias Ringwald static void hci_power_enter_halting_state(void){
46800c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
46810c88d5efSMatthias Ringwald     hci_whitelist_free();
4682a2c9d908SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4683a2c9d908SMatthias Ringwald     hci_periodic_advertiser_list_free();
4684a2c9d908SMatthias Ringwald #endif
46850c88d5efSMatthias Ringwald #endif
4686184dbe2fSMatthias Ringwald     // see hci_run
4687184dbe2fSMatthias Ringwald     hci_stack->state = HCI_STATE_HALTING;
46880c88d5efSMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
4689184dbe2fSMatthias Ringwald     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
4690184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
4691184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4692184dbe2fSMatthias Ringwald     btstack_run_loop_add_timer(&hci_stack->timeout);
4693184dbe2fSMatthias Ringwald }
4694184dbe2fSMatthias Ringwald 
469542bd3d77SMatthias Ringwald // returns error
469642bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
469742bd3d77SMatthias Ringwald     int err;
46988d213e1aSmatthias.ringwald     switch (power_mode){
46998d213e1aSmatthias.ringwald         case HCI_POWER_ON:
47008d213e1aSmatthias.ringwald             err = hci_power_control_on();
470142bd3d77SMatthias Ringwald             if (err != 0) {
4702f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
470397b61c7bS[email protected]                 return err;
470497b61c7bS[email protected]             }
47050c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
47068d213e1aSmatthias.ringwald             break;
47078d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
47088d213e1aSmatthias.ringwald             // do nothing
47098d213e1aSmatthias.ringwald             break;
47108d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4711b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
47128d213e1aSmatthias.ringwald             break;
47137bbeb3adSMilanka Ringwald         default:
47147bbeb3adSMilanka Ringwald             btstack_assert(false);
47157bbeb3adSMilanka Ringwald             break;
47168d213e1aSmatthias.ringwald     }
471742bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
471842bd3d77SMatthias Ringwald }
47197301ad89Smatthias.ringwald 
472042bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
47218d213e1aSmatthias.ringwald     switch (power_mode){
47228d213e1aSmatthias.ringwald         case HCI_POWER_ON:
47238d213e1aSmatthias.ringwald             // do nothing
47248d213e1aSmatthias.ringwald             break;
47258d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
47268d213e1aSmatthias.ringwald             // no connections yet, just turn it off
47278d213e1aSmatthias.ringwald             hci_power_control_off();
47288d213e1aSmatthias.ringwald             break;
47298d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4730b546ac54Smatthias.ringwald             // no connections yet, just turn it off
473172ea5239Smatthias.ringwald             hci_power_control_sleep();
47328d213e1aSmatthias.ringwald             break;
47337bbeb3adSMilanka Ringwald         default:
47347bbeb3adSMilanka Ringwald             btstack_assert(false);
47357bbeb3adSMilanka Ringwald             break;
47368d213e1aSmatthias.ringwald     }
473742bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
473842bd3d77SMatthias Ringwald }
47397301ad89Smatthias.ringwald 
474042bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
47418d213e1aSmatthias.ringwald     switch (power_mode){
47428d213e1aSmatthias.ringwald         case HCI_POWER_ON:
47438d213e1aSmatthias.ringwald             // do nothing
47448d213e1aSmatthias.ringwald             break;
47458d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
47460c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
47478d213e1aSmatthias.ringwald             break;
47488d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4749b546ac54Smatthias.ringwald             // see hci_run
47503a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
475174b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
47528d213e1aSmatthias.ringwald             break;
47537bbeb3adSMilanka Ringwald         default:
47547bbeb3adSMilanka Ringwald             btstack_assert(false);
47557bbeb3adSMilanka Ringwald             break;
47568d213e1aSmatthias.ringwald     }
475742bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
475842bd3d77SMatthias Ringwald }
47597301ad89Smatthias.ringwald 
476042bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
47618d213e1aSmatthias.ringwald     switch (power_mode){
47628d213e1aSmatthias.ringwald         case HCI_POWER_ON:
47630c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
47648d213e1aSmatthias.ringwald             break;
47658d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
47668d213e1aSmatthias.ringwald             // do nothing
47678d213e1aSmatthias.ringwald             break;
47688d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4769b546ac54Smatthias.ringwald             // see hci_run
47703a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
477174b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
47728d213e1aSmatthias.ringwald             break;
47737bbeb3adSMilanka Ringwald         default:
47747bbeb3adSMilanka Ringwald             btstack_assert(false);
47757bbeb3adSMilanka Ringwald             break;
47768d213e1aSmatthias.ringwald     }
477700278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
477842bd3d77SMatthias Ringwald }
47798d213e1aSmatthias.ringwald 
478042bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
47818d213e1aSmatthias.ringwald     switch (power_mode){
47828d213e1aSmatthias.ringwald         case HCI_POWER_ON:
47830c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
47848d213e1aSmatthias.ringwald             break;
47858d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
47860c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
47878d213e1aSmatthias.ringwald             break;
47888d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4789b546ac54Smatthias.ringwald             // do nothing
47908d213e1aSmatthias.ringwald             break;
47917bbeb3adSMilanka Ringwald         default:
47927bbeb3adSMilanka Ringwald             btstack_assert(false);
47937bbeb3adSMilanka Ringwald             break;
47948d213e1aSmatthias.ringwald     }
479542bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
479642bd3d77SMatthias Ringwald }
47978d213e1aSmatthias.ringwald 
479842bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
479942bd3d77SMatthias Ringwald     int err;
48008d213e1aSmatthias.ringwald     switch (power_mode){
48018d213e1aSmatthias.ringwald         case HCI_POWER_ON:
48023144bce4Smatthias.ringwald             err = hci_power_control_wake();
48033144bce4Smatthias.ringwald             if (err) return err;
48040c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
48058d213e1aSmatthias.ringwald             break;
48068d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
48070c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
48088d213e1aSmatthias.ringwald             break;
48098d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
4810b546ac54Smatthias.ringwald             // do nothing
48118d213e1aSmatthias.ringwald             break;
48127bbeb3adSMilanka Ringwald         default:
48137bbeb3adSMilanka Ringwald             btstack_assert(false);
48147bbeb3adSMilanka Ringwald             break;
48158d213e1aSmatthias.ringwald     }
481642bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
481742bd3d77SMatthias Ringwald }
48187bbeb3adSMilanka Ringwald 
481942bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
482042bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
482124f87726SMatthias Ringwald     int err = 0;
482242bd3d77SMatthias Ringwald     switch (hci_stack->state){
482342bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
482442bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
482542bd3d77SMatthias Ringwald             break;
482642bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
482742bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
482842bd3d77SMatthias Ringwald             break;
482942bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
483042bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
483142bd3d77SMatthias Ringwald             break;
483242bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
483342bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
483442bd3d77SMatthias Ringwald             break;
483542bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
483642bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
483742bd3d77SMatthias Ringwald             break;
483842bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
483942bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
484042bd3d77SMatthias Ringwald             break;
48417bbeb3adSMilanka Ringwald         default:
48427bbeb3adSMilanka Ringwald             btstack_assert(false);
48437bbeb3adSMilanka Ringwald             break;
484411e23e5fSmatthias.ringwald     }
484524f87726SMatthias Ringwald     if (err != 0){
484642bd3d77SMatthias Ringwald         return err;
484742bd3d77SMatthias Ringwald     }
484868d92d03Smatthias.ringwald 
4849038bc64cSmatthias.ringwald     // create internal event
4850ee8bf225Smatthias.ringwald 	hci_emit_state();
4851ee8bf225Smatthias.ringwald 
485268d92d03Smatthias.ringwald 	// trigger next/first action
485368d92d03Smatthias.ringwald 	hci_run();
485468d92d03Smatthias.ringwald 
4855475c8125Smatthias.ringwald     return 0;
4856475c8125Smatthias.ringwald }
4857475c8125Smatthias.ringwald 
485835454696SMatthias Ringwald 
4859091e35e3SMatthias Ringwald static void hci_halting_run(void) {
4860091e35e3SMatthias Ringwald 
4861091e35e3SMatthias Ringwald     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
4862091e35e3SMatthias Ringwald 
4863091e35e3SMatthias Ringwald     hci_connection_t *connection;
4864d5f71a7eSMatthias Ringwald #ifdef ENABLE_BLE
4865d5f71a7eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4866911801caSMatthias Ringwald     bool stop_advertismenets;
4867d5f71a7eSMatthias Ringwald #endif
4868d5f71a7eSMatthias Ringwald #endif
4869091e35e3SMatthias Ringwald 
4870091e35e3SMatthias Ringwald     switch (hci_stack->substate) {
48710c88d5efSMatthias Ringwald         case HCI_HALTING_CLASSIC_STOP:
48720c88d5efSMatthias Ringwald #ifdef ENABLE_CLASSIC
4873911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
4874911801caSMatthias Ringwald 
48750c88d5efSMatthias Ringwald             if (hci_stack->connectable || hci_stack->discoverable){
48760c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
48770c88d5efSMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, 0);
48780c88d5efSMatthias Ringwald                 return;
48790c88d5efSMatthias Ringwald             }
48800c88d5efSMatthias Ringwald #endif
48810c88d5efSMatthias Ringwald             /* fall through */
48820c88d5efSMatthias Ringwald 
48830c88d5efSMatthias Ringwald         case HCI_HALTING_LE_ADV_STOP:
48840c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
48850c88d5efSMatthias Ringwald 
48860c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
48870c88d5efSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4888911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
4889911801caSMatthias Ringwald 
4890911801caSMatthias Ringwald             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
4891911801caSMatthias Ringwald 
4892911801caSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4893911801caSMatthias Ringwald             if (hci_extended_advertising_supported()){
4894c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
4895911801caSMatthias Ringwald                 btstack_linked_list_iterator_t it;
4896911801caSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
4897911801caSMatthias Ringwald                 // stop all periodic advertisements and check if an extended set is active
4898911801caSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
4899911801caSMatthias Ringwald                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
4900911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
4901911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
4902911801caSMatthias Ringwald                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
49030c88d5efSMatthias Ringwald                         return;
49040c88d5efSMatthias Ringwald                     }
4905911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
4906911801caSMatthias Ringwald                         stop_advertismenets = true;
4907911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4908911801caSMatthias Ringwald                     }
4909911801caSMatthias Ringwald                 }
4910c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
4911911801caSMatthias Ringwald                 if (stop_advertismenets){
4912911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4913911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
4914911801caSMatthias Ringwald                     return;
4915911801caSMatthias Ringwald                 }
4916911801caSMatthias Ringwald             }
4917911801caSMatthias Ringwald             else
4918a2c9d908SMatthias Ringwald #else /* ENABLE_LE_PERIPHERAL */
4919911801caSMatthias Ringwald             {
4920911801caSMatthias Ringwald                 if (stop_advertismenets) {
4921911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
4922911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
4923911801caSMatthias Ringwald                     return;
4924911801caSMatthias Ringwald                 }
4925911801caSMatthias Ringwald             }
4926911801caSMatthias Ringwald #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
4927911801caSMatthias Ringwald #endif  /* ENABLE_LE_PERIPHERAL */
4928911801caSMatthias Ringwald #endif  /* ENABLE_BLE */
4929911801caSMatthias Ringwald 
49300c88d5efSMatthias Ringwald             /* fall through */
49310c88d5efSMatthias Ringwald 
49320c88d5efSMatthias Ringwald         case HCI_HALTING_LE_SCAN_STOP:
49330c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
4934911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
4935091e35e3SMatthias Ringwald 
4936091e35e3SMatthias Ringwald #ifdef ENABLE_BLE
4937091e35e3SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
49380c88d5efSMatthias Ringwald             if (hci_stack->le_scanning_active){
4939c42da3bcSMatthias Ringwald                 hci_le_scan_stop();
49400c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
49410c88d5efSMatthias Ringwald                 return;
49420c88d5efSMatthias Ringwald             }
4943091e35e3SMatthias Ringwald #endif
4944091e35e3SMatthias Ringwald #endif
49450c88d5efSMatthias Ringwald 
49460c88d5efSMatthias Ringwald             /* fall through */
49470c88d5efSMatthias Ringwald 
49480c88d5efSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL:
49490c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
4950911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
49510c88d5efSMatthias Ringwald 
4952091e35e3SMatthias Ringwald             // close all open connections
4953091e35e3SMatthias Ringwald             connection = (hci_connection_t *) hci_stack->connections;
4954091e35e3SMatthias Ringwald             if (connection) {
4955091e35e3SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4956091e35e3SMatthias Ringwald 
4957091e35e3SMatthias Ringwald                 // check state
4958091e35e3SMatthias Ringwald                 if (connection->state == SENT_DISCONNECT) return;
4959091e35e3SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
4960091e35e3SMatthias Ringwald 
4961091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4962091e35e3SMatthias Ringwald 
4963091e35e3SMatthias Ringwald                 // finally, send the disconnect command
4964091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4965091e35e3SMatthias Ringwald                 return;
4966091e35e3SMatthias Ringwald             }
4967091e35e3SMatthias Ringwald 
4968346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4969346f8c2cSMatthias Ringwald             // stop BIGs and BIG Syncs
4970346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_bigs != NULL){
4971346f8c2cSMatthias Ringwald                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
4972346f8c2cSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4973346f8c2cSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4974346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
4975346f8c2cSMatthias Ringwald                 return;
4976346f8c2cSMatthias Ringwald             }
4977346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_big_syncs != NULL){
4978346f8c2cSMatthias Ringwald                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
4979346f8c2cSMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
4980346f8c2cSMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
4981346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
4982346f8c2cSMatthias Ringwald                 return;
4983346f8c2cSMatthias Ringwald             }
4984346f8c2cSMatthias Ringwald #endif
4985346f8c2cSMatthias Ringwald 
4986091e35e3SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
4987091e35e3SMatthias Ringwald 
4988091e35e3SMatthias Ringwald             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4989091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING: wait 50 ms");
49900c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
4991091e35e3SMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
4992091e35e3SMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
4993091e35e3SMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
4994091e35e3SMatthias Ringwald             break;
4995091e35e3SMatthias Ringwald 
4996091e35e3SMatthias Ringwald         case HCI_HALTING_CLOSE:
4997091e35e3SMatthias Ringwald             // close left over connections (that had not been properly closed before)
4998091e35e3SMatthias Ringwald             hci_discard_connections();
4999091e35e3SMatthias Ringwald 
5000091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, calling off");
5001091e35e3SMatthias Ringwald 
5002091e35e3SMatthias Ringwald             // switch mode
5003091e35e3SMatthias Ringwald             hci_power_control_off();
5004091e35e3SMatthias Ringwald 
5005091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, emitting state");
5006091e35e3SMatthias Ringwald             hci_emit_state();
5007091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, done");
5008091e35e3SMatthias Ringwald             break;
5009091e35e3SMatthias Ringwald 
50100c88d5efSMatthias Ringwald         case HCI_HALTING_W4_CLOSE_TIMER:
5011091e35e3SMatthias Ringwald             // keep waiting
5012091e35e3SMatthias Ringwald 
5013091e35e3SMatthias Ringwald             break;
5014091e35e3SMatthias Ringwald         default:
5015091e35e3SMatthias Ringwald             break;
5016091e35e3SMatthias Ringwald     }
5017091e35e3SMatthias Ringwald };
5018091e35e3SMatthias Ringwald 
5019091e35e3SMatthias Ringwald static void hci_falling_asleep_run(void){
5020091e35e3SMatthias Ringwald     hci_connection_t * connection;
5021091e35e3SMatthias Ringwald     switch(hci_stack->substate) {
5022091e35e3SMatthias Ringwald         case HCI_FALLING_ASLEEP_DISCONNECT:
5023091e35e3SMatthias Ringwald             log_info("HCI_STATE_FALLING_ASLEEP");
5024091e35e3SMatthias Ringwald             // close all open connections
5025091e35e3SMatthias Ringwald             connection =  (hci_connection_t *) hci_stack->connections;
5026091e35e3SMatthias Ringwald             if (connection){
5027091e35e3SMatthias Ringwald 
5028091e35e3SMatthias Ringwald                 // send disconnect
5029091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5030091e35e3SMatthias Ringwald 
5031091e35e3SMatthias Ringwald                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5032091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5033091e35e3SMatthias Ringwald 
5034091e35e3SMatthias Ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
5035091e35e3SMatthias Ringwald                 hci_shutdown_connection(connection);
5036091e35e3SMatthias Ringwald                 return;
5037091e35e3SMatthias Ringwald             }
5038091e35e3SMatthias Ringwald 
5039091e35e3SMatthias Ringwald             if (hci_classic_supported()){
5040091e35e3SMatthias Ringwald                 // disable page and inquiry scan
5041091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5042091e35e3SMatthias Ringwald 
5043091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, disabling inq scans");
5044091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5045091e35e3SMatthias Ringwald 
5046091e35e3SMatthias Ringwald                 // continue in next sub state
5047091e35e3SMatthias Ringwald                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5048091e35e3SMatthias Ringwald                 break;
5049091e35e3SMatthias Ringwald             }
5050091e35e3SMatthias Ringwald 
5051091e35e3SMatthias Ringwald             /* fall through */
5052091e35e3SMatthias Ringwald 
5053091e35e3SMatthias Ringwald             case HCI_FALLING_ASLEEP_COMPLETE:
5054091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, calling sleep");
5055091e35e3SMatthias Ringwald                 // switch mode
5056091e35e3SMatthias Ringwald                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5057091e35e3SMatthias Ringwald                 hci_emit_state();
5058091e35e3SMatthias Ringwald                 break;
5059091e35e3SMatthias Ringwald 
5060091e35e3SMatthias Ringwald                 default:
5061091e35e3SMatthias Ringwald                     break;
5062091e35e3SMatthias Ringwald     }
5063091e35e3SMatthias Ringwald }
5064091e35e3SMatthias Ringwald 
506535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
506635454696SMatthias Ringwald 
5067758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
5068758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
5069a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5070baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5071758b46ceSmatthias.ringwald     hci_run();
5072758b46ceSmatthias.ringwald }
5073758b46ceSmatthias.ringwald 
507415a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
5075381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
5076381fbed8Smatthias.ringwald 
50773a9fb326S[email protected]     if (hci_stack->discoverable == enable){
507871fd255dSMatthias Ringwald         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5079381fbed8Smatthias.ringwald         return;
5080381fbed8Smatthias.ringwald     }
5081381fbed8Smatthias.ringwald 
50823a9fb326S[email protected]     hci_stack->discoverable = enable;
5083758b46ceSmatthias.ringwald     hci_update_scan_enable();
5084758b46ceSmatthias.ringwald }
5085b031bebbSmatthias.ringwald 
508615a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
5087758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
5088758b46ceSmatthias.ringwald 
5089758b46ceSmatthias.ringwald     // don't emit event
50903a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
5091758b46ceSmatthias.ringwald 
50923a9fb326S[email protected]     hci_stack->connectable = enable;
5093758b46ceSmatthias.ringwald     hci_update_scan_enable();
5094381fbed8Smatthias.ringwald }
509535454696SMatthias Ringwald #endif
5096381fbed8Smatthias.ringwald 
509715a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
50986535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
50995061f3afS[email protected] }
51005061f3afS[email protected] 
51012b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
51022b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
51032b838201SMatthias Ringwald 
51042b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
51052b838201SMatthias Ringwald     hci_reserve_packet_buffer();
51062b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
51072b838201SMatthias Ringwald 
51082b838201SMatthias Ringwald     uint16_t size = 0;
51092b838201SMatthias Ringwald     uint16_t num_handles = 0;
51102b838201SMatthias Ringwald     packet[size++] = 0x35;
51112b838201SMatthias Ringwald     packet[size++] = 0x0c;
51122b838201SMatthias Ringwald     size++;  // skip param len
51132b838201SMatthias Ringwald     size++;  // skip num handles
51142b838201SMatthias Ringwald 
51152b838201SMatthias Ringwald     // add { handle, packets } entries
51162b838201SMatthias Ringwald     btstack_linked_item_t * it;
51172b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
51182b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
51192b838201SMatthias Ringwald         if (connection->num_packets_completed){
51202b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
51212b838201SMatthias Ringwald             size += 2;
51222b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
51232b838201SMatthias Ringwald             size += 2;
51242b838201SMatthias Ringwald             //
51252b838201SMatthias Ringwald             num_handles++;
51262b838201SMatthias Ringwald             connection->num_packets_completed = 0;
51272b838201SMatthias Ringwald         }
51282b838201SMatthias Ringwald     }
51292b838201SMatthias Ringwald 
51302b838201SMatthias Ringwald     packet[2] = size - 3;
51312b838201SMatthias Ringwald     packet[3] = num_handles;
51322b838201SMatthias Ringwald 
51332b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
51342b838201SMatthias Ringwald 
51352b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
51362b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
51372b838201SMatthias Ringwald 
51382b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
51392b838201SMatthias Ringwald     if (hci_transport_synchronous()){
5140e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5141068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
51422b838201SMatthias Ringwald     }
51432b838201SMatthias Ringwald }
51442b838201SMatthias Ringwald #endif
51452b838201SMatthias Ringwald 
514626fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
514726fe9592SMatthias Ringwald     UNUSED(ds);
514826fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
5149beceeddeSMatthias Ringwald     // allow packet handlers to defer final shutdown
5150beceeddeSMatthias Ringwald     hci_emit_state();
515126fe9592SMatthias Ringwald     hci_run();
515226fe9592SMatthias Ringwald }
515326fe9592SMatthias Ringwald 
5154f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
51554ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
5156b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5157b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5158b5d8b22bS[email protected]         if (connection) {
515928a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5160b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
5161f30077b7SMatthias Ringwald                 return true;
5162b5d8b22bS[email protected]             }
516328a0332dSMatthias Ringwald         } else {
5164b5d8b22bS[email protected]             // connection gone -> discard further fragments
516528a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5166b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
5167b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
5168b5d8b22bS[email protected]         }
5169b5d8b22bS[email protected]     }
5170f30077b7SMatthias Ringwald     return false;
51712b838201SMatthias Ringwald }
5172b031bebbSmatthias.ringwald 
517368ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
517468ab6207SMatthias Ringwald static bool hci_run_iso_fragments(void){
517568ab6207SMatthias Ringwald     if (hci_stack->iso_fragmentation_total_size > 0u) {
517668ab6207SMatthias Ringwald         // TODO: flow control
517768ab6207SMatthias Ringwald         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
517868ab6207SMatthias Ringwald             hci_send_iso_packet_fragments();
517968ab6207SMatthias Ringwald             return true;
518068ab6207SMatthias Ringwald         }
518168ab6207SMatthias Ringwald     }
518268ab6207SMatthias Ringwald     return false;
518368ab6207SMatthias Ringwald }
518468ab6207SMatthias Ringwald #endif
518568ab6207SMatthias Ringwald 
518635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
51876c0d5426SMatthias Ringwald 
51886c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
51896c0d5426SMatthias Ringwald static bool hci_classic_operation_active(void) {
51906c0d5426SMatthias Ringwald     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
51916c0d5426SMatthias Ringwald         return true;
51926c0d5426SMatthias Ringwald     }
51936c0d5426SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
51946c0d5426SMatthias Ringwald         return true;
51956c0d5426SMatthias Ringwald     }
51966c0d5426SMatthias Ringwald     btstack_linked_item_t * it;
51976c0d5426SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
51986c0d5426SMatthias Ringwald         hci_connection_t *connection = (hci_connection_t *) it;
51996c0d5426SMatthias Ringwald         switch (connection->state) {
52006c0d5426SMatthias Ringwald             case SENT_CREATE_CONNECTION:
52016c0d5426SMatthias Ringwald             case SENT_CANCEL_CONNECTION:
52026c0d5426SMatthias Ringwald             case SENT_DISCONNECT:
52036c0d5426SMatthias Ringwald                 return true;
52046c0d5426SMatthias Ringwald             default:
52056c0d5426SMatthias Ringwald                 break;
52066c0d5426SMatthias Ringwald         }
52076c0d5426SMatthias Ringwald     }
52086c0d5426SMatthias Ringwald     return false;
52096c0d5426SMatthias Ringwald }
52106c0d5426SMatthias Ringwald #endif
52116c0d5426SMatthias Ringwald 
5212f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
5213f30077b7SMatthias Ringwald 
521459d59ecfSMatthias Ringwald     // assert stack is working and classic is active
521559d59ecfSMatthias Ringwald     if (hci_classic_supported() == false)      return false;
521659d59ecfSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
521759d59ecfSMatthias Ringwald 
5218b031bebbSmatthias.ringwald     // decline incoming connections
52193a9fb326S[email protected]     if (hci_stack->decline_reason){
52203a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
52213a9fb326S[email protected]         hci_stack->decline_reason = 0;
52223a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5223f30077b7SMatthias Ringwald         return true;
5224ce4c8fabSmatthias.ringwald     }
522559d59ecfSMatthias Ringwald 
5226baa4881eSMatthias Ringwald     if (hci_stack->gap_tasks_classic != 0){
5227ab4831a3SMatthias Ringwald         hci_run_gap_tasks_classic();
5228f30077b7SMatthias Ringwald         return true;
5229b031bebbSmatthias.ringwald     }
523027741fe7SMatthias Ringwald 
5231f5875de5SMatthias Ringwald     // start/stop inquiry
5232a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
52336c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
52346c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
52356c0d5426SMatthias Ringwald #endif
52366c0d5426SMatthias Ringwald         {
5237f5875de5SMatthias Ringwald             uint8_t duration = hci_stack->inquiry_state;
5238beb3c81dSMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
523930199e24SMatthias Ringwald             if (hci_stack->inquiry_max_period_length != 0){
524030199e24SMatthias 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);
524130199e24SMatthias Ringwald             } else {
5242496bb884SMatthias Ringwald                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
524330199e24SMatthias Ringwald             }
5244f30077b7SMatthias Ringwald             return true;
5245f5875de5SMatthias Ringwald         }
52466c0d5426SMatthias Ringwald     }
5247f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5248f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5249f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
5250f30077b7SMatthias Ringwald         return true;
5251f5875de5SMatthias Ringwald     }
525230199e24SMatthias Ringwald 
525330199e24SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5254bc06f564SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
525530199e24SMatthias Ringwald         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
525630199e24SMatthias Ringwald         return true;
525730199e24SMatthias Ringwald     }
525830199e24SMatthias Ringwald 
5259b7f1ee76SMatthias Ringwald     // remote name request
5260b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
52616c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
52626c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
52636c0d5426SMatthias Ringwald #endif
52646c0d5426SMatthias Ringwald         {
5265b7f1ee76SMatthias Ringwald             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5266b7f1ee76SMatthias Ringwald             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5267ee8a36c8SMatthias Ringwald                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5268f30077b7SMatthias Ringwald             return true;
5269b7f1ee76SMatthias Ringwald         }
52706c0d5426SMatthias Ringwald     }
5271cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
5272cf01e888SMatthias Ringwald     // Local OOB data
527359d59ecfSMatthias Ringwald     if (hci_stack->classic_read_local_oob_data){
5274cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
52751e83575aSMatthias Ringwald         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5276cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
5277cf01e888SMatthias Ringwald         } else {
5278cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
5279cf01e888SMatthias Ringwald         }
5280cf01e888SMatthias Ringwald     }
5281cf01e888SMatthias Ringwald #endif
52820a51f88bSMatthias Ringwald     // pairing
52830a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
52840a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
52853f659ee4SMilanka Ringwald         uint8_t pin_code[16];
52860a51f88bSMatthias Ringwald         switch (state){
52870a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
5288cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
52893f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
52903f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
52913f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
52920a51f88bSMatthias Ringwald                 break;
52930a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5294cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
52950a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
52960a51f88bSMatthias Ringwald                 break;
52970a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
5298cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5299d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
53000a51f88bSMatthias Ringwald                 break;
53010a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5302cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
53030a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
53040a51f88bSMatthias Ringwald                 break;
53050a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5306cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
53070a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
53080a51f88bSMatthias Ringwald                 break;
53090a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5310cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
53110a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
53120a51f88bSMatthias Ringwald                 break;
53130a51f88bSMatthias Ringwald             default:
53140a51f88bSMatthias Ringwald                 break;
53150a51f88bSMatthias Ringwald         }
5316f30077b7SMatthias Ringwald         return true;
5317f30077b7SMatthias Ringwald     }
5318f30077b7SMatthias Ringwald     return false;
53190a51f88bSMatthias Ringwald }
532035454696SMatthias Ringwald #endif
5321b031bebbSmatthias.ringwald 
5322a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
5323be7ef9d8SMatthias Ringwald 
5324c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5325c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void){
5326c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5327c42da3bcSMatthias Ringwald     if (hci_extended_advertising_supported()) {
5328c42da3bcSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5329c42da3bcSMatthias Ringwald         } else
5330c42da3bcSMatthias Ringwald #endif
5331c42da3bcSMatthias Ringwald     {
5332c42da3bcSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5333c42da3bcSMatthias Ringwald     }
5334c42da3bcSMatthias Ringwald }
5335c42da3bcSMatthias Ringwald #endif
5336c42da3bcSMatthias Ringwald 
5337be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5338be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5339be7ef9d8SMatthias Ringwald uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5340be7ef9d8SMatthias Ringwald     uint8_t  operation = 0;
5341be7ef9d8SMatthias Ringwald     if (pos == 0){
5342be7ef9d8SMatthias Ringwald         // first fragment or complete data
5343be7ef9d8SMatthias Ringwald         operation |= 1;
5344be7ef9d8SMatthias Ringwald     }
5345be7ef9d8SMatthias Ringwald     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5346be7ef9d8SMatthias Ringwald         // last fragment or complete data
5347be7ef9d8SMatthias Ringwald         operation |= 2;
5348be7ef9d8SMatthias Ringwald     }
5349be7ef9d8SMatthias Ringwald     return operation;
5350be7ef9d8SMatthias Ringwald }
5351be7ef9d8SMatthias Ringwald #endif
5352be7ef9d8SMatthias Ringwald #endif
5353be7ef9d8SMatthias Ringwald 
5354f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
5355f30077b7SMatthias Ringwald 
5356f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t lit;
5357f40c73b4SMatthias Ringwald 
5358a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
5359a41310b7SMatthias Ringwald 
536049a6c69cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5361a41310b7SMatthias Ringwald     bool scanning_stop = false;
5362a41310b7SMatthias Ringwald     bool connecting_stop = false;
5363be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5364c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
53654bafedd5SMatthias Ringwald     bool periodic_sync_stop = false;
53664bafedd5SMatthias Ringwald #endif
5367be7ef9d8SMatthias Ringwald #endif
5368c814a904SMatthias Ringwald #endif
5369be7ef9d8SMatthias Ringwald 
537049a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
537149a6c69cSMatthias Ringwald     bool advertising_stop = false;
537249a6c69cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
537349a6c69cSMatthias Ringwald     le_advertising_set_t * advertising_stop_set = NULL;
537449a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
537549a6c69cSMatthias Ringwald     bool periodic_advertising_stop = false;
5376a41310b7SMatthias Ringwald #endif
537749a6c69cSMatthias Ringwald #endif
5378a41310b7SMatthias Ringwald #endif
5379a41310b7SMatthias Ringwald 
53809136bde8SMatthias Ringwald     // check if own address changes
53819136bde8SMatthias Ringwald     bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
53829136bde8SMatthias Ringwald 
538329c24bebSMatthias Ringwald     // check if whitelist needs modification
538429c24bebSMatthias Ringwald     bool whitelist_modification_pending = false;
538529c24bebSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
538629c24bebSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
538729c24bebSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
538829c24bebSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
538929c24bebSMatthias Ringwald             whitelist_modification_pending = true;
539029c24bebSMatthias Ringwald             break;
539129c24bebSMatthias Ringwald         }
539229c24bebSMatthias Ringwald     }
5393f40c73b4SMatthias Ringwald 
539421debf25SMatthias Ringwald     // check if resolving list needs modification
539521debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
539621debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
53971ffa425cSMatthias Ringwald     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5398ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
539921debf25SMatthias Ringwald         resolving_list_modification_pending = true;
540021debf25SMatthias Ringwald     }
540121debf25SMatthias Ringwald #endif
540229c24bebSMatthias Ringwald 
5403f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
540449a6c69cSMatthias Ringwald 
5405f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
540649a6c69cSMatthias Ringwald     // check if periodic advertiser list needs modification
5407f40c73b4SMatthias Ringwald     bool periodic_list_modification_pending = false;
5408f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5409f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
5410f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5411f40c73b4SMatthias Ringwald         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5412f40c73b4SMatthias Ringwald             periodic_list_modification_pending = true;
5413f40c73b4SMatthias Ringwald             break;
5414f40c73b4SMatthias Ringwald         }
5415f40c73b4SMatthias Ringwald     }
5416f40c73b4SMatthias Ringwald #endif
5417f40c73b4SMatthias Ringwald 
5418fde725feSMatthias Ringwald     // scanning control
54193251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
542029c24bebSMatthias Ringwald         // stop if:
542129c24bebSMatthias Ringwald         // - parameter change required
542229c24bebSMatthias Ringwald         // - it's disabled
542329c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
542421debf25SMatthias Ringwald         // - resolving list modified
542551e51a58SMatthias Ringwald         // - own address changes
542629c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
542721debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
542821debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
5429d54b2c94SMatthias Ringwald             (scanning_uses_whitelist && whitelist_modification_pending) ||
543051e51a58SMatthias Ringwald             resolving_list_modification_pending ||
543151e51a58SMatthias Ringwald             random_address_change){
543221debf25SMatthias Ringwald 
54332d5c2a27SMatthias Ringwald             scanning_stop = true;
5434fde725feSMatthias Ringwald         }
5435fde725feSMatthias Ringwald     }
5436fde725feSMatthias Ringwald 
543729c24bebSMatthias Ringwald     // connecting control
5438f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
5439f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
5440f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
5441f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
5442af64f147SMatthias Ringwald             // stop connecting if:
5443af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
5444af64f147SMatthias Ringwald             // - if it got disabled
544521debf25SMatthias Ringwald             // - resolving list modified
544651e51a58SMatthias Ringwald             // - own address changes
5447f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5448f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
544921debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
545051e51a58SMatthias Ringwald                 resolving_list_modification_pending ||
545151e51a58SMatthias Ringwald                 random_address_change) {
545221debf25SMatthias Ringwald 
545329c24bebSMatthias Ringwald                 connecting_stop = true;
545429c24bebSMatthias Ringwald             }
5455f496d06eSMatthias Ringwald             break;
5456f496d06eSMatthias Ringwald         default:
5457f496d06eSMatthias Ringwald             break;
545829c24bebSMatthias Ringwald     }
545949a6c69cSMatthias Ringwald 
54604bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
546149a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
54624bafedd5SMatthias Ringwald     // periodic sync control
54634bafedd5SMatthias Ringwald     bool sync_with_advertiser_list;
54644bafedd5SMatthias Ringwald     switch(hci_stack->le_periodic_sync_state){
54654bafedd5SMatthias Ringwald         case LE_CONNECTING_DIRECT:
54664bafedd5SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
546749a6c69cSMatthias Ringwald             // stop sync if:
54684bafedd5SMatthias Ringwald             // - sync with advertiser list and advertiser list modification pending
546949a6c69cSMatthias Ringwald             // - if it got disabled
54704bafedd5SMatthias Ringwald             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
54714bafedd5SMatthias Ringwald             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
54724bafedd5SMatthias Ringwald                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
54734bafedd5SMatthias Ringwald                 periodic_sync_stop = true;
54744bafedd5SMatthias Ringwald             }
54754bafedd5SMatthias Ringwald             break;
54764bafedd5SMatthias Ringwald         default:
54774bafedd5SMatthias Ringwald             break;
54784bafedd5SMatthias Ringwald     }
54794bafedd5SMatthias Ringwald #endif
5480d70217a2SMatthias Ringwald #endif
548129c24bebSMatthias Ringwald 
548249a6c69cSMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
548349a6c69cSMatthias Ringwald 
5484d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
548545c102fdSMatthias Ringwald     // le advertisement control
5486935aa76eSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
548729c24bebSMatthias Ringwald         // stop if:
548829c24bebSMatthias Ringwald         // - parameter change required
54899136bde8SMatthias Ringwald         // - random address used in advertising and changes
549029c24bebSMatthias Ringwald         // - it's disabled
5491ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
549221debf25SMatthias Ringwald         // - resolving list modified
549351e51a58SMatthias Ringwald         // - own address changes
5494a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
54959136bde8SMatthias Ringwald         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
54964e5d21eaSMatthias Ringwald         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
5497a61834b6SMatthias Ringwald         if (advertising_change ||
54989136bde8SMatthias Ringwald             (advertising_uses_random_address && random_address_change) ||
5499a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
55009136bde8SMatthias Ringwald             (advertising_uses_whitelist && whitelist_modification_pending) ||
550151e51a58SMatthias Ringwald             resolving_list_modification_pending ||
550251e51a58SMatthias Ringwald             random_address_change) {
550321debf25SMatthias Ringwald 
5504fde725feSMatthias Ringwald             advertising_stop = true;
5505fde725feSMatthias Ringwald         }
5506fde725feSMatthias Ringwald     }
5507be7ef9d8SMatthias Ringwald 
5508be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5509be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported() && (advertising_stop == false)){
5510be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
5511be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5512be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
5513be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
551453f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5515be7ef9d8SMatthias Ringwald                 // stop if:
5516be7ef9d8SMatthias Ringwald                 // - parameter change required
5517be7ef9d8SMatthias Ringwald                 // - random address used in connectable advertising and changes
5518be7ef9d8SMatthias Ringwald                 // - it's disabled
5519be7ef9d8SMatthias Ringwald                 // - whitelist change required but used for advertisement filter policy
5520be7ef9d8SMatthias Ringwald                 // - resolving list modified
5521be7ef9d8SMatthias Ringwald                 // - own address changes
5522be7ef9d8SMatthias Ringwald                 // - advertisement set will be removed
552357a04237SMatthias Ringwald                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
552457a04237SMatthias Ringwald                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
552553f240c0SMatthias Ringwald                 bool advertising_uses_random_address =
552653f240c0SMatthias Ringwald                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
552753f240c0SMatthias Ringwald                         advertising_connectable;
5528be7ef9d8SMatthias Ringwald                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
5529be7ef9d8SMatthias Ringwald                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
553053f240c0SMatthias Ringwald                 bool advertising_set_random_address_change =
553153f240c0SMatthias Ringwald                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
553253f240c0SMatthias Ringwald                 bool advertising_set_will_be_removed =
553353f240c0SMatthias Ringwald                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
5534be7ef9d8SMatthias Ringwald                 if (advertising_parameter_change ||
5535be7ef9d8SMatthias Ringwald                     (advertising_uses_random_address && advertising_set_random_address_change) ||
5536be7ef9d8SMatthias Ringwald                     (advertising_enabled == false) ||
5537be7ef9d8SMatthias Ringwald                     (advertising_uses_whitelist && whitelist_modification_pending) ||
5538be7ef9d8SMatthias Ringwald                     resolving_list_modification_pending ||
5539be7ef9d8SMatthias Ringwald                     advertising_set_will_be_removed) {
5540be7ef9d8SMatthias Ringwald 
5541be7ef9d8SMatthias Ringwald                     advertising_stop = true;
5542be7ef9d8SMatthias Ringwald                     advertising_stop_set = advertising_set;
5543be7ef9d8SMatthias Ringwald                     break;
5544be7ef9d8SMatthias Ringwald                 }
5545be7ef9d8SMatthias Ringwald             }
5546c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
554753f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
554853f240c0SMatthias Ringwald                 // stop if:
554953f240c0SMatthias Ringwald                 // - it's disabled
555053f240c0SMatthias Ringwald                 // - parameter change required
555153f240c0SMatthias Ringwald                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
555253f240c0SMatthias Ringwald                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
555353f240c0SMatthias Ringwald                 if ((periodic_enabled == false) || periodic_parameter_change){
555449a6c69cSMatthias Ringwald                     periodic_advertising_stop = true;
555553f240c0SMatthias Ringwald                     advertising_stop_set = advertising_set;
555653f240c0SMatthias Ringwald                 }
555753f240c0SMatthias Ringwald             }
555849a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
555953f240c0SMatthias Ringwald         }
5560be7ef9d8SMatthias Ringwald     }
5561be7ef9d8SMatthias Ringwald #endif
5562be7ef9d8SMatthias Ringwald 
5563a41310b7SMatthias Ringwald #endif
5564fde725feSMatthias Ringwald 
5565a41310b7SMatthias Ringwald 
5566a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
5567a41310b7SMatthias Ringwald 
5568131d4778SMatthias Ringwald 
5569131d4778SMatthias Ringwald     // 2.1 Outgoing connection
5570131d4778SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5571131d4778SMatthias Ringwald     if (connecting_stop){
5572131d4778SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
5573131d4778SMatthias Ringwald         return true;
5574131d4778SMatthias Ringwald     }
5575131d4778SMatthias Ringwald #endif
5576131d4778SMatthias Ringwald 
5577131d4778SMatthias Ringwald     // 2.2 Scanning
5578a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5579a41310b7SMatthias Ringwald     if (scanning_stop){
55805226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
5581c42da3bcSMatthias Ringwald         hci_le_scan_stop();
5582a41310b7SMatthias Ringwald         return true;
5583a41310b7SMatthias Ringwald     }
5584a41310b7SMatthias Ringwald 
5585131d4778SMatthias Ringwald     // 2.3 Periodic Sync
55864bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
558749a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
558849a6c69cSMatthias Ringwald         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
558949a6c69cSMatthias Ringwald         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
559049a6c69cSMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
559149a6c69cSMatthias Ringwald         return true;
559249a6c69cSMatthias Ringwald     }
559349a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
55944bafedd5SMatthias Ringwald     if (periodic_sync_stop){
55954bafedd5SMatthias Ringwald         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
55964bafedd5SMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
55974bafedd5SMatthias Ringwald         return true;
55984bafedd5SMatthias Ringwald     }
559949a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5600a8016f96SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5601a8016f96SMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
5602a41310b7SMatthias Ringwald 
5603131d4778SMatthias Ringwald     // 2.4 Advertising: legacy, extended, periodic
5604a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5605fde725feSMatthias Ringwald     if (advertising_stop){
5606e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5607e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()) {
5608be7ef9d8SMatthias Ringwald             uint8_t advertising_stop_handle;
5609be7ef9d8SMatthias Ringwald             if (advertising_stop_set != NULL){
5610be7ef9d8SMatthias Ringwald                 advertising_stop_handle = advertising_stop_set->advertising_handle;
5611be7ef9d8SMatthias Ringwald                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5612be7ef9d8SMatthias Ringwald             } else {
5613be7ef9d8SMatthias Ringwald                 advertising_stop_handle = 0;
5614be7ef9d8SMatthias Ringwald                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5615be7ef9d8SMatthias Ringwald             }
5616be7ef9d8SMatthias Ringwald             const uint8_t advertising_handles[] = { advertising_stop_handle };
5617e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
5618e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
5619e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
5620e464cd48SMatthias Ringwald         } else
5621e464cd48SMatthias Ringwald #endif
5622e464cd48SMatthias Ringwald         {
5623be7ef9d8SMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
562445c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
5625e464cd48SMatthias Ringwald         }
5626f30077b7SMatthias Ringwald         return true;
562745c102fdSMatthias Ringwald     }
562853f240c0SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5629c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
563049a6c69cSMatthias Ringwald     if (periodic_advertising_stop){
563153f240c0SMatthias Ringwald         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
563253f240c0SMatthias Ringwald         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
563353f240c0SMatthias Ringwald         return true;
563453f240c0SMatthias Ringwald     }
5635c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5636c814a904SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
5637a8016f96SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
5638fde725feSMatthias Ringwald 
5639131d4778SMatthias Ringwald 
5640a41310b7SMatthias Ringwald     // Phase 3: modify
5641a41310b7SMatthias Ringwald 
56429136bde8SMatthias Ringwald     if (random_address_change){
56439136bde8SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5644e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5645e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()) {
5646e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
5647e464cd48SMatthias Ringwald         }
5648e464cd48SMatthias Ringwald #endif
5649e464cd48SMatthias Ringwald         {
56509136bde8SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
5651e464cd48SMatthias Ringwald         }
56529136bde8SMatthias Ringwald         return true;
56539136bde8SMatthias Ringwald     }
56549136bde8SMatthias Ringwald 
5655a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5656a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
5657a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
565863671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
565963671e69SMatthias Ringwald         if (hci_extended_advertising_supported()){
566063671e69SMatthias Ringwald             // prepare arrays for all PHYs
566163671e69SMatthias Ringwald             uint8_t  scan_types[1]     = { hci_stack->le_scan_type     };
566263671e69SMatthias Ringwald             uint16_t scan_intervals[1] = { hci_stack->le_scan_interval };
566363671e69SMatthias Ringwald             uint16_t scan_windows[1]   =    { hci_stack->le_scan_window   };
566463671e69SMatthias Ringwald             uint8_t  scanning_phys     = 1;  // LE 1M PHY
566563671e69SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
566663671e69SMatthias Ringwald                          hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows);
566763671e69SMatthias Ringwald         } else
566863671e69SMatthias Ringwald #endif
566963671e69SMatthias Ringwald         {
5670a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
5671a41310b7SMatthias Ringwald                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
567263671e69SMatthias Ringwald         }
5673a41310b7SMatthias Ringwald         return true;
5674a41310b7SMatthias Ringwald     }
5675a41310b7SMatthias Ringwald #endif
5676a41310b7SMatthias Ringwald 
5677a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
567845c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
567945c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
56806bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
5681e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5682e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
5683e464cd48SMatthias Ringwald             // map advertisment type to advertising event properties
5684e464cd48SMatthias Ringwald             uint16_t adv_event_properties = 0;
5685e464cd48SMatthias Ringwald             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
5686e464cd48SMatthias Ringwald             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
5687e464cd48SMatthias Ringwald                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
5688e464cd48SMatthias Ringwald             }
5689174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
5690e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5691e464cd48SMatthias Ringwald                          0,
5692e464cd48SMatthias Ringwald                          adv_event_properties,
5693e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
5694e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
5695e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
5696e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
5697e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
5698e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
5699e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_filter_policy,
5700e464cd48SMatthias Ringwald                          0x7f,  // tx power: no preference
5701e464cd48SMatthias Ringwald                          0x01,  // primary adv phy: LE 1M
5702e464cd48SMatthias Ringwald                          0,     // secondary adv max skip
5703e464cd48SMatthias Ringwald                          0,     // secondary adv phy
5704e464cd48SMatthias Ringwald                          0,     // adv sid
5705e464cd48SMatthias Ringwald                          0      // scan request notification
5706e464cd48SMatthias Ringwald                          );
5707e464cd48SMatthias Ringwald         }
5708e464cd48SMatthias Ringwald #endif
5709e464cd48SMatthias Ringwald         {
571045c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
571145c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
571245c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
571345c102fdSMatthias Ringwald                          hci_stack->le_advertisements_type,
57146bcfa632SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
571545c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
571645c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
571745c102fdSMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
571845c102fdSMatthias Ringwald                          hci_stack->le_advertisements_filter_policy);
5719e464cd48SMatthias Ringwald         }
5720f30077b7SMatthias Ringwald         return true;
572145c102fdSMatthias Ringwald     }
5722be7ef9d8SMatthias Ringwald 
5723501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
5724501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
57257a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
57267a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
57276535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
57286535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
57293c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
5730e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5731e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
5732174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
5733e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
5734e464cd48SMatthias Ringwald         } else
5735e464cd48SMatthias Ringwald #endif
5736e464cd48SMatthias Ringwald         {
57377a85e4f5SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
5738e464cd48SMatthias Ringwald         }
5739f30077b7SMatthias Ringwald         return true;
574045c102fdSMatthias Ringwald     }
5741be7ef9d8SMatthias Ringwald 
5742501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
5743501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5744f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
5745f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
57466535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
57476535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
57483c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
5749e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5750e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
5751174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
5752e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
5753e464cd48SMatthias Ringwald         } else
5754e464cd48SMatthias Ringwald #endif
5755e464cd48SMatthias Ringwald         {
5756214bfd60SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
5757e464cd48SMatthias Ringwald         }
5758f30077b7SMatthias Ringwald         return true;
5759501f56b3SMatthias Ringwald     }
5760be7ef9d8SMatthias Ringwald 
5761be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5762be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported()) {
5763be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
5764be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5765be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
5766be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5767be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
5768be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
5769174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5770be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
5771be7ef9d8SMatthias Ringwald                 return true;
5772be7ef9d8SMatthias Ringwald             }
5773f66adbdeSMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
5774f66adbdeSMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
5775f66adbdeSMatthias Ringwald                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
5776f66adbdeSMatthias Ringwald                 return true;
5777f66adbdeSMatthias Ringwald             }
5778be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
5779be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5780174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5781be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
5782be7ef9d8SMatthias Ringwald                              advertising_set->advertising_handle,
578357a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_event_properties,
578457a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_min,
578557a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_max,
578657a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_channel_map,
578757a04237SMatthias Ringwald                              advertising_set->extended_params.own_address_type,
578857a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address_type,
578957a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address,
579057a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_filter_policy,
579157a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_tx_power,
579257a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_phy,
579357a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_max_skip,
579457a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_phy,
579557a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_sid,
579657a04237SMatthias Ringwald                              advertising_set->extended_params.scan_request_notification_enable
5797be7ef9d8SMatthias Ringwald                 );
5798be7ef9d8SMatthias Ringwald                 return true;
5799be7ef9d8SMatthias Ringwald             }
5800be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
5801be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->adv_data_pos;
5802be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
5803be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5804be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
5805be7ef9d8SMatthias Ringwald                     // last fragment or complete data
5806be7ef9d8SMatthias Ringwald                     operation |= 2;
5807be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos = 0;
5808be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5809be7ef9d8SMatthias Ringwald                 } else {
5810be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos += data_to_upload;
5811be7ef9d8SMatthias Ringwald                 }
5812174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
58130cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
5814be7ef9d8SMatthias Ringwald                 return true;
5815be7ef9d8SMatthias Ringwald             }
5816be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
5817be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->scan_data_pos;
5818be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
5819be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
5820be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
5821be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos = 0;
5822be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5823be7ef9d8SMatthias Ringwald                 } else {
5824be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos += data_to_upload;
5825be7ef9d8SMatthias Ringwald                 }
5826174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
5827be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
5828be7ef9d8SMatthias Ringwald                 return true;
5829be7ef9d8SMatthias Ringwald             }
5830c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
583153f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
583253f240c0SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
583353f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
583453f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
583553f240c0SMatthias Ringwald                              advertising_set->advertising_handle,
583653f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_min,
583753f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_max,
583853f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_properties);
583953f240c0SMatthias Ringwald                 return true;
584053f240c0SMatthias Ringwald             }
584153f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
58420cbe4690SMatthias Ringwald                 uint16_t pos = advertising_set->periodic_data_pos;
584353f240c0SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
584453f240c0SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
584553f240c0SMatthias Ringwald                 if ((operation & 0x02) != 0){
584653f240c0SMatthias Ringwald                     // last fragment or complete data
584753f240c0SMatthias Ringwald                     operation |= 2;
58480cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos = 0;
584953f240c0SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
585053f240c0SMatthias Ringwald                 } else {
58510cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos += data_to_upload;
585253f240c0SMatthias Ringwald                 }
585353f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
58540cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
585553f240c0SMatthias Ringwald                 return true;
585653f240c0SMatthias Ringwald             }
5857c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5858be7ef9d8SMatthias Ringwald         }
5859be7ef9d8SMatthias Ringwald     }
5860be7ef9d8SMatthias Ringwald #endif
5861be7ef9d8SMatthias Ringwald 
5862d70217a2SMatthias Ringwald #endif
58639956955bSMatthias Ringwald 
5864057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5865a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
5866a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
58674bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
58684bafedd5SMatthias Ringwald     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
58694bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
58704bafedd5SMatthias Ringwald #endif
5871057ab60cSMatthias Ringwald #endif
5872057ab60cSMatthias Ringwald 
5873a41310b7SMatthias Ringwald     // LE Whitelist Management
5874a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
58759956955bSMatthias Ringwald         // add/remove entries
5876665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5877665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
5878665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
5879453459ddSMatthias Ringwald 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
5880453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5881453459ddSMatthias Ringwald 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
5882453459ddSMatthias Ringwald 				return true;
5883453459ddSMatthias Ringwald 			}
58849956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
5885453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
5886453459ddSMatthias Ringwald                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
58879956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
5888f30077b7SMatthias Ringwald                 return true;
58899956955bSMatthias Ringwald             }
5890453459ddSMatthias Ringwald             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
5891665d90f2SMatthias Ringwald 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
58929956955bSMatthias Ringwald 				btstack_memory_whitelist_entry_free(entry);
58939956955bSMatthias Ringwald             }
58949956955bSMatthias Ringwald         }
589591915b0bSMatthias Ringwald     }
58969956955bSMatthias Ringwald 
589721debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
589821debf25SMatthias Ringwald     // LE Resolving List Management
5899ea151974SMatthias Ringwald     if (resolving_list_supported) {
590021debf25SMatthias Ringwald 		uint16_t i;
590121debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
590221debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
590321debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
590421debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
590521debf25SMatthias Ringwald 				return true;
590621debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
590721debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
590821debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
590921debf25SMatthias Ringwald 				return true;
591021debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
591102b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
5912ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
5913ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
5914ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
5915ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
591621debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
591721debf25SMatthias Ringwald 				return true;
591802b02cffSMatthias Ringwald 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
591902b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
592002b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
592102b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
592202b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
592302b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
592402b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
592502b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
592602b02cffSMatthias Ringwald 					sm_key_t peer_irk;
592702b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
592802b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5929f5228c62SMatthias Ringwald 
5930f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
5931f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
5932f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
5933f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
5934f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
5935f5228c62SMatthias Ringwald 						if (entry->address_type != peer_identity_addr_type) continue;
5936f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
5937f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
5938f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
5939f5228c62SMatthias Ringwald 					}
5940f5228c62SMatthias Ringwald #endif
5941f5228c62SMatthias Ringwald 
5942ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
5943ea151974SMatthias Ringwald 								 peer_identity_addreses);
594402b02cffSMatthias Ringwald 					return true;
594502b02cffSMatthias Ringwald 				}
594602b02cffSMatthias Ringwald 
594702b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
594802b02cffSMatthias Ringwald 
594902b02cffSMatthias Ringwald 				/* fall through */
595002b02cffSMatthias Ringwald 
595121debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_ADD_ENTRIES:
595221debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
595321debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
595421debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
595502b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
595602b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
595721debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
595821debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
595921debf25SMatthias Ringwald 					sm_key_t peer_irk;
596021debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
596121debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
5962*e938c062SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
596321debf25SMatthias Ringwald 					const uint8_t *local_irk = gap_get_persistent_irk();
596421debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
596521debf25SMatthias Ringwald 					uint8_t local_irk_flipped[16];
596621debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
596721debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
596821debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
5969ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
5970ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
597121debf25SMatthias Ringwald 					return true;
597221debf25SMatthias Ringwald 				}
597302b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
597421debf25SMatthias Ringwald 				break;
597502b02cffSMatthias Ringwald 
597621debf25SMatthias Ringwald 			default:
597721debf25SMatthias Ringwald 				break;
597821debf25SMatthias Ringwald 		}
5979ea151974SMatthias Ringwald 	}
598021debf25SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
598121debf25SMatthias Ringwald #endif
5982a41310b7SMatthias Ringwald 
5983f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5984f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5985f40c73b4SMatthias Ringwald     // LE Whitelist Management
5986f40c73b4SMatthias Ringwald     if (periodic_list_modification_pending){
5987f40c73b4SMatthias Ringwald         // add/remove entries
5988f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5989f40c73b4SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
5990f40c73b4SMatthias Ringwald             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5991f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
5992f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5993f40c73b4SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
5994f40c73b4SMatthias Ringwald                 return true;
5995f40c73b4SMatthias Ringwald             }
5996f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
5997f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5998f40c73b4SMatthias Ringwald                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
59999e88556bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6000f40c73b4SMatthias Ringwald                 return true;
6001f40c73b4SMatthias Ringwald             }
6002f40c73b4SMatthias Ringwald             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6003f40c73b4SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6004f40c73b4SMatthias Ringwald                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6005f40c73b4SMatthias Ringwald             }
6006f40c73b4SMatthias Ringwald         }
6007f40c73b4SMatthias Ringwald     }
6008f40c73b4SMatthias Ringwald #endif
6009f40c73b4SMatthias Ringwald #endif
6010f40c73b4SMatthias Ringwald 
601173799937SMatthias Ringwald     // post-pone all actions until stack is fully working
601273799937SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
601373799937SMatthias Ringwald 
601473799937SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
601573799937SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
601673799937SMatthias Ringwald 
6017a41310b7SMatthias Ringwald     // Phase 4: restore state
601829c24bebSMatthias Ringwald 
601929c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6020af64f147SMatthias Ringwald     // re-start scanning
602129c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
602229c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
602363671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
602463671e69SMatthias Ringwald         if (hci_extended_advertising_supported()){
602563671e69SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0);
602663671e69SMatthias Ringwald         } else
602763671e69SMatthias Ringwald #endif
602863671e69SMatthias Ringwald         {
602929c24bebSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
603063671e69SMatthias Ringwald         }
603129c24bebSMatthias Ringwald         return true;
603229c24bebSMatthias Ringwald     }
603329c24bebSMatthias Ringwald #endif
603429c24bebSMatthias Ringwald 
603513eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6036af64f147SMatthias Ringwald     // re-start connecting
6037af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
60389956955bSMatthias Ringwald         bd_addr_t null_addr;
60399956955bSMatthias Ringwald         memset(null_addr, 0, 6);
60406bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
60416bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
60429956955bSMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
6043cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
6044cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
60459956955bSMatthias Ringwald                      1,         // use whitelist
60469956955bSMatthias Ringwald                      0,         // peer address type
60479956955bSMatthias Ringwald                      null_addr, // peer bd addr
60486bcfa632SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
604973044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_min,    // conn interval min
605073044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_max,    // conn interval max
605173044eb2SMatthias Ringwald                      hci_stack->le_connection_latency,         // conn latency
605273044eb2SMatthias Ringwald                      hci_stack->le_supervision_timeout,        // conn latency
605373044eb2SMatthias Ringwald                      hci_stack->le_minimum_ce_length,          // min ce length
605473044eb2SMatthias Ringwald                      hci_stack->le_maximum_ce_length           // max ce length
60559956955bSMatthias Ringwald         );
6056f30077b7SMatthias Ringwald         return true;
60579956955bSMatthias Ringwald     }
60584bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
60594bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
60604bafedd5SMatthias Ringwald         switch(hci_stack->le_periodic_sync_request){
60614bafedd5SMatthias Ringwald             case LE_CONNECTING_DIRECT:
60624bafedd5SMatthias Ringwald             case LE_CONNECTING_WHITELIST:
60634bafedd5SMatthias Ringwald                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
60644bafedd5SMatthias Ringwald                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
60654bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_options,
60664bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertising_sid,
60674bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address_type,
60684bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address,
60694bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_skip,
60704bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_timeout,
60714bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_cte_type);
60724bafedd5SMatthias Ringwald                 return true;
60734bafedd5SMatthias Ringwald             default:
60744bafedd5SMatthias Ringwald                 break;
60754bafedd5SMatthias Ringwald         }
60764bafedd5SMatthias Ringwald     }
60774bafedd5SMatthias Ringwald #endif
6078d70217a2SMatthias Ringwald #endif
6079a41310b7SMatthias Ringwald 
6080a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6081a41310b7SMatthias Ringwald     // re-start advertising
6082935aa76eSMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6083a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
6084935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6085b892db1cSMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6086e464cd48SMatthias Ringwald 
6087e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6088e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
6089e464cd48SMatthias Ringwald             const uint8_t advertising_handles[] = { 0 };
6090e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6091e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6092e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6093e464cd48SMatthias Ringwald         } else
6094e464cd48SMatthias Ringwald #endif
6095e464cd48SMatthias Ringwald         {
6096a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6097e464cd48SMatthias Ringwald         }
6098a41310b7SMatthias Ringwald         return true;
6099a41310b7SMatthias Ringwald     }
6100be7ef9d8SMatthias Ringwald 
6101be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6102be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported()) {
6103be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6104be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6105be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)) {
6106be7ef9d8SMatthias Ringwald             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6107be7ef9d8SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
61088caa405cSMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6109be7ef9d8SMatthias Ringwald                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6110be7ef9d8SMatthias Ringwald                 const uint16_t durations[] = { advertising_set->enable_timeout };
6111be7ef9d8SMatthias Ringwald                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6112be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6113be7ef9d8SMatthias Ringwald                 return true;
6114be7ef9d8SMatthias Ringwald             }
6115c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
611653f240c0SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
611753f240c0SMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
611853f240c0SMatthias Ringwald                 uint8_t enable = 1;
611953f240c0SMatthias Ringwald                 if (advertising_set->periodic_include_adi){
612053f240c0SMatthias Ringwald                     enable |= 2;
612153f240c0SMatthias Ringwald                 }
612253f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
612353f240c0SMatthias Ringwald                 return true;
612453f240c0SMatthias Ringwald             }
6125c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6126be7ef9d8SMatthias Ringwald         }
6127be7ef9d8SMatthias Ringwald     }
6128be7ef9d8SMatthias Ringwald #endif
6129a41310b7SMatthias Ringwald #endif
6130a41310b7SMatthias Ringwald 
6131f30077b7SMatthias Ringwald     return false;
61327bdc6798S[email protected] }
61337aa35f6aSMatthias Ringwald 
61347aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
61357aa35f6aSMatthias Ringwald static bool hci_run_iso_tasks(void){
61367aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
61372a6c0f82SMatthias Ringwald 
61382a6c0f82SMatthias Ringwald     // BIG
61397aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
61407aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
61417aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
61427aa35f6aSMatthias Ringwald         switch (big->state){
61437aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
61447aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
61457aa35f6aSMatthias Ringwald                 hci_send_cmd(&hci_le_create_big,
61467aa35f6aSMatthias Ringwald                              big->params->big_handle,
61477aa35f6aSMatthias Ringwald                              big->params->advertising_handle,
61487aa35f6aSMatthias Ringwald                              big->params->num_bis,
61497aa35f6aSMatthias Ringwald                              big->params->sdu_interval_us,
61507aa35f6aSMatthias Ringwald                              big->params->max_sdu,
61517aa35f6aSMatthias Ringwald                              big->params->max_transport_latency_ms,
61527aa35f6aSMatthias Ringwald                              big->params->rtn,
61537aa35f6aSMatthias Ringwald                              big->params->phy,
61547aa35f6aSMatthias Ringwald                              big->params->packing,
61557aa35f6aSMatthias Ringwald                              big->params->framing,
61567aa35f6aSMatthias Ringwald                              big->params->encryption,
61577aa35f6aSMatthias Ringwald                              big->params->broadcast_code);
61587aa35f6aSMatthias Ringwald                 return true;
61597aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
61607aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
61617aa35f6aSMatthias Ringwald                 hci_send_cmd(&hci_le_setup_iso_data_path, big->bis_con_handles[big->state_vars.next_bis], 0, 0,  0, 0, 0,  0, 0, NULL);
61627aa35f6aSMatthias Ringwald                 return true;
61637aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
61647aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
61652a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6166c1f83111SMatthias Ringwald                 return true;
61677aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
61687aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
61692a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
61707aa35f6aSMatthias Ringwald                 return true;
61717aa35f6aSMatthias Ringwald             default:
61727aa35f6aSMatthias Ringwald                 break;
61737aa35f6aSMatthias Ringwald         }
61747aa35f6aSMatthias Ringwald     }
61752a6c0f82SMatthias Ringwald 
61762a6c0f82SMatthias Ringwald     // BIG Sync
61772a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
61782a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
61792a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
61802a6c0f82SMatthias Ringwald         switch (big_sync->state){
61812a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
61822a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
61832a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_create_sync,
61842a6c0f82SMatthias Ringwald                              big_sync->params->big_handle,
61852a6c0f82SMatthias Ringwald                              big_sync->params->sync_handle,
61862a6c0f82SMatthias Ringwald                              big_sync->params->encryption,
61872a6c0f82SMatthias Ringwald                              big_sync->params->broadcast_code,
61882a6c0f82SMatthias Ringwald                              big_sync->params->mse,
61892a6c0f82SMatthias Ringwald                              big_sync->params->big_sync_timeout_10ms,
61902a6c0f82SMatthias Ringwald                              big_sync->params->num_bis,
61912a6c0f82SMatthias Ringwald                              big_sync->params->bis_indices);
61922a6c0f82SMatthias Ringwald                 return true;
61932a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
61942a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
61952a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_setup_iso_data_path, big_sync->bis_con_handles[big_sync->state_vars.next_bis], 1, 0, 0, 0, 0, 0, 0, NULL);
61962a6c0f82SMatthias Ringwald                 return true;
61972a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
61982a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
61992a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6200c1f83111SMatthias Ringwald                 return true;
62012a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
62022a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
62032a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
62042a6c0f82SMatthias Ringwald                 return true;
62052a6c0f82SMatthias Ringwald             default:
62062a6c0f82SMatthias Ringwald                 break;
62072a6c0f82SMatthias Ringwald         }
62082a6c0f82SMatthias Ringwald     }
62092a6c0f82SMatthias Ringwald 
62107aa35f6aSMatthias Ringwald     return false;
62117aa35f6aSMatthias Ringwald }
62127aa35f6aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6213b2f949feS[email protected] #endif
62147bdc6798S[email protected] 
621588a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
6216f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
6217a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
621805ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
621932ab9390Smatthias.ringwald 
62200bf6344aS[email protected]         switch(connection->state){
62210bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
62224f3229d8S[email protected]                 switch(connection->address_type){
622335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6224f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
62259da54300S[email protected]                         log_info("sending hci_create_connection");
6226b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
62274f3229d8S[email protected]                         break;
622835454696SMatthias Ringwald #endif
62294f3229d8S[email protected]                     default:
6230a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
6231d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
62329da54300S[email protected]                         log_info("sending hci_le_create_connection");
62336bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
62346bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6235e90f848dSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6236e90f848dSMatthias Ringwald                         if (hci_extended_advertising_supported()) {
6237e90f848dSMatthias Ringwald                             uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval };
6238e90f848dSMatthias Ringwald                             uint16_t le_connection_scan_window[1]   = { hci_stack->le_connection_scan_window };
6239e90f848dSMatthias Ringwald                             uint16_t le_connection_interval_min[1]  = { hci_stack->le_connection_interval_min };
6240e90f848dSMatthias Ringwald                             uint16_t le_connection_interval_max[1]  = { hci_stack->le_connection_interval_max };
6241e90f848dSMatthias Ringwald                             uint16_t le_connection_latency[1]       = { hci_stack->le_connection_latency };
6242e90f848dSMatthias Ringwald                             uint16_t le_supervision_timeout[1]      = { hci_stack->le_supervision_timeout };
6243e90f848dSMatthias Ringwald                             uint16_t le_minimum_ce_length[1]        = { hci_stack->le_minimum_ce_length };
6244e90f848dSMatthias Ringwald                             uint16_t le_maximum_ce_length[1]        = { hci_stack->le_maximum_ce_length };
6245e90f848dSMatthias Ringwald                             hci_send_cmd(&hci_le_extended_create_connection,
6246e90f848dSMatthias Ringwald                                          0,         // don't use whitelist
6247e90f848dSMatthias Ringwald                                          hci_stack->le_connection_own_addr_type,   // our addr type:
6248e90f848dSMatthias Ringwald                                          connection->address_type,      // peer address type
6249e90f848dSMatthias Ringwald                                          connection->address,           // peer bd addr
6250e90f848dSMatthias Ringwald                                          1,                             // initiating PHY - 1M
6251e90f848dSMatthias Ringwald                                          le_connection_scan_interval,   // conn scan interval
6252e90f848dSMatthias Ringwald                                          le_connection_scan_window,     // conn scan windows
6253e90f848dSMatthias Ringwald                                          le_connection_interval_min,    // conn interval min
6254e90f848dSMatthias Ringwald                                          le_connection_interval_max,    // conn interval max
6255e90f848dSMatthias Ringwald                                          le_connection_latency,         // conn latency
6256e90f848dSMatthias Ringwald                                          le_supervision_timeout,        // conn latency
6257e90f848dSMatthias Ringwald                                          le_minimum_ce_length,          // min ce length
6258e90f848dSMatthias Ringwald                                          le_maximum_ce_length           // max ce length
6259e90f848dSMatthias Ringwald                             );                        }
6260e90f848dSMatthias Ringwald                         else
6261e90f848dSMatthias Ringwald #endif
6262e90f848dSMatthias Ringwald                         {
62634f3229d8S[email protected]                             hci_send_cmd(&hci_le_create_connection,
6264cbe54ab2SJakob Krantz                                          hci_stack->le_connection_scan_interval,    // conn scan interval
6265cbe54ab2SJakob Krantz                                          hci_stack->le_connection_scan_window,      // conn scan windows
62664f3229d8S[email protected]                                          0,         // don't use whitelist
62674f3229d8S[email protected]                                          connection->address_type, // peer address type
62684f3229d8S[email protected]                                          connection->address,      // peer bd addr
62696bcfa632SMatthias Ringwald                                          hci_stack->le_connection_own_addr_type,   // our addr type:
627073044eb2SMatthias Ringwald                                          hci_stack->le_connection_interval_min,    // conn interval min
627173044eb2SMatthias Ringwald                                          hci_stack->le_connection_interval_max,    // conn interval max
627273044eb2SMatthias Ringwald                                          hci_stack->le_connection_latency,         // conn latency
627373044eb2SMatthias Ringwald                                          hci_stack->le_supervision_timeout,        // conn latency
627473044eb2SMatthias Ringwald                                          hci_stack->le_minimum_ce_length,          // min ce length
627573044eb2SMatthias Ringwald                                          hci_stack->le_maximum_ce_length          // max ce length
62764f3229d8S[email protected]                             );
6277e90f848dSMatthias Ringwald                         }
62784f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
6279b2f949feS[email protected] #endif
6280d70217a2SMatthias Ringwald #endif
62814f3229d8S[email protected]                         break;
62824f3229d8S[email protected]                 }
6283f30077b7SMatthias Ringwald                 return true;
6284ad83dc6aS[email protected] 
628535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
62860bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
62875cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
6288f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
628976ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
6290895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6291c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6292f30077b7SMatthias Ringwald                     return true;
6293ee025741SMatthias Ringwald                 }
6294ee025741SMatthias Ringwald                 break;
629535454696SMatthias Ringwald #endif
62960bf6344aS[email protected] 
6297a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
6298d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
62990bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
63000bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
63010bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
6302f30077b7SMatthias Ringwald                 return true;
6303a6725849S[email protected] #endif
6304d70217a2SMatthias Ringwald #endif
63050bf6344aS[email protected]             case SEND_DISCONNECT:
63060bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
63076ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6308f30077b7SMatthias Ringwald                 return true;
63090bf6344aS[email protected] 
63100bf6344aS[email protected]             default:
63110bf6344aS[email protected]                 break;
6312c7e0c5f6Smatthias.ringwald         }
6313c7e0c5f6Smatthias.ringwald 
6314cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
6315cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
6316cabf004eSMatthias Ringwald 
631794418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
631894418890SMatthias Ringwald 
6319ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
632050f49832SMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6321608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
63228daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
632330e72d78SMatthias Ringwald 
6324e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6325e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
632630e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
6327e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
632832ab9390Smatthias.ringwald             } else {
632932ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
633032ab9390Smatthias.ringwald             }
6331f30077b7SMatthias Ringwald             return true;
633232ab9390Smatthias.ringwald         }
63331d6b20aeS[email protected] 
63348daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
63359da54300S[email protected]             log_info("denying to pin request");
63368daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
633734d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6338f30077b7SMatthias Ringwald             return true;
63394c57c146S[email protected]         }
63404c57c146S[email protected] 
6341c950c316SMatthias Ringwald         // security assessment requires remote features
63422dd8985bSMatthias Ringwald         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6343c950c316SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6344c950c316SMatthias Ringwald             hci_ssp_assess_security_on_io_cap_request(connection);
6345c950c316SMatthias 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
6346c950c316SMatthias Ringwald         }
6347c950c316SMatthias Ringwald 
63488daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
63498daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
6350a8d20135SMatthias Ringwald             // set authentication requirements:
6351a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
6352532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
6353a8d20135SMatthias Ringwald             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
63549faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
63559faad3abS[email protected]                 authreq |= 1;
6356106d6d11S[email protected]             }
6357532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
63588daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
6359532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
6360532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6361532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
6362532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
6363532454f9SMatthias Ringwald                     bonding = false;
6364532454f9SMatthias Ringwald                 }
6365532454f9SMatthias Ringwald             }
6366532454f9SMatthias Ringwald             if (bonding){
6367a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
6368a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
6369532454f9SMatthias Ringwald                 } else {
6370a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
6371a8d20135SMatthias Ringwald                 }
6372532454f9SMatthias Ringwald             }
63731849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
63741849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
63751849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
63761849becdSMatthias Ringwald                     have_oob_data |= 1;
63771849becdSMatthias Ringwald             }
63781849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
63791849becdSMatthias Ringwald                 have_oob_data |= 2;
63801849becdSMatthias Ringwald             }
63811849becdSMatthias Ringwald #endif
63821849becdSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
638311b03efaSMatthias Ringwald             return true;
6384f8fb5f6eS[email protected]         }
638511b03efaSMatthias Ringwald 
63868daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
63878daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
638811b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
6389f30077b7SMatthias Ringwald             return true;
639032ab9390Smatthias.ringwald         }
639132ab9390Smatthias.ringwald 
63921849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
63937ca4a7edSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
63947ca4a7edSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
63951849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
63961849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
63971849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
63981849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
63991849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
64001849becdSMatthias Ringwald             // verify P-256 OOB
64011e83575aSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
64021849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
64031849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
64041849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
64051849becdSMatthias Ringwald                 }
64061849becdSMatthias Ringwald             }
64071849becdSMatthias Ringwald             // verify P-192 OOB
64081849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
64091849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
64101849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
64111849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
64121849becdSMatthias Ringwald                 }
64131849becdSMatthias Ringwald             }
64147ca4a7edSMatthias Ringwald 
64157ca4a7edSMatthias Ringwald             // assess security
64167ca4a7edSMatthias Ringwald             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
64177ca4a7edSMatthias Ringwald             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
64187ca4a7edSMatthias Ringwald             if (need_level_4 && !can_reach_level_4){
64197ca4a7edSMatthias Ringwald                 log_info("Level 4 required, but not possible -> abort");
64207ca4a7edSMatthias Ringwald                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
64217ca4a7edSMatthias Ringwald                 // send oob negative reply
64227ca4a7edSMatthias Ringwald                 c_256 = NULL;
64237ca4a7edSMatthias Ringwald                 c_192 = NULL;
64247ca4a7edSMatthias Ringwald             }
64257ca4a7edSMatthias Ringwald 
64261849becdSMatthias Ringwald             // Reply
64271849becdSMatthias Ringwald             if (c_256 != zero) {
64281849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
64291849becdSMatthias Ringwald             } else if (c_192 != zero){
64301849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
64311849becdSMatthias Ringwald             } else {
64321ae74bf3SMatthias Ringwald                 hci_stack->classic_oob_con_handle = connection->con_handle;
64331849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
64341849becdSMatthias Ringwald             }
64351849becdSMatthias Ringwald             return true;
64361849becdSMatthias Ringwald         }
64371849becdSMatthias Ringwald #endif
64381849becdSMatthias Ringwald 
64398daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
64408daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
644134d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
6442f30077b7SMatthias Ringwald             return true;
6443dbe1a790S[email protected]         }
6444dbe1a790S[email protected] 
6445367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
6446367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
6447367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
6448367aedc0SMatthias Ringwald             return true;
6449367aedc0SMatthias Ringwald         }
6450367aedc0SMatthias Ringwald 
64518daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
64528daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
645334d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
6454f30077b7SMatthias Ringwald             return true;
6455dbe1a790S[email protected]         }
6456afd4e962S[email protected] 
6457ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
6458ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
64591bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
64606ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
64616ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6462f30077b7SMatthias Ringwald             return true;
6463ad83dc6aS[email protected]         }
646476f27cffSMatthias Ringwald 
64652a75353aSMatthias Ringwald         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
646634d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
6467abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
646834d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
6469f30077b7SMatthias Ringwald             return true;
6470afd4e962S[email protected]         }
647176f27cffSMatthias Ringwald 
6472dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
6473dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
6474dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
6475f30077b7SMatthias Ringwald             return true;
6476dce78009S[email protected]         }
6477447016ffSMatthias Ringwald 
6478573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
6479573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
6480573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
6481f30077b7SMatthias Ringwald             return true;
6482573897a0SMatthias Ringwald         }
6483447016ffSMatthias Ringwald 
6484447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
6485447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
6486447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
6487447016ffSMatthias Ringwald             return true;
6488447016ffSMatthias Ringwald         }
6489447016ffSMatthias Ringwald 
6490447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
6491447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
6492447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
6493447016ffSMatthias Ringwald             return true;
6494447016ffSMatthias Ringwald         }
6495447016ffSMatthias Ringwald 
6496447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
6497447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
6498447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
6499447016ffSMatthias Ringwald             return true;
6500447016ffSMatthias Ringwald         }
650176f27cffSMatthias Ringwald #endif
650276f27cffSMatthias Ringwald 
650376f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
650476f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
65051714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
65061714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
65071714cbbdSMatthias Ringwald #endif
65086ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
65096ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
65106ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
6511f30077b7SMatthias Ringwald                 return true;
651276f27cffSMatthias Ringwald             }
65136ef3696aSMatthias Ringwald         }
6514da886c03S[email protected] 
65156cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
6516f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
6517f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
6518f8ee3071SMatthias Ringwald             case 0:
6519f8ee3071SMatthias Ringwald                 break;
6520f8ee3071SMatthias Ringwald             case 0xffff:
6521f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
6522f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
6523f30077b7SMatthias Ringwald                 return true;
6524f8ee3071SMatthias Ringwald             default:
6525f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
6526f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
6527f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
6528f30077b7SMatthias Ringwald                 return true;
6529f8ee3071SMatthias Ringwald         }
653088a03c8dSMatthias Ringwald 
6531140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
6532140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
6533140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
6534140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
6535140c0557SMatthias Ringwald             return true;
6536140c0557SMatthias Ringwald         }
6537140c0557SMatthias Ringwald 
6538965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
6539278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
6540965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
6541278ff8a9SMatthias 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);
6542278ff8a9SMatthias Ringwald             return true;
6543278ff8a9SMatthias Ringwald         }
6544278ff8a9SMatthias Ringwald 
654588a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
654688a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
654788a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
654888a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
654988a03c8dSMatthias Ringwald             return true;
655088a03c8dSMatthias Ringwald         }
655122df2fe2SMatthias Ringwald #endif
65529afaa4d4SMatthias Ringwald 
65539afaa4d4SMatthias Ringwald         if (connection->gap_connection_tasks != 0){
655422df2fe2SMatthias Ringwald #ifdef ENABLE_CLASSIC
65559afaa4d4SMatthias Ringwald             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
65569afaa4d4SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
65579afaa4d4SMatthias Ringwald                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
65589afaa4d4SMatthias Ringwald                 return true;
65599afaa4d4SMatthias Ringwald             }
656022df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
656122df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
656222df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
656322df2fe2SMatthias Ringwald                 return true;
65649afaa4d4SMatthias Ringwald             }
65656cdc2862SMatthias Ringwald #endif
656622df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
656722df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
656822df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
656922df2fe2SMatthias Ringwald                 return true;
657022df2fe2SMatthias Ringwald             }
657122df2fe2SMatthias Ringwald         }
6572f8ee3071SMatthias Ringwald 
6573a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
657473cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
657573cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
657673cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
6577da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
657873cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
6579c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
6580c37a3166S[email protected]                              0x0000, 0xffff);
6581f30077b7SMatthias Ringwald                 return true;
658273cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
658373cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
658473cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
658573cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
658673cd8a2aSMatthias Ringwald                              0x0000, 0xffff);
6587f30077b7SMatthias Ringwald                 return true;
658873cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
658973cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
65901e0338ebSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
65911e0338ebSMatthias Ringwald                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
6592f30077b7SMatthias Ringwald                 return true;
659373cd8a2aSMatthias Ringwald             default:
659473cd8a2aSMatthias Ringwald                 break;
6595c37a3166S[email protected]         }
65964ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
6597b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
6598b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
6599b90f6e0aSMatthias 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);
6600f30077b7SMatthias Ringwald             return true;
6601b90f6e0aSMatthias Ringwald         }
6602c37a3166S[email protected] #endif
6603dbe1a790S[email protected]     }
6604f30077b7SMatthias Ringwald     return false;
6605f30077b7SMatthias Ringwald }
6606c7e0c5f6Smatthias.ringwald 
6607f30077b7SMatthias Ringwald static void hci_run(void){
6608f30077b7SMatthias Ringwald 
6609df9e2780SMatthias Ringwald     // stack state sub statemachines
6610df9e2780SMatthias Ringwald     switch (hci_stack->state) {
6611df9e2780SMatthias Ringwald         case HCI_STATE_INITIALIZING:
6612df9e2780SMatthias Ringwald             hci_initializing_run();
6613d0dea5fbSMatthias Ringwald             break;
6614df9e2780SMatthias Ringwald         case HCI_STATE_HALTING:
6615df9e2780SMatthias Ringwald             hci_halting_run();
6616d0dea5fbSMatthias Ringwald             break;
6617df9e2780SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
6618df9e2780SMatthias Ringwald             hci_falling_asleep_run();
6619d0dea5fbSMatthias Ringwald             break;
6620df9e2780SMatthias Ringwald         default:
6621df9e2780SMatthias Ringwald             break;
6622df9e2780SMatthias Ringwald     }
6623df9e2780SMatthias Ringwald 
6624d0dea5fbSMatthias Ringwald     // allow to run after initialization to working transition
6625d0dea5fbSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING){
6626d0dea5fbSMatthias Ringwald         return;
6627d0dea5fbSMatthias Ringwald     }
6628d0dea5fbSMatthias Ringwald 
6629f30077b7SMatthias Ringwald     bool done;
6630f30077b7SMatthias Ringwald 
6631f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
6632f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
6633f30077b7SMatthias Ringwald     if (done) return;
6634f30077b7SMatthias Ringwald 
663568ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
663668ab6207SMatthias Ringwald     done = hci_run_iso_fragments();
663768ab6207SMatthias Ringwald     if (done) return;
663868ab6207SMatthias Ringwald #endif
663968ab6207SMatthias Ringwald 
6640f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
6641f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
6642f30077b7SMatthias Ringwald     if (!hci_can_send_comand_packet_transport()) return;
6643f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
6644f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
6645f30077b7SMatthias Ringwald         return;
6646f30077b7SMatthias Ringwald     }
6647f30077b7SMatthias Ringwald #endif
6648f30077b7SMatthias Ringwald 
6649f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
6650f30077b7SMatthias Ringwald 
6651f30077b7SMatthias Ringwald     // global/non-connection oriented commands
6652f30077b7SMatthias Ringwald 
6653f30077b7SMatthias Ringwald 
6654f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
6655f30077b7SMatthias Ringwald     // general gap classic
6656f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
6657f30077b7SMatthias Ringwald     if (done) return;
6658f30077b7SMatthias Ringwald #endif
6659f30077b7SMatthias Ringwald 
6660f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
6661f30077b7SMatthias Ringwald     // general gap le
6662f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
6663f30077b7SMatthias Ringwald     if (done) return;
66647aa35f6aSMatthias Ringwald 
66657aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
66667aa35f6aSMatthias Ringwald     // ISO related tasks, e.g. BIG create/terminate/sync
66677aa35f6aSMatthias Ringwald     done = hci_run_iso_tasks();
66687aa35f6aSMatthias Ringwald     if (done) return;
66697aa35f6aSMatthias Ringwald #endif
6670f30077b7SMatthias Ringwald #endif
6671f30077b7SMatthias Ringwald 
6672f30077b7SMatthias Ringwald     // send pending HCI commands
6673df9e2780SMatthias Ringwald     hci_run_general_pending_commands();
66743429f56bSmatthias.ringwald }
667516833f0aSmatthias.ringwald 
66763e2050f7SMatthias Ringwald uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
667735454696SMatthias Ringwald     // house-keeping
667835454696SMatthias Ringwald 
667935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6680c8e4258aSmatthias.ringwald     bd_addr_t addr;
6681c8e4258aSmatthias.ringwald     hci_connection_t * conn;
6682c123d999SMatthias Ringwald #endif
6683c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
66846f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
66859cbd2215SMatthias Ringwald #endif
66864ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
66874ae8623eSMatthias Ringwald     uint8_t i;
66884ae8623eSMatthias Ringwald     uint8_t num_cis;
66894ae8623eSMatthias Ringwald     hci_con_handle_t cis_handle;
66904ae8623eSMatthias Ringwald     uint8_t status;
66914ae8623eSMatthias Ringwald #endif
6692c8e4258aSmatthias.ringwald 
66936f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
66946f35bb46SMatthias Ringwald     switch (opcode) {
66959cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
66969cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
66979cbd2215SMatthias Ringwald             break;
66989cbd2215SMatthias Ringwald 
66999cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
67006f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
6701724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
67029da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
6703c8e4258aSmatthias.ringwald 
670472cf8859SMatthias Ringwald             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
670572cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
670679e0fa07SMatthias Ringwald                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
67073e2050f7SMatthias Ringwald                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
670872cf8859SMatthias Ringwald             }
670972cf8859SMatthias Ringwald 
6710f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
6711ad83dc6aS[email protected]             if (!conn) {
6712f16129ceSMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
671317f1ba2aSmatthias.ringwald                 if (!conn) {
671417f1ba2aSmatthias.ringwald                     // notify client that alloc failed
67152deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
67163e2050f7SMatthias Ringwald                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
671717f1ba2aSmatthias.ringwald                 }
6718ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
6719f3e2cd2aSMatthias Ringwald                 conn->role  = HCI_ROLE_MASTER;
6720ad83dc6aS[email protected]             }
6721aee5d5c1SMatthias Ringwald 
6722ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
67233e2050f7SMatthias Ringwald             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
6724ad83dc6aS[email protected]             switch (conn->state) {
6725ad83dc6aS[email protected]                 // if connection active exists
6726ad83dc6aS[email protected]                 case OPEN:
6727f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
672872cf8859SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
67293e2050f7SMatthias Ringwald                     // packet not sent to controller
67303e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6731672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
6732672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
6733672e36abSMatthias Ringwald                     break;
6734ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
67356c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
67366c0d5426SMatthias Ringwald                     if (hci_classic_operation_active()){
67376c0d5426SMatthias Ringwald                         return ERROR_CODE_SUCCESS;
67386c0d5426SMatthias Ringwald                     }
67396c0d5426SMatthias Ringwald #endif
6740532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
6741532f91a5SMatthias Ringwald                     break;
6742ad83dc6aS[email protected]                 default:
6743ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
67443e2050f7SMatthias Ringwald                     // packet not sent to controller
67453e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
6746ad83dc6aS[email protected]             }
6747c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
6748229331c6SMatthias Ringwald 
6749229331c6SMatthias Ringwald             // track outgoing connection
6750f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
67516535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
67526f35bb46SMatthias Ringwald             break;
6753ee752bb8SMatthias Ringwald 
67545b7087c7SMatthias Ringwald #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
67556f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
6756ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
6757ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
6758ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
67596f35bb46SMatthias Ringwald             break;
67606f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
6761c91e6e4fSMatthias Ringwald             // accept_synchronous_connection? Voice setting at offset 18
6762ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
6763ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
67641f34df2cSMatthias Ringwald             // track outgoing connection
67651f34df2cSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
67661f34df2cSMatthias Ringwald             reverse_bd_addr(&packet[3], hci_stack->outgoing_addr);
67676f35bb46SMatthias Ringwald             break;
6768ee752bb8SMatthias Ringwald #endif
676935454696SMatthias Ringwald #endif
67704b3e1e19SMatthias Ringwald 
6771a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
6772d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
67736f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
6774b04dfa37SMatthias Ringwald             // white list used?
67756f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
6776b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
6777b04dfa37SMatthias Ringwald                 case 0:
6778b04dfa37SMatthias Ringwald                     // whitelist not used
6779b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
6780b04dfa37SMatthias Ringwald                     break;
6781b04dfa37SMatthias Ringwald                 case 1:
6782b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
6783b04dfa37SMatthias Ringwald                     break;
6784b04dfa37SMatthias Ringwald                 default:
6785b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
6786b04dfa37SMatthias Ringwald                     break;
6787b04dfa37SMatthias Ringwald             }
6788c163146eSMatthias Ringwald             // track outgoing connection
678905002aecSMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
6790c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
67916f35bb46SMatthias Ringwald             break;
67926f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
67936ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
67946f35bb46SMatthias Ringwald             break;
67959cbd2215SMatthias Ringwald #endif
67964ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
67974ae8623eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
67984ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
67994ae8623eSMatthias Ringwald             status = ERROR_CODE_SUCCESS;
68004ae8623eSMatthias Ringwald             num_cis = packet[3];
68014ae8623eSMatthias Ringwald             // setup hci_iso_streams
68024ae8623eSMatthias Ringwald             for (i=0;i<num_cis;i++){
68034ae8623eSMatthias Ringwald                 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i));
6804a90016deSMatthias Ringwald                 status = hci_iso_stream_create(cis_handle, 0xff);
68054ae8623eSMatthias Ringwald                 if (status != ERROR_CODE_SUCCESS) {
68064ae8623eSMatthias Ringwald                     break;
68074ae8623eSMatthias Ringwald                 }
68084ae8623eSMatthias Ringwald             }
68094ae8623eSMatthias Ringwald             // free structs on error
68104ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
6811a90016deSMatthias Ringwald                 hci_iso_stream_requested_finalize(0xff);
68124ae8623eSMatthias Ringwald                 return status;
68134ae8623eSMatthias Ringwald             }
68144ae8623eSMatthias Ringwald             break;
68154ae8623eSMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
68164ae8623eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
68174ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
68184ae8623eSMatthias Ringwald             cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3);
6819a90016deSMatthias Ringwald             status = hci_iso_stream_create(cis_handle, 0xff);
68204ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
68214ae8623eSMatthias Ringwald                 return status;
68224ae8623eSMatthias Ringwald             }
68234ae8623eSMatthias Ringwald             break;
68244ae8623eSMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
68254ae8623eSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
68264ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
68276f35bb46SMatthias Ringwald         default:
68286f35bb46SMatthias Ringwald             break;
6829b04dfa37SMatthias Ringwald     }
683069a97523S[email protected] 
68313a9fb326S[email protected]     hci_stack->num_cmd_packets--;
68325bb5bc3eS[email protected] 
68335bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
68343e2050f7SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
68353e2050f7SMatthias Ringwald     if (err != 0){
68363e2050f7SMatthias Ringwald         return ERROR_CODE_HARDWARE_FAILURE;
68373e2050f7SMatthias Ringwald     }
68383e2050f7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
683931452debSmatthias.ringwald }
68408adf0ddaSmatthias.ringwald 
68412bd8b7e7S[email protected] // disconnect because of security block
68422bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
68432bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
68442bd8b7e7S[email protected]     if (!connection) return;
68452bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
68462bd8b7e7S[email protected] }
68472bd8b7e7S[email protected] 
68482bd8b7e7S[email protected] 
6849dbe1a790S[email protected] // Configure Secure Simple Pairing
6850dbe1a790S[email protected] 
685135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
685235454696SMatthias Ringwald 
6853dbe1a790S[email protected] // enable will enable SSP during init
685415a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
68553a9fb326S[email protected]     hci_stack->ssp_enable = enable;
6856dbe1a790S[email protected] }
6857dbe1a790S[email protected] 
685895d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
685915a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
68602bd8b7e7S[email protected] }
68612bd8b7e7S[email protected] 
6862dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
686315a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
68643a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
6865dbe1a790S[email protected] }
686615a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
68673a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
6868dbe1a790S[email protected] }
6869dbe1a790S[email protected] 
6870dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
687115a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
68723a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
6873dbe1a790S[email protected] }
68745d23aae8SMatthias Ringwald 
68755d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
68765d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
68775d23aae8SMatthias Ringwald }
687822d445d8SMatthias Ringwald bool gap_secure_connections_active(void){
6879eaf85bc8SMatthias Ringwald     return hci_stack->secure_connections_active;
688022d445d8SMatthias Ringwald }
68815d23aae8SMatthias Ringwald 
688235454696SMatthias Ringwald #endif
6883dbe1a790S[email protected] 
688494be1a66SMatthias Ringwald // va_list part of hci_send_cmd
68853e2050f7SMatthias Ringwald uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
6886d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
68879d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
68883e2050f7SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
68899d14b626S[email protected]     }
68909d14b626S[email protected] 
68915127cc62S[email protected]     // for HCI INITIALIZATION
68929da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
68935127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
68945127cc62S[email protected] 
68959d14b626S[email protected]     hci_reserve_packet_buffer();
68969d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
689794be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
68983e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_packet(packet, size);
6899bfea0222SMatthias Ringwald 
6900593702caSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
69013e2050f7SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
6902e2d22487SMatthias Ringwald         hci_release_packet_buffer();
6903068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
6904bfea0222SMatthias Ringwald     }
6905bfea0222SMatthias Ringwald 
69063e2050f7SMatthias Ringwald     return status;
690794be1a66SMatthias Ringwald }
69089d14b626S[email protected] 
690994be1a66SMatthias Ringwald /**
691094be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
691194be1a66SMatthias Ringwald  */
69123e2050f7SMatthias Ringwald uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
69131cd208adSmatthias.ringwald     va_list argptr;
69141cd208adSmatthias.ringwald     va_start(argptr, cmd);
69153e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
69161cd208adSmatthias.ringwald     va_end(argptr);
69173e2050f7SMatthias Ringwald     return status;
691893b8dc03Smatthias.ringwald }
6919c8e4258aSmatthias.ringwald 
6920ee091cf1Smatthias.ringwald // Create various non-HCI events.
6921ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
6922ee091cf1Smatthias.ringwald 
6923d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
6924fb37a842SMatthias Ringwald     // dump packet
6925d6b06661SMatthias Ringwald     if (dump) {
692692da54c4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
6927d6b06661SMatthias Ringwald     }
69281ef6bb52SMatthias Ringwald 
6929fb37a842SMatthias Ringwald     // dispatch to all event handlers
69301ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
69311ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
69321ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
69331ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
6934d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
69351ef6bb52SMatthias Ringwald     }
6936d6b06661SMatthias Ringwald }
6937d6b06661SMatthias Ringwald 
6938d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
6939fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
69403d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
6941d6b06661SMatthias Ringwald }
6942d6b06661SMatthias Ringwald 
694335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6944701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
69453bc639ceSMatthias Ringwald     // notify SCO sender if waiting
6946701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
6947701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
69483bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
6949701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
6950701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
69513d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
69523bc639ceSMatthias Ringwald     }
69533bc639ceSMatthias Ringwald }
69541cfb383eSMatthias Ringwald 
69551cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
69569784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
6957ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
69581cfb383eSMatthias Ringwald 
69591cfb383eSMatthias Ringwald     uint8_t * eir_data;
69601cfb383eSMatthias Ringwald     ad_context_t context;
69611cfb383eSMatthias Ringwald     const uint8_t * name;
69621cfb383eSMatthias Ringwald     uint8_t         name_len;
69631cfb383eSMatthias Ringwald 
69649784dac1SMatthias Ringwald     if (size < 3) return;
69659784dac1SMatthias Ringwald 
69661cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
6967a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
69681cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
69691cfb383eSMatthias Ringwald 
69709784dac1SMatthias Ringwald     switch (event_type){
69719784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
69729784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
69739784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
69749784dac1SMatthias Ringwald             break;
69759784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
69769784dac1SMatthias Ringwald             if (size != 257) return;
69779784dac1SMatthias Ringwald             if (num_responses != 1) return;
69789784dac1SMatthias Ringwald             break;
69799784dac1SMatthias Ringwald         default:
69809784dac1SMatthias Ringwald             return;
69819784dac1SMatthias Ringwald     }
69829784dac1SMatthias Ringwald 
69831cfb383eSMatthias Ringwald     // event[1] is set at the end
69841cfb383eSMatthias Ringwald     int i;
69851cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
69861cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
69871cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
6988ac973fd6SMatthias Ringwald         uint8_t event_size = 27;    // if name is not set by EIR
69891cfb383eSMatthias Ringwald 
69906535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
69910e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
69926535961aSMatthias Ringwald         (void)memcpy(&event[9],
69936535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
69946535961aSMatthias Ringwald                      3); // class of device
69956535961aSMatthias Ringwald         (void)memcpy(&event[12],
69966535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
69976535961aSMatthias Ringwald                      2); // clock offset
69981cfb383eSMatthias Ringwald 
69991cfb383eSMatthias Ringwald         switch (event_type){
70001cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
70011cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
70021cfb383eSMatthias Ringwald                 break;
70031cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
70041cfb383eSMatthias Ringwald                 event[14] = 1;
7005a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
70061cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
70071cfb383eSMatthias Ringwald                 break;
70081cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
70091cfb383eSMatthias Ringwald                 event[14] = 1;
7010a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
701179186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
70121cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
70131cfb383eSMatthias Ringwald                 name = NULL;
7014a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
7015a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
70161cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
70171cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
70181cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
7019ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
70201cfb383eSMatthias Ringwald                     switch (data_type){
70211cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
70221cfb383eSMatthias Ringwald                             if (name) continue;
7023cf373d3aSMatthias Ringwald                             /* fall through */
70241cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
70251cfb383eSMatthias Ringwald                             name = data;
70261cfb383eSMatthias Ringwald                             name_len = data_size;
70271cfb383eSMatthias Ringwald                             break;
7028ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7029ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
7030ac9136ccSMatthias Ringwald                             event[16] = 1;
70313c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
7032ac9136ccSMatthias Ringwald                             break;
70331cfb383eSMatthias Ringwald                         default:
70341cfb383eSMatthias Ringwald                             break;
70351cfb383eSMatthias Ringwald                     }
70361cfb383eSMatthias Ringwald                 }
70371cfb383eSMatthias Ringwald                 if (name){
7038ac9136ccSMatthias Ringwald                     event[25] = 1;
70391cfb383eSMatthias Ringwald                     // truncate name if needed
70401cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7041ac9136ccSMatthias Ringwald                     event[26] = len;
7042ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
70431cfb383eSMatthias Ringwald                     event_size += len;
70441cfb383eSMatthias Ringwald                 }
70451cfb383eSMatthias Ringwald                 break;
70467bbeb3adSMilanka Ringwald             default:
70477bbeb3adSMilanka Ringwald                 return;
70481cfb383eSMatthias Ringwald         }
70491cfb383eSMatthias Ringwald         event[1] = event_size - 2;
70501cfb383eSMatthias Ringwald         hci_emit_event(event, event_size, 1);
70511cfb383eSMatthias Ringwald     }
70521cfb383eSMatthias Ringwald }
705335454696SMatthias Ringwald #endif
70543bc639ceSMatthias Ringwald 
705571de195eSMatthias Ringwald void hci_emit_state(void){
70563a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7057425d1371Smatthias.ringwald     uint8_t event[3];
705880d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
70594ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
70603a9fb326S[email protected]     event[2] = hci_stack->state;
7061d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7062c8e4258aSmatthias.ringwald }
7063c8e4258aSmatthias.ringwald 
706435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
70652deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7066425d1371Smatthias.ringwald     uint8_t event[13];
7067c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7068425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
706917f1ba2aSmatthias.ringwald     event[2] = status;
70702deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
70712deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
7072c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
7073c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
7074d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7075c8e4258aSmatthias.ringwald }
707652db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
707752db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
707852db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
707952db98b2SMatthias Ringwald     uint8_t event[4];
708052db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
708152db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
708252db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
708352db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
708452db98b2SMatthias Ringwald }
708535454696SMatthias Ringwald #endif
7086c8e4258aSmatthias.ringwald 
708735454696SMatthias Ringwald #ifdef ENABLE_BLE
7088d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7089667ba9d1SMatthias 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){
70904f3229d8S[email protected]     uint8_t event[21];
70914f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
70924ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
70934f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
70944f3229d8S[email protected]     event[3] = status;
7095fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
70964f3229d8S[email protected]     event[6] = 0; // TODO: role
70976e2e9a6bS[email protected]     event[7] = address_type;
7098724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
7099f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
7100f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
7101f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
71024f3229d8S[email protected]     event[20] = 0; // master clock accuracy
7103d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
71044f3229d8S[email protected] }
710535454696SMatthias Ringwald #endif
7106d70217a2SMatthias Ringwald #endif
71074f3229d8S[email protected] 
7108fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
7109fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
7110fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7111fd43c0e0SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7112fd43c0e0SMatthias Ringwald }
7113fd43c0e0SMatthias Ringwald 
7114fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7115425d1371Smatthias.ringwald     uint8_t event[6];
71163c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
71174ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
71183c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
7119fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
71203c4d4b90Smatthias.ringwald     event[5] = reason;
7121d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
71223c4d4b90Smatthias.ringwald }
71233c4d4b90Smatthias.ringwald 
7124b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
7125e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7126425d1371Smatthias.ringwald     uint8_t event[3];
712780d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
71284ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
712943bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
7130d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
713143bfb1bdSmatthias.ringwald }
7132038bc64cSmatthias.ringwald 
7133b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
7134e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
7135425d1371Smatthias.ringwald     uint8_t event[2];
713680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
71374ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
7138d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7139038bc64cSmatthias.ringwald }
71401b0e3922Smatthias.ringwald 
714135454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
714235454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
714335454696SMatthias Ringwald     uint8_t event[9];
714435454696SMatthias Ringwald     int pos = 0;
714535454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
71464ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
714735454696SMatthias Ringwald     event[pos++] = status;
714835454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
7149d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7150381fbed8Smatthias.ringwald }
7151458bf4e8S[email protected] 
715235454696SMatthias Ringwald 
715335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
715435454696SMatthias Ringwald 
7155b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7156df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7157a00031e2S[email protected]     uint8_t event[5];
7158e00caf9cS[email protected]     int pos = 0;
71595611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7160e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
7161f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
7162e00caf9cS[email protected]     pos += 2;
7163e00caf9cS[email protected]     event[pos++] = level;
7164d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7165e00caf9cS[email protected] }
7166e00caf9cS[email protected] 
716735454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
716835454696SMatthias Ringwald     if (!connection) return LEVEL_0;
71698daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7170fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
71718daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7172170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
71734051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7174170fafaeSMatthias Ringwald     // LEVEL 4 always requires 128 bit encrytion key size
71750e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7176170fafaeSMatthias Ringwald         security_level = LEVEL_3;
7177170fafaeSMatthias Ringwald     }
7178170fafaeSMatthias Ringwald     return security_level;
717935454696SMatthias Ringwald }
718035454696SMatthias Ringwald 
718171fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
718271fd255dSMatthias Ringwald     uint8_t event[4];
718371fd255dSMatthias Ringwald     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
718435454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
718571fd255dSMatthias Ringwald     event[2] = discoverable;
718671fd255dSMatthias Ringwald     event[3] = connectable;
7187d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7188ad83dc6aS[email protected] }
7189ad83dc6aS[email protected] 
719098a2fd1cSMatthias Ringwald // query if remote side supports eSCO
719120dcdd22SMatthias Ringwald bool hci_remote_esco_supported(hci_con_handle_t con_handle){
719298a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
719320dcdd22SMatthias Ringwald     if (!connection) return false;
719476ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
719598a2fd1cSMatthias Ringwald }
719698a2fd1cSMatthias Ringwald 
719767aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
719867aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
719967aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
720067aae551SMatthias Ringwald }
720167aae551SMatthias Ringwald 
72022bd8b7e7S[email protected] // query if remote side supports SSP
720320dcdd22SMatthias Ringwald bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
72042bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
720520dcdd22SMatthias Ringwald     if (!connection) return false;
720667aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
72072bd8b7e7S[email protected] }
72082bd8b7e7S[email protected] 
720920dcdd22SMatthias Ringwald bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7210df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7211df3354fcS[email protected] }
7212df3354fcS[email protected] 
72136ffc78ceSMatthias Ringwald /**
72146ffc78ceSMatthias Ringwald  * Check if remote supported features query has completed
72156ffc78ceSMatthias Ringwald  */
72166ffc78ceSMatthias Ringwald bool hci_remote_features_available(hci_con_handle_t handle){
72176ffc78ceSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(handle);
72186ffc78ceSMatthias Ringwald     if (!connection) return false;
72196ffc78ceSMatthias Ringwald     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
72206ffc78ceSMatthias Ringwald }
72216ffc78ceSMatthias Ringwald 
7222d6596031SMatthias Ringwald /**
7223d6596031SMatthias Ringwald  * Trigger remote supported features query
7224d6596031SMatthias Ringwald  */
7225c9742cd1SMatthias Ringwald 
7226c9742cd1SMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7227c9742cd1SMatthias Ringwald     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7228c9742cd1SMatthias Ringwald         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7229c9742cd1SMatthias Ringwald     }
7230c9742cd1SMatthias Ringwald }
7231c9742cd1SMatthias Ringwald 
7232d6596031SMatthias Ringwald void hci_remote_features_query(hci_con_handle_t con_handle){
7233d6596031SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7234d6596031SMatthias Ringwald     if (!connection) return;
7235c9742cd1SMatthias Ringwald     hci_trigger_remote_features_for_connection(connection);
7236d6596031SMatthias Ringwald     hci_run();
7237d6596031SMatthias Ringwald }
7238d6596031SMatthias Ringwald 
7239458bf4e8S[email protected] // GAP API
7240458bf4e8S[email protected] /**
7241458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
7242458bf4e8S[email protected]  * @praram enabled
7243458bf4e8S[email protected]  */
72444c57c146S[email protected] void gap_set_bondable_mode(int enable){
72453a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
7246458bf4e8S[email protected] }
72474ef6443cSMatthias Ringwald /**
72484ef6443cSMatthias Ringwald  * @brief Get bondable mode.
72494ef6443cSMatthias Ringwald  * @return 1 if bondable
72504ef6443cSMatthias Ringwald  */
72514ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
72524ef6443cSMatthias Ringwald     return hci_stack->bondable;
72534ef6443cSMatthias Ringwald }
7254cb230b9dS[email protected] 
7255cb230b9dS[email protected] /**
725634d2123cS[email protected]  * @brief map link keys to security levels
7257cb230b9dS[email protected]  */
725834d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
725934d2123cS[email protected]     switch (link_key_type){
72603c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
72613c68dfa9S[email protected]             return LEVEL_4;
72623c68dfa9S[email protected]         case COMBINATION_KEY:
72633c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
72643c68dfa9S[email protected]             return LEVEL_3;
72653c68dfa9S[email protected]         default:
72663c68dfa9S[email protected]             return LEVEL_2;
72673c68dfa9S[email protected]     }
7268cb230b9dS[email protected] }
7269cb230b9dS[email protected] 
72708b35e16aSMatthias Ringwald /**
72718b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
72728b35e16aSMatthias Ringwald  */
727336c3546bSMatthias Ringwald bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
72748b35e16aSMatthias Ringwald     switch (link_key_type){
72758b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
72768b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
727736c3546bSMatthias Ringwald             return true;
72788b35e16aSMatthias Ringwald         default:
727936c3546bSMatthias Ringwald             return false;
72808b35e16aSMatthias Ringwald     }
72818b35e16aSMatthias Ringwald }
72828b35e16aSMatthias Ringwald 
72838b35e16aSMatthias Ringwald /**
72848b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
72858b35e16aSMatthias Ringwald  */
72867040ba26SMatthias Ringwald bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
72878b35e16aSMatthias Ringwald     switch (link_key_type){
72888b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
72898b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
72907040ba26SMatthias Ringwald             return true;
72918b35e16aSMatthias Ringwald         default:
72927040ba26SMatthias Ringwald             return false;
72938b35e16aSMatthias Ringwald     }
72948b35e16aSMatthias Ringwald }
72958b35e16aSMatthias Ringwald 
7296552b9260SMatthias Ringwald bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
72975127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
7298106d6d11S[email protected]     return level > LEVEL_2;
7299106d6d11S[email protected] }
7300106d6d11S[email protected] 
730134d2123cS[email protected] /**
730234d2123cS[email protected]  * @brief get current security level
730334d2123cS[email protected]  */
730434d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
730534d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
730634d2123cS[email protected]     if (!connection) return LEVEL_0;
730734d2123cS[email protected]     return gap_security_level_for_connection(connection);
730834d2123cS[email protected] }
730934d2123cS[email protected] 
7310cb230b9dS[email protected] /**
7311cb230b9dS[email protected]  * @brief request connection to device to
7312cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
7313cb230b9dS[email protected]  */
731434d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
731534d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
731634d2123cS[email protected]     if (!connection){
7317a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
731834d2123cS[email protected]         return;
731934d2123cS[email protected]     }
7320defbf200SMatthias Ringwald 
7321defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
7322defbf200SMatthias Ringwald 
7323bc00e12cSMatthias 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)
7324bc00e12cSMatthias Ringwald     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
7325bc00e12cSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
7326bc00e12cSMatthias Ringwald         requested_level = LEVEL_4;
7327bc00e12cSMatthias Ringwald     }
7328bc00e12cSMatthias Ringwald 
732934d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
733083d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
733183d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
733283d08d7cSMatthias Ringwald 
7333dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
7334dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
7335dbd5dcc3SMatthias Ringwald     if (authentication_active){
73361cf0a6c8SMatthias Ringwald         // authentication already active
733783d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
733883d08d7cSMatthias Ringwald             // increase requested level as new level is higher
733983d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
734083d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
734183d08d7cSMatthias Ringwald         }
73421cf0a6c8SMatthias Ringwald     } else {
734383d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
734483d08d7cSMatthias Ringwald         if (requested_level <= current_level){
7345a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
734634d2123cS[email protected]             return;
734734d2123cS[email protected]         }
7348a00031e2S[email protected] 
7349e060c07dSMatthias Ringwald         // store request
735034d2123cS[email protected]         connection->requested_security_level = requested_level;
7351a00031e2S[email protected] 
73521cf0a6c8SMatthias Ringwald         // start to authenticate connection
73531eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
73547fdbaf79SMatthias Ringwald 
73557fdbaf79SMatthias Ringwald         // request remote features if not already active, also trigger hci_run
73567fdbaf79SMatthias Ringwald         hci_remote_features_query(con_handle);
7357e00caf9cS[email protected]     }
73581cf0a6c8SMatthias Ringwald }
7359ad83dc6aS[email protected] 
7360ad83dc6aS[email protected] /**
7361ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
7362ad83dc6aS[email protected]  * @param device
7363ad83dc6aS[email protected]  * @param request MITM protection
7364ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
7365ad83dc6aS[email protected]  */
7366ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
7367ad83dc6aS[email protected] 
7368ad83dc6aS[email protected]     // create connection state machine
7369f16129ceSMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
7370ad83dc6aS[email protected] 
7371ad83dc6aS[email protected]     if (!connection){
7372ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
7373ad83dc6aS[email protected]     }
7374ad83dc6aS[email protected] 
7375ad83dc6aS[email protected]     // delete linkn key
737615a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
7377ad83dc6aS[email protected] 
7378ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
7379ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
7380ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
7381f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
7382ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
7383ad83dc6aS[email protected] 
7384ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
7385ad83dc6aS[email protected] 
7386ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
7387ad83dc6aS[email protected]     // handle: authentication failure
7388ad83dc6aS[email protected]     // handle: disconnect on done
7389ad83dc6aS[email protected] 
7390ad83dc6aS[email protected]     hci_run();
7391ad83dc6aS[email protected] 
7392ad83dc6aS[email protected]     return 0;
7393ad83dc6aS[email protected] }
73948e618f72S[email protected] 
73958e618f72S[email protected] void gap_set_local_name(const char * local_name){
73968e618f72S[email protected]     hci_stack->local_name = local_name;
7397baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
739859d59ecfSMatthias Ringwald     // also update EIR if not set by user
739959d59ecfSMatthias Ringwald     if (hci_stack->eir_data == NULL){
7400baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
740159d59ecfSMatthias Ringwald     }
740259d59ecfSMatthias Ringwald     hci_run();
74038e618f72S[email protected] }
74041aeec2ebSMatthias Ringwald #endif
74058e618f72S[email protected] 
740635454696SMatthias Ringwald 
740735454696SMatthias Ringwald #ifdef ENABLE_BLE
740835454696SMatthias Ringwald 
7409d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7410d8e8f12aSMatthias Ringwald void gap_start_scan(void){
7411fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
74127bdc6798S[email protected]     hci_run();
74137bdc6798S[email protected] }
74148e618f72S[email protected] 
7415d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
7416fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
74177bdc6798S[email protected]     hci_run();
74187bdc6798S[email protected] }
74194f3229d8S[email protected] 
7420a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
7421ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
7422a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
7423ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
7424ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
74258b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
7426ef11999fSmatthias.ringwald     hci_run();
7427ef11999fSmatthias.ringwald }
74284f3229d8S[email protected] 
7429a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
7430a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
7431a7a719e9SMatthias Ringwald }
7432a7a719e9SMatthias Ringwald 
7433667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
74344f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
74354f3229d8S[email protected]     if (!conn){
7436d32b3f05SMatthias Ringwald         // disallow if le connection is already outgoing
7437d32b3f05SMatthias Ringwald         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
7438d32b3f05SMatthias Ringwald             log_error("le connection already active");
7439d32b3f05SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
7440d32b3f05SMatthias Ringwald         }
7441d32b3f05SMatthias Ringwald 
7442d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
74432e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
74444f3229d8S[email protected]         if (!conn){
74454f3229d8S[email protected]             // notify client that alloc failed
74466e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
7447d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
7448472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
74494f3229d8S[email protected]         }
7450d5b1a89eSMatthias Ringwald 
7451d5b1a89eSMatthias Ringwald         // set le connecting state
7452d5b1a89eSMatthias Ringwald         if (hci_is_le_connection_type(addr_type)){
7453d5b1a89eSMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
7454d5b1a89eSMatthias Ringwald         }
7455d5b1a89eSMatthias Ringwald 
74564f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
7457d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
7458564fca32S[email protected]         hci_run();
7459b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
74604f3229d8S[email protected]     }
74610bf6344aS[email protected] 
74620bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
7463a1df452eSMatthias Ringwald         (conn->state == SEND_CREATE_CONNECTION) ||
74640e588213SMatthias Ringwald         (conn->state == SENT_CREATE_CONNECTION)) {
74652e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
7466d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
7467616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
74680bf6344aS[email protected]     }
74690bf6344aS[email protected] 
7470b0136355SMatthias Ringwald     // check if connection was just disconnected
7471b0136355SMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
7472b0136355SMatthias Ringwald         log_info("gap_connect: send create connection (again)");
7473b0136355SMatthias Ringwald         conn->state = SEND_CREATE_CONNECTION;
7474b0136355SMatthias Ringwald         hci_run();
7475b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
7476b0136355SMatthias Ringwald     }
7477b0136355SMatthias Ringwald 
7478d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
7479d5b1a89eSMatthias Ringwald     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
74804f3229d8S[email protected]     hci_run();
7481b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
74824f3229d8S[email protected] }
74834f3229d8S[email protected] 
74847851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
7485d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
7486665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
7487a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
74880bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
74890bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
74900bf6344aS[email protected]         switch (conn->state){
7491a6725849S[email protected]             case SEND_CREATE_CONNECTION:
74927851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
74939c77c9dbSMatthias Ringwald             case SENT_CANCEL_CONNECTION:
74947851196eSmatthias.ringwald                 return conn;
74957851196eSmatthias.ringwald             default:
74967851196eSmatthias.ringwald                 break;
74977851196eSmatthias.ringwald         };
74987851196eSmatthias.ringwald     }
74997851196eSmatthias.ringwald     return NULL;
75007851196eSmatthias.ringwald }
75017851196eSmatthias.ringwald 
7502d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
750314f2d8f0SMatthias Ringwald     hci_connection_t * conn;
750414f2d8f0SMatthias Ringwald     switch (hci_stack->le_connecting_request){
750514f2d8f0SMatthias Ringwald         case LE_CONNECTING_IDLE:
750614f2d8f0SMatthias Ringwald             break;
750714f2d8f0SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
750814f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
750914f2d8f0SMatthias Ringwald             hci_run();
751014f2d8f0SMatthias Ringwald             break;
751114f2d8f0SMatthias Ringwald         case LE_CONNECTING_DIRECT:
751214f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
751314f2d8f0SMatthias Ringwald             conn = gap_get_outgoing_connection();
751414f2d8f0SMatthias Ringwald             if (conn == NULL){
751514f2d8f0SMatthias Ringwald                 hci_run();
751614f2d8f0SMatthias Ringwald             } else {
75177851196eSmatthias.ringwald                 switch (conn->state){
75187851196eSmatthias.ringwald                     case SEND_CREATE_CONNECTION:
75197851196eSmatthias.ringwald                         // skip sending create connection and emit event instead
75202e77e513S[email protected]                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
7521665d90f2SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
75227851196eSmatthias.ringwald                         btstack_memory_hci_connection_free( conn );
75230bf6344aS[email protected]                         break;
7524a6725849S[email protected]                     case SENT_CREATE_CONNECTION:
75257851196eSmatthias.ringwald                         // request to send cancel connection
75260bf6344aS[email protected]                         conn->state = SEND_CANCEL_CONNECTION;
75270bf6344aS[email protected]                         hci_run();
75280bf6344aS[email protected]                         break;
75290bf6344aS[email protected]                     default:
75300bf6344aS[email protected]                         break;
75310bf6344aS[email protected]                 }
753214f2d8f0SMatthias Ringwald             }
753314f2d8f0SMatthias Ringwald             break;
753443dfd98aSMatthias Ringwald         default:
753514f2d8f0SMatthias Ringwald             btstack_unreachable();
753614f2d8f0SMatthias Ringwald             break;
753714f2d8f0SMatthias Ringwald     }
753814f2d8f0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
7539e31f89a7S[email protected] }
75404f3229d8S[email protected] 
7541c37a3166S[email protected] /**
75426012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
7543cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
7544cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
75456012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
75466012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
75476012052bSMatthias Ringwald  * @param conn_latency, default: 4
75486012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
75496012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
75506012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
75516012052bSMatthias Ringwald  */
75526012052bSMatthias Ringwald 
7553cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
7554cbe54ab2SJakob Krantz     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
7555cbe54ab2SJakob Krantz     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
7556cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
7557cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
75586012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
75596012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
75606012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
75616012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
75626012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
75636012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
75646012052bSMatthias Ringwald }
756513e645d2SMatthias Ringwald #endif
75666012052bSMatthias Ringwald 
75676012052bSMatthias Ringwald /**
7568c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
7569c37a3166S[email protected]  * @param handle
7570c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
7571c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
7572c37a3166S[email protected]  * @param conn_latency
7573c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
75746b65794dSMilanka Ringwald  * @return 0 if ok
7575c37a3166S[email protected]  */
7576c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7577c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7578c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7579c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7580c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
7581c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
7582c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
7583c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
758484cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
7585cfc59f1bSMatthias Ringwald     hci_run();
7586c37a3166S[email protected]     return 0;
7587c37a3166S[email protected] }
7588c37a3166S[email protected] 
758945c102fdSMatthias Ringwald /**
7590b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
7591b68d7bc3SMatthias Ringwald  * @param handle
7592b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
7593b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
7594b68d7bc3SMatthias Ringwald  * @param conn_latency
7595b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
75966b65794dSMilanka Ringwald  * @return 0 if ok
7597b68d7bc3SMatthias Ringwald  */
7598b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
7599b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
7600b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7601b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7602b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
7603b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
7604b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
7605b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
7606b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
760709c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
760809c9c963SMatthias Ringwald     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
7609b68d7bc3SMatthias Ringwald     return 0;
7610b68d7bc3SMatthias Ringwald }
7611b68d7bc3SMatthias Ringwald 
7612d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
7613d70217a2SMatthias Ringwald 
7614b68d7bc3SMatthias Ringwald /**
761545c102fdSMatthias Ringwald  * @brief Set Advertisement Data
761645c102fdSMatthias Ringwald  * @param advertising_data_length
761745c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
761845c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
761945c102fdSMatthias Ringwald  */
762045c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
762145c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
762245c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
7623501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7624bbc366e6SMatthias Ringwald     hci_run();
762545c102fdSMatthias Ringwald }
7626501f56b3SMatthias Ringwald 
7627501f56b3SMatthias Ringwald /**
7628501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
7629501f56b3SMatthias Ringwald  * @param advertising_data_length
7630501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
7631501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
7632501f56b3SMatthias Ringwald  */
7633501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
7634501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
7635501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
7636501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7637bbc366e6SMatthias Ringwald     hci_run();
763845c102fdSMatthias Ringwald }
763945c102fdSMatthias Ringwald 
764045c102fdSMatthias Ringwald /**
764145c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
764245c102fdSMatthias Ringwald  * @param adv_int_min
764345c102fdSMatthias Ringwald  * @param adv_int_max
764445c102fdSMatthias Ringwald  * @param adv_type
764545c102fdSMatthias Ringwald  * @param direct_address_type
764645c102fdSMatthias Ringwald  * @param direct_address
764745c102fdSMatthias Ringwald  * @param channel_map
764845c102fdSMatthias Ringwald  * @param filter_policy
764945c102fdSMatthias Ringwald  *
765045c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
765145c102fdSMatthias Ringwald  */
765245c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
7653b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
765445c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
765545c102fdSMatthias Ringwald 
765645c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
765745c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
765845c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
765945c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
766045c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
766145c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
76626535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
76636535961aSMatthias Ringwald                  6);
766445c102fdSMatthias Ringwald 
76656bf435a6SMatthias Ringwald     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
76666bf435a6SMatthias Ringwald     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
7667bbc366e6SMatthias Ringwald     hci_run();
766845c102fdSMatthias Ringwald  }
766945c102fdSMatthias Ringwald 
767045c102fdSMatthias Ringwald /**
767145c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
767245c102fdSMatthias Ringwald  * @param enabled
767345c102fdSMatthias Ringwald  */
767445c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
7675a408e724SMatthias Ringwald     if (enabled == 0){
7676a408e724SMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7677a408e724SMatthias Ringwald     } else {
7678a408e724SMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
7679a408e724SMatthias Ringwald     }
7680bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
7681cfc59f1bSMatthias Ringwald     hci_run();
768245c102fdSMatthias Ringwald }
768345c102fdSMatthias Ringwald 
7684a5770ecbSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
7685a5770ecbSMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
7686a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_t it;
7687a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
7688a5770ecbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
7689a5770ecbSMatthias Ringwald         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
7690a5770ecbSMatthias Ringwald         if ( item->advertising_handle == advertising_handle ) {
7691a5770ecbSMatthias Ringwald             return item;
7692a5770ecbSMatthias Ringwald         }
7693a5770ecbSMatthias Ringwald     }
7694a5770ecbSMatthias Ringwald     return NULL;
7695a5770ecbSMatthias Ringwald }
7696a5770ecbSMatthias Ringwald 
7697a5770ecbSMatthias 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){
7698a5770ecbSMatthias Ringwald     // find free advertisement handle
7699a5770ecbSMatthias Ringwald     uint8_t advertisement_handle;
7700a5770ecbSMatthias Ringwald     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
7701a5770ecbSMatthias Ringwald         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
7702a5770ecbSMatthias Ringwald     }
7703a5770ecbSMatthias Ringwald     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
7704a5770ecbSMatthias Ringwald     // clear
7705a5770ecbSMatthias Ringwald     memset(storage, 0, sizeof(le_advertising_set_t));
7706a5770ecbSMatthias Ringwald     // copy params
77070cbe4690SMatthias Ringwald     storage->advertising_handle = advertisement_handle;
770857a04237SMatthias Ringwald     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7709a5770ecbSMatthias Ringwald     // add to list
7710a5770ecbSMatthias Ringwald     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
7711a5770ecbSMatthias Ringwald     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
77120cbe4690SMatthias Ringwald     *out_advertising_handle = advertisement_handle;
7713a5770ecbSMatthias Ringwald     // set tasks and start
7714a5770ecbSMatthias Ringwald     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7715a5770ecbSMatthias Ringwald     hci_run();
7716a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7717a5770ecbSMatthias Ringwald }
7718a5770ecbSMatthias Ringwald 
7719a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
7720a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7721a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
772257a04237SMatthias Ringwald     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
7723a5770ecbSMatthias Ringwald     // set tasks and start
7724a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7725a5770ecbSMatthias Ringwald     hci_run();
7726a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7727a5770ecbSMatthias Ringwald }
7728a5770ecbSMatthias Ringwald 
7729a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
7730a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7731a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
773257a04237SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
7733a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7734a5770ecbSMatthias Ringwald }
7735a5770ecbSMatthias Ringwald 
7736a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
7737a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7738a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7739a5770ecbSMatthias Ringwald     memcpy(advertising_set->random_address, random_address, 6);
7740a5770ecbSMatthias Ringwald     // set tasks and start
7741a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
7742a5770ecbSMatthias Ringwald     hci_run();
7743a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7744a5770ecbSMatthias Ringwald }
7745a5770ecbSMatthias Ringwald 
77462e4aaf70SMatthias Ringwald uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
7747a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7748a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7749a5770ecbSMatthias Ringwald     advertising_set->adv_data = advertising_data;
7750a5770ecbSMatthias Ringwald     advertising_set->adv_data_len = advertising_data_length;
7751a5770ecbSMatthias Ringwald     // set tasks and start
7752a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
7753a5770ecbSMatthias Ringwald     hci_run();
7754a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7755a5770ecbSMatthias Ringwald }
7756a5770ecbSMatthias Ringwald 
77572e4aaf70SMatthias 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){
7758a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7759a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7760a5770ecbSMatthias Ringwald     advertising_set->scan_data = scan_response_data;
7761a5770ecbSMatthias Ringwald     advertising_set->scan_data_len = scan_response_data_length;
7762a5770ecbSMatthias Ringwald     // set tasks and start
7763a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
7764a5770ecbSMatthias Ringwald     hci_run();
7765a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7766a5770ecbSMatthias Ringwald }
7767a5770ecbSMatthias Ringwald 
7768a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
7769a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7770a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7771a5770ecbSMatthias Ringwald     advertising_set->enable_timeout = timeout;
7772a5770ecbSMatthias Ringwald     advertising_set->enable_max_scan_events = num_extended_advertising_events;
7773a5770ecbSMatthias Ringwald     // set tasks and start
7774a5770ecbSMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
7775a5770ecbSMatthias Ringwald     hci_run();
7776a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7777a5770ecbSMatthias Ringwald }
7778a5770ecbSMatthias Ringwald 
7779a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
7780a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7781a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7782a5770ecbSMatthias Ringwald     // set tasks and start
7783a5770ecbSMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
7784a5770ecbSMatthias Ringwald     hci_run();
7785a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7786a5770ecbSMatthias Ringwald }
7787a5770ecbSMatthias Ringwald 
7788c814a904SMatthias Ringwald uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
7789c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7790c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7791c814a904SMatthias Ringwald     // set tasks and start
7792c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
7793c814a904SMatthias Ringwald     hci_run();
7794c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
7795c814a904SMatthias Ringwald }
7796c814a904SMatthias Ringwald 
7797c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
7798c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
7799c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7800c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7801c814a904SMatthias Ringwald     // periodic advertising requires neither connectable, scannable, legacy or anonymous
7802c814a904SMatthias Ringwald     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
7803c814a904SMatthias Ringwald     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
7804c814a904SMatthias Ringwald     // set tasks and start
7805c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
7806c814a904SMatthias Ringwald     hci_run();
7807c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
7808c814a904SMatthias Ringwald }
7809c814a904SMatthias Ringwald 
7810c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
7811c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7812c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7813c814a904SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
7814c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
7815c814a904SMatthias Ringwald }
7816c814a904SMatthias Ringwald 
7817c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
7818c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
7819c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7820c814a904SMatthias Ringwald     advertising_set->periodic_data = periodic_data;
7821c814a904SMatthias Ringwald     advertising_set->periodic_data_len = periodic_data_length;
7822c814a904SMatthias Ringwald     // set tasks and start
7823c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
7824c814a904SMatthias Ringwald     hci_run();
7825c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
7826c814a904SMatthias Ringwald }
7827c814a904SMatthias Ringwald 
782853f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
782953f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
783053f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
783153f240c0SMatthias Ringwald     // set tasks and start
783253f240c0SMatthias Ringwald     advertising_set->periodic_include_adi = include_adi;
783353f240c0SMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
783453f240c0SMatthias Ringwald     hci_run();
783553f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
783653f240c0SMatthias Ringwald }
783753f240c0SMatthias Ringwald 
783853f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
783953f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
784053f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
784153f240c0SMatthias Ringwald     // set tasks and start
784253f240c0SMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
784353f240c0SMatthias Ringwald     hci_run();
784453f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
784553f240c0SMatthias Ringwald }
7846c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
784753f240c0SMatthias Ringwald 
7848a5770ecbSMatthias Ringwald #endif
7849a5770ecbSMatthias Ringwald 
785035454696SMatthias Ringwald #endif
785106e5cf96SMatthias Ringwald 
785206e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
785306e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
785406e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
785506e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
785606e5cf96SMatthias Ringwald 
785764068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
785806e5cf96SMatthias Ringwald     // update advertisement parameters, too
785906e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
7860bbc366e6SMatthias Ringwald     hci_run();
786164068776SMatthias Ringwald #endif
786264068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
786306e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
786464068776SMatthias Ringwald #endif
786506e5cf96SMatthias Ringwald }
786606e5cf96SMatthias Ringwald 
78679136bde8SMatthias Ringwald void hci_le_random_address_set(const bd_addr_t random_address){
78689136bde8SMatthias Ringwald     memcpy(hci_stack->le_random_address, random_address, 6);
78699136bde8SMatthias Ringwald     hci_stack->le_random_address_set = true;
78709136bde8SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
78719136bde8SMatthias Ringwald     hci_run();
78729136bde8SMatthias Ringwald }
78739136bde8SMatthias Ringwald 
7874d70217a2SMatthias Ringwald #endif
787545c102fdSMatthias Ringwald 
7876616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
78775917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
78785917a5c5S[email protected]     if (!conn){
78797851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
7880616edd56SMatthias Ringwald         return 0;
78815917a5c5S[email protected]     }
78827fd7aa6fSMatthias Ringwald     // ignore if already disconnected
78837fd7aa6fSMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
78847fd7aa6fSMatthias Ringwald         return 0;
78857fd7aa6fSMatthias Ringwald     }
78865917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
78875917a5c5S[email protected]     hci_run();
7888616edd56SMatthias Ringwald     return 0;
78894f3229d8S[email protected] }
789004a6ef8cSmatthias.ringwald 
7891228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
7892228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
7893228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
789422df2fe2SMatthias Ringwald     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
7895228e430cSMatthias Ringwald     hci_run();
7896228e430cSMatthias Ringwald     return 1;
7897228e430cSMatthias Ringwald }
7898228e430cSMatthias Ringwald 
7899a1bf5ae7SMatthias Ringwald /**
7900a1bf5ae7SMatthias Ringwald  * @brief Get connection type
7901a1bf5ae7SMatthias Ringwald  * @param con_handle
7902a1bf5ae7SMatthias Ringwald  * @result connection_type
7903a1bf5ae7SMatthias Ringwald  */
7904a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
7905a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
7906a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
7907a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
7908a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
7909a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
7910a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
7911a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
7912a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
7913f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
7914a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
7915a1bf5ae7SMatthias Ringwald         default:
7916a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
7917a1bf5ae7SMatthias Ringwald     }
7918a1bf5ae7SMatthias Ringwald }
7919a1bf5ae7SMatthias Ringwald 
79202dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
79212dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
79222dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
79232dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
79242dceb1d6SMatthias Ringwald }
79252dceb1d6SMatthias Ringwald 
79262dceb1d6SMatthias Ringwald 
792744f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
7928667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
792988a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
793088a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
793188a03c8dSMatthias Ringwald     conn->request_role = role;
793288a03c8dSMatthias Ringwald     hci_run();
7933d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
793488a03c8dSMatthias Ringwald }
793544f858f3SMatthias Ringwald #endif
793688a03c8dSMatthias Ringwald 
7937a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
79384f551432SMatthias Ringwald 
7939b45b7749SMilanka 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, uint8_t phy_options){
7940b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
7941b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
7942b90f6e0aSMatthias Ringwald 
7943b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
7944b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
7945b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
7946b90f6e0aSMatthias Ringwald     conn->le_phy_update_phy_options = phy_options;
7947b90f6e0aSMatthias Ringwald 
7948b90f6e0aSMatthias Ringwald     hci_run();
7949b90f6e0aSMatthias Ringwald 
7950b90f6e0aSMatthias Ringwald     return 0;
7951b90f6e0aSMatthias Ringwald }
7952b90f6e0aSMatthias Ringwald 
7953667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
79547a92a9dbSMatthias Ringwald     // check if already in list
79557a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
79567a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
79577a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
79587a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
79597a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
79607a92a9dbSMatthias Ringwald             continue;
79617a92a9dbSMatthias Ringwald         }
79627a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
79637a92a9dbSMatthias Ringwald             continue;
79647a92a9dbSMatthias Ringwald         }
7965287379ccSMatthias Ringwald 		// disallow if already scheduled to add
7966287379ccSMatthias Ringwald 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
79677a92a9dbSMatthias Ringwald 			return ERROR_CODE_COMMAND_DISALLOWED;
79687a92a9dbSMatthias Ringwald 		}
7969287379ccSMatthias Ringwald 		// still on controller, but scheduled to remove -> re-add
7970287379ccSMatthias Ringwald 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
7971287379ccSMatthias Ringwald 		return ERROR_CODE_SUCCESS;
7972287379ccSMatthias Ringwald     }
79737a92a9dbSMatthias Ringwald     // alloc and add to list
7974e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
7975e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
7976e83201bcSMatthias Ringwald     entry->address_type = address_type;
79776535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
7978e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
7979665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
7980226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
7981ac9c45e0SMatthias Ringwald }
7982ac9c45e0SMatthias Ringwald 
7983667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
7984665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
7985665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
7986665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
7987665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
79887a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
79897a92a9dbSMatthias Ringwald             continue;
79907a92a9dbSMatthias Ringwald         }
79917a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
79927a92a9dbSMatthias Ringwald             continue;
79937a92a9dbSMatthias Ringwald         }
7994e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
7995e83201bcSMatthias Ringwald             // remove from controller if already present
7996e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
7997a3b69fdeSMatthias Ringwald         }  else {
7998226db5efSMatthias Ringwald             // directly remove entry from whitelist
7999665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
8000e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
8001e83201bcSMatthias Ringwald         }
8002a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
8003a3b69fdeSMatthias Ringwald     }
8004a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
800542ff5ba1SMatthias Ringwald }
800642ff5ba1SMatthias Ringwald 
8007226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
8008665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
8009665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8010665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8011665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8012e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8013e83201bcSMatthias Ringwald             // remove from controller if already present
8014e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8015e83201bcSMatthias Ringwald             continue;
8016e83201bcSMatthias Ringwald         }
801791915b0bSMatthias Ringwald         // directly remove entry from whitelist
8018665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
8019e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
8020e83201bcSMatthias Ringwald     }
8021226db5efSMatthias Ringwald }
8022226db5efSMatthias Ringwald 
802383dc1a98SMatthias Ringwald // free all entries unconditionally
802483dc1a98SMatthias Ringwald static void hci_whitelist_free(void){
802583dc1a98SMatthias Ringwald     btstack_linked_list_iterator_t lit;
802683dc1a98SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
802783dc1a98SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
802883dc1a98SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
802983dc1a98SMatthias Ringwald         btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
803083dc1a98SMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
803183dc1a98SMatthias Ringwald     }
803283dc1a98SMatthias Ringwald }
803383dc1a98SMatthias Ringwald 
8034a3b69fdeSMatthias Ringwald /**
8035a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
80366b65794dSMilanka Ringwald  * @return 0 if ok
8037a3b69fdeSMatthias Ringwald  */
8038a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
8039a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
8040a3b69fdeSMatthias Ringwald     hci_run();
8041a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8042a3b69fdeSMatthias Ringwald }
8043a3b69fdeSMatthias Ringwald 
8044a3b69fdeSMatthias Ringwald /**
8045a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
8046a3b69fdeSMatthias Ringwald  * @param address_typ
8047a3b69fdeSMatthias Ringwald  * @param address
80486b65794dSMilanka Ringwald  * @return 0 if ok
8049a3b69fdeSMatthias Ringwald  */
8050667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8051a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
8052a3b69fdeSMatthias Ringwald     if (status){
8053a3b69fdeSMatthias Ringwald         return status;
8054a3b69fdeSMatthias Ringwald     }
8055a3b69fdeSMatthias Ringwald     hci_run();
8056a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8057a3b69fdeSMatthias Ringwald }
8058a3b69fdeSMatthias Ringwald 
8059a3b69fdeSMatthias Ringwald /**
8060a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
8061a3b69fdeSMatthias Ringwald  * @param address_typ
8062a3b69fdeSMatthias Ringwald  * @param address
80636b65794dSMilanka Ringwald  * @return 0 if ok
8064a3b69fdeSMatthias Ringwald  */
8065667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8066a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
8067a3b69fdeSMatthias Ringwald     if (status){
8068a3b69fdeSMatthias Ringwald         return status;
8069a3b69fdeSMatthias Ringwald     }
8070a3b69fdeSMatthias Ringwald     hci_run();
8071a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8072a3b69fdeSMatthias Ringwald }
8073a3b69fdeSMatthias Ringwald 
8074226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8075226db5efSMatthias Ringwald /**
807695e257d9SMatthias Ringwald  * @brief Connect with Whitelist
807795e257d9SMatthias Ringwald  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
80786b65794dSMilanka Ringwald  * @return - if ok
807995e257d9SMatthias Ringwald  */
808095e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
808195e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
808295e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
808395e257d9SMatthias Ringwald     }
808495e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
808595e257d9SMatthias Ringwald     hci_run();
808695e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
808795e257d9SMatthias Ringwald }
808895e257d9SMatthias Ringwald 
808995e257d9SMatthias Ringwald /**
8090226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
8091226db5efSMatthias Ringwald  * @param address_typ
8092226db5efSMatthias Ringwald  * @param address
80936b65794dSMilanka Ringwald  * @return 0 if ok
8094226db5efSMatthias Ringwald  */
8095667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
809695e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8097226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
8098226db5efSMatthias Ringwald     }
8099226db5efSMatthias Ringwald 
8100226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
810163f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8102226db5efSMatthias Ringwald         return status;
8103226db5efSMatthias Ringwald     }
8104226db5efSMatthias Ringwald 
8105226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8106226db5efSMatthias Ringwald 
8107226db5efSMatthias Ringwald     hci_run();
810895e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8109226db5efSMatthias Ringwald }
8110226db5efSMatthias Ringwald 
8111226db5efSMatthias Ringwald /**
8112226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
8113226db5efSMatthias Ringwald  * @param address_typ
8114226db5efSMatthias Ringwald  * @param address
81156b65794dSMilanka Ringwald  * @return 0 if ok
8116226db5efSMatthias Ringwald  */
8117667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
811895e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
811995e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
812095e257d9SMatthias Ringwald     }
812195e257d9SMatthias Ringwald 
8122226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
812395e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
812495e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
812595e257d9SMatthias Ringwald     }
8126226db5efSMatthias Ringwald     hci_run();
8127226db5efSMatthias Ringwald     return 0;
8128226db5efSMatthias Ringwald }
8129226db5efSMatthias Ringwald 
8130226db5efSMatthias Ringwald /**
8131226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
8132226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
8133226db5efSMatthias Ringwald  */
813495e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
813595e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
813695e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
813795e257d9SMatthias Ringwald     }
8138226db5efSMatthias Ringwald     hci_whitelist_clear();
8139226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8140e83201bcSMatthias Ringwald     hci_run();
814195e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8142ac9c45e0SMatthias Ringwald }
8143c9db5c21SMilanka Ringwald 
8144b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8145b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8146c9db5c21SMilanka Ringwald     if (!conn) return 0;
8147c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
8148c9db5c21SMilanka Ringwald }
8149d70217a2SMatthias Ringwald #endif
81504f551432SMatthias Ringwald #endif
81514f551432SMatthias Ringwald 
815235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
8153ac9c45e0SMatthias Ringwald /**
8154ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
8155a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8156ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
8157ff00ed1cSMatthias Ringwald  */
8158ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
8159ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
8160baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
816159d59ecfSMatthias Ringwald     hci_run();
8162ff00ed1cSMatthias Ringwald }
8163ff00ed1cSMatthias Ringwald 
8164ff00ed1cSMatthias Ringwald /**
8165f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
8166f5875de5SMatthias Ringwald  * @param duration in 1.28s units
8167f5875de5SMatthias Ringwald  * @return 0 if ok
8168f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8169f5875de5SMatthias Ringwald  */
8170f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
817199449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8172f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8173a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8174f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8175f5875de5SMatthias Ringwald     }
8176f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
817730199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = 0;
817830199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = 0;
817930199e24SMatthias Ringwald     hci_run();
818030199e24SMatthias Ringwald     return 0;
818130199e24SMatthias Ringwald }
818230199e24SMatthias Ringwald 
818330199e24SMatthias Ringwald uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
818430199e24SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
818530199e24SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
818630199e24SMatthias Ringwald     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
818730199e24SMatthias Ringwald     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
818830199e24SMatthias Ringwald     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
818930199e24SMatthias Ringwald     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
819030199e24SMatthias Ringwald 
819130199e24SMatthias Ringwald     hci_stack->inquiry_state = duration;
819230199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = max_period_length;
819330199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = min_period_length;
8194f5875de5SMatthias Ringwald     hci_run();
8195f5875de5SMatthias Ringwald     return 0;
8196f5875de5SMatthias Ringwald }
8197f5875de5SMatthias Ringwald 
8198f5875de5SMatthias Ringwald /**
8199f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
82006b65794dSMilanka Ringwald  * @return 0 if ok
8201f5875de5SMatthias Ringwald  */
8202f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
8203a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
8204f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
8205f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
8206f5875de5SMatthias Ringwald         hci_emit_event(event, sizeof(event), 1);
8207f5875de5SMatthias Ringwald         return 0;
8208f5875de5SMatthias Ringwald     }
820930199e24SMatthias Ringwald     switch (hci_stack->inquiry_state){
821030199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_ACTIVE:
8211f5875de5SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
8212f5875de5SMatthias Ringwald             hci_run();
821330199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
821430199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_PERIODIC:
821530199e24SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
821630199e24SMatthias Ringwald             hci_run();
821730199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
821830199e24SMatthias Ringwald         default:
821930199e24SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
822030199e24SMatthias Ringwald     }
8221f5875de5SMatthias Ringwald }
8222f5875de5SMatthias Ringwald 
8223496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
8224496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
8225496bb884SMatthias Ringwald }
8226496bb884SMatthias Ringwald 
82271dc973e7SMatthias Ringwald void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
8228c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
8229c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_window   = inquiry_scan_window;
8230baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
8231c0c8a829SMatthias Ringwald     hci_run();
8232c0c8a829SMatthias Ringwald }
8233c0c8a829SMatthias Ringwald 
8234b7f1ee76SMatthias Ringwald 
8235b7f1ee76SMatthias Ringwald /**
8236b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
8237b7f1ee76SMatthias Ringwald  * @param addr
8238b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
8239b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
8240b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
8241b7f1ee76SMatthias Ringwald  */
8242667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
8243b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
82446535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
8245b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
8246b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
8247b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
8248b7f1ee76SMatthias Ringwald     hci_run();
8249b7f1ee76SMatthias Ringwald     return 0;
8250b7f1ee76SMatthias Ringwald }
8251b7f1ee76SMatthias Ringwald 
8252667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
82530a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
82546535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
82550a51f88bSMatthias Ringwald     hci_run();
82560a51f88bSMatthias Ringwald     return 0;
82570a51f88bSMatthias Ringwald }
82580a51f88bSMatthias Ringwald 
82590a51f88bSMatthias Ringwald /**
8260aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
8261aad97216SMatthias Ringwald  * @param addr
8262aad97216SMatthias Ringwald  * @param pin_data
8263aad97216SMatthias Ringwald  * @param pin_len
8264aad97216SMatthias Ringwald  * @return 0 if ok
8265aad97216SMatthias Ringwald  */
8266667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
8267aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8268aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
8269aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
8270aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
8271aad97216SMatthias Ringwald }
8272aad97216SMatthias Ringwald 
8273aad97216SMatthias Ringwald /**
82740a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
82750a51f88bSMatthias Ringwald  * @param addr
82760a51f88bSMatthias Ringwald  * @param pin
82770a51f88bSMatthias Ringwald  * @return 0 if ok
82780a51f88bSMatthias Ringwald  */
8279667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
82809d78a7ecSMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
82810a51f88bSMatthias Ringwald }
82820a51f88bSMatthias Ringwald 
82830a51f88bSMatthias Ringwald /**
82840a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
82850a51f88bSMatthias Ringwald  * @param addr
82860a51f88bSMatthias Ringwald  * @param pin
82870a51f88bSMatthias Ringwald  * @return 0 if ok
82880a51f88bSMatthias Ringwald  */
82890a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
8290cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
82910a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
82920a51f88bSMatthias Ringwald }
82930a51f88bSMatthias Ringwald 
82940a51f88bSMatthias Ringwald /**
82950a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
82960a51f88bSMatthias Ringwald  * @param addr
82970a51f88bSMatthias Ringwald  * @param passkey
82980a51f88bSMatthias Ringwald  * @return 0 if ok
82990a51f88bSMatthias Ringwald  */
8300667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
8301cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8302d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
83030a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
83040a51f88bSMatthias Ringwald }
83050a51f88bSMatthias Ringwald 
83060a51f88bSMatthias Ringwald /**
83070a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
83080a51f88bSMatthias Ringwald  * @param addr
83090a51f88bSMatthias Ringwald  * @param pin
83100a51f88bSMatthias Ringwald  * @return 0 if ok
83110a51f88bSMatthias Ringwald  */
8312667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
8313cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
83140a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
83150a51f88bSMatthias Ringwald }
83160a51f88bSMatthias Ringwald 
83170a51f88bSMatthias Ringwald /**
83180a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
83190a51f88bSMatthias Ringwald  * @param addr
83200a51f88bSMatthias Ringwald  * @param passkey
83210a51f88bSMatthias Ringwald  * @return 0 if ok
83220a51f88bSMatthias Ringwald  */
8323667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
8324cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
83250a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
83260a51f88bSMatthias Ringwald }
83270a51f88bSMatthias Ringwald 
83280a51f88bSMatthias Ringwald /**
83290a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
83300a51f88bSMatthias Ringwald  * @param addr
83310a51f88bSMatthias Ringwald  * @param pin
83320a51f88bSMatthias Ringwald  * @return 0 if ok
83330a51f88bSMatthias Ringwald  */
8334667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
8335cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
83360a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
83370a51f88bSMatthias Ringwald }
83380a51f88bSMatthias Ringwald 
8339308eeaffSMatthias Ringwald #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
834044565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
834144565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
834244565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
834344565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
834444565b0cSMatthias Ringwald     hci_run();
834544565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
834644565b0cSMatthias Ringwald }
8347308eeaffSMatthias Ringwald #endif
834844565b0cSMatthias Ringwald 
8349308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
835044565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
83517ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
835244565b0cSMatthias Ringwald }
835344565b0cSMatthias Ringwald 
835444565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
83557ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
835644565b0cSMatthias Ringwald }
835744565b0cSMatthias Ringwald #endif
835844565b0cSMatthias Ringwald 
83591849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
83601849becdSMatthias Ringwald /**
83611849becdSMatthias Ringwald  * @brief Report Remote OOB Data
83621849becdSMatthias Ringwald  * @param bd_addr
83631849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
83641849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
83651849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
83661849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
83671849becdSMatthias Ringwald  */
83681849becdSMatthias 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){
83691849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
83701849becdSMatthias Ringwald     if (connection == NULL) {
83711849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
83721849becdSMatthias Ringwald     }
83731849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
83741849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
8375204e8f1dSMatthias Ringwald 
8376204e8f1dSMatthias Ringwald     // ignore P-256 if not supported by us
8377204e8f1dSMatthias Ringwald     if (hci_stack->secure_connections_active){
83781849becdSMatthias Ringwald         connection->classic_oob_c_256 = c_256;
83791849becdSMatthias Ringwald         connection->classic_oob_r_256 = r_256;
8380204e8f1dSMatthias Ringwald     }
8381204e8f1dSMatthias Ringwald 
83821849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
83831849becdSMatthias Ringwald }
8384cf01e888SMatthias Ringwald /**
8385cf01e888SMatthias Ringwald  * @brief Generate new OOB data
8386cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
8387cf01e888SMatthias Ringwald  */
8388cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
8389cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
8390cf01e888SMatthias Ringwald     hci_run();
8391cf01e888SMatthias Ringwald }
8392cf01e888SMatthias Ringwald 
83931849becdSMatthias Ringwald #endif
83941849becdSMatthias Ringwald 
8395308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
8396308eeaffSMatthias Ringwald uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
8397308eeaffSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
8398308eeaffSMatthias Ringwald     if (connection == NULL) {
8399308eeaffSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8400308eeaffSMatthias Ringwald     }
8401308eeaffSMatthias Ringwald 
8402308eeaffSMatthias Ringwald     memcpy(connection->link_key, link_key, sizeof(link_key_t));
8403308eeaffSMatthias Ringwald     connection->link_key_type = type;
8404308eeaffSMatthias Ringwald 
8405308eeaffSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
8406308eeaffSMatthias Ringwald }
8407308eeaffSMatthias Ringwald 
8408308eeaffSMatthias Ringwald #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
8409f5875de5SMatthias Ringwald /**
8410f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
8411f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
8412f6858d14SMatthias Ringwald  */
8413b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
8414b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
8415f6858d14SMatthias Ringwald }
8416f6858d14SMatthias Ringwald 
8417f6858d14SMatthias Ringwald /**
8418d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
8419d950d659SMatthias Ringwald  */
8420d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
8421d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
8422d950d659SMatthias Ringwald }
8423d950d659SMatthias Ringwald 
8424d950d659SMatthias Ringwald /**
8425d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
8426d950d659SMatthias Ringwald  * @return current voice setting
8427d950d659SMatthias Ringwald  */
84280cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
8429d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
8430d950d659SMatthias Ringwald }
8431d950d659SMatthias Ringwald 
8432400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
8433400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
8434400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
8435400ff5abSMatthias Ringwald     if (!transport_name) return 0;
8436400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
8437400ff5abSMatthias Ringwald }
8438400ff5abSMatthias Ringwald 
8439b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
8440b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
8441b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
8442b3aad8daSMatthias Ringwald  */
844320dcdd22SMatthias Ringwald uint16_t hci_get_sco_packet_length(void){
844420dcdd22SMatthias Ringwald     uint16_t sco_packet_length = 0;
8445cf119f3bSMatthias Ringwald 
84461e20a53eSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
84476f28d2eeSMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
84481431ce27SMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
8449cf119f3bSMatthias Ringwald 
8450400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
8451400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
8452cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
845352e46257SMatthias Ringwald         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
845452e46257SMatthias Ringwald         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
8455400ff5abSMatthias Ringwald     } else {
8456400ff5abSMatthias Ringwald         // 3 byte SCO header + SCO packet size over the air (60 bytes)
8457400ff5abSMatthias Ringwald         sco_packet_length = 3 + 60 * multiplier;
8458d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
8459ad915196SMatthias Ringwald         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
8460d966a453SMatthias Ringwald             sco_packet_length = 3 + 60;
8461d966a453SMatthias Ringwald         }
8462400ff5abSMatthias Ringwald     }
8463a3069afeSMatthias Ringwald #endif
84645b7087c7SMatthias Ringwald 
84655b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
84665b7087c7SMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
84671e20a53eSMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
84685b7087c7SMatthias Ringwald     sco_packet_length = 3 + 60 * multiplier;
84695b7087c7SMatthias Ringwald #endif
8470a3069afeSMatthias Ringwald     return sco_packet_length;
8471b3aad8daSMatthias Ringwald }
8472b3aad8daSMatthias Ringwald 
8473c4c88f1bSJakob Krantz /**
8474c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
8475c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
8476c4c88f1bSJakob Krantz */
8477c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
8478c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
8479c4c88f1bSJakob Krantz }
8480c4c88f1bSJakob Krantz 
8481c4c88f1bSJakob Krantz #endif
8482ec111c8bSMatthias Ringwald 
8483ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
8484ec111c8bSMatthias Ringwald     return hci_stack->state;
8485ec111c8bSMatthias Ringwald }
8486ec111c8bSMatthias Ringwald 
848707e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
84885e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
848907e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
849007e010b6SMilanka Ringwald }
849107e010b6SMilanka Ringwald #endif
8492ec111c8bSMatthias Ringwald 
8493d950d659SMatthias Ringwald /**
8494d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
8495d23838ecSMatthias Ringwald  */
8496c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
8497d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
8498d23838ecSMatthias Ringwald }
8499d23838ecSMatthias Ringwald 
850071de195eSMatthias Ringwald void hci_disconnect_all(void){
8501665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
8502665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
8503665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8504665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
850504a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
850604a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
850704a6ef8cSmatthias.ringwald     }
8508d31fba26S[email protected]     hci_run();
850904a6ef8cSmatthias.ringwald }
851033373e40SMatthias Ringwald 
851133373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
851233373e40SMatthias Ringwald     return hci_stack->manufacturer;
851333373e40SMatthias Ringwald }
85149c6e867eSMatthias Ringwald 
85153e329ddfSandryblack #ifdef ENABLE_BLE
85169c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
85179c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
85189c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
85199c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
85209c6e867eSMatthias Ringwald }
85219c6e867eSMatthias Ringwald 
85229c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
85239c6e867eSMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
85246a79f6baSMatthias Ringwald #endif
85259c6e867eSMatthias Ringwald 
85266d105c71SMatthias Ringwald uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
8527c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8528c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
8529c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
85306a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
8531c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
8532c5fb5ca4SMatthias Ringwald         if (sm_conn->sm_connection_encrypted) {
85339c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
85349c6e867eSMatthias Ringwald         }
85356a79f6baSMatthias Ringwald #endif
85366a79f6baSMatthias Ringwald     } else {
8537c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
85388daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
8539c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
8540c5fb5ca4SMatthias Ringwald         }
8541c5fb5ca4SMatthias Ringwald #endif
85426a79f6baSMatthias Ringwald     }
8543c5fb5ca4SMatthias Ringwald     return 0;
8544c5fb5ca4SMatthias Ringwald }
85459c6e867eSMatthias Ringwald 
8546ff3f1026SMatthias Ringwald bool gap_authenticated(hci_con_handle_t con_handle){
8547c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8548ff3f1026SMatthias Ringwald     if (hci_connection == NULL) return false;
85495f3981bfSMatthias Ringwald 
8550c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
85516a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
85525f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
85535f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
8554c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
8555ff3f1026SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated != 0;
85566a79f6baSMatthias Ringwald #endif
855759a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
85585f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
8559f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
8560ff3f1026SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
856159a1a47aSMatthias Ringwald #endif
85625f3981bfSMatthias Ringwald         default:
8563ff3f1026SMatthias Ringwald             return false;
85645f3981bfSMatthias Ringwald     }
85659c6e867eSMatthias Ringwald }
85669c6e867eSMatthias Ringwald 
8567f461b3dfSMatthias Ringwald bool gap_secure_connection(hci_con_handle_t con_handle){
8568c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8569c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
85708b35e16aSMatthias Ringwald 
8571c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
85726a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
85738b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
85748b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
8575f461b3dfSMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
8576f461b3dfSMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc != 0;
85776a79f6baSMatthias Ringwald #endif
857859a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
85798b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
8580f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
8581f461b3dfSMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
858259a1a47aSMatthias Ringwald #endif
85838b35e16aSMatthias Ringwald         default:
8584f461b3dfSMatthias Ringwald             return false;
85858b35e16aSMatthias Ringwald     }
8586f1dfbe18SMatthias Ringwald }
8587f1dfbe18SMatthias Ringwald 
85881e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
85891e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
85901e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
85911e122704SMatthias Ringwald 
859248f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
85931e122704SMatthias Ringwald 	link_key_t link_key;
85941e122704SMatthias Ringwald 	link_key_type_t link_key_type;
859548f33f37SMatthias Ringwald #endif
85961e122704SMatthias Ringwald 	switch (hci_connection->address_type){
85976a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
85981e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
85991e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
86001e122704SMatthias Ringwald 			return hci_connection->sm_connection.sm_le_db_index >= 0;
86016a79f6baSMatthias Ringwald #endif
86021e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
86031e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
86041e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
86051e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
86061e122704SMatthias Ringwald #endif
86071e122704SMatthias Ringwald 		default:
86081e122704SMatthias Ringwald 			return false;
86091e122704SMatthias Ringwald 	}
86101e122704SMatthias Ringwald }
86111e122704SMatthias Ringwald 
86126a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
86139c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
86149c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
86159c6e867eSMatthias Ringwald     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
86169c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
86179c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
86189c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
86199c6e867eSMatthias Ringwald }
86209c6e867eSMatthias Ringwald #endif
8621f8ee3071SMatthias Ringwald 
8622f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
8623f8ee3071SMatthias 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){
8624f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
86257f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8626f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
8627f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
8628f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
8629f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
8630f8ee3071SMatthias Ringwald     hci_run();
8631f8ee3071SMatthias Ringwald     return 0;
8632f8ee3071SMatthias Ringwald }
8633f8ee3071SMatthias Ringwald 
8634f8ee3071SMatthias Ringwald /**
8635f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
8636f8ee3071SMatthias Ringwald  * @param con_handle
8637f8ee3071SMatthias Ringwald  @ @return 0 if ok
8638f8ee3071SMatthias Ringwald  */
8639f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
8640f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
86417f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8642f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
8643f8ee3071SMatthias Ringwald     hci_run();
8644f8ee3071SMatthias Ringwald     return 0;
8645f8ee3071SMatthias Ringwald }
8646bea424a5SMatthias Ringwald 
8647140c0557SMatthias 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){
8648140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
86497f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8650140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
8651140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
8652140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
8653140c0557SMatthias Ringwald     hci_run();
8654dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8655140c0557SMatthias Ringwald }
8656140c0557SMatthias Ringwald 
8657278ff8a9SMatthias 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){
8658278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
86597f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8660278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
8661278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
8662278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
8663278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
8664278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
8665278ff8a9SMatthias Ringwald     hci_run();
8666278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8667278ff8a9SMatthias Ringwald }
8668278ff8a9SMatthias Ringwald 
8669bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
8670bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
8671bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
8672baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
8673bea424a5SMatthias Ringwald     hci_run();
8674bea424a5SMatthias Ringwald }
8675bea424a5SMatthias Ringwald 
8676bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
8677bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
8678baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
8679bea424a5SMatthias Ringwald     hci_run();
8680bea424a5SMatthias Ringwald }
8681bea424a5SMatthias Ringwald 
868232a12730SMatthias Ringwald void gap_set_page_timeout(uint16_t page_timeout){
868332a12730SMatthias Ringwald     hci_stack->page_timeout = page_timeout;
8684baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
868532a12730SMatthias Ringwald     hci_run();
868632a12730SMatthias Ringwald }
868732a12730SMatthias Ringwald 
8688f8ee3071SMatthias Ringwald #endif
8689beceeddeSMatthias Ringwald 
869021debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
869121debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
869221debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
869321debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
869421debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
869521debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
869602b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
869721debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
869802b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
869902b02cffSMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
870002b02cffSMatthias Ringwald     }
870102b02cffSMatthias Ringwald }
870202b02cffSMatthias Ringwald 
870302b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
870402b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
870502b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
870602b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
870702b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
870802b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
870902b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
871002b02cffSMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
871121debf25SMatthias Ringwald 	}
871221debf25SMatthias Ringwald }
8713cf38a091SMatthias Ringwald 
8714cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
87151ffa425cSMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
8716cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
8717cf38a091SMatthias Ringwald 	}
8718cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
8719cf38a091SMatthias Ringwald 		// restart le resolving list update
8720cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
8721cf38a091SMatthias Ringwald 	}
8722cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
8723cf38a091SMatthias Ringwald }
872421debf25SMatthias Ringwald #endif
872521debf25SMatthias Ringwald 
8726f40c73b4SMatthias Ringwald #ifdef ENABLE_BLE
8727f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8728f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8729f40c73b4SMatthias Ringwald 
8730f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8731f40c73b4SMatthias Ringwald     // check if already in list
8732f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
8733f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8734f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
8735f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
8736f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
8737f40c73b4SMatthias Ringwald             continue;
8738f40c73b4SMatthias Ringwald         }
8739f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
8740f40c73b4SMatthias Ringwald             continue;
8741f40c73b4SMatthias Ringwald         }
8742f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
8743f40c73b4SMatthias Ringwald             continue;
8744f40c73b4SMatthias Ringwald         }
8745f40c73b4SMatthias Ringwald         // disallow if already scheduled to add
8746f40c73b4SMatthias Ringwald         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
8747f40c73b4SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
8748f40c73b4SMatthias Ringwald         }
8749f40c73b4SMatthias Ringwald         // still on controller, but scheduled to remove -> re-add
8750f40c73b4SMatthias Ringwald         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8751f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
8752f40c73b4SMatthias Ringwald     }
8753f40c73b4SMatthias Ringwald     // alloc and add to list
8754f40c73b4SMatthias Ringwald     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
8755f40c73b4SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8756f40c73b4SMatthias Ringwald     entry->sid = advertising_sid;
8757f40c73b4SMatthias Ringwald     entry->address_type = address_type;
8758f40c73b4SMatthias Ringwald     (void)memcpy(entry->address, address, 6);
8759f40c73b4SMatthias Ringwald     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
8760f40c73b4SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
8761f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8762f40c73b4SMatthias Ringwald }
8763f40c73b4SMatthias Ringwald 
8764f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8765f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
8766f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8767f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8768f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8769f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
8770f40c73b4SMatthias Ringwald             continue;
8771f40c73b4SMatthias Ringwald         }
8772f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
8773f40c73b4SMatthias Ringwald             continue;
8774f40c73b4SMatthias Ringwald         }
8775f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
8776f40c73b4SMatthias Ringwald             continue;
8777f40c73b4SMatthias Ringwald         }
8778f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8779f40c73b4SMatthias Ringwald             // remove from controller if already present
8780f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8781f40c73b4SMatthias Ringwald         }  else {
8782f40c73b4SMatthias Ringwald             // directly remove entry from whitelist
8783f40c73b4SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
8784f40c73b4SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
8785f40c73b4SMatthias Ringwald         }
8786f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
8787f40c73b4SMatthias Ringwald     }
8788f40c73b4SMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8789f40c73b4SMatthias Ringwald }
8790f40c73b4SMatthias Ringwald 
8791f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_clear(void){
8792f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
8793f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
8794f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8795f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
8796f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
8797f40c73b4SMatthias Ringwald             // remove from controller if already present
8798f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
8799f40c73b4SMatthias Ringwald             continue;
8800f40c73b4SMatthias Ringwald         }
8801f40c73b4SMatthias Ringwald         // directly remove entry from whitelist
8802f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
8803f40c73b4SMatthias Ringwald         btstack_memory_periodic_advertiser_list_entry_free(entry);
8804f40c73b4SMatthias Ringwald     }
8805f40c73b4SMatthias Ringwald }
8806f40c73b4SMatthias Ringwald 
8807f40c73b4SMatthias Ringwald // free all entries unconditionally
8808f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_free(void){
8809f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t lit;
8810f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
8811f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
8812f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
8813f40c73b4SMatthias Ringwald         btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
8814f40c73b4SMatthias Ringwald         btstack_memory_periodic_advertiser_list_entry_free(entry);
8815f40c73b4SMatthias Ringwald     }
8816f40c73b4SMatthias Ringwald }
8817f40c73b4SMatthias Ringwald 
8818f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_clear(void){
8819f40c73b4SMatthias Ringwald     hci_periodic_advertiser_list_clear();
8820f40c73b4SMatthias Ringwald     hci_run();
8821f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8822f40c73b4SMatthias Ringwald }
8823f40c73b4SMatthias Ringwald 
8824f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8825f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
8826f40c73b4SMatthias Ringwald     if (status){
8827f40c73b4SMatthias Ringwald         return status;
8828f40c73b4SMatthias Ringwald     }
8829f40c73b4SMatthias Ringwald     hci_run();
8830f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8831f40c73b4SMatthias Ringwald }
8832f40c73b4SMatthias Ringwald 
8833f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
8834f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
8835f40c73b4SMatthias Ringwald     if (status){
8836f40c73b4SMatthias Ringwald         return status;
8837f40c73b4SMatthias Ringwald     }
8838f40c73b4SMatthias Ringwald     hci_run();
8839f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8840f40c73b4SMatthias Ringwald }
88414bafedd5SMatthias Ringwald 
88424bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
88434bafedd5SMatthias Ringwald                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
88444bafedd5SMatthias Ringwald     // abort if already active
88454bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
88464bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
88474bafedd5SMatthias Ringwald     }
88484bafedd5SMatthias Ringwald     // store request
88494bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
88504bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_options = options;
88514bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
88524bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
88534bafedd5SMatthias Ringwald     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
88544bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_skip = skip;
88554bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_timeout = sync_timeout;
88564bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
88574bafedd5SMatthias Ringwald 
88584bafedd5SMatthias Ringwald     hci_run();
88594bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
88604bafedd5SMatthias Ringwald }
88614bafedd5SMatthias Ringwald 
88624bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync_cancel(void){
88634bafedd5SMatthias Ringwald     // abort if not requested
88644bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
88654bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
88664bafedd5SMatthias Ringwald     }
88674bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
88684bafedd5SMatthias Ringwald     hci_run();
88694bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
88704bafedd5SMatthias Ringwald }
88714bafedd5SMatthias Ringwald 
88724bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
887349a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
887449a6c69cSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
887549a6c69cSMatthias Ringwald     }
887649a6c69cSMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
887749a6c69cSMatthias Ringwald     hci_run();
887849a6c69cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
88794bafedd5SMatthias Ringwald }
88804bafedd5SMatthias Ringwald 
8881f40c73b4SMatthias Ringwald #endif
8882f40c73b4SMatthias Ringwald #endif
88834ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
8884a90016deSMatthias Ringwald static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle) {
88854ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
88864ae8623eSMatthias Ringwald     if (iso_stream == NULL){
88874ae8623eSMatthias Ringwald         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
88884ae8623eSMatthias Ringwald     } else {
88894ae8623eSMatthias Ringwald         iso_stream->state = HCI_ISO_STREAM_STATE_REQUESTED;
889015a15be3SMatthias Ringwald         iso_stream->con_handle = con_handle;
8891a90016deSMatthias Ringwald         iso_stream->big_handle = big_handle;
88924ae8623eSMatthias Ringwald         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
88934ae8623eSMatthias Ringwald         return ERROR_CODE_SUCCESS;
88944ae8623eSMatthias Ringwald     }
88954ae8623eSMatthias Ringwald }
88964ae8623eSMatthias Ringwald 
889715a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
88984ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
88994ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
89004ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
89014ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
890215a15be3SMatthias Ringwald         if (iso_stream->con_handle == con_handle ) {
89034ae8623eSMatthias Ringwald             return iso_stream;
89044ae8623eSMatthias Ringwald         }
89054ae8623eSMatthias Ringwald     }
89064ae8623eSMatthias Ringwald     return NULL;
89074ae8623eSMatthias Ringwald }
89084ae8623eSMatthias Ringwald 
89094ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
8910346f8c2cSMatthias Ringwald     log_info("hci_iso_stream_finalize con_handle 0x%04x, big_handle 0x%02x", iso_stream->con_handle, iso_stream->big_handle);
89114ae8623eSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
89124ae8623eSMatthias Ringwald     btstack_memory_hci_iso_stream_free(iso_stream);
89134ae8623eSMatthias Ringwald }
89144ae8623eSMatthias Ringwald 
8915a90016deSMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t big_handle) {
89164ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
89174ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
89184ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
89194ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
8920a90016deSMatthias Ringwald         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
8921a90016deSMatthias Ringwald             (iso_stream->big_handle == big_handle)){
89224ae8623eSMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
89234ae8623eSMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
89244ae8623eSMatthias Ringwald         }
89254ae8623eSMatthias Ringwald     }
89264ae8623eSMatthias Ringwald }
8927a90016deSMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle){
89284ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
89294ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
89304ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
89314ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
89324ae8623eSMatthias Ringwald         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
89334ae8623eSMatthias Ringwald             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
89344ae8623eSMatthias Ringwald         }
89354ae8623eSMatthias Ringwald     }
89364ae8623eSMatthias Ringwald }
8937d39e4f95SMatthias Ringwald 
8938d39e4f95SMatthias Ringwald static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
8939d39e4f95SMatthias Ringwald     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
8940d39e4f95SMatthias Ringwald     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
8941d39e4f95SMatthias Ringwald     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
8942d39e4f95SMatthias Ringwald     return (sdu_len_offset + 2 + sdu_len) == size;
8943d39e4f95SMatthias Ringwald }
8944d39e4f95SMatthias Ringwald 
8945d39e4f95SMatthias Ringwald static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
8946d39e4f95SMatthias Ringwald     if (hci_stack->iso_packet_handler == NULL) {
8947d39e4f95SMatthias Ringwald         return;
8948d39e4f95SMatthias Ringwald     }
8949d39e4f95SMatthias Ringwald     if (size < 4) {
8950d39e4f95SMatthias Ringwald         return;
8951d39e4f95SMatthias Ringwald     }
8952d39e4f95SMatthias Ringwald 
8953d39e4f95SMatthias Ringwald     // parse header
8954d39e4f95SMatthias Ringwald     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
8955d39e4f95SMatthias Ringwald     uint16_t iso_data_len = little_endian_read_16(packet, 2);
8956d39e4f95SMatthias Ringwald     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
895715a15be3SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
8958d39e4f95SMatthias Ringwald     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
8959d39e4f95SMatthias Ringwald 
8960d39e4f95SMatthias Ringwald     // assert packet is complete
8961d39e4f95SMatthias Ringwald     if ((iso_data_len + 4u) != size){
8962d39e4f95SMatthias Ringwald         return;
8963d39e4f95SMatthias Ringwald     }
8964d39e4f95SMatthias Ringwald 
8965d39e4f95SMatthias Ringwald     if ((pb_flag & 0x01) == 0){
8966d39e4f95SMatthias Ringwald         if (pb_flag == 0x02){
8967d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and a complete SDU.
8968d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(packet, size)) {
8969d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
8970d39e4f95SMatthias Ringwald             }
8971d39e4f95SMatthias Ringwald         } else {
8972d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
8973d39e4f95SMatthias Ringwald             if (iso_stream == NULL){
8974d39e4f95SMatthias Ringwald                 return;
8975d39e4f95SMatthias Ringwald             }
8976d39e4f95SMatthias Ringwald             if (size > HCI_ISO_PAYLOAD_SIZE){
8977d39e4f95SMatthias Ringwald                 return;
8978d39e4f95SMatthias Ringwald             }
8979d39e4f95SMatthias Ringwald             memcpy(iso_stream->reassembly_buffer, packet, size);
8980d39e4f95SMatthias Ringwald             // fix pb_flag
8981d39e4f95SMatthias Ringwald             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
8982d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = size;
8983d39e4f95SMatthias Ringwald         }
8984d39e4f95SMatthias Ringwald     } else {
8985d39e4f95SMatthias Ringwald         // iso_data_load contains continuation or last fragment of an SDU
8986d39e4f95SMatthias Ringwald         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
8987d39e4f95SMatthias Ringwald         if (ts_flag != 0){
8988d39e4f95SMatthias Ringwald            return;
8989d39e4f95SMatthias Ringwald         }
8990d39e4f95SMatthias Ringwald         // append fragment
8991d39e4f95SMatthias Ringwald         if (iso_stream == NULL){
8992d39e4f95SMatthias Ringwald             return;
8993d39e4f95SMatthias Ringwald         }
8994d39e4f95SMatthias Ringwald         if (iso_stream->reassembly_pos == 0){
8995d39e4f95SMatthias Ringwald             return;
8996d39e4f95SMatthias Ringwald         }
8997d39e4f95SMatthias Ringwald         if ((iso_stream->reassembly_pos + iso_data_len) > size){
8998d39e4f95SMatthias Ringwald             // reset reassembly buffer
8999d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
9000d39e4f95SMatthias Ringwald             return;
9001d39e4f95SMatthias Ringwald         }
9002d39e4f95SMatthias Ringwald         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
9003d39e4f95SMatthias Ringwald         iso_stream->reassembly_pos += iso_data_len;
9004d39e4f95SMatthias Ringwald 
9005d39e4f95SMatthias Ringwald         // deliver if last fragment and SDU complete
9006d39e4f95SMatthias Ringwald         if (pb_flag == 0x03){
9007d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9008d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9009d39e4f95SMatthias Ringwald             }
9010d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
9011d39e4f95SMatthias Ringwald         }
9012d39e4f95SMatthias Ringwald     }
9013d39e4f95SMatthias Ringwald }
9014d39e4f95SMatthias Ringwald 
90157aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
90167aa35f6aSMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
90177aa35f6aSMatthias Ringwald     uint16_t pos = 0;
90187aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
90197aa35f6aSMatthias Ringwald     event[pos++] = 4 + (2 * big->num_bis);
90207aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
90217aa35f6aSMatthias Ringwald     event[pos++] = status;
90227aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
90237aa35f6aSMatthias Ringwald     event[pos++] = big->num_bis;
90247aa35f6aSMatthias Ringwald     uint8_t i;
90257aa35f6aSMatthias Ringwald     for (i=0;i<big->num_bis;i++){
90267aa35f6aSMatthias Ringwald         little_endian_store_16(event, pos, big->bis_con_handles[i]);
90277aa35f6aSMatthias Ringwald         pos += 2;
90287aa35f6aSMatthias Ringwald     }
90297aa35f6aSMatthias Ringwald     hci_emit_event(event, pos, 0);
90307aa35f6aSMatthias Ringwald }
90317aa35f6aSMatthias Ringwald 
90327aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big){
90337aa35f6aSMatthias Ringwald     uint8_t event [4];
90347aa35f6aSMatthias Ringwald     uint16_t pos = 0;
90357aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
90367aa35f6aSMatthias Ringwald     event[pos++] = 2;
90377aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
90387aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
90397aa35f6aSMatthias Ringwald     hci_emit_event(event, pos, 0);
90407aa35f6aSMatthias Ringwald }
90417aa35f6aSMatthias Ringwald 
90422a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
90432a6c0f82SMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
90442a6c0f82SMatthias Ringwald     uint16_t pos = 0;
90452a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
90462a6c0f82SMatthias Ringwald     event[pos++] = 4;
90472a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
90482a6c0f82SMatthias Ringwald     event[pos++] = status;
90492a6c0f82SMatthias Ringwald     event[pos++] = big_sync->big_handle;
90502a6c0f82SMatthias Ringwald     event[pos++] = big_sync->num_bis;
90512a6c0f82SMatthias Ringwald     uint8_t i;
90522a6c0f82SMatthias Ringwald     for (i=0;i<big_sync->num_bis;i++){
90532a6c0f82SMatthias Ringwald         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
90542a6c0f82SMatthias Ringwald         pos += 2;
90552a6c0f82SMatthias Ringwald     }
90562a6c0f82SMatthias Ringwald     hci_emit_event(event, pos, 0);
90572a6c0f82SMatthias Ringwald }
90582a6c0f82SMatthias Ringwald 
90592a6c0f82SMatthias Ringwald static void hci_emit_big_sync_stopped(const le_audio_big_sync_t * big_sync){
90602a6c0f82SMatthias Ringwald     uint8_t event [4];
90612a6c0f82SMatthias Ringwald     uint16_t pos = 0;
90622a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
90632a6c0f82SMatthias Ringwald     event[pos++] = 2;
90642a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
90652a6c0f82SMatthias Ringwald     event[pos++] = big_sync->big_handle;
90662a6c0f82SMatthias Ringwald     hci_emit_event(event, pos, 0);
90672a6c0f82SMatthias Ringwald }
90682a6c0f82SMatthias Ringwald 
90695ade6657SMatthias Ringwald static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
90705ade6657SMatthias Ringwald     uint8_t event[6];
90715ade6657SMatthias Ringwald     uint16_t pos = 0;
90725ade6657SMatthias Ringwald     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
90735ade6657SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
90745ade6657SMatthias Ringwald     event[pos++] = big->big_handle;
90755ade6657SMatthias Ringwald     event[pos++] = bis_index;
90765ade6657SMatthias Ringwald     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
90775ade6657SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
90785ade6657SMatthias Ringwald }
90795ade6657SMatthias Ringwald 
90807aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
90817aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
90827aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
90837aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
90847aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
90857aa35f6aSMatthias Ringwald         if ( big->big_handle == big_handle ) {
90867aa35f6aSMatthias Ringwald             return big;
90877aa35f6aSMatthias Ringwald         }
90887aa35f6aSMatthias Ringwald     }
90897aa35f6aSMatthias Ringwald     return NULL;
90907aa35f6aSMatthias Ringwald }
90917aa35f6aSMatthias Ringwald 
90922a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
90932a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_t it;
90942a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
90952a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
90962a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
90972a6c0f82SMatthias Ringwald         if ( big_sync->big_handle == big_handle ) {
90982a6c0f82SMatthias Ringwald             return big_sync;
90992a6c0f82SMatthias Ringwald         }
91002a6c0f82SMatthias Ringwald     }
91012a6c0f82SMatthias Ringwald     return NULL;
91022a6c0f82SMatthias Ringwald }
91032a6c0f82SMatthias Ringwald 
910401d4f05fSMatthias Ringwald void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
910501d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = num_packets;
910601d4f05fSMatthias Ringwald }
910701d4f05fSMatthias Ringwald 
91085ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void){
91095ade6657SMatthias Ringwald     btstack_linked_list_iterator_t it;
91105ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
91115ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
91125ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
91135ade6657SMatthias Ringwald         if (big->can_send_now_requested){
9114d4e5d4faSMatthias Ringwald             // check if no outgoing iso packets pending and no can send now have to be emitted
91155ade6657SMatthias Ringwald             uint8_t i;
91165ade6657SMatthias Ringwald             bool can_send = true;
91175ade6657SMatthias Ringwald             for (i=0;i<big->num_bis;i++){
91185ade6657SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
911901d4f05fSMatthias Ringwald                 if ((iso_stream == NULL) || (iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
91205ade6657SMatthias Ringwald                     can_send = false;
91215ade6657SMatthias Ringwald                     break;
91225ade6657SMatthias Ringwald                 }
91235ade6657SMatthias Ringwald             }
91245ade6657SMatthias Ringwald             if (can_send){
91255ade6657SMatthias Ringwald                 // propagate can send now to individual streams
91265ade6657SMatthias Ringwald                 big->can_send_now_requested = false;
91275ade6657SMatthias Ringwald                 for (i=0;i<big->num_bis;i++){
91285ade6657SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
91295ade6657SMatthias Ringwald                     iso_stream->emit_ready_to_send = true;
91305ade6657SMatthias Ringwald                 }
91315ade6657SMatthias Ringwald             }
91325ade6657SMatthias Ringwald         }
91335ade6657SMatthias Ringwald     }
91345ade6657SMatthias Ringwald 
91355ade6657SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return;
91365ade6657SMatthias Ringwald 
91375ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
91385ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
91395ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
91405ade6657SMatthias Ringwald         // report bis ready
91415ade6657SMatthias Ringwald         uint8_t i;
91425ade6657SMatthias Ringwald         for (i=0;i<big->num_bis;i++){
91435ade6657SMatthias Ringwald             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
91445ade6657SMatthias Ringwald             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
91455ade6657SMatthias Ringwald                 iso_stream->emit_ready_to_send = false;
91465ade6657SMatthias Ringwald                 hci_emit_bis_can_send_now(big, i);
91475ade6657SMatthias Ringwald                 break;
91485ade6657SMatthias Ringwald             }
91495ade6657SMatthias Ringwald         }
91505ade6657SMatthias Ringwald     }
91515ade6657SMatthias Ringwald }
91525ade6657SMatthias Ringwald 
91537aa35f6aSMatthias Ringwald uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
91547aa35f6aSMatthias Ringwald     if (hci_big_for_handle(big_params->big_handle) != NULL){
91557aa35f6aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
91567aa35f6aSMatthias Ringwald     }
91577aa35f6aSMatthias Ringwald     if (big_params->num_bis == 0){
91587aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
91597aa35f6aSMatthias Ringwald     }
91607aa35f6aSMatthias Ringwald     if (big_params->num_bis > MAX_NR_BIS){
91617aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
91627aa35f6aSMatthias Ringwald     }
91637aa35f6aSMatthias Ringwald 
9164fb16346aSMatthias Ringwald     // reserve ISO Streams
9165fb16346aSMatthias Ringwald     uint8_t i;
9166fb16346aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
9167fb16346aSMatthias Ringwald     for (i=0;i<big_params->num_bis;i++){
9168fb16346aSMatthias Ringwald         status = hci_iso_stream_create(HCI_CON_HANDLE_INVALID, big_params->big_handle);
9169fb16346aSMatthias Ringwald         if (status != ERROR_CODE_SUCCESS) {
9170fb16346aSMatthias Ringwald             break;
9171fb16346aSMatthias Ringwald         }
9172fb16346aSMatthias Ringwald     }
9173fb16346aSMatthias Ringwald 
9174fb16346aSMatthias Ringwald     // free structs on error
9175fb16346aSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
9176fb16346aSMatthias Ringwald         hci_iso_stream_requested_finalize(big_params->big_handle);
9177fb16346aSMatthias Ringwald         return status;
9178fb16346aSMatthias Ringwald     }
9179fb16346aSMatthias Ringwald 
91807aa35f6aSMatthias Ringwald     le_audio_big_t * big = storage;
91817aa35f6aSMatthias Ringwald     big->big_handle = big_params->big_handle;
91827aa35f6aSMatthias Ringwald     big->params = big_params;
91837aa35f6aSMatthias Ringwald     big->state = LE_AUDIO_BIG_STATE_CREATE;
91847aa35f6aSMatthias Ringwald     big->num_bis = big_params->num_bis;
91857aa35f6aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
91867aa35f6aSMatthias Ringwald 
91877aa35f6aSMatthias Ringwald     hci_run();
91887aa35f6aSMatthias Ringwald 
91897aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
91907aa35f6aSMatthias Ringwald }
91917aa35f6aSMatthias Ringwald 
91922a6c0f82SMatthias Ringwald uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
91932a6c0f82SMatthias Ringwald     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
91942a6c0f82SMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
91952a6c0f82SMatthias Ringwald     }
91962a6c0f82SMatthias Ringwald     if (big_sync_params->num_bis == 0){
91972a6c0f82SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
91982a6c0f82SMatthias Ringwald     }
91992a6c0f82SMatthias Ringwald     if (big_sync_params->num_bis > MAX_NR_BIS){
92002a6c0f82SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
92012a6c0f82SMatthias Ringwald     }
92022a6c0f82SMatthias Ringwald 
92032a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = storage;
92042a6c0f82SMatthias Ringwald     big_sync->big_handle = big_sync_params->big_handle;
92052a6c0f82SMatthias Ringwald     big_sync->params = big_sync_params;
92062a6c0f82SMatthias Ringwald     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
92072a6c0f82SMatthias Ringwald     big_sync->num_bis = big_sync_params->num_bis;
92082a6c0f82SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
92092a6c0f82SMatthias Ringwald 
92102a6c0f82SMatthias Ringwald     hci_run();
92112a6c0f82SMatthias Ringwald 
92122a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
92132a6c0f82SMatthias Ringwald }
92142a6c0f82SMatthias Ringwald 
92157aa35f6aSMatthias Ringwald uint8_t gap_big_terminate(uint8_t big_handle){
92167aa35f6aSMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
92177aa35f6aSMatthias Ringwald     if (big == NULL){
92187aa35f6aSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
92197aa35f6aSMatthias Ringwald     }
92207aa35f6aSMatthias Ringwald     switch (big->state){
92217aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
92227aa35f6aSMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
92232a6c0f82SMatthias Ringwald             hci_emit_big_terminated(big);
92242a6c0f82SMatthias Ringwald             break;
92252a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
92262a6c0f82SMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
92277aa35f6aSMatthias Ringwald             break;
92287aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
92297aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
92307aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
92317aa35f6aSMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
92327aa35f6aSMatthias Ringwald             hci_run();
92337aa35f6aSMatthias Ringwald             break;
92342a6c0f82SMatthias Ringwald         default:
92352a6c0f82SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
92362a6c0f82SMatthias Ringwald     }
92372a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
92382a6c0f82SMatthias Ringwald }
92392a6c0f82SMatthias Ringwald 
92402a6c0f82SMatthias Ringwald uint8_t gap_big_sync_terminate(uint8_t big_handle){
92412a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
92422a6c0f82SMatthias Ringwald     if (big_sync == NULL){
92432a6c0f82SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
92442a6c0f82SMatthias Ringwald     }
92452a6c0f82SMatthias Ringwald     switch (big_sync->state){
92462a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
92472a6c0f82SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
92482a6c0f82SMatthias Ringwald             hci_emit_big_sync_stopped(big_sync);
92492a6c0f82SMatthias Ringwald             break;
92507aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
92512a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
92522a6c0f82SMatthias Ringwald             break;
92532a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
92542a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
92552a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
92562a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
92572a6c0f82SMatthias Ringwald             hci_run();
92587aa35f6aSMatthias Ringwald             break;
92597aa35f6aSMatthias Ringwald         default:
92607aa35f6aSMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
92617aa35f6aSMatthias Ringwald     }
92627aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
92637aa35f6aSMatthias Ringwald }
9264d39e4f95SMatthias Ringwald 
92655ade6657SMatthias Ringwald uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
92665ade6657SMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
92675ade6657SMatthias Ringwald     if (big == NULL){
92685ade6657SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
92695ade6657SMatthias Ringwald     }
92705ade6657SMatthias Ringwald     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
92715ade6657SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
92725ade6657SMatthias Ringwald     }
92735ade6657SMatthias Ringwald     big->can_send_now_requested = true;
92745ade6657SMatthias Ringwald     hci_iso_notify_can_send_now();
92755ade6657SMatthias Ringwald     return ERROR_CODE_SUCCESS;
92765ade6657SMatthias Ringwald }
9277f40c73b4SMatthias Ringwald #endif
92784ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
9279f40c73b4SMatthias Ringwald 
9280eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
928118976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
928218976c74SMatthias Ringwald     hci_connection_t * conn;
928318976c74SMatthias Ringwald 
928418976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
928518976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
928618976c74SMatthias Ringwald 
92877d33cb26SMilanka Ringwald     // setup Controller info
92887d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
92897d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
92907d33cb26SMilanka Ringwald 
929118976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
929218976c74SMatthias Ringwald     addr[5] = 0x01;
929318976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
929418976c74SMatthias Ringwald     conn->con_handle = addr[5];
929518976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
929618976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
92977d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
929818976c74SMatthias Ringwald 
929918976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
930018976c74SMatthias Ringwald     addr[5] = 0x02;
930118976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
930218976c74SMatthias Ringwald     conn->con_handle = addr[5];
930318976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
930418976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
93057d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
930618976c74SMatthias Ringwald 
930718976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
930818976c74SMatthias Ringwald     addr[5] = 0x03;
930918976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
931018976c74SMatthias Ringwald     conn->con_handle = addr[5];
931118976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
931218976c74SMatthias Ringwald     conn->state = OPEN;
93137d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
931418976c74SMatthias Ringwald 
931518976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
931618976c74SMatthias Ringwald     addr[5] = 0x04;
931718976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
931818976c74SMatthias Ringwald     conn->con_handle = addr[5];
931918976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
932018976c74SMatthias Ringwald     conn->state = OPEN;
93217d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
932218976c74SMatthias Ringwald 
932318976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
932418976c74SMatthias Ringwald     addr[5] = 0x05;
932518976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
932618976c74SMatthias Ringwald     conn->con_handle = addr[5];
932718976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
932818976c74SMatthias Ringwald     conn->state = OPEN;
93297d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
93308046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
933118976c74SMatthias Ringwald }
933218976c74SMatthias Ringwald 
9333eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
9334eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
9335eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9336eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9337eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
9338eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
9339eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
9340eddac615SMatthias Ringwald     }
9341eddac615SMatthias Ringwald }
93421470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
9343b6ffb67fSMatthias Ringwald     hci_stack->le_scanning_param_update = false;
93441470db0cSMatthias Ringwald     hci_init_done();
93451470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
93461470db0cSMatthias Ringwald }
9347eddac615SMatthias Ringwald #endif
9348