xref: /btstack/src/hci.c (revision 620553bdf214b06f6e38a50858c2aa4911f242be)
11f504dbdSmatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
232fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
242fca4dadSMilanka Ringwald  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "hci.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
411f504dbdSmatthias.ringwald  *  hci.c
421f504dbdSmatthias.ringwald  *
431f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
441f504dbdSmatthias.ringwald  *
451f504dbdSmatthias.ringwald  */
461f504dbdSmatthias.ringwald 
477907f069SMatthias Ringwald #include "btstack_config.h"
4828171530Smatthias.ringwald 
497f2435e6Smatthias.ringwald 
5006b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
51aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
528f2a52f4SMatthias Ringwald #include "btstack_run_loop_embedded.h"
53a484130cSMatthias Ringwald #endif
5406b9e820SMatthias Ringwald #endif
55a484130cSMatthias Ringwald 
56a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
57472a5742SMatthias Ringwald #include "gap.h"
5821debf25SMatthias Ringwald #include "ble/le_device_db.h"
5945c102fdSMatthias Ringwald #endif
6045c102fdSMatthias Ringwald 
6193b8dc03Smatthias.ringwald #include <stdarg.h>
6293b8dc03Smatthias.ringwald #include <string.h>
635838a2edSMatthias Ringwald #include <inttypes.h>
647f2435e6Smatthias.ringwald 
6516ece135SMatthias Ringwald #include "btstack_debug.h"
660e2df43fSMatthias Ringwald #include "btstack_event.h"
674a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
684a3574a1SMatthias Ringwald #include "btstack_memory.h"
6961f37892SMatthias Ringwald #include "bluetooth_company_id.h"
701cfb383eSMatthias Ringwald #include "bluetooth_data_types.h"
714a3574a1SMatthias Ringwald #include "gap.h"
724a3574a1SMatthias Ringwald #include "hci.h"
734a3574a1SMatthias Ringwald #include "hci_cmd.h"
74d8905019Smatthias.ringwald #include "hci_dump.h"
751cfb383eSMatthias Ringwald #include "ad_parser.h"
7693b8dc03Smatthias.ringwald 
778ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
788ad9cf99SMatthias Ringwald #include <stdio.h>  // sprintf
798ad9cf99SMatthias Ringwald #endif
808ad9cf99SMatthias Ringwald 
812b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
822b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_NUM
832b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
842b838201SMatthias Ringwald #endif
852b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_LEN
862b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
872b838201SMatthias Ringwald #endif
882b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_NUM
892b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
902b838201SMatthias Ringwald #endif
912b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_LEN
922b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
932b838201SMatthias Ringwald #endif
942b838201SMatthias Ringwald #endif
951b0e3922Smatthias.ringwald 
96616cfd90SMatthias Ringwald #ifndef MAX_NR_CONTROLLER_ACL_BUFFERS
97616cfd90SMatthias Ringwald #define MAX_NR_CONTROLLER_ACL_BUFFERS 255
98616cfd90SMatthias Ringwald #endif
99616cfd90SMatthias Ringwald #ifndef MAX_NR_CONTROLLER_SCO_PACKETS
100616cfd90SMatthias Ringwald #define MAX_NR_CONTROLLER_SCO_PACKETS 255
101616cfd90SMatthias Ringwald #endif
102616cfd90SMatthias Ringwald 
1036bcf18c2SMatthias Ringwald #ifndef HCI_ACL_CHUNK_SIZE_ALIGNMENT
1046bcf18c2SMatthias Ringwald #define HCI_ACL_CHUNK_SIZE_ALIGNMENT 1
1056bcf18c2SMatthias Ringwald #endif
1066bcf18c2SMatthias Ringwald 
107aa81e641SMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
108aa81e641SMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
109aa81e641SMatthias Ringwald #endif
110aa81e641SMatthias Ringwald 
1111e20a53eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
1121e20a53eSMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT."
1131e20a53eSMatthias Ringwald #endif
1141e20a53eSMatthias Ringwald 
115169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
11662473419SMatthias Ringwald 
11762473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
118659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
11962473419SMatthias Ringwald #endif
120ee091cf1Smatthias.ringwald 
1211cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1221cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1231cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1241cfb383eSMatthias Ringwald #endif
1251cfb383eSMatthias Ringwald 
126f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
127f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN       0x01
128f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX       0x30
12930199e24SMatthias Ringwald #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02
13030199e24SMatthias Ringwald #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03
131beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE         0x00
132beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
133beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE       0x81
134beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
135beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
13630199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_PERIODIC     0x84
13730199e24SMatthias Ringwald #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85
138f5875de5SMatthias Ringwald 
139b7f1ee76SMatthias Ringwald // GAP Remote Name Request
140b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
141b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
142b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
143b7f1ee76SMatthias Ringwald 
1440a51f88bSMatthias Ringwald // GAP Pairing
1450a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1460a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1470a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1480a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1490a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1500a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1510a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
152cc15bb2cSMatthias Ringwald #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE  7
1530a51f88bSMatthias Ringwald 
15425e46151SMatthias Ringwald //
1559ce37759SMatthias Ringwald // compact storage of relevant supported HCI Commands.
1569ce37759SMatthias Ringwald // X-Macro below provides enumeration and mapping table into the supported
15725e46151SMatthias Ringwald // commands bitmap (64 bytes) from HCI Read Local Supported Commands
15825e46151SMatthias Ringwald //
15925e46151SMatthias Ringwald 
16025e46151SMatthias Ringwald // format: command name, byte offset, bit nr in 64-byte supported commands
1618c021356SMatthias Ringwald // currently stored in 32-bit variable
16225e46151SMatthias Ringwald #define SUPPORTED_HCI_COMMANDS \
1639ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES         ,  2, 5) \
16425e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \
1659ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE                      , 14, 7) \
16625e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \
1679ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE              , 20, 4) \
168ff7d1758SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2                 , 22, 2) \
1699ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED               , 24, 6) \
1709ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \
1719ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST         , 32, 3) \
1729ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND  , 32, 6) \
17325e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \
17425e46151SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE      , 35, 1) \
175a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH           , 35, 3) \
1769ce37759SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY                    , 35, 5) \
17763671e69SMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE    , 36, 6) \
17879b7ea2dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2                , 41, 5) \
179a391128dSMatthias Ringwald     X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE           , 45, 7) \
18025e46151SMatthias Ringwald 
18125e46151SMatthias Ringwald // enumerate supported commands
18225e46151SMatthias Ringwald #define X(name, offset, bit) name,
18325e46151SMatthias Ringwald enum {
18425e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS
18525e46151SMatthias Ringwald     SUPPORTED_HCI_COMMANDS_COUNT
18625e46151SMatthias Ringwald };
18725e46151SMatthias Ringwald #undef X
18825e46151SMatthias Ringwald 
189b83d5eabSMatthias Ringwald // prototypes
19035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
191758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
19271fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable);
19335454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
19420dcdd22SMatthias Ringwald static bool hci_remote_ssp_supported(hci_con_handle_t con_handle);
19567aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
19635454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
19735454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
198a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
19935454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
200ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
20196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
20252db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
2039784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
20452db98b2SMatthias Ringwald #endif
2051cfb383eSMatthias Ringwald 
2067586ee35S[email protected] static int  hci_power_control_on(void);
2077586ee35S[email protected] static void hci_power_control_off(void);
2086da48142SSean Wilson static void hci_state_reset(void);
209685ec254SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds);
210fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
211fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
212b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
213b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
214b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
215b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
216b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
21795d71764SMatthias Ringwald static void hci_run(void);
218617c03d6SMatthias Ringwald static bool hci_is_le_connection(hci_connection_t * connection);
2196a5ffed8SMatthias Ringwald 
2206a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
221f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
222dbe0d85cSMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection);
2236a5ffed8SMatthias Ringwald #endif
2245d509858SMatthias Ringwald 
225a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
226e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
22739677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
228384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
229667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
2309c77c9dbSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void);
231c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void);
23273799937SMatthias Ringwald static bool hci_run_general_gap_le(void);
2335d509858SMatthias Ringwald #endif
23425df6c61SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
235ee54aff5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
23625df6c61SMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle);
237ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
238ee54aff5SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
2394ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
240969d876aSMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id);
2414ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream);
242778463d0SMatthias Ringwald static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id);
24315a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle);
24415a15be3SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t big_handle);
24515a15be3SMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle);
246d39e4f95SMatthias Ringwald static void hci_iso_packet_handler(uint8_t * packet, uint16_t size);
2477aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle);
248d3a89d91SMatthias Ringwald static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id);
2495ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void);
2507aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status);
2517aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big);
2522a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status);
253d04a9afcSMatthias Ringwald static void hci_emit_big_sync_stopped(uint8_t big_handle);
254d3a89d91SMatthias Ringwald static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status);
25514045fdbSMatthias Ringwald static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status);
2562a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle);
25714045fdbSMatthias Ringwald 
2584ae8623eSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
259ee54aff5SMatthias Ringwald #endif /* ENABLE_BLE */
260758b46ceSmatthias.ringwald 
26106b35ec0Smatthias.ringwald // the STACK is here
2623a9fb326S[email protected] #ifndef HAVE_MALLOC
2633a9fb326S[email protected] static hci_stack_t   hci_stack_static;
2643a9fb326S[email protected] #endif
2653a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
26616833f0aSmatthias.ringwald 
2671c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
26863168530SMatthias Ringwald // default name
26963168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
27063168530SMatthias Ringwald 
27166fb9560S[email protected] // test helper
27266fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
2731c9e5e9dSMatthias Ringwald #endif
27466fb9560S[email protected] 
275aee5d5c1SMatthias Ringwald // reset connection state on create and on reconnect
276aee5d5c1SMatthias Ringwald // don't overwrite addr, con handle, role
277aee5d5c1SMatthias Ringwald static void hci_connection_init(hci_connection_t * conn){
2788daf94bcSMatthias Ringwald     conn->authentication_flags = AUTH_FLAG_NONE;
27996a45072S[email protected]     conn->bonding_flags = 0;
28096a45072S[email protected]     conn->requested_security_level = LEVEL_0;
28152db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
28288a03c8dSMatthias Ringwald     conn->request_role = HCI_ROLE_INVALID;
283140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = 0xffff;
284965a4ccfSMatthias Ringwald     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
285e9f98c4aSMatthias Ringwald     conn->link_key_type = INVALID_LINK_KEY;
28691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
28791a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
28896a45072S[email protected]     hci_connection_timestamp(conn);
28952db98b2SMatthias Ringwald #endif
29096a45072S[email protected]     conn->acl_recombination_length = 0;
29196a45072S[email protected]     conn->acl_recombination_pos = 0;
292ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
293760b20efSMatthias Ringwald 
294da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
295b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
296b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
297b90f6e0aSMatthias Ringwald #endif
2980f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2990f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
3000f3b27c5SMatthias Ringwald #endif
301cb439cf1SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
302cb439cf1SMatthias Ringwald     conn->classic_oob_c_192 = NULL;
303cb439cf1SMatthias Ringwald     conn->classic_oob_r_192 = NULL;
304cb439cf1SMatthias Ringwald     conn->classic_oob_c_256 = NULL;
305cb439cf1SMatthias Ringwald     conn->classic_oob_r_256 = NULL;
306cb439cf1SMatthias Ringwald #endif
307aee5d5c1SMatthias Ringwald }
308aee5d5c1SMatthias Ringwald 
309aee5d5c1SMatthias Ringwald /**
310aee5d5c1SMatthias Ringwald  * create connection for given address
311aee5d5c1SMatthias Ringwald  *
312aee5d5c1SMatthias Ringwald  * @return connection OR NULL, if no memory left
313aee5d5c1SMatthias Ringwald  */
31488f925b1SMatthias Ringwald static hci_connection_t *
31588f925b1SMatthias Ringwald create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type, hci_role_t role) {
316aee5d5c1SMatthias Ringwald     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
317aee5d5c1SMatthias Ringwald 
318aee5d5c1SMatthias Ringwald     hci_connection_t * conn = btstack_memory_hci_connection_get();
319aee5d5c1SMatthias Ringwald     if (!conn) return NULL;
320aee5d5c1SMatthias Ringwald     hci_connection_init(conn);
321aee5d5c1SMatthias Ringwald 
322aee5d5c1SMatthias Ringwald     bd_addr_copy(conn->address, addr);
323aee5d5c1SMatthias Ringwald     conn->address_type = addr_type;
324aee5d5c1SMatthias Ringwald     conn->con_handle = HCI_CON_HANDLE_INVALID;
32588f925b1SMatthias Ringwald     conn->role = role;
3263bd96807SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
3273bd96807SMatthias Ringwald     conn->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
328027f4677SMatthias Ringwald     conn->le_past_advertising_handle = 0xff;
3293bd96807SMatthias Ringwald #endif
330665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
331aee5d5c1SMatthias Ringwald 
33296a45072S[email protected]     return conn;
33396a45072S[email protected] }
33466fb9560S[email protected] 
335da886c03S[email protected] 
336da886c03S[email protected] /**
337da886c03S[email protected]  * get le connection parameter range
338da886c03S[email protected] *
339da886c03S[email protected]  * @return le connection parameter range struct
340da886c03S[email protected]  */
3414ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
3424ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
343da886c03S[email protected] }
344da886c03S[email protected] 
345da886c03S[email protected] /**
346da886c03S[email protected]  * set le connection parameter range
347da886c03S[email protected]  *
348da886c03S[email protected]  */
349da886c03S[email protected] 
3504ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
3514ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
352da886c03S[email protected] }
353da886c03S[email protected] 
354da886c03S[email protected] /**
35573cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
35673cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
35773cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
35873cd8a2aSMatthias Ringwald  * @param conn_latency
35973cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
3606b65794dSMilanka Ringwald  * @return 1 if included
36173cd8a2aSMatthias Ringwald  */
36273cd8a2aSMatthias 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){
36373cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
36473cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
36573cd8a2aSMatthias Ringwald 
36673cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
36773cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
36873cd8a2aSMatthias Ringwald 
36973cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
37073cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
37173cd8a2aSMatthias Ringwald 
37273cd8a2aSMatthias Ringwald     return 1;
37373cd8a2aSMatthias Ringwald }
37473cd8a2aSMatthias Ringwald 
37573cd8a2aSMatthias Ringwald /**
3762b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
3772b6ab3e6SMatthias Ringwald  * @note: default: 1
3782b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
3792b6ab3e6SMatthias Ringwald  */
380d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3812b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
3822b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
3832b6ab3e6SMatthias Ringwald }
384d4e4907bSMatthias Ringwald #endif
3852b6ab3e6SMatthias Ringwald 
3862b6ab3e6SMatthias Ringwald /**
387da886c03S[email protected]  * get hci connections iterator
388da886c03S[email protected]  *
389da886c03S[email protected]  * @return hci connections iterator
390da886c03S[email protected]  */
391da886c03S[email protected] 
392665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
393665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
394da886c03S[email protected] }
395da886c03S[email protected] 
39697addcc5Smatthias.ringwald /**
397ee091cf1Smatthias.ringwald  * get connection for a given handle
398ee091cf1Smatthias.ringwald  *
399ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
400ee091cf1Smatthias.ringwald  */
4015061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
402665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
403665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
404665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
405665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
4063ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
407da886c03S[email protected]             return item;
408ee091cf1Smatthias.ringwald         }
409ee091cf1Smatthias.ringwald     }
410ee091cf1Smatthias.ringwald     return NULL;
411ee091cf1Smatthias.ringwald }
412ee091cf1Smatthias.ringwald 
41396a45072S[email protected] /**
41496a45072S[email protected]  * get connection for given address
41596a45072S[email protected]  *
41696a45072S[email protected]  * @return connection OR NULL, if not found
41796a45072S[email protected]  */
418667ba9d1SMatthias Ringwald hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
419665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
420665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
421665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
422665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
42396a45072S[email protected]         if (connection->address_type != addr_type)  continue;
42496a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
42562bda3fbS[email protected]         return connection;
42662bda3fbS[email protected]     }
42762bda3fbS[email protected]     return NULL;
42862bda3fbS[email protected] }
42962bda3fbS[email protected] 
430d5f71a7eSMatthias Ringwald #ifdef ENABLE_CLASSIC
431d5f71a7eSMatthias Ringwald 
4323e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
4333e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
4343e5e0926SMatthias Ringwald }
43552db98b2SMatthias Ringwald 
436228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
437228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
438228e430cSMatthias Ringwald }
439228e430cSMatthias Ringwald 
440ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
441ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
442ee752bb8SMatthias Ringwald     int connections = 0;
443ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
444ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
445ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
446ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
447ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
448ee752bb8SMatthias Ringwald         connections++;
449ee752bb8SMatthias Ringwald     }
450ee752bb8SMatthias Ringwald     return connections;
451ee752bb8SMatthias Ringwald }
452ee752bb8SMatthias Ringwald #endif
453ee752bb8SMatthias Ringwald 
454ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
45591a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
456aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
457528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
458c785ef68Smatthias.ringwald         // connections might be timed out
459c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
460c785ef68Smatthias.ringwald     }
461f316a845SMatthias Ringwald #else
462c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
4635f26aadcSMatthias Ringwald         // connections might be timed out
4645f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
4655f26aadcSMatthias Ringwald     }
4665f26aadcSMatthias Ringwald #endif
467c785ef68Smatthias.ringwald }
468ee091cf1Smatthias.ringwald 
469ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
470aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
471528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
472f316a845SMatthias Ringwald #else
473528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
4745f26aadcSMatthias Ringwald #endif
475ee091cf1Smatthias.ringwald }
476ee091cf1Smatthias.ringwald 
47743bfb1bdSmatthias.ringwald /**
47880ca58a0Smatthias.ringwald  * add authentication flags and reset timer
47996a45072S[email protected]  * @note: assumes classic connection
4802e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
4817fde4af9Smatthias.ringwald  */
4827fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
4837fde4af9Smatthias.ringwald     bd_addr_t addr;
484724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
485f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4867fde4af9Smatthias.ringwald     if (conn) {
48728ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
48880ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
4897fde4af9Smatthias.ringwald     }
4907fde4af9Smatthias.ringwald }
4917fde4af9Smatthias.ringwald 
4921714cbbdSMatthias Ringwald static bool hci_pairing_active(hci_connection_t * hci_connection){
4938daf94bcSMatthias Ringwald     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
4941714cbbdSMatthias Ringwald }
4951714cbbdSMatthias Ringwald 
4961714cbbdSMatthias Ringwald static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
4971714cbbdSMatthias Ringwald     if (hci_pairing_active(hci_connection)) return;
4981714cbbdSMatthias Ringwald     if (ssp){
4998daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
5001714cbbdSMatthias Ringwald     } else {
5018daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
5021714cbbdSMatthias Ringwald     }
5031714cbbdSMatthias Ringwald     // if we are initiator, we have sent an HCI Authenticate Request
5041714cbbdSMatthias Ringwald     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
5051714cbbdSMatthias Ringwald 
5065a561920SMatthias Ringwald     // if we are responder, use minimal service security level as required level
5075a561920SMatthias Ringwald     if (!initiator){
508acadfdd0SMatthias 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);
5095a561920SMatthias Ringwald     }
5105a561920SMatthias Ringwald 
5115a561920SMatthias Ringwald     log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level);
51277208d90SMatthias Ringwald 
51377208d90SMatthias Ringwald     uint8_t event[12];
51477208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_STARTED;
51577208d90SMatthias Ringwald     event[1] = 10;
516bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
5174159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
51877208d90SMatthias Ringwald     event[10] = (uint8_t) ssp;
51977208d90SMatthias Ringwald     event[11] = (uint8_t) initiator;
52077208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5211714cbbdSMatthias Ringwald }
5221714cbbdSMatthias Ringwald 
5231714cbbdSMatthias Ringwald static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
5243c439ac4SMatthias Ringwald     hci_connection->requested_security_level = LEVEL_0;
5251714cbbdSMatthias Ringwald     if (!hci_pairing_active(hci_connection)) return;
5268daf94bcSMatthias Ringwald     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
5271e7371deSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
528cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_192 = NULL;
529cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_192 = NULL;
530cb439cf1SMatthias Ringwald     hci_connection->classic_oob_c_256 = NULL;
531cb439cf1SMatthias Ringwald     hci_connection->classic_oob_r_256 = NULL;
5321e7371deSMatthias Ringwald #endif
5331714cbbdSMatthias Ringwald     log_info("pairing complete, status %02x", status);
53477208d90SMatthias Ringwald 
5353176c896SMatthias Ringwald     uint8_t event[11];
53677208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_COMPLETE;
53777208d90SMatthias Ringwald     event[1] = 9;
538bfaf6993SMatthias Ringwald     little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle);
5394159a80bSMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[4]);
54077208d90SMatthias Ringwald     event[10] = status;
54177208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5425999ee11SMatthias Ringwald 
5435999ee11SMatthias Ringwald     // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted
5445999ee11SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){
5455999ee11SMatthias Ringwald         hci_connection->bonding_flags &= ~BONDING_DEDICATED;
5465999ee11SMatthias Ringwald         hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
5475999ee11SMatthias Ringwald         hci_connection->bonding_status = status;
5485999ee11SMatthias Ringwald     }
5491714cbbdSMatthias Ringwald }
5501714cbbdSMatthias Ringwald 
55120dcdd22SMatthias Ringwald bool hci_authentication_active_for_handle(hci_con_handle_t handle){
5525061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
55320dcdd22SMatthias Ringwald     if (!conn) return false;
55420dcdd22SMatthias Ringwald     return hci_pairing_active(conn);
55580ca58a0Smatthias.ringwald }
55680ca58a0Smatthias.ringwald 
55715a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
55855597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5592bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
560a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
561c12e46e7Smatthias.ringwald }
56255597469SMatthias Ringwald 
56355597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
56455597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
5652bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
56655597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
567c12e46e7Smatthias.ringwald }
5681b6fb31bSMatthias Ringwald 
569e8ad470fSMatthias Ringwald bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
570e8ad470fSMatthias Ringwald 	if (!hci_stack->link_key_db) return false;
57176b0318eSMatthias Ringwald 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
57276b0318eSMatthias Ringwald 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
57376b0318eSMatthias Ringwald 	return result;
574e8ad470fSMatthias Ringwald }
575e8ad470fSMatthias Ringwald 
576ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
577ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
578ceecb9d9SMatthias Ringwald     link_key_t link_key;
579ceecb9d9SMatthias Ringwald     link_key_type_t type;
580ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
581ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
582ceecb9d9SMatthias Ringwald     if (!ok) {
583ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
584ceecb9d9SMatthias Ringwald         return;
585ceecb9d9SMatthias Ringwald     }
586ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
587ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
588ceecb9d9SMatthias Ringwald     }
589ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
590ceecb9d9SMatthias Ringwald }
591ceecb9d9SMatthias Ringwald 
5921b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
5931b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
5941b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
5951b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
5961b6fb31bSMatthias Ringwald }
5971b6fb31bSMatthias 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){
5981b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
5991b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
6001b6fb31bSMatthias Ringwald }
6011b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
6021b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
6031b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
6041b6fb31bSMatthias Ringwald }
60535454696SMatthias Ringwald #endif
606c12e46e7Smatthias.ringwald 
607eb8076ddSMatthias Ringwald static bool hci_is_le_connection_type(bd_addr_type_t address_type){
608eb8076ddSMatthias Ringwald     switch (address_type){
609ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
610ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6113739bc96SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC_IDENTITY:
6123739bc96SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM_IDENTITY:
613eb8076ddSMatthias Ringwald             return true;
614ce41473eSMatthias Ringwald         default:
615eb8076ddSMatthias Ringwald             return false;
616ce41473eSMatthias Ringwald     }
6170bf6344aS[email protected] }
6180bf6344aS[email protected] 
619617c03d6SMatthias Ringwald static bool hci_is_le_connection(hci_connection_t * connection){
620eb8076ddSMatthias Ringwald     return hci_is_le_connection_type(connection->address_type);
621eb8076ddSMatthias Ringwald }
622eb8076ddSMatthias Ringwald 
6237fde4af9Smatthias.ringwald /**
62443bfb1bdSmatthias.ringwald  * count connections
62543bfb1bdSmatthias.ringwald  */
62640d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
62756c253c9Smatthias.ringwald     int count = 0;
628665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
629a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
63015a27967SMatthias Ringwald         count++;
63115a27967SMatthias Ringwald     }
63243bfb1bdSmatthias.ringwald     return count;
63343bfb1bdSmatthias.ringwald }
634c8e4258aSmatthias.ringwald 
6358f733c6fSMatthias Ringwald uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
636ee303eddS[email protected] 
637f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
638f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
639ee303eddS[email protected] 
640665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
641a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
642998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
643ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
644ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
645ce41473eSMatthias Ringwald         }
646f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
647ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
648ee303eddS[email protected]         }
649ee303eddS[email protected]     }
650d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
651ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
652ee303eddS[email protected]     int free_slots_le = 0;
653ee303eddS[email protected] 
654ee303eddS[email protected]     if (free_slots_classic < 0){
6559da54300S[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);
656998906cdSmatthias.ringwald         return 0;
657998906cdSmatthias.ringwald     }
658ee303eddS[email protected] 
659ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
660ee303eddS[email protected]         // if we have LE slots, they are used
661ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
662ee303eddS[email protected]         if (free_slots_le < 0){
6639da54300S[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);
664ee303eddS[email protected]             return 0;
665998906cdSmatthias.ringwald         }
666ee303eddS[email protected]     } else {
667ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
668ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
669ee303eddS[email protected]         if (free_slots_classic < 0){
6709da54300S[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);
671ee303eddS[email protected]             return 0;
672ee303eddS[email protected]         }
673ee303eddS[email protected]     }
674ee303eddS[email protected] 
675ee303eddS[email protected]     switch (address_type){
676ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
6772125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
678ee303eddS[email protected]             return 0;
679ee303eddS[email protected] 
680f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6818f733c6fSMatthias Ringwald             return (uint16_t) free_slots_classic;
682ee303eddS[email protected] 
683ee303eddS[email protected]         default:
6848f733c6fSMatthias Ringwald            if (hci_stack->le_acl_packets_total_num > 0){
6858f733c6fSMatthias Ringwald                return (uint16_t) free_slots_le;
686ee303eddS[email protected]            }
6878f733c6fSMatthias Ringwald            return (uint16_t) free_slots_classic;
688cb00d3aaS[email protected]     }
689998906cdSmatthias.ringwald }
690998906cdSmatthias.ringwald 
6912125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
6922125de09SMatthias Ringwald     // get connection type
6932125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
6942125de09SMatthias Ringwald     if (!connection){
6952125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
6962125de09SMatthias Ringwald         return 0;
6972125de09SMatthias Ringwald     }
6982125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
6992125de09SMatthias Ringwald }
7002125de09SMatthias Ringwald 
70135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
702701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
703f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
704665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
705760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
706760b20efSMatthias Ringwald         // explicit flow control
707665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
708e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
709ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
710ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
711e35edcc1S[email protected]         }
712e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
713701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
71444d0e3d5S[email protected]             return 0;
71544d0e3d5S[email protected]         }
716e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
71749205f5dSMatthias Ringwald     } else {
718fa7f2dfdSMatthias Ringwald         // implicit flow control
7196f28d2eeSMatthias Ringwald         int num_ready = 0;
7206f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
7216f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
7226f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
7236f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
7246f28d2eeSMatthias Ringwald             num_ready++;
72549205f5dSMatthias Ringwald         }
7266f28d2eeSMatthias Ringwald         return num_ready;
7276f28d2eeSMatthias Ringwald     }
728e35edcc1S[email protected] }
72935454696SMatthias Ringwald #endif
73044d0e3d5S[email protected] 
7312b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
7322b838201SMatthias Ringwald static int hci_can_send_comand_packet_transport(void){
733ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
734ac928cc2S[email protected] 
735ac928cc2S[email protected]     // check for async hci transport implementations
736ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
737ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
738ac928cc2S[email protected]             return 0;
739ac928cc2S[email protected]         }
740ac928cc2S[email protected]     }
7412b838201SMatthias Ringwald     return 1;
7422b838201SMatthias Ringwald }
743ac928cc2S[email protected] 
7442b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
7451972f31fSMatthias Ringwald bool hci_can_send_command_packet_now(void){
7461972f31fSMatthias Ringwald     if (hci_can_send_comand_packet_transport() == 0) return false;
7474ea43905SMatthias Ringwald     return hci_stack->num_cmd_packets > 0u;
748ac928cc2S[email protected] }
749ac928cc2S[email protected] 
7509d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
751ac928cc2S[email protected]     // check for async hci transport implementations
7521972f31fSMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return true;
7539d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
754ac928cc2S[email protected] }
7559d04d3a7SMatthias Ringwald 
7561972f31fSMatthias Ringwald static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
7571972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
7589d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
759ac928cc2S[email protected] }
7609d04d3a7SMatthias Ringwald 
7611972f31fSMatthias Ringwald bool hci_can_send_acl_le_packet_now(void){
7621972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
7639d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
7649d04d3a7SMatthias Ringwald }
7659d04d3a7SMatthias Ringwald 
7661972f31fSMatthias Ringwald bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
7671972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false;
768e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
769ac928cc2S[email protected] }
770ac928cc2S[email protected] 
7711972f31fSMatthias Ringwald bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
7721972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
773ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
7746b4af23dS[email protected] }
7756b4af23dS[email protected] 
77635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7771972f31fSMatthias Ringwald bool hci_can_send_acl_classic_packet_now(void){
7781972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
779f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
78035454696SMatthias Ringwald }
78135454696SMatthias Ringwald 
7821972f31fSMatthias Ringwald bool hci_can_send_prepared_sco_packet_now(void){
7831972f31fSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false;
784f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
785f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
786f234b250SMatthias Ringwald     } else {
787701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
78844d0e3d5S[email protected]     }
789f234b250SMatthias Ringwald }
79044d0e3d5S[email protected] 
7911972f31fSMatthias Ringwald bool hci_can_send_sco_packet_now(void){
7921972f31fSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return false;
793701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
79444d0e3d5S[email protected] }
79544d0e3d5S[email protected] 
796d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
797d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
798d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
799d057580eSMatthias Ringwald }
80035454696SMatthias Ringwald #endif
801d057580eSMatthias Ringwald 
80295d71764SMatthias Ringwald // used for internal checks in l2cap.c
80302c7fc01SMatthias Ringwald bool hci_is_packet_buffer_reserved(void){
804c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
805c8b9416aS[email protected] }
806c8b9416aS[email protected] 
8076b65794dSMilanka Ringwald // reserves outgoing packet buffer.
8086b65794dSMilanka Ringwald // @return 1 if successful
809cafc12e8SMatthias Ringwald bool hci_reserve_packet_buffer(void){
8109d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
8119d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
812cafc12e8SMatthias Ringwald         return false;
8139d14b626S[email protected]     }
81402c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = true;
815cafc12e8SMatthias Ringwald     return true;
8166b4af23dS[email protected] }
8176b4af23dS[email protected] 
81868a0fcf7S[email protected] void hci_release_packet_buffer(void){
81902c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
82068a0fcf7S[email protected] }
82168a0fcf7S[email protected] 
8226b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
8237f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
8246b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
8256b4af23dS[email protected] }
8266b4af23dS[email protected] 
8278ad9cf99SMatthias Ringwald // used for debugging
8288ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
8298ad9cf99SMatthias Ringwald static void hci_controller_dump_packets(void){
8308ad9cf99SMatthias Ringwald     // format: "{handle:04x}:{count:02d} "
8318ad9cf99SMatthias Ringwald     char summaries[3][7 * 8 + 1];
8328ad9cf99SMatthias Ringwald     uint16_t totals[3];
8338ad9cf99SMatthias Ringwald     uint8_t index;
8348ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8358ad9cf99SMatthias Ringwald         summaries[index][0] = 0;
8368ad9cf99SMatthias Ringwald         totals[index] = 0;
8378ad9cf99SMatthias Ringwald     }
8388ad9cf99SMatthias Ringwald     btstack_linked_item_t *it;
8398ad9cf99SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
8408ad9cf99SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
8418ad9cf99SMatthias Ringwald         switch (connection->address_type){
8428ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_ACL:
8438ad9cf99SMatthias Ringwald                 index = 0;
8448ad9cf99SMatthias Ringwald                 break;
8458ad9cf99SMatthias Ringwald             case BD_ADDR_TYPE_SCO:
8468ad9cf99SMatthias Ringwald                 index = 2;
8478ad9cf99SMatthias Ringwald                 break;
8488ad9cf99SMatthias Ringwald             default:
8498ad9cf99SMatthias Ringwald                 index = 1;
850ce7ca7c8SMatthias Ringwald                 break;
8518ad9cf99SMatthias Ringwald         }
8528ad9cf99SMatthias Ringwald         totals[index] += connection->num_packets_sent;
8538ad9cf99SMatthias Ringwald         char item_text[10];
8548ad9cf99SMatthias Ringwald         sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent);
8558ad9cf99SMatthias Ringwald         btstack_strcat(summaries[index], sizeof(summaries[0]), item_text);
8568ad9cf99SMatthias Ringwald     }
8578ad9cf99SMatthias Ringwald     for (index = 0 ; index < 3 ; index++){
8588ad9cf99SMatthias Ringwald         if (summaries[index][0] == 0){
8598ad9cf99SMatthias Ringwald             summaries[index][0] = '-';
8608ad9cf99SMatthias Ringwald             summaries[index][1] = 0;
8618ad9cf99SMatthias Ringwald         }
8628ad9cf99SMatthias Ringwald     }
8638ad9cf99SMatthias 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]);
8648ad9cf99SMatthias Ringwald }
8658ad9cf99SMatthias Ringwald #endif
8668ad9cf99SMatthias Ringwald 
8673e2050f7SMatthias Ringwald static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){
868452cf3bbS[email protected] 
869452cf3bbS[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);
870452cf3bbS[email protected] 
871452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
872452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
8734ea43905SMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
874452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
875452cf3bbS[email protected]     }
876452cf3bbS[email protected] 
8770f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
878fcf88f47SMatthias Ringwald     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
8790f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
8800f3b27c5SMatthias Ringwald     }
8810f3b27c5SMatthias Ringwald #endif
882452cf3bbS[email protected] 
883d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
884d999b54eSMatthias Ringwald 
8853e2050f7SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
886452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
887ff3cc4a5SMatthias Ringwald     while (true){
888452cf3bbS[email protected] 
889d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
890d999b54eSMatthias Ringwald 
891452cf3bbS[email protected]         // get current data
8924ea43905SMatthias Ringwald         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
893452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
8941979f09cSMatthias Ringwald         bool more_fragments = false;
895452cf3bbS[email protected] 
896452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
897452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
8981979f09cSMatthias Ringwald             more_fragments = true;
8996bcf18c2SMatthias Ringwald             current_acl_data_packet_length = max_acl_data_packet_length & (~(HCI_ACL_CHUNK_SIZE_ALIGNMENT-1));
900452cf3bbS[email protected]         }
901452cf3bbS[email protected] 
902452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
9034ea43905SMatthias Ringwald         if (acl_header_pos > 0u){
904f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
9054ea43905SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
906f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
907452cf3bbS[email protected]         }
908452cf3bbS[email protected] 
909452cf3bbS[email protected]         // update header len
9104ea43905SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
911452cf3bbS[email protected] 
912452cf3bbS[email protected]         // count packet
913ce41473eSMatthias Ringwald         connection->num_packets_sent++;
9141979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
915d999b54eSMatthias Ringwald 
916d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
917d999b54eSMatthias Ringwald         if (more_fragments){
918d999b54eSMatthias Ringwald             // update start of next fragment to send
919d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
920d999b54eSMatthias Ringwald         } else {
921d999b54eSMatthias Ringwald             // done
922d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
923d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
924d999b54eSMatthias Ringwald         }
925452cf3bbS[email protected] 
926452cf3bbS[email protected]         // send packet
927452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
928452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
9295bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
93081d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
9313e2050f7SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
9323e2050f7SMatthias Ringwald         if (err != 0){
9333e2050f7SMatthias Ringwald             // no error from HCI Transport expected
9343e2050f7SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
9353e2050f7SMatthias Ringwald         }
936452cf3bbS[email protected] 
9378ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
9388ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
9398ad9cf99SMatthias Ringwald #endif
9408ad9cf99SMatthias Ringwald 
9411979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
942d999b54eSMatthias Ringwald 
943452cf3bbS[email protected]         // done yet?
944452cf3bbS[email protected]         if (!more_fragments) break;
945452cf3bbS[email protected] 
946452cf3bbS[email protected]         // can send more?
9473e2050f7SMatthias Ringwald         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status;
948452cf3bbS[email protected]     }
949452cf3bbS[email protected] 
950d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
951452cf3bbS[email protected] 
952d051460cS[email protected]     // release buffer now for synchronous transport
953203bace6S[email protected]     if (hci_transport_synchronous()){
95481d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
955452cf3bbS[email protected]         hci_release_packet_buffer();
956fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
957452cf3bbS[email protected]     }
958452cf3bbS[email protected] 
9593e2050f7SMatthias Ringwald     return status;
960452cf3bbS[email protected] }
961452cf3bbS[email protected] 
962826f7347S[email protected] // pre: caller has reserved the packet buffer
9633e2050f7SMatthias Ringwald uint8_t hci_send_acl_packet_buffer(int size){
9643e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
965826f7347S[email protected] 
966d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
967d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
968d713a683S[email protected] 
9695061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
97097b61c7bS[email protected]     if (!connection) {
9715fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
97297b61c7bS[email protected]         hci_release_packet_buffer();
973068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
9743e2050f7SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
97597b61c7bS[email protected]     }
97652db98b2SMatthias Ringwald 
97779a2851bSMilanka Ringwald     // check for free places on Bluetooth module
97879a2851bSMilanka Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
97979a2851bSMilanka Ringwald         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
98079a2851bSMilanka Ringwald         hci_release_packet_buffer();
98179a2851bSMilanka Ringwald         hci_emit_transport_packet_sent();
98279a2851bSMilanka Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
98379a2851bSMilanka Ringwald     }
98479a2851bSMilanka Ringwald 
98552db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
98656cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
98752db98b2SMatthias Ringwald #endif
98856cf178bSmatthias.ringwald 
989452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
9907856c818Smatthias.ringwald 
991452cf3bbS[email protected]     // setup data
992452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
993452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
9946218e6f1Smatthias.ringwald 
995452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
996ee091cf1Smatthias.ringwald }
997ee091cf1Smatthias.ringwald 
99835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
99944d0e3d5S[email protected] // pre: caller has reserved the packet buffer
10003e2050f7SMatthias Ringwald uint8_t hci_send_sco_packet_buffer(int size){
10013e2050f7SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
100244d0e3d5S[email protected] 
100344d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
10044b3e1e19SMatthias Ringwald 
10054b3e1e19SMatthias Ringwald     // skip checks in loopback mode
10064b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
100744d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
100844d0e3d5S[email protected] 
100944d0e3d5S[email protected]         // check for free places on Bluetooth module
1010701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
1011cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
101244d0e3d5S[email protected]             hci_release_packet_buffer();
1013068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
101444d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
101544d0e3d5S[email protected]         }
101644d0e3d5S[email protected] 
1017e35edcc1S[email protected]         // track send packet in connection struct
1018e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
1019e35edcc1S[email protected]         if (!connection) {
1020e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
1021e35edcc1S[email protected]             hci_release_packet_buffer();
1022068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
10233e2050f7SMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1024e35edcc1S[email protected]         }
1025f234b250SMatthias Ringwald 
1026f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
1027f234b250SMatthias Ringwald             // token used
10281972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = false;
1029f234b250SMatthias Ringwald         } else {
1030760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
1031ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
10326f28d2eeSMatthias Ringwald             } else {
1033e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
1034760b20efSMatthias Ringwald             }
10354b3e1e19SMatthias Ringwald         }
1036f234b250SMatthias Ringwald     }
103744d0e3d5S[email protected] 
103844d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
1039543e835cSMatthias Ringwald 
104043149fc9SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
104143149fc9SMatthias Ringwald     hci_stack->sco_transport->send_packet(packet, size);
104243149fc9SMatthias Ringwald     hci_release_packet_buffer();
104343149fc9SMatthias Ringwald     hci_emit_transport_packet_sent();
104443149fc9SMatthias Ringwald 
104543149fc9SMatthias Ringwald     return 0;
104643149fc9SMatthias Ringwald #else
104743149fc9SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
1048543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
1049543e835cSMatthias Ringwald         hci_release_packet_buffer();
1050fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
1051543e835cSMatthias Ringwald     }
1052543e835cSMatthias Ringwald 
10533e2050f7SMatthias Ringwald     if (err != 0){
10543e2050f7SMatthias Ringwald         return ERROR_CODE_HARDWARE_FAILURE;
10553e2050f7SMatthias Ringwald     }
10563e2050f7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
105743149fc9SMatthias Ringwald #endif
105844d0e3d5S[email protected] }
105935454696SMatthias Ringwald #endif
106044d0e3d5S[email protected] 
10610a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
106268ab6207SMatthias Ringwald static uint8_t hci_send_iso_packet_fragments(void){
106368ab6207SMatthias Ringwald 
106468ab6207SMatthias Ringwald     uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length;
106568ab6207SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
106668ab6207SMatthias Ringwald     // multiple packets could be send on a synchronous HCI transport
106768ab6207SMatthias Ringwald     while (true){
106868ab6207SMatthias Ringwald 
106968ab6207SMatthias Ringwald         // get current data
107068ab6207SMatthias Ringwald         const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u;
107168ab6207SMatthias Ringwald         int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos;
107268ab6207SMatthias Ringwald         bool more_fragments = false;
107368ab6207SMatthias Ringwald 
107468ab6207SMatthias Ringwald         // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
107568ab6207SMatthias Ringwald         if (current_iso_data_packet_length > max_iso_data_packet_length){
107668ab6207SMatthias Ringwald             more_fragments = true;
107768ab6207SMatthias Ringwald             current_iso_data_packet_length = max_iso_data_packet_length;
107868ab6207SMatthias Ringwald         }
107968ab6207SMatthias Ringwald 
108068ab6207SMatthias Ringwald         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
108168ab6207SMatthias Ringwald         uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
108268ab6207SMatthias Ringwald         uint8_t pb_flags;
108368ab6207SMatthias Ringwald         if (iso_header_pos == 0u){
108468ab6207SMatthias Ringwald             // first fragment, keep TS field
108568ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x00 : 0x02;
108668ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u);
108768ab6207SMatthias Ringwald         } else {
108868ab6207SMatthias Ringwald             // later fragment, drop TS field
108968ab6207SMatthias Ringwald             pb_flags = more_fragments ? 0x01 : 0x03;
109068ab6207SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u);
109168ab6207SMatthias Ringwald         }
109268ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags);
109368ab6207SMatthias Ringwald 
109468ab6207SMatthias Ringwald         // update header len
109568ab6207SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length);
109668ab6207SMatthias Ringwald 
109768ab6207SMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
109868ab6207SMatthias Ringwald         if (more_fragments){
109968ab6207SMatthias Ringwald             // update start of next fragment to send
110068ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos += current_iso_data_packet_length;
110168ab6207SMatthias Ringwald         } else {
110268ab6207SMatthias Ringwald             // done
110368ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_pos = 0;
110468ab6207SMatthias Ringwald             hci_stack->iso_fragmentation_total_size = 0;
110568ab6207SMatthias Ringwald         }
110668ab6207SMatthias Ringwald 
110768ab6207SMatthias Ringwald         // send packet
110868ab6207SMatthias Ringwald         uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos];
110968ab6207SMatthias Ringwald         const int size = current_iso_data_packet_length + 4;
111068ab6207SMatthias Ringwald         hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size);
111168ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = true;
111268ab6207SMatthias Ringwald         int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size);
111368ab6207SMatthias Ringwald         if (err != 0){
111468ab6207SMatthias Ringwald             // no error from HCI Transport expected
111568ab6207SMatthias Ringwald             status = ERROR_CODE_HARDWARE_FAILURE;
111668ab6207SMatthias Ringwald         }
111768ab6207SMatthias Ringwald 
111868ab6207SMatthias Ringwald         // done yet?
111968ab6207SMatthias Ringwald         if (!more_fragments) break;
112068ab6207SMatthias Ringwald 
112168ab6207SMatthias Ringwald         // can send more?
112268ab6207SMatthias Ringwald         if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false;
112368ab6207SMatthias Ringwald     }
112468ab6207SMatthias Ringwald 
112568ab6207SMatthias Ringwald     // release buffer now for synchronous transport
112668ab6207SMatthias Ringwald     if (hci_transport_synchronous()){
112768ab6207SMatthias Ringwald         hci_stack->iso_fragmentation_tx_active = false;
112868ab6207SMatthias Ringwald         hci_release_packet_buffer();
112968ab6207SMatthias Ringwald         hci_emit_transport_packet_sent();
113068ab6207SMatthias Ringwald     }
113168ab6207SMatthias Ringwald 
113268ab6207SMatthias Ringwald     return status;
113368ab6207SMatthias Ringwald }
113468ab6207SMatthias Ringwald 
1135ace08712SMatthias Ringwald uint8_t hci_send_iso_packet_buffer(uint16_t size){
1136ace08712SMatthias Ringwald     btstack_assert(hci_stack->hci_packet_buffer_reserved);
1137ace08712SMatthias Ringwald 
1138e5413aa0SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff;
1139e5413aa0SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle);
1140e5413aa0SMatthias Ringwald     if (iso_stream == NULL){
1141977f918dSMatthias Ringwald         hci_release_packet_buffer();
1142977f918dSMatthias Ringwald         hci_iso_notify_can_send_now();
1143e5413aa0SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1144e5413aa0SMatthias Ringwald     }
1145e5413aa0SMatthias Ringwald 
1146e5413aa0SMatthias Ringwald     // TODO: check for space on controller
1147e5413aa0SMatthias Ringwald 
1148977f918dSMatthias Ringwald     // skip iso packets if needed
1149977f918dSMatthias Ringwald     if (iso_stream->num_packets_to_skip > 0){
1150977f918dSMatthias Ringwald         iso_stream->num_packets_to_skip--;
1151977f918dSMatthias Ringwald         // pretend it was processed and trigger next one
1152977f918dSMatthias Ringwald         hci_release_packet_buffer();
1153977f918dSMatthias Ringwald         hci_iso_notify_can_send_now();
1154977f918dSMatthias Ringwald         return ERROR_CODE_SUCCESS;
1155977f918dSMatthias Ringwald     }
1156977f918dSMatthias Ringwald 
1157e5413aa0SMatthias Ringwald     // track outgoing packet sent
1158e5413aa0SMatthias Ringwald     log_info("Outgoing ISO packet for con handle 0x%04x", con_handle);
1159e5413aa0SMatthias Ringwald     iso_stream->num_packets_sent++;
1160e5413aa0SMatthias Ringwald 
116168ab6207SMatthias Ringwald     // setup data
116268ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_total_size = size;
116368ab6207SMatthias Ringwald     hci_stack->iso_fragmentation_pos = 4;   // start of L2CAP packet
116468ab6207SMatthias Ringwald 
116568ab6207SMatthias Ringwald     return hci_send_iso_packet_fragments();
1166ace08712SMatthias Ringwald }
1167ace08712SMatthias Ringwald #endif
1168ace08712SMatthias Ringwald 
1169c3b46f5aSMatthias Ringwald static void acl_handler(uint8_t *packet, uint16_t size){
1170e76a89eeS[email protected] 
11717856c818Smatthias.ringwald     // get info
11727856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
11735061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
11747856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
11757856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
11767856c818Smatthias.ringwald 
11777856c818Smatthias.ringwald     // ignore non-registered handle
11787856c818Smatthias.ringwald     if (!conn){
1179c3b46f5aSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , con_handle);
11807856c818Smatthias.ringwald         return;
11817856c818Smatthias.ringwald     }
11827856c818Smatthias.ringwald 
1183e76a89eeS[email protected]     // assert packet is complete
11844ea43905SMatthias Ringwald     if ((acl_length + 4u) != size){
1185c3b46f5aSMatthias Ringwald         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
1186e76a89eeS[email protected]         return;
1187e76a89eeS[email protected]     }
1188e76a89eeS[email protected] 
118952db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
11907856c818Smatthias.ringwald     // update idle timestamp
11917856c818Smatthias.ringwald     hci_connection_timestamp(conn);
119252db98b2SMatthias Ringwald #endif
11937856c818Smatthias.ringwald 
11942b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
11952b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
11962b838201SMatthias Ringwald     conn->num_packets_completed++;
11972b838201SMatthias Ringwald #endif
11982b838201SMatthias Ringwald 
11997856c818Smatthias.ringwald     // handle different packet types
12004ea43905SMatthias Ringwald     switch (acl_flags & 0x03u) {
12017856c818Smatthias.ringwald 
12027856c818Smatthias.ringwald         case 0x01: // continuation fragment
12037856c818Smatthias.ringwald 
12040ca847afS[email protected]             // sanity checks
12054ea43905SMatthias Ringwald             if (conn->acl_recombination_pos == 0u) {
12069da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
12077856c818Smatthias.ringwald                 return;
12087856c818Smatthias.ringwald             }
12094ea43905SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
12100ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
12110ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
12120ca847afS[email protected]                 conn->acl_recombination_pos = 0;
12130ca847afS[email protected]                 return;
12140ca847afS[email protected]             }
12157856c818Smatthias.ringwald 
12167856c818Smatthias.ringwald             // append fragment payload (header already stored)
12176535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
12186535961aSMatthias Ringwald                          &packet[4], acl_length);
12197856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
12207856c818Smatthias.ringwald 
12217856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
12224ea43905SMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
1223d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
12247856c818Smatthias.ringwald                 // reset recombination buffer
12257856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
12267856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
12277856c818Smatthias.ringwald             }
12287856c818Smatthias.ringwald             break;
12297856c818Smatthias.ringwald 
12307856c818Smatthias.ringwald         case 0x02: { // first fragment
12317856c818Smatthias.ringwald 
123223a77e1aS[email protected]             // sanity check
123323a77e1aS[email protected]             if (conn->acl_recombination_pos) {
123460737d2bSMatthias Ringwald                 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet
123560737d2bSMatthias Ringwald                 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){
123660737d2bSMatthias Ringwald                     log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle);
123760737d2bSMatthias Ringwald                 }
123823a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
123923a77e1aS[email protected]             }
124023a77e1aS[email protected] 
12417856c818Smatthias.ringwald             // peek into L2CAP packet!
12427856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
12437856c818Smatthias.ringwald 
12447856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
12454ea43905SMatthias Ringwald             if (acl_length >= (l2cap_length + 4u)){
12467856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
12474ea43905SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4u);
12487856c818Smatthias.ringwald             } else {
12490ca847afS[email protected] 
12500ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
12510ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
12520ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
12530ca847afS[email protected]                     return;
12540ca847afS[email protected]                 }
12550ca847afS[email protected] 
12567856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
12576535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
12584ea43905SMatthias Ringwald                              packet, acl_length + 4u);
12594ea43905SMatthias Ringwald                 conn->acl_recombination_pos    = acl_length + 4u;
12607856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
12614ea43905SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
12627856c818Smatthias.ringwald             }
12637856c818Smatthias.ringwald             break;
12647856c818Smatthias.ringwald 
12657856c818Smatthias.ringwald         }
12667856c818Smatthias.ringwald         default:
1267c3b46f5aSMatthias Ringwald             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
12687856c818Smatthias.ringwald             return;
12697856c818Smatthias.ringwald     }
127094ab26f8Smatthias.ringwald 
127194ab26f8Smatthias.ringwald     // execute main loop
127294ab26f8Smatthias.ringwald     hci_run();
127316833f0aSmatthias.ringwald }
127422909952Smatthias.ringwald 
12751ab2dc58SMatthias Ringwald static void hci_connection_stop_timer(hci_connection_t * conn){
12761ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
12771ab2dc58SMatthias Ringwald #ifdef ENABLE_CLASSIC
12781ab2dc58SMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout_sco);
12791ab2dc58SMatthias Ringwald #endif
12801ab2dc58SMatthias Ringwald }
12811ab2dc58SMatthias Ringwald 
128267a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
12839da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
12843c4d4b90Smatthias.ringwald 
1285b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1286cb70c5abSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1287cb70c5abSMatthias Ringwald     bd_addr_type_t addr_type = conn->address_type;
1288cb70c5abSMatthias Ringwald #endif
1289cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1290cb70c5abSMatthias Ringwald     hci_con_handle_t con_handle = conn->con_handle;
1291ee752bb8SMatthias Ringwald #endif
1292b3264428SMatthias Ringwald #endif
1293ee752bb8SMatthias Ringwald 
12941ab2dc58SMatthias Ringwald     hci_connection_stop_timer(conn);
1295c785ef68Smatthias.ringwald 
1296665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1297a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
12983c4d4b90Smatthias.ringwald 
12993c4d4b90Smatthias.ringwald     // now it's gone
1300c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
1301ee752bb8SMatthias Ringwald 
1302b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1303034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1304ee752bb8SMatthias Ringwald     // update SCO
1305cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1306ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1307ee752bb8SMatthias Ringwald     }
1308034e9b53SMatthias Ringwald #endif
1309cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1310cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1311cb70c5abSMatthias Ringwald         hci_stack->sco_transport->close(con_handle);
1312cb70c5abSMatthias Ringwald     }
1313cb70c5abSMatthias Ringwald #endif
1314b3264428SMatthias Ringwald #endif
1315c7e0c5f6Smatthias.ringwald }
1316c7e0c5f6Smatthias.ringwald 
131735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
131835454696SMatthias Ringwald 
131929e39de4SMatthias Ringwald static const uint16_t hci_acl_packet_type_sizes[] = {
13208f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
13218f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
13228f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
13238f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
13248f8108aaSmatthias.ringwald };
132529e39de4SMatthias Ringwald static const uint8_t hci_acl_packet_type_feature_requirement_bit[] = {
132665389bfcS[email protected]      0, // 3 slot packets
132765389bfcS[email protected]      1, // 5 slot packets
132865389bfcS[email protected]     25, // EDR 2 mpbs
132965389bfcS[email protected]     26, // EDR 3 mbps
133065389bfcS[email protected]     39, // 3 slot EDR packts
133165389bfcS[email protected]     40, // 5 slot EDR packet
133265389bfcS[email protected] };
133329e39de4SMatthias Ringwald static const uint16_t hci_acl_packet_type_feature_packet_mask[] = {
133465389bfcS[email protected]     0x0f00, // 3 slot packets
133565389bfcS[email protected]     0xf000, // 5 slot packets
133665389bfcS[email protected]     0x1102, // EDR 2 mpbs
133765389bfcS[email protected]     0x2204, // EDR 3 mbps
133865389bfcS[email protected]     0x0300, // 3 slot EDR packts
133965389bfcS[email protected]     0x3000, // 5 slot EDR packet
134065389bfcS[email protected] };
13418f8108aaSmatthias.ringwald 
134265389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
134365389bfcS[email protected]     // enable packet types based on size
13448f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
1345f16a69bbS[email protected]     unsigned int i;
13468f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
134729e39de4SMatthias Ringwald         if (hci_acl_packet_type_sizes[i] == 0) continue;
134829e39de4SMatthias Ringwald         if (hci_acl_packet_type_sizes[i] <= buffer_size){
13498f8108aaSmatthias.ringwald             packet_types |= 1 << i;
13508f8108aaSmatthias.ringwald         }
13518f8108aaSmatthias.ringwald     }
135265389bfcS[email protected]     // disable packet types due to missing local supported features
135329e39de4SMatthias Ringwald     for (i=0;i<sizeof(hci_acl_packet_type_feature_requirement_bit); i++){
135429e39de4SMatthias Ringwald         unsigned int bit_idx = hci_acl_packet_type_feature_requirement_bit[i];
135565389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
135665389bfcS[email protected]         if (feature_set) continue;
135729e39de4SMatthias Ringwald         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_acl_packet_type_feature_packet_mask[i]);
135829e39de4SMatthias Ringwald         packet_types &= ~hci_acl_packet_type_feature_packet_mask[i];
135965389bfcS[email protected]     }
13608f8108aaSmatthias.ringwald     return packet_types;
13618f8108aaSmatthias.ringwald }
13628f8108aaSmatthias.ringwald 
13638f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
136429e39de4SMatthias Ringwald     // flip bits for "may not be used"
136529e39de4SMatthias Ringwald     return hci_stack->usable_packet_types_acl ^ 0x3306;
13668f8108aaSmatthias.ringwald }
136729e39de4SMatthias Ringwald 
1368c92ca2c8SMatthias Ringwald static const struct {
1369c92ca2c8SMatthias Ringwald     uint8_t feature_index;
1370c92ca2c8SMatthias Ringwald     uint16_t feature_packet_mask;
1371c92ca2c8SMatthias Ringwald } hci_sco_packet_type_feature_requirements[] = {
1372c92ca2c8SMatthias Ringwald         { 12, SCO_PACKET_TYPES_HV2 },                           // HV2 packets
1373c92ca2c8SMatthias Ringwald         { 13, SCO_PACKET_TYPES_HV3 },                           // HV3 packets
1374c92ca2c8SMatthias Ringwald         { 31, SCO_PACKET_TYPES_ESCO },                          // eSCO links (EV3 packets)
1375c92ca2c8SMatthias Ringwald         { 32, SCO_PACKET_TYPES_EV4 },                           // EV4 packets
1376c92ca2c8SMatthias Ringwald         { 45, SCO_PACKET_TYPES_2EV3 | SCO_PACKET_TYPES_2EV5 },  // EDR eSCO 2 Mb/s
1377c92ca2c8SMatthias Ringwald         { 46, SCO_PACKET_TYPES_3EV3 | SCO_PACKET_TYPES_3EV5 },  // EDR eSCO 3 Mb/s
13786afff830SMatthias Ringwald         { 47, SCO_PACKET_TYPES_2EV5 | SCO_PACKET_TYPES_3EV5 },  // 3-slot EDR eSCO packets, 2-EV3/3-EV3 use single slot
1379c92ca2c8SMatthias Ringwald };
1380c92ca2c8SMatthias Ringwald 
1381d7891039SMatthias Ringwald // map packet types to payload length, prefer eSCO over SCO and large over small packets
1382d7891039SMatthias Ringwald static const struct {
1383d7891039SMatthias Ringwald     uint16_t type;
1384d7891039SMatthias Ringwald     uint16_t payload_length;
1385d7891039SMatthias Ringwald } hci_sco_packet_type_to_payload_length[] = {
1386d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_3EV5, HCI_SCO_3EV5_SIZE}, // 540
1387d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_2EV5, HCI_SCO_2EV5_SIZE}, // 360
1388d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV5,  HCI_SCO_EV5_SIZE},  // 180
1389d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV4,  HCI_SCO_EV4_SIZE},  // 120
1390d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_3EV3, HCI_SCO_3EV3_SIZE}, //  90
1391d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_2EV3, HCI_SCO_2EV3_SIZE}, //  60
1392d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_EV3,  HCI_SCO_EV3_SIZE},  //  30
1393d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV3,  HCI_SCO_HV3_SIZE},  //  30
1394d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV2,  HCI_SCO_HV2_SIZE},  //  20
1395d7891039SMatthias Ringwald         {SCO_PACKET_TYPES_HV1,  HCI_SCO_HV1_SIZE}   //  10
1396d7891039SMatthias Ringwald };
1397d7891039SMatthias Ringwald 
1398c92ca2c8SMatthias Ringwald static uint16_t hci_sco_packet_types_for_features(const uint8_t * local_supported_features){
1399c92ca2c8SMatthias Ringwald     uint16_t packet_types = SCO_PACKET_TYPES_ALL;
1400c92ca2c8SMatthias Ringwald     unsigned int i;
1401c92ca2c8SMatthias Ringwald     // disable packet types due to missing local supported features
1402c92ca2c8SMatthias Ringwald     for (i=0;i<(sizeof(hci_sco_packet_type_feature_requirements)/sizeof(hci_sco_packet_type_feature_requirements[0])); i++){
1403c92ca2c8SMatthias Ringwald         unsigned int bit_idx = hci_sco_packet_type_feature_requirements[i].feature_index;
1404c92ca2c8SMatthias Ringwald         bool feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
1405c92ca2c8SMatthias Ringwald         if (feature_set) continue;
1406c92ca2c8SMatthias Ringwald         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, hci_sco_packet_type_feature_requirements[i].feature_packet_mask);
1407c92ca2c8SMatthias Ringwald         packet_types &= ~hci_sco_packet_type_feature_requirements[i].feature_packet_mask;
1408c92ca2c8SMatthias Ringwald     }
1409c92ca2c8SMatthias Ringwald     return packet_types;
1410c92ca2c8SMatthias Ringwald }
1411c92ca2c8SMatthias Ringwald 
1412c92ca2c8SMatthias Ringwald uint16_t hci_usable_sco_packet_types(void){
1413c92ca2c8SMatthias Ringwald     return hci_stack->usable_packet_types_sco;
1414c92ca2c8SMatthias Ringwald }
1415c92ca2c8SMatthias Ringwald 
1416d7891039SMatthias Ringwald static uint16_t hci_sco_payload_length_for_packet_types(uint16_t packet_types){
1417d7891039SMatthias Ringwald     uint8_t i;
1418d7891039SMatthias Ringwald     for (i=0;i<sizeof(hci_sco_packet_type_to_payload_length)/sizeof(hci_sco_packet_type_to_payload_length[0]);i++){
1419d7891039SMatthias Ringwald         if ((hci_sco_packet_type_to_payload_length[i].type & packet_types) != 0){
1420d7891039SMatthias Ringwald             return hci_sco_packet_type_to_payload_length[i].payload_length;
1421d7891039SMatthias Ringwald         }
1422d7891039SMatthias Ringwald     }
1423d7891039SMatthias Ringwald     return 0;
1424d7891039SMatthias Ringwald }
1425d7891039SMatthias Ringwald 
142635454696SMatthias Ringwald #endif
14278f8108aaSmatthias.ringwald 
1428facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
14297dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
14303a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
14317dc17943Smatthias.ringwald }
14327dc17943Smatthias.ringwald 
1433f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
14343a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
14357dc17943Smatthias.ringwald }
14367dc17943Smatthias.ringwald 
143706b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
143820dcdd22SMatthias Ringwald bool hci_extended_sco_link_supported(void){
14393e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
14403e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
14413e68d23dSMatthias Ringwald }
144206b9e820SMatthias Ringwald #endif
14433e68d23dSMatthias Ringwald 
144420dcdd22SMatthias Ringwald bool hci_non_flushable_packet_boundary_flag_supported(void){
14456ac9a97eS[email protected]     // No. 54, byte 6, bit 6
14464ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
14476ac9a97eS[email protected] }
14486ac9a97eS[email protected] 
14499885fb2dSMatthias Ringwald #ifdef ENABLE_CLASSIC
145015a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
14516ac9a97eS[email protected]     // No. 51, byte 6, bit 3
14524ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1453f5d8d141S[email protected] }
14549885fb2dSMatthias Ringwald #endif
1455f5d8d141S[email protected] 
14567f02f414SMatthias Ringwald static int hci_classic_supported(void){
145735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
14586ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
14593a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
146035454696SMatthias Ringwald #else
146135454696SMatthias Ringwald     return 0;
146235454696SMatthias Ringwald #endif
1463f5d8d141S[email protected] }
1464f5d8d141S[email protected] 
14657f02f414SMatthias Ringwald static int hci_le_supported(void){
1466a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
14676ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
14684ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1469f5d8d141S[email protected] #else
1470f5d8d141S[email protected]     return 0;
1471f5d8d141S[email protected] #endif
1472f5d8d141S[email protected] }
1473f5d8d141S[email protected] 
14741ffa425cSMatthias Ringwald static bool hci_command_supported(uint8_t command_index){
14751ffa425cSMatthias Ringwald     return (hci_stack->local_supported_commands & (1LU << command_index)) != 0;
14761ffa425cSMatthias Ringwald }
14771ffa425cSMatthias Ringwald 
1478b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1479b95a5a35SMatthias Ringwald 
148063671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
148163671e69SMatthias Ringwald static bool hci_extended_advertising_supported(void){
148263671e69SMatthias Ringwald     return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE);
148363671e69SMatthias Ringwald }
148463671e69SMatthias Ringwald #endif
148563671e69SMatthias Ringwald 
1486f5873674SMatthias Ringwald static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
14876bcfa632SMatthias Ringwald     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
14886bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
148969a97523S[email protected]     } else {
14906bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
149169a97523S[email protected]     }
149269a97523S[email protected] }
149369a97523S[email protected] 
14946bcfa632SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
14956bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
14966bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
14976bcfa632SMatthias Ringwald }
14986bcfa632SMatthias Ringwald 
14996bcfa632SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
15006bcfa632SMatthias Ringwald void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
15016bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_advertisements_own_addr_type;
15026bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
15036bcfa632SMatthias Ringwald };
15046bcfa632SMatthias Ringwald #endif
15056bcfa632SMatthias Ringwald 
1506e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
15076bcfa632SMatthias Ringwald 
15086bcfa632SMatthias Ringwald /**
15096bcfa632SMatthias Ringwald  * @brief Get own addr type and address used for LE connections (Central)
15106bcfa632SMatthias Ringwald  */
15116bcfa632SMatthias Ringwald void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
15126bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_connection_own_addr_type;
15136bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
15146bcfa632SMatthias Ringwald }
15156bcfa632SMatthias Ringwald 
1516384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
15179ec2630cSMatthias Ringwald 
1518a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1519a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset];
1520d1dc057bS[email protected]     offset += 1;
1521d1dc057bS[email protected] 
1522a0698cb4SMatthias Ringwald     uint16_t i;
152303fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1524a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
152533e6948bSMatthias Ringwald         // sanity checks on data_length:
152633e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
152733e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
15284ea43905SMatthias Ringwald         if ((offset + 9u + data_length + 1u) > size)    return;
152933e6948bSMatthias Ringwald         // setup event
15304ea43905SMatthias Ringwald         uint8_t event_size = 10u + data_length;
1531a0698cb4SMatthias Ringwald         uint16_t pos = 0;
1532045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
153357c9da5bS[email protected]         event[pos++] = event_size;
15346535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1535d1dc057bS[email protected]         offset += 8;
1536d1dc057bS[email protected]         pos += 8;
1537d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
153833e6948bSMatthias Ringwald         event[pos++] = data_length;
153933e6948bSMatthias Ringwald         offset++;
15406535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
154157c9da5bS[email protected]         pos +=    data_length;
15424ea43905SMatthias Ringwald         offset += data_length + 1u; // rssi
1543d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
154457c9da5bS[email protected]     }
154557c9da5bS[email protected] }
1546a0698cb4SMatthias Ringwald 
1547a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
1548a0698cb4SMatthias Ringwald void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) {
1549a0698cb4SMatthias Ringwald     uint16_t offset = 3;
1550a0698cb4SMatthias Ringwald     uint8_t num_reports = packet[offset++];
1551c95a0fc7SMatthias Ringwald     uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var
1552a0698cb4SMatthias Ringwald     uint8_t i;
1553a0698cb4SMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
1554a0698cb4SMatthias Ringwald         // sanity checks on data_length:
1555a0698cb4SMatthias Ringwald         uint16_t data_length = packet[offset + 23];
155643ce0351SMatthias Ringwald         if (data_length > LE_EXTENDED_ADVERTISING_DATA_SIZE) return;
1557a0698cb4SMatthias Ringwald         if ((offset + 24u + data_length) > size)    return;
1558a0698cb4SMatthias Ringwald         uint16_t event_type = little_endian_read_16(packet, offset);
1559a0698cb4SMatthias Ringwald         offset += 2;
1560a0698cb4SMatthias Ringwald         if ((event_type & 0x10) != 0) {
1561a0698cb4SMatthias Ringwald            // setup legacy event
1562a0698cb4SMatthias Ringwald             uint8_t legacy_event_type;
1563a0698cb4SMatthias Ringwald             switch (event_type){
1564a0698cb4SMatthias Ringwald                 case 0b0010011:
1565a0698cb4SMatthias Ringwald                     // ADV_IND
1566a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1567a0698cb4SMatthias Ringwald                     break;
1568a0698cb4SMatthias Ringwald                 case 0b0010101:
1569a0698cb4SMatthias Ringwald                     // ADV_DIRECT_IND
1570a0698cb4SMatthias Ringwald                     legacy_event_type = 1;
1571a0698cb4SMatthias Ringwald                     break;
1572a0698cb4SMatthias Ringwald                 case 0b0010010:
1573a0698cb4SMatthias Ringwald                     // ADV_SCAN_IND
1574a0698cb4SMatthias Ringwald                     legacy_event_type = 2;
1575a0698cb4SMatthias Ringwald                     break;
1576a0698cb4SMatthias Ringwald                 case 0b0010000:
1577a0698cb4SMatthias Ringwald                     // ADV_NONCONN_IND
1578a0698cb4SMatthias Ringwald                     legacy_event_type = 3;
1579a0698cb4SMatthias Ringwald                     break;
1580a0698cb4SMatthias Ringwald                 case 0b0011011:
1581a0698cb4SMatthias Ringwald                 case 0b0011010:
1582a0698cb4SMatthias Ringwald                     // SCAN_RSP
1583a0698cb4SMatthias Ringwald                     legacy_event_type = 4;
1584a0698cb4SMatthias Ringwald                     break;
1585a0698cb4SMatthias Ringwald                 default:
1586a0698cb4SMatthias Ringwald                     legacy_event_type = 0;
1587a0698cb4SMatthias Ringwald                     break;
1588a0698cb4SMatthias Ringwald             }
1589a0698cb4SMatthias Ringwald             uint16_t pos = 0;
1590a0698cb4SMatthias Ringwald             event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1591a0698cb4SMatthias Ringwald             event[pos++] = 10u + data_length;
1592a0698cb4SMatthias Ringwald             event[pos++] = legacy_event_type;
1593a0698cb4SMatthias Ringwald             // copy address type + address
1594a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + 6);
1595a0698cb4SMatthias Ringwald             offset += 7;
1596a0698cb4SMatthias Ringwald             pos += 7;
1597a0698cb4SMatthias Ringwald             // skip primary_phy, secondary_phy, advertising_sid, tx_power
1598a0698cb4SMatthias Ringwald             offset += 4;
1599a0698cb4SMatthias Ringwald             // copy rssi
1600a0698cb4SMatthias Ringwald             event[pos++] = packet[offset++];
1601a0698cb4SMatthias Ringwald             // skip periodic advertising interval and direct address
1602a0698cb4SMatthias Ringwald             offset += 9;
1603a0698cb4SMatthias Ringwald             // copy data len + data;
1604a0698cb4SMatthias Ringwald             (void) memcpy(&event[pos], &packet[offset], 1 + data_length);
1605a0698cb4SMatthias Ringwald             pos    += 1 +data_length;
1606a0698cb4SMatthias Ringwald             offset += 1+ data_length;
1607a0698cb4SMatthias Ringwald             hci_emit_event(event, pos, 1);
1608a0698cb4SMatthias Ringwald         } else {
1609c95a0fc7SMatthias Ringwald             event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT;
1610c95a0fc7SMatthias Ringwald             uint8_t report_len = 24 + data_length;
1611c95a0fc7SMatthias Ringwald             event[1] = report_len;
16120f7610adSMatthias Ringwald             little_endian_store_16(event, 2, event_type);
16130f7610adSMatthias Ringwald             memcpy(&event[4], &packet[offset], report_len);
1614c95a0fc7SMatthias Ringwald             offset += report_len;
1615c95a0fc7SMatthias Ringwald             hci_emit_event(event, 2 + report_len, 1);
1616a0698cb4SMatthias Ringwald         }
1617a0698cb4SMatthias Ringwald     }
1618a0698cb4SMatthias Ringwald }
1619a0698cb4SMatthias Ringwald #endif
1620a0698cb4SMatthias Ringwald 
1621b2f949feS[email protected] #endif
1622e8c8828eSMatthias Ringwald #endif
162357c9da5bS[email protected] 
16242b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
16252b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1626bbc366e6SMatthias Ringwald static void hci_update_advertisements_enabled_for_current_roles(void){
1627a408e724SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){
16282b6ab3e6SMatthias Ringwald         // get number of active le slave connections
16292b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
16302b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
16312b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
16322b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
16332b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
16342b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
16352b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
16362b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
16372b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
16382b6ab3e6SMatthias Ringwald             num_slave_connections++;
16392b6ab3e6SMatthias Ringwald         }
16402b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1641bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1642bbc366e6SMatthias Ringwald     } else {
1643bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = false;
16442b6ab3e6SMatthias Ringwald     }
16452b6ab3e6SMatthias Ringwald }
16462b6ab3e6SMatthias Ringwald #endif
16472b6ab3e6SMatthias Ringwald #endif
16482b6ab3e6SMatthias Ringwald 
164959d59ecfSMatthias Ringwald #ifdef ENABLE_CLASSIC
165059d59ecfSMatthias Ringwald static void gap_run_set_local_name(void){
165159d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
165259d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
165359d59ecfSMatthias Ringwald     // construct HCI Command and send
165459d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_local_name.opcode;
165559d59ecfSMatthias Ringwald     hci_stack->last_cmd_opcode = opcode;
165659d59ecfSMatthias Ringwald     packet[0] = opcode & 0xff;
165759d59ecfSMatthias Ringwald     packet[1] = opcode >> 8;
165859d59ecfSMatthias Ringwald     packet[2] = DEVICE_NAME_LEN;
165959d59ecfSMatthias Ringwald     memset(&packet[3], 0, DEVICE_NAME_LEN);
166059d59ecfSMatthias Ringwald     uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
166159d59ecfSMatthias Ringwald     uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
166259d59ecfSMatthias Ringwald     // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
166359d59ecfSMatthias Ringwald     (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
166459d59ecfSMatthias Ringwald     // expand '00:00:00:00:00:00' in name with bd_addr
166559d59ecfSMatthias Ringwald     btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
166659d59ecfSMatthias Ringwald     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
166759d59ecfSMatthias Ringwald }
166859d59ecfSMatthias Ringwald 
166959d59ecfSMatthias Ringwald static void gap_run_set_eir_data(void){
167059d59ecfSMatthias Ringwald     hci_reserve_packet_buffer();
167159d59ecfSMatthias Ringwald     uint8_t * packet = hci_stack->hci_packet_buffer;
167259d59ecfSMatthias Ringwald     // construct HCI Command in-place and send
167359d59ecfSMatthias Ringwald     uint16_t opcode = hci_write_extended_inquiry_response.opcode;
167459d59ecfSMatthias Ringwald     hci_stack->last_cmd_opcode = opcode;
167559d59ecfSMatthias Ringwald     uint16_t offset = 0;
167659d59ecfSMatthias Ringwald     packet[offset++] = opcode & 0xff;
167759d59ecfSMatthias Ringwald     packet[offset++] = opcode >> 8;
167859d59ecfSMatthias Ringwald     packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
167959d59ecfSMatthias Ringwald     packet[offset++] = 0;  // FEC not required
168059d59ecfSMatthias Ringwald     memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
168159d59ecfSMatthias Ringwald     if (hci_stack->eir_data){
168259d59ecfSMatthias Ringwald         // copy items and expand '00:00:00:00:00:00' in name with bd_addr
168359d59ecfSMatthias Ringwald         ad_context_t context;
168459d59ecfSMatthias Ringwald         for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
168559d59ecfSMatthias Ringwald             uint8_t data_type   = ad_iterator_get_data_type(&context);
168659d59ecfSMatthias Ringwald             uint8_t size        = ad_iterator_get_data_len(&context);
168759d59ecfSMatthias Ringwald             const uint8_t *data = ad_iterator_get_data(&context);
168859d59ecfSMatthias Ringwald             // copy item
168959d59ecfSMatthias Ringwald             packet[offset++] = size + 1;
169059d59ecfSMatthias Ringwald             packet[offset++] = data_type;
169159d59ecfSMatthias Ringwald             memcpy(&packet[offset], data, size);
169259d59ecfSMatthias Ringwald             // update name item
169359d59ecfSMatthias Ringwald             if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
169459d59ecfSMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
169559d59ecfSMatthias Ringwald             }
169659d59ecfSMatthias Ringwald             offset += size;
169759d59ecfSMatthias Ringwald         }
169859d59ecfSMatthias Ringwald     } else {
169959d59ecfSMatthias Ringwald         uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
170059d59ecfSMatthias Ringwald         uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
170159d59ecfSMatthias Ringwald         packet[offset++] = bytes_to_copy + 1;
170259d59ecfSMatthias Ringwald         packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
170359d59ecfSMatthias Ringwald         (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
170459d59ecfSMatthias Ringwald         // expand '00:00:00:00:00:00' in name with bd_addr
170559d59ecfSMatthias Ringwald         btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
170659d59ecfSMatthias Ringwald     }
170759d59ecfSMatthias Ringwald     hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
170859d59ecfSMatthias Ringwald }
1709ab4831a3SMatthias Ringwald 
1710ab4831a3SMatthias Ringwald static void hci_run_gap_tasks_classic(void){
1711baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) {
1712baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE;
1713ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1714ab4831a3SMatthias Ringwald         return;
1715ab4831a3SMatthias Ringwald     }
1716baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) {
1717baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME;
1718ab4831a3SMatthias Ringwald         gap_run_set_local_name();
1719ab4831a3SMatthias Ringwald         return;
1720ab4831a3SMatthias Ringwald     }
1721baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) {
1722baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA;
1723ab4831a3SMatthias Ringwald         gap_run_set_eir_data();
1724ab4831a3SMatthias Ringwald         return;
1725ab4831a3SMatthias Ringwald     }
1726baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) {
1727baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY;
1728ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1729ab4831a3SMatthias Ringwald         return;
1730ab4831a3SMatthias Ringwald     }
1731ab4831a3SMatthias Ringwald     // write page scan activity
1732baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) {
1733baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
1734ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
1735ab4831a3SMatthias Ringwald         return;
1736ab4831a3SMatthias Ringwald     }
1737ab4831a3SMatthias Ringwald     // write page scan type
1738baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) {
1739baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE;
1740ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
1741ab4831a3SMatthias Ringwald         return;
1742ab4831a3SMatthias Ringwald     }
174332a12730SMatthias Ringwald     // write page timeout
1744baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) {
1745baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT;
174632a12730SMatthias Ringwald         hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout);
174732a12730SMatthias Ringwald         return;
174832a12730SMatthias Ringwald     }
1749ab4831a3SMatthias Ringwald     // send scan enable
1750baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) {
1751baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE;
1752ab4831a3SMatthias Ringwald         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1753ab4831a3SMatthias Ringwald         return;
1754ab4831a3SMatthias Ringwald     }
1755c0c8a829SMatthias Ringwald     // send write scan activity
1756baa4881eSMatthias Ringwald     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) {
1757baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
1758c0c8a829SMatthias Ringwald         hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window);
1759c0c8a829SMatthias Ringwald         return;
1760c0c8a829SMatthias Ringwald     }
1761f50ed5acSAndrey Fominykh     // send write inquiry transmit power level
1762f50ed5acSAndrey Fominykh     if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL) != 0) {
1763f50ed5acSAndrey Fominykh         hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
1764f50ed5acSAndrey Fominykh         hci_send_cmd(&hci_write_inquiry_transmit_power_level, hci_stack->inquiry_tx_power_level);
1765f50ed5acSAndrey Fominykh         return;
1766f50ed5acSAndrey Fominykh     }
1767ab4831a3SMatthias Ringwald }
176859d59ecfSMatthias Ringwald #endif
176959d59ecfSMatthias Ringwald 
17706fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
177106b9e820SMatthias Ringwald 
177296b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
177396b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
17749796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
177596b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
1776a1df452eSMatthias Ringwald     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
177796b53536SMatthias Ringwald         baud_rate = 3000000;
177896b53536SMatthias Ringwald     }
177996b53536SMatthias Ringwald     return baud_rate;
178096b53536SMatthias Ringwald }
178196b53536SMatthias Ringwald 
1782ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
17839ec2630cSMatthias Ringwald     UNUSED(ds);
17849ec2630cSMatthias Ringwald 
17850305bdeaSMatthias Ringwald     switch (hci_stack->substate){
17860305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
17877b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
17880305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
17897b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
17900305bdeaSMatthias Ringwald             hci_run();
17910305bdeaSMatthias Ringwald             break;
17929f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
17939f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
17949f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
17959f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
17969f007422SMatthias Ringwald             }
1797cf373d3aSMatthias Ringwald 
1798cf373d3aSMatthias Ringwald             /* fall through */
1799cf373d3aSMatthias Ringwald 
1800e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1801e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1802e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1803e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1804e47e68c7SMatthias Ringwald             hci_run();
1805688c2635SMatthias Ringwald             break;
18067224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
18077224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
180896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1809cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
18107dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18117224be7eSMatthias Ringwald             }
1812834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
181361f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1814834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1815834bce8cSMatthias Ringwald                     log_info("Link Reset");
1816834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1817834bce8cSMatthias Ringwald                 }
1818772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1819772a36d3SMatthias Ringwald                 hci_run();
1820772a36d3SMatthias Ringwald             }
18214696bddbSMatthias Ringwald             break;
1822559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1823559961d0SMatthias Ringwald             // otherwise continue
1824559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1825559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1826559961d0SMatthias Ringwald             break;
18270305bdeaSMatthias Ringwald         default:
18280305bdeaSMatthias Ringwald             break;
18290305bdeaSMatthias Ringwald     }
18300305bdeaSMatthias Ringwald }
183106b9e820SMatthias Ringwald #endif
18320305bdeaSMatthias Ringwald 
183371de195eSMatthias Ringwald static void hci_initializing_next_state(void){
183474b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
183574b323a9SMatthias Ringwald }
183674b323a9SMatthias Ringwald 
1837f795c86eSMatthias Ringwald static void hci_init_done(void){
1838f795c86eSMatthias Ringwald     // done. tell the app
1839f795c86eSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1840f795c86eSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1841f795c86eSMatthias Ringwald     hci_emit_state();
1842f795c86eSMatthias Ringwald }
1843f795c86eSMatthias Ringwald 
184474b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
184571de195eSMatthias Ringwald static void hci_initializing_run(void){
1846148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1847f4c579d4SMatthias Ringwald 
18480d37aff3SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
18490d37aff3SMatthias Ringwald 
1850f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1851f9fd20c2SMatthias Ringwald     bool need_baud_change = hci_stack->config
1852f4c579d4SMatthias Ringwald             && hci_stack->chipset
1853f4c579d4SMatthias Ringwald             && hci_stack->chipset->set_baudrate_command
1854f4c579d4SMatthias Ringwald             && hci_stack->hci_transport->set_baudrate
1855f4c579d4SMatthias Ringwald             && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1856f4c579d4SMatthias Ringwald #endif
1857f4c579d4SMatthias Ringwald 
185874b323a9SMatthias Ringwald     switch (hci_stack->substate){
185974b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
186074b323a9SMatthias Ringwald             hci_state_reset();
1861a0cf2f3fSMatthias Ringwald 
18626fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
18630305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1864659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1865528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1866528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1867a0cf2f3fSMatthias Ringwald #endif
18680305bdeaSMatthias Ringwald             // send command
186974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
18700305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
187174b323a9SMatthias Ringwald             break;
187276fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
187376fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
187476fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
187576fcb19bSMatthias Ringwald             break;
1876e28e41c0SMatthias Ringwald 
1877e28e41c0SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
1878e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1879e47e68c7SMatthias Ringwald             hci_state_reset();
1880e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1881659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1882528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1883528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1884e47e68c7SMatthias Ringwald             // send command
1885e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1886e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1887e47e68c7SMatthias Ringwald             break;
18888d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
18898d29070eSMatthias Ringwald             hci_state_reset();
18908d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
18918d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
18928d29070eSMatthias Ringwald             break;
1893f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1894f4c579d4SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1895f4c579d4SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1896f4c579d4SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1897f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1898f4c579d4SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1899f4c579d4SMatthias Ringwald             break;
1900f4c579d4SMatthias Ringwald         }
1901c97af506SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
1902c97af506SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1903c97af506SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1904c97af506SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1905c97af506SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1906c97af506SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1907c97af506SMatthias Ringwald             break;
19088250c242SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
19098250c242SMatthias Ringwald #ifdef ENABLE_CLASSIC
19108250c242SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
19118250c242SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
19128250c242SMatthias Ringwald             break;
19138250c242SMatthias Ringwald #endif
19148250c242SMatthias Ringwald             /* fall through */
19158250c242SMatthias Ringwald 
1916f4c579d4SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE:
1917f4c579d4SMatthias Ringwald             if (need_baud_change) {
191896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
19193fb36a29SMatthias Ringwald                 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1920f8fbdce0SMatthias Ringwald                 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
192174b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
19224ea43905SMatthias Ringwald                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
19234696bddbSMatthias Ringwald                 // STLC25000D: baudrate change happens within 0.5 s after command was send,
19244696bddbSMatthias Ringwald                 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
192561f37892SMatthias Ringwald                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1926659d758cSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1927528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
19284696bddbSMatthias Ringwald                }
192974b323a9SMatthias Ringwald                break;
1930fab26ab3SMatthias Ringwald             }
19316fe16221SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1932f4c579d4SMatthias Ringwald 
1933f4c579d4SMatthias Ringwald             /* fall through */
1934f4c579d4SMatthias Ringwald 
193574b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
19366fe16221SMatthias Ringwald         case HCI_INIT_CUSTOM_PRE_INIT:
193774b323a9SMatthias Ringwald             // Custom initialization
19383fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1939ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
19401979f09cSMatthias Ringwald                 bool send_cmd = false;
1941ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1942f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
19431979f09cSMatthias Ringwald                         send_cmd = true;
19446fe16221SMatthias Ringwald                         switch (hci_stack->substate){
19456fe16221SMatthias Ringwald                             case HCI_INIT_CUSTOM_INIT:
1946e47e68c7SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1947e47e68c7SMatthias Ringwald                                 break;
19486fe16221SMatthias Ringwald                             case HCI_INIT_CUSTOM_PRE_INIT:
19496fe16221SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_CUSTOM_PRE_INIT;
19506fe16221SMatthias Ringwald                                 break;
19516fe16221SMatthias Ringwald                             default:
19526fe16221SMatthias Ringwald                                 btstack_assert(false);
19536fe16221SMatthias Ringwald                                 break;
19546fe16221SMatthias Ringwald                         }
19556fe16221SMatthias Ringwald                         break;
1956f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
19571979f09cSMatthias Ringwald                         send_cmd = true;
1958f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1959e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1960659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1961528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1962528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
1963a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1964772a36d3SMatthias Ringwald                             && hci_stack->config
19653fb36a29SMatthias Ringwald                             && hci_stack->chipset
19663fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1967772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
19682caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
1969772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1970772a36d3SMatthias Ringwald                         } else {
19719f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1972772a36d3SMatthias Ringwald                         }
1973e47e68c7SMatthias Ringwald                         break;
1974f41911edSMatthias Ringwald                     default:
1975f41911edSMatthias Ringwald                         break;
1976e47e68c7SMatthias Ringwald                 }
1977ee720f3aSMatthias Ringwald 
1978ee720f3aSMatthias Ringwald                 if (send_cmd){
19794ea43905SMatthias Ringwald                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1980ee720f3aSMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1981ee720f3aSMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
19820305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
198374b323a9SMatthias Ringwald                     break;
198474b323a9SMatthias Ringwald                 }
1985148ca237SMatthias Ringwald                 log_info("Init script done");
198692a0d36dSMatthias Ringwald 
19876fe16221SMatthias Ringwald                 // Custom Pre-Init complete, start regular init with HCI Reset
19886fe16221SMatthias Ringwald                 if (hci_stack->substate == HCI_INIT_CUSTOM_PRE_INIT){
19896fe16221SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_SEND_RESET;
19906fe16221SMatthias Ringwald                     hci_send_cmd(&hci_reset);
19916fe16221SMatthias Ringwald                     break;
19926fe16221SMatthias Ringwald                 }
19936fe16221SMatthias Ringwald 
1994559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1995ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1996a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1997a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1998e021ff1eSMatthias Ringwald 
1999559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
200092a0d36dSMatthias Ringwald                     if (need_baud_change) {
20019796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
2002cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
200392a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
200492a0d36dSMatthias Ringwald                     }
2005559961d0SMatthias Ringwald 
2006f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
2007f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
2008f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
2009f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
2010559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
2011f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
2012559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
2013559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
2014559961d0SMatthias Ringwald                     break;
201592a0d36dSMatthias Ringwald                 }
201674b323a9SMatthias Ringwald             }
201706b9e820SMatthias Ringwald #endif
2018521bd5ffSMatthias Ringwald             /* fall through */
201906b9e820SMatthias Ringwald 
202006b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
202106b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
202206b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
202306b9e820SMatthias Ringwald             break;
202453860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
202553860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
202653860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
202753860077SMatthias Ringwald             break;
202874b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
20295ffe9d0bSMatthias Ringwald             // only read buffer size if supported
20301ffa425cSMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){
203174b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
20320305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_read_buffer_size);
203374b323a9SMatthias Ringwald                 break;
20345ffe9d0bSMatthias Ringwald             }
2035521bd5ffSMatthias Ringwald 
20365ffe9d0bSMatthias Ringwald             /* fall through */
20375ffe9d0bSMatthias Ringwald 
203853860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
203953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
20400305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
204174b323a9SMatthias Ringwald             break;
20422b838201SMatthias Ringwald 
20432b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
20442b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
20452b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
20462b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
20472b838201SMatthias Ringwald             break;
20482b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
20492b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
20502b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
20512b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
20522b838201SMatthias Ringwald             break;
20532b838201SMatthias Ringwald #endif
20542b838201SMatthias Ringwald 
205574b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
20560305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
205774b323a9SMatthias Ringwald             if (hci_le_supported()){
20585ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
205974b323a9SMatthias Ringwald             } else {
206074b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
20615ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
206274b323a9SMatthias Ringwald             }
206374b323a9SMatthias Ringwald             break;
20642b838201SMatthias Ringwald 
2065ff7d1758SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK_2:
20668254e329SMatthias Ringwald             // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244,
20678254e329SMatthias Ringwald             // setting Event Mask 2 causes Controller to drop Encryption Change events.
20688254e329SMatthias Ringwald             if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2)
20698254e329SMatthias Ringwald             && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){
2070ff7d1758SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2;
2071ff7d1758SMatthias Ringwald                 // Encryption Change Event v2 - bit 25
2072ff7d1758SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0);
2073ff7d1758SMatthias Ringwald                 break;
2074ff7d1758SMatthias Ringwald             }
2075ff7d1758SMatthias Ringwald 
207635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2077ff7d1758SMatthias Ringwald             /* fall through */
2078ff7d1758SMatthias Ringwald 
207974b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
2080f795c86eSMatthias Ringwald             if (hci_classic_supported() && gap_ssp_supported()){
208174b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
20820305bdeaSMatthias Ringwald                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
208374b323a9SMatthias Ringwald                 break;
2084e7c662faSMatthias Ringwald             }
2085521bd5ffSMatthias Ringwald 
2086e7c662faSMatthias Ringwald             /* fall through */
2087e7c662faSMatthias Ringwald 
2088f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
2089f795c86eSMatthias Ringwald             if (hci_classic_supported()){
2090f6858d14SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
20918a114470SMatthias Ringwald                 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
2092f6858d14SMatthias Ringwald                 break;
2093f795c86eSMatthias Ringwald             }
2094521bd5ffSMatthias Ringwald 
2095f795c86eSMatthias Ringwald             /* fall through */
2096f795c86eSMatthias Ringwald 
20975d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
2098f3052906SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
20991ffa425cSMatthias Ringwald             if (hci_classic_supported() && hci_stack->secure_connections_enable
21001ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) {
2101c214d65bSMatthias Ringwald                 hci_stack->secure_connections_active = true;
21025d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
21031ffa425cSMatthias Ringwald                 hci_send_cmd(&hci_write_secure_connections_host_support, 1);
21045d23aae8SMatthias Ringwald                 break;
2105f3052906SMatthias Ringwald             }
2106521bd5ffSMatthias Ringwald 
2107a391128dSMatthias Ringwald             /* fall through */
2108a391128dSMatthias Ringwald 
2109a391128dSMatthias Ringwald         case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE:
2110a391128dSMatthias Ringwald             // skip set min encryption key size
2111a391128dSMatthias Ringwald             if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) {
2112a391128dSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE;
2113a391128dSMatthias Ringwald                 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size);
2114a391128dSMatthias Ringwald                 break;
2115a391128dSMatthias Ringwald             }
2116a391128dSMatthias Ringwald 
2117e4c6114dSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2118521bd5ffSMatthias Ringwald             /* fall through */
2119521bd5ffSMatthias Ringwald 
2120483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
2121729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
2122e4c6114dSMatthias Ringwald             // skip write synchronous flow control if not supported
21231ffa425cSMatthias Ringwald             if (hci_classic_supported()
21241ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) {
2125729ed62eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
2126729ed62eSMatthias Ringwald                 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
2127729ed62eSMatthias Ringwald                 break;
2128f795c86eSMatthias Ringwald             }
2129f795c86eSMatthias Ringwald             /* fall through */
2130f795c86eSMatthias Ringwald 
2131483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
2132e4c6114dSMatthias Ringwald             // skip write default erroneous data reporting if not supported
21331ffa425cSMatthias Ringwald             if (hci_classic_supported()
21341ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) {
2135483c5078SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
2136483c5078SMatthias Ringwald                 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
2137483c5078SMatthias Ringwald                 break;
2138f795c86eSMatthias Ringwald             }
2139e4c6114dSMatthias Ringwald #endif
2140f795c86eSMatthias Ringwald 
2141f795c86eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM)
2142521bd5ffSMatthias Ringwald             /* fall through */
2143521bd5ffSMatthias Ringwald 
21448051253fSMatthias Ringwald         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
2145a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
2146e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
2147a42798c3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
21488051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2149a42798c3SMatthias Ringwald                 log_info("BCM: Route SCO data via HCI transport");
2150a42798c3SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
21518051253fSMatthias Ringwald #endif
21528051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
21538051253fSMatthias Ringwald                 log_info("BCM: Route SCO data via PCM interface");
21541d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
2155f795c86eSMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz
21561d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
21571d2bbd54SMatthias Ringwald #else
21581d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
21591d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
21601d2bbd54SMatthias Ringwald #endif
21618051253fSMatthias Ringwald #endif
2162a42798c3SMatthias Ringwald                 break;
2163f795c86eSMatthias Ringwald             }
2164f795c86eSMatthias Ringwald #endif
2165f795c86eSMatthias Ringwald 
21664e821764SMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
2167521bd5ffSMatthias Ringwald             /* fall through */
2168521bd5ffSMatthias Ringwald 
21694e821764SMatthias Ringwald         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
2170e4c6114dSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
21714e821764SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
21724e821764SMatthias Ringwald                 log_info("BCM: Config PCM interface for I2S");
21731d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
21741d2bbd54SMatthias Ringwald                 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
21751d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
21761d2bbd54SMatthias Ringwald #else
21771d2bbd54SMatthias Ringwald                 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
21781d2bbd54SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
21791d2bbd54SMatthias Ringwald #endif
21804e821764SMatthias Ringwald                 break;
2181f795c86eSMatthias Ringwald             }
21821be678e9SMatthias Ringwald         case HCI_INIT_BCM_WRITE_PCM_DATA_FORMAT_PARAM:
21831be678e9SMatthias Ringwald             if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){
21841be678e9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_PCM_DATA_FORMAT_PARAM;
21851be678e9SMatthias Ringwald                 log_info("BCM: Config PCM Data format");
21861be678e9SMatthias Ringwald                 // msb first, fill bits 0, left justified
21871be678e9SMatthias Ringwald                 hci_send_cmd(&hci_bcm_write_pcm_data_format_param, 0, 0, 3, 3, 0);
21881be678e9SMatthias Ringwald                 break;
21891be678e9SMatthias Ringwald             }
219035454696SMatthias Ringwald #endif
21914e821764SMatthias Ringwald #endif
21924e821764SMatthias Ringwald 
2193a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2194521bd5ffSMatthias Ringwald             /* fall through */
2195521bd5ffSMatthias Ringwald 
219674b323a9SMatthias Ringwald         // LE INIT
219774b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
2198f795c86eSMatthias Ringwald             if (hci_le_supported()){
219974b323a9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
220079b7ea2dSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){
220179b7ea2dSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size_v2);
220279b7ea2dSMatthias Ringwald                 } else {
22030305bdeaSMatthias Ringwald                     hci_send_cmd(&hci_le_read_buffer_size);
220479b7ea2dSMatthias Ringwald                 }
220574b323a9SMatthias Ringwald                 break;
2206f795c86eSMatthias Ringwald             }
2207521bd5ffSMatthias Ringwald 
2208f795c86eSMatthias Ringwald             /* fall through */
2209f795c86eSMatthias Ringwald 
2210699a5fcaSMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
2211699a5fcaSMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
22121ffa425cSMatthias Ringwald             if (hci_le_supported()
22131ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) {
2214699a5fcaSMatthias Ringwald                 // LE Supported Host = 1, Simultaneous Host = 0
2215699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
2216699a5fcaSMatthias Ringwald                 hci_send_cmd(&hci_write_le_host_supported, 1, 0);
2217daabb8b8SMatthias Ringwald                 break;
2218f795c86eSMatthias Ringwald             }
2219521bd5ffSMatthias Ringwald 
2220f795c86eSMatthias Ringwald             /* fall through */
2221f795c86eSMatthias Ringwald 
2222699a5fcaSMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
2223f795c86eSMatthias Ringwald             if (hci_le_supported()){
2224699a5fcaSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
222591d9e5d0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x07); // all events from core v5.3 without LE Enhanced Connection Complete
222674b323a9SMatthias Ringwald                 break;
2227f795c86eSMatthias Ringwald             }
2228b435e062SMatthias Ringwald #endif
2229b435e062SMatthias Ringwald 
2230b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2231521bd5ffSMatthias Ringwald             /* fall through */
2232521bd5ffSMatthias Ringwald 
2233dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
22341ffa425cSMatthias Ringwald             if (hci_le_supported()
22351ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) {
2236dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
2237dcd678baSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_data_length);
2238dcd678baSMatthias Ringwald                 break;
2239f795c86eSMatthias Ringwald             }
2240521bd5ffSMatthias Ringwald 
2241f795c86eSMatthias Ringwald             /* fall through */
2242f795c86eSMatthias Ringwald 
2243dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
22441ffa425cSMatthias Ringwald             if (hci_le_supported()
22451ffa425cSMatthias Ringwald             && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) {
2246dcd678baSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
2247b435e062SMatthias 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);
2248dcd678baSMatthias Ringwald                 break;
2249f795c86eSMatthias Ringwald             }
2250b435e062SMatthias Ringwald #endif
2251b435e062SMatthias Ringwald 
2252b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2253521bd5ffSMatthias Ringwald             /* fall through */
2254521bd5ffSMatthias Ringwald 
22553b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
2256f795c86eSMatthias Ringwald             if (hci_le_supported()){
22573b6d4121SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
22583b6d4121SMatthias Ringwald                 hci_send_cmd(&hci_le_read_white_list_size);
22593b6d4121SMatthias Ringwald                 break;
2260f795c86eSMatthias Ringwald             }
2261521bd5ffSMatthias Ringwald 
226274b323a9SMatthias Ringwald #endif
22634f982f31SMatthias Ringwald 
22643a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
22653a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
22663a74541eSMatthias Ringwald             /* fall through */
22673a74541eSMatthias Ringwald 
22683a74541eSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN:
22693a74541eSMatthias Ringwald             if (hci_extended_advertising_supported()){
22703a74541eSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN;
22713a74541eSMatthias Ringwald                 hci_send_cmd(&hci_le_read_maximum_advertising_data_length);
22723a74541eSMatthias Ringwald                 break;
22733a74541eSMatthias Ringwald             }
22743a74541eSMatthias Ringwald #endif
22753a74541eSMatthias Ringwald #endif
2276521bd5ffSMatthias Ringwald             /* fall through */
2277521bd5ffSMatthias Ringwald 
2278c63ee49aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2279c63ee49aSMatthias Ringwald     case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS:
2280c63ee49aSMatthias Ringwald             if (hci_le_supported()) {
2281c63ee49aSMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS;
2282c63ee49aSMatthias Ringwald                 hci_send_cmd(&hci_le_set_host_feature, 32, 1);
2283c63ee49aSMatthias Ringwald                 break;
2284c63ee49aSMatthias Ringwald             }
2285c63ee49aSMatthias Ringwald #endif
2286c63ee49aSMatthias Ringwald 
2287c63ee49aSMatthias Ringwald             /* fall through */
2288c63ee49aSMatthias Ringwald 
2289f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
22904f982f31SMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
229173799937SMatthias Ringwald             // main init sequence complete
22924f982f31SMatthias Ringwald #ifdef ENABLE_CLASSIC
229373799937SMatthias Ringwald             // check if initial Classic GAP Tasks are completed
2294baa4881eSMatthias Ringwald             if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) {
22954f982f31SMatthias Ringwald                 hci_run_gap_tasks_classic();
22964f982f31SMatthias Ringwald                 break;
22974f982f31SMatthias Ringwald             }
22984f982f31SMatthias Ringwald #endif
229973799937SMatthias Ringwald #ifdef ENABLE_BLE
230073799937SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
230173799937SMatthias Ringwald             // check if initial LE GAP Tasks are completed
230273799937SMatthias Ringwald             if (hci_le_supported() && hci_stack->le_scanning_param_update) {
230373799937SMatthias Ringwald                 hci_run_general_gap_le();
230473799937SMatthias Ringwald                 break;
230573799937SMatthias Ringwald             }
230673799937SMatthias Ringwald #endif
230773799937SMatthias Ringwald #endif
2308f795c86eSMatthias Ringwald             hci_init_done();
2309f795c86eSMatthias Ringwald             break;
2310f795c86eSMatthias Ringwald 
231174b323a9SMatthias Ringwald         default:
231274b323a9SMatthias Ringwald             return;
231374b323a9SMatthias Ringwald     }
231455975f88SMatthias Ringwald }
231555975f88SMatthias Ringwald 
231607fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
231707fd2f31SMatthias Ringwald     bool command_completed = false;
23180e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
2319f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
23206155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
232107fd2f31SMatthias Ringwald             command_completed = true;
2322148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
23236155b3d3S[email protected]         } else {
2324d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
23256155b3d3S[email protected]         }
23266155b3d3S[email protected]     }
23270f97eae7SMatthias Ringwald 
23280e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
23296155b3d3S[email protected]         uint8_t  status = packet[2];
2330f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
23316155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
23326155b3d3S[email protected]             if (status){
233307fd2f31SMatthias Ringwald                 command_completed = true;
2334148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
23356155b3d3S[email protected]             } else {
23366155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
23376155b3d3S[email protected]             }
23386155b3d3S[email protected]         } else {
2339148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
23406155b3d3S[email protected]         }
23416155b3d3S[email protected]     }
23426fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2343e47e68c7SMatthias Ringwald     // Vendor == CSR
23440e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
2345e47e68c7SMatthias Ringwald         // TODO: track actual command
234607fd2f31SMatthias Ringwald         command_completed = true;
2347e47e68c7SMatthias Ringwald     }
2348a2481739S[email protected] 
23494e9daa6fSMatthias Ringwald     // Vendor == Toshiba
23500e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
23514e9daa6fSMatthias Ringwald         // TODO: track actual command
235207fd2f31SMatthias Ringwald         command_completed = true;
2353004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
2354004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
23554e9daa6fSMatthias Ringwald     }
235607fd2f31SMatthias Ringwald #endif
235707fd2f31SMatthias Ringwald 
235807fd2f31SMatthias Ringwald     return command_completed;
235907fd2f31SMatthias Ringwald }
236007fd2f31SMatthias Ringwald 
236107fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
236207fd2f31SMatthias Ringwald 
236307fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
236407fd2f31SMatthias Ringwald 
236507fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
236607fd2f31SMatthias Ringwald 
23676fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
23684e9daa6fSMatthias Ringwald 
23690f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
23700f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
23710f97eae7SMatthias Ringwald     //
23720f97eae7SMatthias Ringwald     // HCI Reset
23730f97eae7SMatthias Ringwald     // Timeout 100 ms
23740f97eae7SMatthias Ringwald     // HCI Reset
23750f97eae7SMatthias Ringwald     // Command Complete Reset
23760f97eae7SMatthias Ringwald     // HCI Read Local Version Information
23770f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
23780f97eae7SMatthias Ringwald     // hang...
23790f97eae7SMatthias Ringwald     //
23800f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
23810f97eae7SMatthias Ringwald     if (!command_completed
2382a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
23830e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
23840f97eae7SMatthias Ringwald 
2385f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
23860f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
23870f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
23880f97eae7SMatthias Ringwald             return;
23890f97eae7SMatthias Ringwald         }
23900f97eae7SMatthias Ringwald     }
23910f97eae7SMatthias Ringwald 
23929f007422SMatthias Ringwald     // CSR & H5
23939f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
23949f007422SMatthias Ringwald     if (!command_completed
2395a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
23960e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
23979f007422SMatthias Ringwald 
23989f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
23999f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
24009f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
24019f007422SMatthias Ringwald             return;
24029f007422SMatthias Ringwald         }
24039f007422SMatthias Ringwald     }
24049f007422SMatthias Ringwald 
24059f007422SMatthias 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
24069f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
24079f007422SMatthias Ringwald     if (command_completed){
24089f007422SMatthias Ringwald         switch (hci_stack->substate){
24099f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
24109f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
24119f007422SMatthias Ringwald                 break;
24129f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
24139f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
24149f007422SMatthias Ringwald                 break;
24159f007422SMatthias Ringwald             default:
24169f007422SMatthias Ringwald                 break;
24179f007422SMatthias Ringwald         }
24189f007422SMatthias Ringwald     }
24190f97eae7SMatthias Ringwald 
242006b9e820SMatthias Ringwald #endif
24210f97eae7SMatthias Ringwald 
2422a2481739S[email protected]     if (!command_completed) return;
2423a2481739S[email protected] 
242407fd2f31SMatthias Ringwald     bool need_baud_change = false;
242507fd2f31SMatthias Ringwald     bool need_addr_change = false;
242606b9e820SMatthias Ringwald 
24276fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
242806b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
24293fb36a29SMatthias Ringwald                         && hci_stack->chipset
24303fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
2431db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
24329796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
2433db8bc6ffSMatthias Ringwald 
243406b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
24353fb36a29SMatthias Ringwald                         && hci_stack->chipset
24363fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
243706b9e820SMatthias Ringwald #endif
2438a80162e9SMatthias Ringwald 
24395c363727SMatthias Ringwald     switch(hci_stack->substate){
244006b9e820SMatthias Ringwald 
24416fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
24429f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
2443d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
24449f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
2445f4c579d4SMatthias Ringwald 
2446f4c579d4SMatthias Ringwald             /* fall through */
2447f4c579d4SMatthias Ringwald #endif
2448f4c579d4SMatthias Ringwald 
244974b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
2450528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2451f4c579d4SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
24522f48d920SMatthias Ringwald             return;
2453f4c579d4SMatthias Ringwald 
2454f4c579d4SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
2455a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
24564696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
2457fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
245861f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
245996b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2460cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
2461fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
24624696bddbSMatthias Ringwald             }
246374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
246474b323a9SMatthias Ringwald             return;
2465a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
2466528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
2467a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
2468a80162e9SMatthias Ringwald             return;
246974b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
247074b323a9SMatthias Ringwald             // repeat custom init
247174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
247274b323a9SMatthias Ringwald             return;
24736fe16221SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_PRE_INIT:
24746fe16221SMatthias Ringwald             // repeat custom init
24756fe16221SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
24766fe16221SMatthias Ringwald             return;
247706b9e820SMatthias Ringwald #endif
247806b9e820SMatthias Ringwald 
2479a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
24800e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
2481efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
2482efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
2483eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
2484eb3a5314SMatthias Ringwald                 return;
2485eb3a5314SMatthias Ringwald             }
248653860077SMatthias Ringwald             if (need_addr_change){
248753860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
248853860077SMatthias Ringwald                 return;
248953860077SMatthias Ringwald             }
249053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
249153860077SMatthias Ringwald             return;
24926fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
24937224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
24947224be7eSMatthias Ringwald             if (need_baud_change){
249596b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
2496cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
2497fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
24987224be7eSMatthias Ringwald             }
2499eb3a5314SMatthias Ringwald             if (need_addr_change){
2500eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
2501eb3a5314SMatthias Ringwald                 return;
2502eb3a5314SMatthias Ringwald             }
2503eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
2504eb3a5314SMatthias Ringwald             return;
250553860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
25066ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
25076ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
25086ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
250953860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
251053860077SMatthias Ringwald                 return;
251153860077SMatthias Ringwald             }
251253860077SMatthias Ringwald             // skipping st warm boot
251353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
251453860077SMatthias Ringwald             return;
251553860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
251653860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
251753860077SMatthias Ringwald             return;
251806b9e820SMatthias Ringwald #endif
2519e7c662faSMatthias Ringwald 
2520f795c86eSMatthias Ringwald         case HCI_INIT_DONE:
2521eb8d95caSMatthias Ringwald             // set state if we came here by fall through
2522eb8d95caSMatthias Ringwald             hci_stack->substate = HCI_INIT_DONE;
2523f795c86eSMatthias Ringwald             return;
2524a650ba4dSMatthias Ringwald 
25256155b3d3S[email protected]         default:
252674b323a9SMatthias Ringwald             break;
25276155b3d3S[email protected]     }
252855975f88SMatthias Ringwald     hci_initializing_next_state();
25296155b3d3S[email protected] }
25306155b3d3S[email protected] 
25310bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
25323bb5ff27SMatthias Ringwald     // CC2564C might emit Connection Complete for rejected incoming SCO connection
25331a4fdac4SMatthias Ringwald     // To prevent accidentally free'ing the HCI connection for the ACL connection,
25341a4fdac4SMatthias Ringwald     // check if we have been aware of the HCI connection
25351f34df2cSMatthias Ringwald     switch (conn->state){
25361a4fdac4SMatthias Ringwald         case SENT_CREATE_CONNECTION:
25371f34df2cSMatthias Ringwald         case RECEIVED_CONNECTION_REQUEST:
25389071873aSMatthias Ringwald         case ACCEPTED_CONNECTION_REQUEST:
25391f34df2cSMatthias Ringwald             break;
25401f34df2cSMatthias Ringwald         default:
25411f34df2cSMatthias Ringwald             return;
25421f34df2cSMatthias Ringwald     }
25433bb5ff27SMatthias Ringwald 
2544229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
25450bbba85bSMatthias Ringwald     bd_addr_t bd_address;
25466535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
25470bbba85bSMatthias Ringwald 
25486bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
25496bc9fa5eSMatthias Ringwald     // cache needed data
25506bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
25516bc9fa5eSMatthias Ringwald #endif
25526bc9fa5eSMatthias Ringwald 
25530bbba85bSMatthias Ringwald     // connection failed, remove entry
25540bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
25550bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
25560bbba85bSMatthias Ringwald 
25576bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
25580bbba85bSMatthias Ringwald     // notify client if dedicated bonding
25590bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
25600bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
25610bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
25620bbba85bSMatthias Ringwald     }
25630bbba85bSMatthias Ringwald 
25640bbba85bSMatthias Ringwald     // if authentication error, also delete link key
25650bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
25660bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
25670bbba85bSMatthias Ringwald     }
25681c79b5e3SMatthias Ringwald #else
25691c79b5e3SMatthias Ringwald     UNUSED(status);
25706bc9fa5eSMatthias Ringwald #endif
25710bbba85bSMatthias Ringwald }
25720bbba85bSMatthias Ringwald 
2573be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
25742f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
25752f5c44baSMatthias Ringwald     // SSP Controller
25762f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
25772f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
25782f5c44baSMatthias Ringwald     }
25792f5c44baSMatthias Ringwald     // eSCO
25802f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
25812f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
25822f5c44baSMatthias Ringwald     }
25832f5c44baSMatthias Ringwald     // Extended features
25842f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
25852f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
25862f5c44baSMatthias Ringwald     }
25870b78a447SMatthias Ringwald     // SCO packet types
25880b78a447SMatthias Ringwald     conn->remote_supported_sco_packets = hci_sco_packet_types_for_features(features);
25892f5c44baSMatthias Ringwald }
25902f5c44baSMatthias Ringwald 
25912f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
25922f5c44baSMatthias Ringwald     // SSP Host
25932f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
25942f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
25952f5c44baSMatthias Ringwald     }
259650c51a77SMatthias Ringwald     // SC Host
259750c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
259850c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
259950c51a77SMatthias Ringwald     }
260050c51a77SMatthias Ringwald }
260150c51a77SMatthias Ringwald 
260250c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
260350c51a77SMatthias Ringwald     // SC Controller
260450c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
260550c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
260650c51a77SMatthias Ringwald     }
26072f5c44baSMatthias Ringwald }
26082f5c44baSMatthias Ringwald 
2609de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
2610461a2bc4SMatthias Ringwald     conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE;
2611de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2612cb7b3e6fSMatthias Ringwald     log_info("Remote features %02x, bonding flags %" PRIx32, conn->remote_supported_features[0], conn->bonding_flags);
2613de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
2614de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2615de0df013SMatthias Ringwald     }
2616de0df013SMatthias Ringwald }
2617128825c3SMatthias Ringwald static bool hci_remote_sc_enabled(hci_connection_t * connection){
2618128825c3SMatthias Ringwald     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2619128825c3SMatthias Ringwald     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2620128825c3SMatthias Ringwald }
2621128825c3SMatthias Ringwald 
2622be500194SMatthias Ringwald #endif
2623de0df013SMatthias Ringwald 
262467c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
262567c6c9dcSMatthias Ringwald     // handle BT initialization
262667c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
262767c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
262867c6c9dcSMatthias Ringwald     }
262967c6c9dcSMatthias Ringwald 
263067c6c9dcSMatthias Ringwald     // help with BT sleep
263167c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
263267c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
263372a2585aSMatthias Ringwald         && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
263472a2585aSMatthias Ringwald         && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){
263567c6c9dcSMatthias Ringwald         hci_initializing_next_state();
263667c6c9dcSMatthias Ringwald     }
263767c6c9dcSMatthias Ringwald }
263867c6c9dcSMatthias Ringwald 
26399866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
26404aa2f135SMatthias Ringwald static void hci_handle_mutual_authentication_completed(hci_connection_t * conn){
26414aa2f135SMatthias Ringwald     // bonding complete if connection is authenticated (either initiated or BR/EDR SC)
26424aa2f135SMatthias Ringwald     conn->requested_security_level = LEVEL_0;
26434aa2f135SMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_connection(conn);
26444aa2f135SMatthias Ringwald     hci_emit_security_level(conn->con_handle, security_level);
26454aa2f135SMatthias Ringwald 
264667718330SMatthias Ringwald     // dedicated bonding
2647de9f0299SMatthias Ringwald     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
2648de9f0299SMatthias Ringwald         conn->bonding_flags &= ~BONDING_DEDICATED;
2649de9f0299SMatthias Ringwald         conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS;
2650db3c1f89SMatthias Ringwald #ifdef ENABLE_EXPLICIT_DEDICATED_BONDING_DISCONNECT
2651db3c1f89SMatthias Ringwald         // emit dedicated bonding complete, don't disconnect
2652db3c1f89SMatthias Ringwald         hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2653db3c1f89SMatthias Ringwald #else
2654db3c1f89SMatthias Ringwald         // request disconnect, event is emitted after disconnect
2655db3c1f89SMatthias Ringwald         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2656db3c1f89SMatthias Ringwald #endif
2657de9f0299SMatthias Ringwald     }
265867718330SMatthias Ringwald }
2659abdad579SMatthias Ringwald 
266067718330SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
266167718330SMatthias Ringwald     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
266267718330SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
266367718330SMatthias Ringwald 
266467718330SMatthias Ringwald     // mutual authentication complete if authenticated and we have retrieved the encryption key size
26658daf94bcSMatthias Ringwald     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
26664aa2f135SMatthias Ringwald         hci_handle_mutual_authentication_completed(conn);
26674cd03f8aSMatthias Ringwald     } else {
26684cd03f8aSMatthias Ringwald         // otherwise trigger remote feature request and send authentication request
2669dbe0d85cSMatthias Ringwald         hci_trigger_remote_features_for_connection(conn);
26704cd03f8aSMatthias Ringwald         if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) {
2671abdad579SMatthias Ringwald             conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
26729866fdc7SMatthias Ringwald         }
26734cd03f8aSMatthias Ringwald     }
26744cd03f8aSMatthias Ringwald }
26759866fdc7SMatthias Ringwald #endif
26769866fdc7SMatthias Ringwald 
26773b631737SMatthias Ringwald static void hci_store_local_supported_commands(const uint8_t * packet){
267825e46151SMatthias Ringwald     // create mapping table
267925e46151SMatthias Ringwald #define X(name, offset, bit) { offset, bit },
268025e46151SMatthias Ringwald     static struct {
268125e46151SMatthias Ringwald         uint8_t byte_offset;
268225e46151SMatthias Ringwald         uint8_t bit_position;
268325e46151SMatthias Ringwald     } supported_hci_commands_map [] = {
268425e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
268525e46151SMatthias Ringwald     };
268625e46151SMatthias Ringwald #undef X
268725e46151SMatthias Ringwald 
268825e46151SMatthias Ringwald     // create names for debug purposes
268925e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
269025e46151SMatthias Ringwald #define X(name, offset, bit) #name,
269125e46151SMatthias Ringwald     static const char * command_names[] = {
269225e46151SMatthias Ringwald         SUPPORTED_HCI_COMMANDS
269325e46151SMatthias Ringwald     };
269425e46151SMatthias Ringwald #undef X
269525e46151SMatthias Ringwald #endif
269625e46151SMatthias Ringwald 
26971ffa425cSMatthias Ringwald     hci_stack->local_supported_commands = 0;
269825e46151SMatthias Ringwald     const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1];
269925e46151SMatthias Ringwald     uint16_t i;
270025e46151SMatthias Ringwald     for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){
270125e46151SMatthias Ringwald         if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){
270225e46151SMatthias Ringwald #ifdef ENABLE_LOG_DEBUG
270325e46151SMatthias 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);
270425e46151SMatthias Ringwald #else
27051ffa425cSMatthias Ringwald             log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position);
270625e46151SMatthias Ringwald #endif
27071ffa425cSMatthias Ringwald             hci_stack->local_supported_commands |= (1LU << i);
270825e46151SMatthias Ringwald         }
270925e46151SMatthias Ringwald     }
2710cb7b3e6fSMatthias Ringwald     log_info("Local supported commands summary %08" PRIx32, hci_stack->local_supported_commands);
27113b631737SMatthias Ringwald }
27123b631737SMatthias Ringwald 
27134f781026SMatthias Ringwald static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2714b08371a9SMilanka Ringwald     UNUSED(size);
2715e76a89eeS[email protected] 
27164781fa78SDirk Helbig     uint8_t status = 0;
27174781fa78SDirk Helbig     if( size > OFFSET_OF_DATA_IN_COMMAND_COMPLETE ) {
27184781fa78SDirk Helbig         status = hci_event_command_complete_get_return_parameters(packet)[0];
27194781fa78SDirk Helbig     }
27209cbd2215SMatthias Ringwald     uint16_t manufacturer;
27219cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
27221f7b95a1Smatthias.ringwald     hci_connection_t * conn;
2723c7a108afSMatthias Ringwald #endif
2724c7a108afSMatthias Ringwald #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS))
27254781fa78SDirk Helbig     hci_con_handle_t handle;
27269cbd2215SMatthias Ringwald #endif
2727d3a89d91SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2728d3a89d91SMatthias Ringwald     le_audio_cig_t * cig;
2729d3a89d91SMatthias Ringwald #endif
2730d3a89d91SMatthias Ringwald 
27316bef4003SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
27326bef4003SMatthias Ringwald     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
27337ec5eeaaSmatthias.ringwald 
2734645b7c25SMatthias Ringwald     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2735645b7c25SMatthias Ringwald     switch (opcode){
2736645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
27374781fa78SDirk Helbig             if (status) break;
27389e263bd7SMatthias Ringwald             // terminate, name 248 chars
27399e263bd7SMatthias Ringwald             packet[6+248] = 0;
27409e263bd7SMatthias Ringwald             log_info("local name: %s", &packet[6]);
2741645b7c25SMatthias Ringwald             break;
2742645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
27431d279b20Smatthias.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"
2744c3b46f5aSMatthias Ringwald             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2745429122ccSMatthias Ringwald                 uint16_t acl_len = little_endian_read_16(packet, 6);
2746429122ccSMatthias Ringwald                 uint16_t sco_len = packet[8];
2747429122ccSMatthias Ringwald 
2748429122ccSMatthias Ringwald                 // determine usable ACL/SCO payload size
2749429122ccSMatthias Ringwald                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2750429122ccSMatthias Ringwald                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2751429122ccSMatthias Ringwald 
2752616cfd90SMatthias Ringwald                 hci_stack->acl_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet,  9), MAX_NR_CONTROLLER_ACL_BUFFERS);
2753616cfd90SMatthias Ringwald                 hci_stack->sco_packets_total_num = (uint8_t) btstack_min(little_endian_read_16(packet, 11), MAX_NR_CONTROLLER_SCO_PACKETS);
2754a8b12447S[email protected] 
2755429122ccSMatthias Ringwald                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2756429122ccSMatthias Ringwald                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
27571a06f663S[email protected]                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2758c3b46f5aSMatthias Ringwald             }
2759645b7c25SMatthias Ringwald             break;
2760645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_RSSI:
27614781fa78SDirk Helbig             if (status == ERROR_CODE_SUCCESS){
2762891b9fc2SMatthias Ringwald                 uint8_t event[5];
2763891b9fc2SMatthias Ringwald                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2764891b9fc2SMatthias Ringwald                 event[1] = 3;
27656535961aSMatthias Ringwald                 (void)memcpy(&event[2], &packet[6], 3);
2766891b9fc2SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2767891b9fc2SMatthias Ringwald             }
2768645b7c25SMatthias Ringwald             break;
2769a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
277079b7ea2dSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2:
277179b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9);
277279b7ea2dSMatthias Ringwald             hci_stack->le_iso_packets_total_num = packet[11];
277379b7ea2dSMatthias Ringwald             log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u",
277479b7ea2dSMatthias Ringwald                      hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num);
277579b7ea2dSMatthias Ringwald 
277679b7ea2dSMatthias Ringwald             /* fall through */
277779b7ea2dSMatthias Ringwald 
2778645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2779f8fbdce0SMatthias Ringwald             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2780ee303eddS[email protected]             hci_stack->le_acl_packets_total_num = packet[8];
27816c26b087S[email protected]             // determine usable ACL payload size
27826c26b087S[email protected]             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
27836c26b087S[email protected]                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
27846c26b087S[email protected]             }
278579b7ea2dSMatthias 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);
2786645b7c25SMatthias Ringwald             break;
2787b435e062SMatthias Ringwald #endif
2788b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2789645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2790dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2791dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2792dcd678baSMatthias 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);
2793645b7c25SMatthias Ringwald             break;
2794b435e062SMatthias Ringwald #endif
2795d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2796645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2797e691bb38SMatthias Ringwald             hci_stack->le_whitelist_capacity = packet[6];
279815d0a15bSMatthias Ringwald             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2799645b7c25SMatthias Ringwald             break;
280065a46ef3S[email protected] #endif
28013a74541eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
28023a74541eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
28033a74541eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH:
28043a74541eSMatthias Ringwald             hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6);
28053a74541eSMatthias Ringwald             break;
280625df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS:
280725df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
280825df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
280925df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
281025df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
281125df6c61SMatthias Ringwald                 uint8_t adv_status = packet[6];
281225df6c61SMatthias Ringwald                 uint8_t tx_power   = packet[7];
281325df6c61SMatthias 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 };
281425df6c61SMatthias Ringwald                 if (adv_status == 0){
281525df6c61SMatthias Ringwald                     advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
281625df6c61SMatthias Ringwald                 }
281725df6c61SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
281825df6c61SMatthias Ringwald             }
281925df6c61SMatthias Ringwald             break;
282025df6c61SMatthias Ringwald         case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET:
282125df6c61SMatthias Ringwald             if (hci_stack->le_advertising_set_in_current_command != 0) {
282225df6c61SMatthias Ringwald                 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command);
282325df6c61SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = 0;
282425df6c61SMatthias Ringwald                 if (advertising_set == NULL) break;
28254781fa78SDirk Helbig                 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, status };
28264781fa78SDirk Helbig                 if (status == 0){
282725df6c61SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set);
282825df6c61SMatthias Ringwald                 }
282925df6c61SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
283025df6c61SMatthias Ringwald             }
283125df6c61SMatthias Ringwald             break;
28323a74541eSMatthias Ringwald #endif
28333a74541eSMatthias Ringwald #endif
2834645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BD_ADDR:
2835645b7c25SMatthias Ringwald             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
28364781fa78SDirk Helbig             log_info("Local Address, Status: 0x%02x: Addr: %s", status, bd_addr_to_str(hci_stack->local_bd_addr));
283733373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
28381624665aSMatthias Ringwald             if (hci_stack->link_key_db){
28391624665aSMatthias Ringwald                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
28401624665aSMatthias Ringwald             }
284133373e40SMatthias Ringwald #endif
2842645b7c25SMatthias Ringwald             break;
284335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2844645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
284571fd255dSMatthias Ringwald             hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
2846645b7c25SMatthias Ringwald             break;
28473d1f2d24SMatthias Ringwald         case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE:
28483d1f2d24SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
28493d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC;
28503d1f2d24SMatthias Ringwald             } else {
28513d1f2d24SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
28523d1f2d24SMatthias Ringwald             }
28533d1f2d24SMatthias Ringwald             break;
2854645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
285530199e24SMatthias Ringwald         case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE:
2856f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2857f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2858f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2859f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2860f5875de5SMatthias Ringwald             }
2861645b7c25SMatthias Ringwald             break;
286235454696SMatthias Ringwald #endif
2863645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
28644f781026SMatthias Ringwald             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
286565389bfcS[email protected] 
286635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2867a5a23fc2S[email protected]             // determine usable ACL packet types based on host buffer size and supported features
286829e39de4SMatthias Ringwald             hci_stack->usable_packet_types_acl = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
2869c92ca2c8SMatthias Ringwald             log_info("ACL Packet types %04x", hci_stack->usable_packet_types_acl);
2870c92ca2c8SMatthias Ringwald             // determine usable SCO packet types based on supported features
2871c92ca2c8SMatthias Ringwald             hci_stack->usable_packet_types_sco = hci_sco_packet_types_for_features(
2872c92ca2c8SMatthias Ringwald                     &hci_stack->local_supported_features[0]);
2873c92ca2c8SMatthias Ringwald             log_info("SCO Packet types %04x - eSCO %u", hci_stack->usable_packet_types_sco, hci_extended_sco_link_supported());
287435454696SMatthias Ringwald #endif
2875f5d8d141S[email protected]             // Classic/LE
2876f5d8d141S[email protected]             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2877645b7c25SMatthias Ringwald             break;
2878645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2879645b7c25SMatthias Ringwald             manufacturer = little_endian_read_16(packet, 10);
2880547a29a6SMatthias Ringwald             // map Cypress & Infineon to Broadcom
2881547a29a6SMatthias Ringwald             switch (manufacturer){
2882547a29a6SMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR:
2883547a29a6SMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_INFINEON_TECHNOLOGIES_AG:
2884547a29a6SMatthias Ringwald                     log_info("Treat Cypress/Infineon as Broadcom");
2885c21d89f3SMatthias Ringwald                     manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2886c21d89f3SMatthias Ringwald                     little_endian_store_16(packet, 10, manufacturer);
2887547a29a6SMatthias Ringwald                     break;
2888547a29a6SMatthias Ringwald                 default:
2889547a29a6SMatthias Ringwald                     break;
2890c21d89f3SMatthias Ringwald             }
2891c21d89f3SMatthias Ringwald             hci_stack->manufacturer = manufacturer;
28924696bddbSMatthias Ringwald             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2893645b7c25SMatthias Ringwald             break;
2894645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
28953b631737SMatthias Ringwald             hci_store_local_supported_commands(packet);
2896645b7c25SMatthias Ringwald             break;
2897e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
2898645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
28994781fa78SDirk Helbig             if (status) return;
29005b9b590fSMatthias Ringwald             hci_stack->synchronous_flow_control_enabled = 1;
2901645b7c25SMatthias Ringwald             break;
2902645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2903573897a0SMatthias Ringwald             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2904573897a0SMatthias Ringwald             conn   = hci_connection_for_handle(handle);
2905c3b46f5aSMatthias Ringwald             if (conn != NULL) {
29069866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
2907573897a0SMatthias Ringwald                 if (status == 0){
29089866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
29094a659b0eSMatthias Ringwald                     log_info("Handle %04x key Size: %u", handle, key_size);
2910170fafaeSMatthias Ringwald                 } else {
2911e9f98c4aSMatthias Ringwald                     key_size = 1;
29129866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2913573897a0SMatthias Ringwald                 }
29149866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2915c3b46f5aSMatthias Ringwald             }
2916645b7c25SMatthias Ringwald             break;
2917cc15bb2cSMatthias Ringwald         // assert pairing complete event is emitted.
2918cc15bb2cSMatthias Ringwald         // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust
2919cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY:
2920cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY:
2921cc15bb2cSMatthias Ringwald         case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY:
29228cc1507eSMatthias Ringwald             hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2923cc15bb2cSMatthias Ringwald             // lookup connection by gap pairing addr
2924cc15bb2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL);
2925cc15bb2cSMatthias Ringwald             if (conn == NULL) break;
2926cc15bb2cSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
2927cc15bb2cSMatthias Ringwald             break;
2928cc15bb2cSMatthias Ringwald 
292975a8e4faSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
293075a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
293175a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
293275a8e4faSMatthias Ringwald             uint8_t event[67];
293375a8e4faSMatthias Ringwald             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
293475a8e4faSMatthias Ringwald             event[1] = 65;
293575a8e4faSMatthias Ringwald             (void)memset(&event[2], 0, 65);
29364781fa78SDirk Helbig             if (status == ERROR_CODE_SUCCESS){
293775a8e4faSMatthias Ringwald                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
293875a8e4faSMatthias Ringwald                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
293975a8e4faSMatthias Ringwald                     event[2] = 3;
294075a8e4faSMatthias Ringwald                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
294175a8e4faSMatthias Ringwald                 } else {
294275a8e4faSMatthias Ringwald                     event[2] = 1;
294375a8e4faSMatthias Ringwald                 }
294475a8e4faSMatthias Ringwald             }
294575a8e4faSMatthias Ringwald             hci_emit_event(event, sizeof(event), 0);
294675a8e4faSMatthias Ringwald             break;
294775a8e4faSMatthias Ringwald         }
29481ae74bf3SMatthias Ringwald 
29491ae74bf3SMatthias Ringwald         // note: only needed if user does not provide OOB data
29501ae74bf3SMatthias Ringwald         case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY:
29511ae74bf3SMatthias Ringwald             conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle);
29521ae74bf3SMatthias Ringwald             hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
29531ae74bf3SMatthias Ringwald             if (conn == NULL) break;
29541ae74bf3SMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE);
29551ae74bf3SMatthias Ringwald             break;
2956e8c8828eSMatthias Ringwald #endif
295775a8e4faSMatthias Ringwald #endif
29584ae8623eSMatthias Ringwald #ifdef ENABLE_BLE
29594ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
2960d3a89d91SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_CIG_PARAMETERS:
2961d3a89d91SMatthias Ringwald             // lookup CIG
2962d3a89d91SMatthias Ringwald             cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
2963d3a89d91SMatthias Ringwald             if (cig != NULL){
2964d3a89d91SMatthias Ringwald                 uint8_t i = 0;
2965d3a89d91SMatthias Ringwald                 if (status == ERROR_CODE_SUCCESS){
2966d3a89d91SMatthias Ringwald                     // assign CIS handles to pre-allocated CIS
2967d3a89d91SMatthias Ringwald                     btstack_linked_list_iterator_t it;
2968d3a89d91SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
2969d3a89d91SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it) && (i < cig->num_cis)) {
2970d3a89d91SMatthias Ringwald                         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
2971d3a89d91SMatthias Ringwald                         if ((iso_stream->group_id == hci_stack->iso_active_operation_group_id) &&
2972d3a89d91SMatthias Ringwald                             (iso_stream->iso_type == HCI_ISO_TYPE_CIS)){
2973d3a89d91SMatthias Ringwald                             hci_con_handle_t cis_handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3+(2*i));
2974969d876aSMatthias Ringwald                             iso_stream->cis_handle  = cis_handle;
2975d3a89d91SMatthias Ringwald                             cig->cis_con_handles[i] = cis_handle;
2976d3a89d91SMatthias Ringwald                             i++;
2977d3a89d91SMatthias Ringwald                         }
2978d3a89d91SMatthias Ringwald                     }
2979444e371eSMatthias Ringwald                     cig->state = LE_AUDIO_CIG_STATE_W4_CIS_REQUEST;
2980d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
2981d3a89d91SMatthias Ringwald                 } else {
2982d3a89d91SMatthias Ringwald                     hci_emit_cig_created(cig, status);
2983d3a89d91SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
2984d3a89d91SMatthias Ringwald                 }
2985d3a89d91SMatthias Ringwald             }
298626b93350SMatthias Ringwald             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
2987d3a89d91SMatthias Ringwald             break;
29884ae8623eSMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
29894ae8623eSMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
2990d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
29914ae8623eSMatthias Ringwald             }
29924ae8623eSMatthias Ringwald             break;
299342529435SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
299442529435SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
2995d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
299642529435SMatthias Ringwald             }
299742529435SMatthias Ringwald             break;
29987aa35f6aSMatthias Ringwald         case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: {
29997aa35f6aSMatthias Ringwald             // lookup BIG by state
30007aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_t it;
30017aa35f6aSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
30027aa35f6aSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
30037aa35f6aSMatthias Ringwald                 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
30047aa35f6aSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
30057aa35f6aSMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
30067aa35f6aSMatthias Ringwald                         big->state_vars.next_bis++;
30077aa35f6aSMatthias Ringwald                         if (big->state_vars.next_bis == big->num_bis){
30087aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_ACTIVE;
30097aa35f6aSMatthias Ringwald                             hci_emit_big_created(big, ERROR_CODE_SUCCESS);
30107aa35f6aSMatthias Ringwald                         } else {
30117aa35f6aSMatthias Ringwald                             big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
30127aa35f6aSMatthias Ringwald                         }
30137aa35f6aSMatthias Ringwald                     } else {
30147aa35f6aSMatthias Ringwald                         big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
30157aa35f6aSMatthias Ringwald                         big->state_vars.status = status;
30162a6c0f82SMatthias Ringwald                     }
30172a6c0f82SMatthias Ringwald                     return;
30182a6c0f82SMatthias Ringwald                 }
30192a6c0f82SMatthias Ringwald             }
30202a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
30212a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
30222a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
30232a6c0f82SMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){
30242a6c0f82SMatthias Ringwald                     if (status == ERROR_CODE_SUCCESS){
30252a6c0f82SMatthias Ringwald                         big_sync->state_vars.next_bis++;
30262a6c0f82SMatthias Ringwald                         if (big_sync->state_vars.next_bis == big_sync->num_bis){
30272a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE;
30282a6c0f82SMatthias Ringwald                             hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS);
30292a6c0f82SMatthias Ringwald                         } else {
30302a6c0f82SMatthias Ringwald                             big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
30312a6c0f82SMatthias Ringwald                         }
30322a6c0f82SMatthias Ringwald                     } else {
30332a6c0f82SMatthias Ringwald                         big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED;
30342a6c0f82SMatthias Ringwald                         big_sync->state_vars.status = status;
30352a6c0f82SMatthias Ringwald                     }
30362a6c0f82SMatthias Ringwald                     return;
30372a6c0f82SMatthias Ringwald                 }
30382a6c0f82SMatthias Ringwald             }
3039f9306a1aSMatthias Ringwald             // Lookup CIS via active group operation
3040f9306a1aSMatthias Ringwald             if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
304126b93350SMatthias Ringwald                 if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
304226b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
304326b93350SMatthias Ringwald 
304426b93350SMatthias Ringwald                     // lookup CIS by state
304526b93350SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
304626b93350SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it)){
304726b93350SMatthias Ringwald                         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3048969d876aSMatthias Ringwald                         handle = iso_stream->cis_handle;
3049532211feSMatthias Ringwald                         bool emit_cis_created = false;
305026b93350SMatthias Ringwald                         switch (iso_stream->state){
305126b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT:
305226b93350SMatthias Ringwald                                 if (status != ERROR_CODE_SUCCESS){
3053532211feSMatthias Ringwald                                     emit_cis_created = true;
305426b93350SMatthias Ringwald                                     break;
305526b93350SMatthias Ringwald                                 }
305626b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_c_to_p > 0){
30571418332dSMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
305826b93350SMatthias Ringwald                                 } else {
3059532211feSMatthias Ringwald                                     emit_cis_created = true;
306026b93350SMatthias Ringwald                                 }
306126b93350SMatthias Ringwald                                 break;
306226b93350SMatthias Ringwald                             case HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT:
3063532211feSMatthias Ringwald                                 emit_cis_created = true;
306426b93350SMatthias Ringwald                                 break;
306526b93350SMatthias Ringwald                             default:
306626b93350SMatthias Ringwald                                 break;
306726b93350SMatthias Ringwald                         }
3068532211feSMatthias Ringwald                         if (emit_cis_created){
306914045fdbSMatthias Ringwald                             hci_cis_handle_created(iso_stream, status);
3070532211feSMatthias Ringwald                         }
307126b93350SMatthias Ringwald                     }
307226b93350SMatthias Ringwald                 } else {
3073f9306a1aSMatthias Ringwald                     cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
3074532211feSMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
3075f9306a1aSMatthias Ringwald                     if (cig != NULL) {
3076f9306a1aSMatthias Ringwald                         // emit cis created if all ISO Paths have been created
3077f9306a1aSMatthias Ringwald                         // assume we are central
3078f9306a1aSMatthias Ringwald                         uint8_t cis_index     = cig->state_vars.next_cis >> 1;
3079f9306a1aSMatthias Ringwald                         uint8_t cis_direction = cig->state_vars.next_cis & 1;
3080f9306a1aSMatthias Ringwald                         bool outgoing_needed  = cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
3081f9306a1aSMatthias Ringwald                         // if outgoing has been setup, or incoming was setup but outgoing not required
3082f9306a1aSMatthias Ringwald                         if ((cis_direction == 1) || (outgoing_needed == false)){
3083532211feSMatthias Ringwald                             // lookup iso stream by cig/cis
3084b5ecaedbSMatthias Ringwald                             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
3085532211feSMatthias Ringwald                             while (btstack_linked_list_iterator_has_next(&it)) {
3086532211feSMatthias Ringwald                                 hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
3087532211feSMatthias Ringwald                                 if ((iso_stream->group_id == cig->cig_id) && (iso_stream->stream_id == cis_index)){
308814045fdbSMatthias Ringwald                                     hci_cis_handle_created(iso_stream, status);
3089532211feSMatthias Ringwald                                 }
3090532211feSMatthias Ringwald                             }
3091f9306a1aSMatthias Ringwald                         }
3092f9306a1aSMatthias Ringwald                         // next state
3093f9306a1aSMatthias Ringwald                         cig->state_vars.next_cis++;
3094f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
3095f9306a1aSMatthias Ringwald                     }
3096f9306a1aSMatthias Ringwald                 }
309726b93350SMatthias Ringwald             }
30982a6c0f82SMatthias Ringwald             break;
30992a6c0f82SMatthias Ringwald         }
31002a6c0f82SMatthias Ringwald         case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: {
31012a6c0f82SMatthias Ringwald             // lookup BIG by state
31022a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_t it;
31032a6c0f82SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
31042a6c0f82SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)) {
31052a6c0f82SMatthias Ringwald                 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
3106d04a9afcSMatthias Ringwald                 uint8_t big_handle = big_sync->big_handle;
31072a6c0f82SMatthias Ringwald                 switch (big_sync->state){
31082a6c0f82SMatthias Ringwald                     case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
3109d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
31102a6c0f82SMatthias Ringwald                         hci_emit_big_sync_created(big_sync, big_sync->state_vars.status);
3111d04a9afcSMatthias Ringwald                         return;
31122a6c0f82SMatthias Ringwald                     default:
3113d04a9afcSMatthias Ringwald                         btstack_linked_list_iterator_remove(&it);
3114d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
31157aa35f6aSMatthias Ringwald                         return;
31167aa35f6aSMatthias Ringwald                 }
31177aa35f6aSMatthias Ringwald             }
31187aa35f6aSMatthias Ringwald             break;
31197aa35f6aSMatthias Ringwald         }
31204ae8623eSMatthias Ringwald #endif
31214ae8623eSMatthias Ringwald #endif
31226f35bb46SMatthias Ringwald         default:
31236f35bb46SMatthias Ringwald             break;
31244f781026SMatthias Ringwald     }
3125645b7c25SMatthias Ringwald }
31264f781026SMatthias Ringwald 
3127afbf1cd7SMatthias Ringwald static void handle_command_status_event(uint8_t * packet, uint16_t size) {
3128afbf1cd7SMatthias Ringwald     UNUSED(size);
3129afbf1cd7SMatthias Ringwald 
3130afbf1cd7SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
3131afbf1cd7SMatthias Ringwald     hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
3132afbf1cd7SMatthias Ringwald 
3133c70df5f8SMatthias Ringwald     // get opcode and command status
3134c70df5f8SMatthias Ringwald     uint16_t opcode = hci_event_command_status_get_command_opcode(packet);
3135c70df5f8SMatthias Ringwald 
3136c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS)
3137c70df5f8SMatthias Ringwald     uint8_t status = hci_event_command_status_get_status(packet);
3138c70df5f8SMatthias Ringwald #endif
3139c70df5f8SMatthias Ringwald 
3140c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3141c70df5f8SMatthias Ringwald     bd_addr_type_t addr_type;
314273bccf35Slouislee91     bd_addr_t addr;
3143c70df5f8SMatthias Ringwald #endif
3144c70df5f8SMatthias Ringwald 
3145c70df5f8SMatthias Ringwald     switch (opcode){
3146afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3147c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
31489071873aSMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
3149c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
3150afbf1cd7SMatthias Ringwald #endif
3151afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3152c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
3153afbf1cd7SMatthias Ringwald #endif
3154c70df5f8SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL)
3155afbf1cd7SMatthias Ringwald             addr_type = hci_stack->outgoing_addr_type;
315673bccf35Slouislee91             memcpy(addr, hci_stack->outgoing_addr, 6);
3157afbf1cd7SMatthias Ringwald 
3158afbf1cd7SMatthias Ringwald             // reset outgoing address info
3159afbf1cd7SMatthias Ringwald             memset(hci_stack->outgoing_addr, 0, 6);
3160afbf1cd7SMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
3161afbf1cd7SMatthias Ringwald 
3162afbf1cd7SMatthias Ringwald             // on error
3163afbf1cd7SMatthias Ringwald             if (status != ERROR_CODE_SUCCESS){
3164afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3165afbf1cd7SMatthias Ringwald                 if (hci_is_le_connection_type(addr_type)){
3166afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3167afbf1cd7SMatthias Ringwald                     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3168afbf1cd7SMatthias Ringwald                 }
3169afbf1cd7SMatthias Ringwald #endif
3170afbf1cd7SMatthias Ringwald                 // error => outgoing connection failed
317173bccf35Slouislee91                 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3172afbf1cd7SMatthias Ringwald                 if (conn != NULL){
3173afbf1cd7SMatthias Ringwald                     hci_handle_connection_failed(conn, status);
3174afbf1cd7SMatthias Ringwald                 }
3175afbf1cd7SMatthias Ringwald             }
3176c70df5f8SMatthias Ringwald             break;
3177c70df5f8SMatthias Ringwald #endif
3178afbf1cd7SMatthias Ringwald #ifdef ENABLE_CLASSIC
3179c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY:
3180afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS) {
3181afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3182afbf1cd7SMatthias Ringwald             } else {
3183afbf1cd7SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3184afbf1cd7SMatthias Ringwald             }
3185c70df5f8SMatthias Ringwald             break;
3186c70df5f8SMatthias Ringwald #endif
3187afbf1cd7SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3188c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CIS:
3189c70df5f8SMatthias Ringwald         case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST:
3190afbf1cd7SMatthias Ringwald             if (status == ERROR_CODE_SUCCESS){
3191d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_confirm(HCI_ISO_GROUP_ID_INVALID);
3192afbf1cd7SMatthias Ringwald             } else {
3193d75a6bbfSMatthias Ringwald                 hci_iso_stream_requested_finalize(HCI_ISO_GROUP_ID_INVALID);
3194afbf1cd7SMatthias Ringwald             }
3195c70df5f8SMatthias Ringwald             break;
3196afbf1cd7SMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
3197c70df5f8SMatthias Ringwald         default:
3198c70df5f8SMatthias Ringwald             break;
3199c70df5f8SMatthias Ringwald     }
3200afbf1cd7SMatthias Ringwald }
3201afbf1cd7SMatthias Ringwald 
32020ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
32030ce3f217SMatthias Ringwald static void event_handle_le_connection_complete(const uint8_t * packet){
32040ce3f217SMatthias Ringwald 	bd_addr_t addr;
32050ce3f217SMatthias Ringwald 	bd_addr_type_t addr_type;
32060ce3f217SMatthias Ringwald 	hci_connection_t * conn;
32070ce3f217SMatthias Ringwald 
320860fb273dSMatthias Ringwald     // read fields
320960fb273dSMatthias Ringwald     uint8_t status = packet[3];
321088f925b1SMatthias Ringwald     hci_role_t role = (hci_role_t) packet[6];
321160fb273dSMatthias Ringwald 
321260fb273dSMatthias Ringwald     // support different connection complete events
321388f925b1SMatthias Ringwald     uint16_t conn_interval;
321460fb273dSMatthias Ringwald     switch (packet[2]){
321560fb273dSMatthias Ringwald         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
321660fb273dSMatthias Ringwald             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
321760fb273dSMatthias Ringwald             break;
321860fb273dSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
321960fb273dSMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
322060fb273dSMatthias Ringwald             conn_interval = hci_subevent_le_enhanced_connection_complete_v1_get_conn_interval(packet);
322160fb273dSMatthias Ringwald             break;
322260fb273dSMatthias Ringwald         case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
322360fb273dSMatthias Ringwald             conn_interval = hci_subevent_le_enhanced_connection_complete_v2_get_conn_interval(packet);
322460fb273dSMatthias Ringwald             break;
322560fb273dSMatthias Ringwald #endif
322660fb273dSMatthias Ringwald         default:
322760fb273dSMatthias Ringwald             btstack_unreachable();
322860fb273dSMatthias Ringwald             return;
322960fb273dSMatthias Ringwald     }
323060fb273dSMatthias Ringwald 
32310ce3f217SMatthias Ringwald 	// Connection management
32320ce3f217SMatthias Ringwald 	reverse_bd_addr(&packet[8], addr);
32330ce3f217SMatthias Ringwald 	addr_type = (bd_addr_type_t)packet[7];
323460fb273dSMatthias Ringwald     log_info("LE Connection_complete (status=%u) type %u, %s", status, addr_type, bd_addr_to_str(addr));
32350ce3f217SMatthias Ringwald 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
32360ce3f217SMatthias Ringwald 
32370ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
32380ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
323960fb273dSMatthias Ringwald 	if (status){
32400ce3f217SMatthias Ringwald 
32410ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
32420ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
32430ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
32440ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
324560fb273dSMatthias Ringwald 		if (status == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
32461f468175SMatthias Ringwald 		    // reset state
32470ce3f217SMatthias Ringwald             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
32481f468175SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
32490ce3f217SMatthias Ringwald 			// get outgoing connection conn struct for direct connect
32500ce3f217SMatthias Ringwald 			conn = gap_get_outgoing_connection();
32510ce3f217SMatthias Ringwald 		}
32520ce3f217SMatthias Ringwald 
32530ce3f217SMatthias Ringwald 		// outgoing le connection establishment is done
32540ce3f217SMatthias Ringwald 		if (conn){
32550ce3f217SMatthias Ringwald 			// remove entry
32560ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
32570ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
32580ce3f217SMatthias Ringwald 		}
32590ce3f217SMatthias Ringwald 		return;
32600ce3f217SMatthias Ringwald 	}
32610ce3f217SMatthias Ringwald #endif
32620ce3f217SMatthias Ringwald 
32630ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
326460fb273dSMatthias Ringwald     if (role == HCI_ROLE_MASTER){
32650ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
32660ce3f217SMatthias Ringwald 		// if we're master on an le connection, it was an outgoing connection and we're done with it
32670ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
32680ce3f217SMatthias Ringwald 		if (hci_is_le_connection_type(addr_type)){
32690ce3f217SMatthias Ringwald 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
32700ce3f217SMatthias Ringwald 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
32710ce3f217SMatthias Ringwald 		}
32720ce3f217SMatthias Ringwald #endif
32730ce3f217SMatthias Ringwald 	} else {
32740ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
32750ce3f217SMatthias Ringwald 		// if we're slave, it was an incoming connection, advertisements have stopped
3276935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
32770ce3f217SMatthias Ringwald #endif
32780ce3f217SMatthias Ringwald 	}
32790ce3f217SMatthias Ringwald 
32800ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
32810ce3f217SMatthias Ringwald 	if (!conn){
328288f925b1SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type, role);
32830ce3f217SMatthias Ringwald 	}
32840ce3f217SMatthias Ringwald 
32850ce3f217SMatthias Ringwald 	// no memory, sorry.
32860ce3f217SMatthias Ringwald 	if (!conn){
32870ce3f217SMatthias Ringwald 		return;
32880ce3f217SMatthias Ringwald 	}
32890ce3f217SMatthias Ringwald 
32900ce3f217SMatthias Ringwald 	conn->state = OPEN;
32910ce3f217SMatthias Ringwald 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
329260fb273dSMatthias Ringwald     conn->le_connection_interval = conn_interval;
32930ce3f217SMatthias Ringwald 
3294ac0f6b83SMatthias Ringwald     // workaround: PAST doesn't work without LE Read Remote Features on PacketCraft Controller with LMP 568B
3295ac0f6b83SMatthias Ringwald     conn->gap_connection_tasks = GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
3296ac0f6b83SMatthias Ringwald 
32970ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
329860fb273dSMatthias Ringwald 	if (role == HCI_ROLE_SLAVE){
32990ce3f217SMatthias Ringwald 		hci_update_advertisements_enabled_for_current_roles();
33000ce3f217SMatthias Ringwald 	}
33010ce3f217SMatthias Ringwald #endif
33020ce3f217SMatthias Ringwald 
3303dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
3304dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
3305dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
3306dde9ff1eSMatthias Ringwald 
33070ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
33080ce3f217SMatthias Ringwald 
33090ce3f217SMatthias Ringwald 	// restart timer
33100ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
33110ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
33120ce3f217SMatthias Ringwald 
33130ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
33140ce3f217SMatthias Ringwald 
33150ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
33160ce3f217SMatthias Ringwald }
33170ce3f217SMatthias Ringwald #endif
33180ce3f217SMatthias Ringwald 
331917c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
332017c6fe5cSMatthias 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){
332117c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
332217c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
33239a8f78c1SMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible
33249a8f78c1SMatthias Ringwald     // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7
332517c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
33269a8f78c1SMatthias Ringwald         // MITM not possible without keyboard or display
332717c6fe5cSMatthias Ringwald         if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
332817c6fe5cSMatthias Ringwald         if (io_cap_local  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
33299a8f78c1SMatthias Ringwald 
33309a8f78c1SMatthias Ringwald         // MITM possible if one side has keyboard and the other has keyboard or display
33319a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
33329a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_KEYBOARD_ONLY)      return true;
33339a8f78c1SMatthias Ringwald 
33349a8f78c1SMatthias Ringwald         // MITM not possible if one side has only display and other side has no keyboard
33359a8f78c1SMatthias Ringwald         if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
33369a8f78c1SMatthias Ringwald         if (io_cap_local  == SSP_IO_CAPABILITY_DISPLAY_ONLY)       return false;
333717c6fe5cSMatthias Ringwald     }
333817c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
333917c6fe5cSMatthias Ringwald     return true;
334017c6fe5cSMatthias Ringwald }
33413817f9dfSMatthias Ringwald 
3342b3c4163bSMatthias Ringwald static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){
33432dd8985bSMatthias Ringwald     // get requested security level
33442dd8985bSMatthias Ringwald     gap_security_level_t requested_security_level = conn->requested_security_level;
33452dd8985bSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
33462dd8985bSMatthias Ringwald         requested_security_level = LEVEL_4;
33472dd8985bSMatthias Ringwald     }
33482dd8985bSMatthias Ringwald 
3349b3c4163bSMatthias Ringwald     // assess security: LEVEL 4 requires SC
33502dd8985bSMatthias Ringwald     // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller
33512dd8985bSMatthias Ringwald     if ((requested_security_level == LEVEL_4) &&
33522dd8985bSMatthias Ringwald         ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) &&
33532dd8985bSMatthias Ringwald         !hci_remote_sc_enabled(conn)){
3354b3c4163bSMatthias Ringwald         log_info("Level 4 required, but SC not supported -> abort");
3355b3c4163bSMatthias Ringwald         hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3356b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3357b3c4163bSMatthias Ringwald         return;
3358b3c4163bSMatthias Ringwald     }
3359b3c4163bSMatthias Ringwald 
3360c2414c00SMatthias Ringwald     // assess bonding requirements: abort if remote in dedicated bonding mode but we are non-bonding
3361c2414c00SMatthias Ringwald     // - GAP/MOD/NBON/BV-02-C
3362c2414c00SMatthias Ringwald     // - GAP/DM/NBON/BV-01-C
3363c2414c00SMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3364c2414c00SMatthias Ringwald         switch (conn->io_cap_response_auth_req){
3365c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING:
3366c2414c00SMatthias Ringwald             case SSP_IO_AUTHREQ_MITM_PROTECTION_REQUIRED_DEDICATED_BONDING:
3367c2414c00SMatthias Ringwald                 if (hci_stack->bondable == false){
3368c2414c00SMatthias Ringwald                     log_info("Dedicated vs. non-bondable -> abort");
3369c2414c00SMatthias Ringwald                     hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3370c2414c00SMatthias Ringwald                     connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3371c2414c00SMatthias Ringwald                     return;
3372c2414c00SMatthias Ringwald                 }
3373c2414c00SMatthias Ringwald             default:
3374c2414c00SMatthias Ringwald                 break;
3375c2414c00SMatthias Ringwald         }
3376c2414c00SMatthias Ringwald     }
3377c2414c00SMatthias Ringwald 
3378b3c4163bSMatthias Ringwald     // assess security based on io capabilities
3379b3c4163bSMatthias Ringwald     if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
3380b3c4163bSMatthias Ringwald         // responder: fully validate io caps of both sides as well as OOB data
3381b3c4163bSMatthias Ringwald         bool security_possible = false;
3382b3c4163bSMatthias Ringwald         security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io);
3383b3c4163bSMatthias Ringwald 
3384b3c4163bSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3385b3c4163bSMatthias Ringwald         // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256,
3386b3c4163bSMatthias Ringwald         // so we merge the OOB data availability
3387b3c4163bSMatthias Ringwald         uint8_t have_oob_data = conn->io_cap_response_oob_data;
3388b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_192 != NULL){
3389b3c4163bSMatthias Ringwald             have_oob_data |= 1;
3390b3c4163bSMatthias Ringwald         }
3391b3c4163bSMatthias Ringwald         if (conn->classic_oob_c_256 != NULL){
3392b3c4163bSMatthias Ringwald             have_oob_data |= 2;
3393b3c4163bSMatthias Ringwald         }
3394b3c4163bSMatthias Ringwald         // for up to Level 3, either P-192 as well as P-256 will do
3395b3c4163bSMatthias 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
3396b3c4163bSMatthias Ringwald         // if remote does not SC, we should not receive P-256 data either
3397b3c4163bSMatthias Ringwald         if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){
3398b3c4163bSMatthias Ringwald             security_possible = true;
3399b3c4163bSMatthias Ringwald         }
3400b3c4163bSMatthias Ringwald         // for Level 4, P-256 is needed
3401b3c4163bSMatthias Ringwald         if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){
3402b3c4163bSMatthias Ringwald             security_possible = true;
3403b3c4163bSMatthias Ringwald         }
3404b3c4163bSMatthias Ringwald #endif
3405b3c4163bSMatthias Ringwald 
3406b3c4163bSMatthias Ringwald         if (security_possible == false){
34072dd8985bSMatthias Ringwald             log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level);
3408b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3409b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3410b3c4163bSMatthias Ringwald             return;
3411b3c4163bSMatthias Ringwald         }
3412b3c4163bSMatthias Ringwald     } else {
3413b3c4163bSMatthias Ringwald         // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported
34141fe968f5SMatthias Ringwald #ifndef ENABLE_CLASSIC_PAIRING_OOB
34151fe968f5SMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3416b3c4163bSMatthias Ringwald         if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){
3417b3c4163bSMatthias Ringwald             log_info("Level 3+ required, but no input/output -> abort");
3418b3c4163bSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3419b3c4163bSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3420b3c4163bSMatthias Ringwald             return;
3421b3c4163bSMatthias Ringwald         }
3422b3c4163bSMatthias Ringwald #endif
34231fe968f5SMatthias Ringwald #endif
3424b3c4163bSMatthias Ringwald     }
3425b3c4163bSMatthias Ringwald 
3426b3c4163bSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
3427b3c4163bSMatthias Ringwald     if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
3428b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
3429b3c4163bSMatthias Ringwald     } else {
3430b3c4163bSMatthias Ringwald         connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
3431b3c4163bSMatthias Ringwald     }
3432b3c4163bSMatthias Ringwald #endif
3433b3c4163bSMatthias Ringwald }
3434b3c4163bSMatthias Ringwald 
343517c6fe5cSMatthias Ringwald #endif
343617c6fe5cSMatthias Ringwald 
3437c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
34384f781026SMatthias Ringwald 
34394f781026SMatthias Ringwald     uint16_t event_length = packet[1];
34404f781026SMatthias Ringwald 
34414f781026SMatthias Ringwald     // assert packet is complete
34424ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
34434f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
34444f781026SMatthias Ringwald         return;
34454f781026SMatthias Ringwald     }
34464f781026SMatthias Ringwald 
34474f781026SMatthias Ringwald     hci_con_handle_t handle;
34484f781026SMatthias Ringwald     hci_connection_t * conn;
34494f781026SMatthias Ringwald     int i;
34504f781026SMatthias Ringwald 
34514f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
34525e91d96cSMatthias Ringwald     hci_link_type_t link_type;
345348f33f37SMatthias Ringwald     bd_addr_t addr;
3454cef94710SMatthias Ringwald     bd_addr_type_t addr_type;
34554f781026SMatthias Ringwald #endif
34564ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
34574ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream;
34587aa35f6aSMatthias Ringwald     le_audio_big_t   * big;
34592a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync;
34604ae8623eSMatthias Ringwald #endif
346189254d99SMatthias Ringwald #if defined(ENABLE_LE_ISOCHRONOUS_STREAMS) || defined(ENABLE_LE_EXTENDED_ADVERTISING)
346289254d99SMatthias Ringwald     btstack_linked_list_iterator_t it;
346389254d99SMatthias Ringwald #endif
346489254d99SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
346589254d99SMatthias Ringwald     uint8_t advertising_handle;
346689254d99SMatthias Ringwald #endif
34674f781026SMatthias Ringwald 
34684f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
34694f781026SMatthias Ringwald 
34704f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
34714f781026SMatthias Ringwald 
34724f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
34734f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
347456cf178bSmatthias.ringwald             break;
347556cf178bSmatthias.ringwald 
34767ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
3477afbf1cd7SMatthias Ringwald             handle_command_status_event(packet, size);
34787ec5eeaaSmatthias.ringwald             break;
34797ec5eeaaSmatthias.ringwald 
34802e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
34819784dac1SMatthias Ringwald             if (size < 3) return;
34829784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
34834ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
3484d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3485d9a1d8edSMatthias Ringwald             bool notify_sco = false;
3486d9a1d8edSMatthias Ringwald #endif
3487d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3488d9a1d8edSMatthias Ringwald             bool notify_iso = false;
3489d9a1d8edSMatthias Ringwald #endif
34909784dac1SMatthias Ringwald             uint16_t offset = 3;
34919784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
34924ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
34934ea43905SMatthias Ringwald                 offset += 2u;
3494f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
34954ea43905SMatthias Ringwald                 offset += 2u;
34962e440c8aS[email protected] 
34975061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
3498e5413aa0SMatthias Ringwald                 if (conn != NULL) {
349923bed257S[email protected] 
3500ce41473eSMatthias Ringwald                     if (conn->num_packets_sent >= num_packets) {
3501ce41473eSMatthias Ringwald                         conn->num_packets_sent -= num_packets;
3502e35edcc1S[email protected]                     } else {
3503ce41473eSMatthias Ringwald                         log_error("hci_number_completed_packets, more packet slots freed then sent.");
3504ce41473eSMatthias Ringwald                         conn->num_packets_sent = 0;
3505e35edcc1S[email protected]                     }
3506ce41473eSMatthias Ringwald                     // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
3507d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3508d9a1d8edSMatthias Ringwald                     if (conn->address_type == BD_ADDR_TYPE_SCO){
3509d9a1d8edSMatthias Ringwald                         notify_sco = true;
3510d9a1d8edSMatthias Ringwald                     }
3511d9a1d8edSMatthias Ringwald #endif
3512e5413aa0SMatthias Ringwald                 }
3513e5413aa0SMatthias Ringwald 
35148ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
35158ad9cf99SMatthias Ringwald                 hci_controller_dump_packets();
35168ad9cf99SMatthias Ringwald #endif
35178ad9cf99SMatthias Ringwald 
3518e5413aa0SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3519e5413aa0SMatthias Ringwald                 if (conn == NULL){
3520e5413aa0SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle);
3521e5413aa0SMatthias Ringwald                     if (iso_stream != NULL){
3522e5413aa0SMatthias Ringwald                         if (iso_stream->num_packets_sent >= num_packets) {
3523e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent -= num_packets;
3524e5413aa0SMatthias Ringwald                         } else {
3525e5413aa0SMatthias Ringwald                             log_error("hci_number_completed_packets, more packet slots freed then sent.");
3526e5413aa0SMatthias Ringwald                             iso_stream->num_packets_sent = 0;
3527e5413aa0SMatthias Ringwald                         }
35288d72db10SMatthias Ringwald                         if (iso_stream->iso_type == HCI_ISO_TYPE_BIS){
35298d72db10SMatthias Ringwald                             le_audio_big_t * big = hci_big_for_handle(iso_stream->group_id);
3530fe977b37SMatthias Ringwald                             if (big != NULL){
3531fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_valid = true;
3532fe977b37SMatthias Ringwald                                 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms();
3533fe977b37SMatthias Ringwald                             }
3534fe977b37SMatthias Ringwald                         }
3535e5413aa0SMatthias Ringwald                         log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u",
3536e5413aa0SMatthias Ringwald                                  num_packets, handle, iso_stream->num_packets_sent);
3537d9a1d8edSMatthias Ringwald                         notify_iso = true;
3538e5413aa0SMatthias Ringwald                     }
3539d9a1d8edSMatthias Ringwald                 }
3540d9a1d8edSMatthias Ringwald #endif
3541d9a1d8edSMatthias Ringwald             }
3542d9a1d8edSMatthias Ringwald 
3543d9a1d8edSMatthias Ringwald #ifdef ENABLE_CLASSIC
3544d9a1d8edSMatthias Ringwald             if (notify_sco){
3545d9a1d8edSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
3546d9a1d8edSMatthias Ringwald             }
3547d9a1d8edSMatthias Ringwald #endif
3548d9a1d8edSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
3549d9a1d8edSMatthias Ringwald             if (notify_iso){
35505ade6657SMatthias Ringwald                 hci_iso_notify_can_send_now();
3551e5413aa0SMatthias Ringwald             }
3552e5413aa0SMatthias Ringwald #endif
35536772a24cSmatthias.ringwald             break;
35542e440c8aS[email protected]         }
355535454696SMatthias Ringwald 
355635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
35579afaa4d4SMatthias Ringwald         case HCI_EVENT_FLUSH_OCCURRED:
35589afaa4d4SMatthias Ringwald             // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog()
35599afaa4d4SMatthias Ringwald             handle = hci_event_flush_occurred_get_handle(packet);
35609afaa4d4SMatthias Ringwald             conn = hci_connection_for_handle(handle);
35619afaa4d4SMatthias Ringwald             if (conn) {
35629afaa4d4SMatthias Ringwald                 log_info("Flush occurred, disconnect 0x%04x", handle);
35639afaa4d4SMatthias Ringwald                 conn->state = SEND_DISCONNECT;
35649afaa4d4SMatthias Ringwald             }
35659afaa4d4SMatthias Ringwald             break;
35669afaa4d4SMatthias Ringwald 
3567f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
3568f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
3569f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
3570f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
3571f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
3572f5875de5SMatthias Ringwald             }
3573f5875de5SMatthias Ringwald             break;
3574b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
3575b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
3576b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
3577b7f1ee76SMatthias Ringwald             }
3578b7f1ee76SMatthias Ringwald             break;
35791f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
3580724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
35815e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
358272cf8859SMatthias Ringwald 
358372cf8859SMatthias Ringwald             // CVE-2020-26555: reject incoming connection from device with same BD ADDR
358472cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){
358572cf8859SMatthias Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
358672cf8859SMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
358772cf8859SMatthias Ringwald                 break;
358872cf8859SMatthias Ringwald             }
358972cf8859SMatthias Ringwald 
359007e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
35915e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
3592d152b6c6SMatthias Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS;
359307e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
359407e010b6SMilanka Ringwald                     break;
359507e010b6SMilanka Ringwald                 }
359607e010b6SMilanka Ringwald             }
359707e010b6SMilanka Ringwald 
359837eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
35995e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
36005e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
36012e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
36021f7b95a1Smatthias.ringwald             if (!conn) {
360388f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_SLAVE);
36041f7b95a1Smatthias.ringwald             }
3605ce4c8fabSmatthias.ringwald             if (!conn) {
3606ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
36074536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3608058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
3609f23819bcSMatthias Ringwald                 hci_run();
3610f23819bcSMatthias Ringwald                 // avoid event to higher layer
3611f23819bcSMatthias Ringwald                 return;
3612ce4c8fabSmatthias.ringwald             }
361332ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
3614f3a16b9aSMatthias Ringwald             // store info about eSCO
36155e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
361676ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
3617f3a16b9aSMatthias Ringwald             }
3618d7891039SMatthias Ringwald             // propagate remote supported sco packet packets from existing ACL to new SCO connection
3619d7891039SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_SCO){
3620d7891039SMatthias Ringwald                 hci_connection_t * acl_conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3621d7891039SMatthias Ringwald                 btstack_assert(acl_conn != NULL);
3622d7891039SMatthias Ringwald                 conn->remote_supported_sco_packets = acl_conn->remote_supported_sco_packets;
3623d7891039SMatthias Ringwald             }
362432ab9390Smatthias.ringwald             hci_run();
36251f7b95a1Smatthias.ringwald             break;
36261f7b95a1Smatthias.ringwald 
36276772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
3628fe1ed1b8Smatthias.ringwald             // Connection management
3629724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
36309da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
3631f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
36322e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3633fe1ed1b8Smatthias.ringwald             if (conn) {
3634893b4ccdSMatthias Ringwald                 switch (conn->state){
3635893b4ccdSMatthias Ringwald                     // expected states
3636893b4ccdSMatthias Ringwald                     case ACCEPTED_CONNECTION_REQUEST:
3637893b4ccdSMatthias Ringwald                     case SENT_CREATE_CONNECTION:
3638893b4ccdSMatthias Ringwald                         break;
3639893b4ccdSMatthias Ringwald                     // unexpected state -> ignore
3640893b4ccdSMatthias Ringwald                     default:
3641893b4ccdSMatthias Ringwald                         // don't forward event to app
3642893b4ccdSMatthias Ringwald                         return;
3643893b4ccdSMatthias Ringwald                 }
3644b448a0e7Smatthias.ringwald                 if (!packet[2]){
3645c8e4258aSmatthias.ringwald                     conn->state = OPEN;
3646f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
36476909f064SMatthias Ringwald 
364822df2fe2SMatthias Ringwald                     // trigger write supervision timeout if we're master
3649d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
365022df2fe2SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
36516909f064SMatthias Ringwald                     }
36526909f064SMatthias Ringwald 
365322df2fe2SMatthias Ringwald                     // trigger write automatic flush timeout
36549afaa4d4SMatthias Ringwald                     if (hci_stack->automatic_flush_timeout != 0){
36559afaa4d4SMatthias Ringwald                         conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
36569afaa4d4SMatthias Ringwald                     }
36579afaa4d4SMatthias Ringwald 
3658c785ef68Smatthias.ringwald                     // restart timer
3659528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
3660528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
3661c785ef68Smatthias.ringwald 
366218c4a0a3SMatthias Ringwald                     // trigger remote features for dedicated bonding
366318c4a0a3SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
366418c4a0a3SMatthias Ringwald                         hci_trigger_remote_features_for_connection(conn);
366518c4a0a3SMatthias Ringwald                     }
366618c4a0a3SMatthias Ringwald 
36679da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
366843bfb1bdSmatthias.ringwald 
366943bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
3670b448a0e7Smatthias.ringwald                 } else {
36710bbba85bSMatthias Ringwald                     // connection failed
36720bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
3673fe1ed1b8Smatthias.ringwald                 }
3674fe1ed1b8Smatthias.ringwald             }
36756772a24cSmatthias.ringwald             break;
3676fe1ed1b8Smatthias.ringwald 
367744d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
3678724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
36791f34df2cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
36801f34df2cSMatthias Ringwald             log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr));
36819071873aSMatthias Ringwald             btstack_assert(conn != NULL);
36829071873aSMatthias Ringwald 
36839071873aSMatthias Ringwald             if (packet[2] != ERROR_CODE_SUCCESS){
36849071873aSMatthias Ringwald                 // connection failed, remove entry
36851f34df2cSMatthias Ringwald                 hci_handle_connection_failed(conn, packet[2]);
368644d0e3d5S[email protected]                 break;
368744d0e3d5S[email protected]             }
36889071873aSMatthias Ringwald 
36891a06f663S[email protected]             conn->state = OPEN;
3690f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
3691ee752bb8SMatthias Ringwald 
3692d7891039SMatthias Ringwald             // update sco payload length for eSCO connections
3693d7891039SMatthias Ringwald             if (hci_event_synchronous_connection_complete_get_tx_packet_length(packet) > 0){
3694d7891039SMatthias Ringwald                 conn->sco_payload_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);
3695d7891039SMatthias Ringwald                 log_info("eSCO Complete, set payload len %u", conn->sco_payload_length);
3696d7891039SMatthias Ringwald             }
3697d7891039SMatthias Ringwald 
3698ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3699ee752bb8SMatthias Ringwald             // update SCO
3700ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
3701ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
3702ee752bb8SMatthias Ringwald             }
3703f234b250SMatthias Ringwald             // trigger can send now
3704f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
37051972f31fSMatthias Ringwald                 hci_stack->sco_can_send_now = true;
3706f234b250SMatthias Ringwald             }
3707fa7f2dfdSMatthias Ringwald 
3708fa7f2dfdSMatthias Ringwald             // setup implict sco flow control
3709fa7f2dfdSMatthias Ringwald             conn->sco_tx_ready = 0;
3710fa7f2dfdSMatthias Ringwald             conn->sco_tx_active  = 0;
3711fa7f2dfdSMatthias Ringwald             conn->sco_established_ms = btstack_run_loop_get_time_ms();
3712fa7f2dfdSMatthias Ringwald 
3713ee752bb8SMatthias Ringwald #endif
3714cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3715cb70c5abSMatthias Ringwald             // configure sco transport
3716cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
3717cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
3718cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
3719cb70c5abSMatthias Ringwald             }
3720cb70c5abSMatthias Ringwald #endif
372144d0e3d5S[email protected]             break;
372244d0e3d5S[email protected] 
3723afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3724f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
3725afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
3726afd4e962S[email protected]             if (!conn) break;
3727afd4e962S[email protected]             if (!packet[2]){
37282f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
37292f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
37302f5c44baSMatthias Ringwald 
37315ccef624SMatthias Ringwald                 // read extended features if possible
37321ffa425cSMatthias Ringwald                 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES)
37331ffa425cSMatthias Ringwald                 && ((conn->remote_supported_features[0] & 2) != 0)) {
37345ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
37355ccef624SMatthias Ringwald                     break;
37365ccef624SMatthias Ringwald                 }
37375ccef624SMatthias Ringwald             }
37385ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
37395ccef624SMatthias Ringwald             break;
37405ccef624SMatthias Ringwald 
37415ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
37425ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
37435ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
37445ccef624SMatthias Ringwald             if (!conn) break;
37455ccef624SMatthias Ringwald             // status = ok, page = 1
374650c51a77SMatthias Ringwald             if (!packet[2]) {
374750c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
374850c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
37495ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
375050c51a77SMatthias Ringwald                 bool done = false;
375150c51a77SMatthias Ringwald                 switch (page_number){
375250c51a77SMatthias Ringwald                     case 1:
37532f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
375450c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
375550c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
375650c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
375750c51a77SMatthias Ringwald                         } else {
375850c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
375950c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
376050c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
376150c51a77SMatthias Ringwald                             }
376250c51a77SMatthias Ringwald                             done = true;
376350c51a77SMatthias Ringwald                         }
376450c51a77SMatthias Ringwald                         break;
376550c51a77SMatthias Ringwald                     case 2:
376650c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
376750c51a77SMatthias Ringwald                         done = true;
376850c51a77SMatthias Ringwald                         break;
376950c51a77SMatthias Ringwald                     default:
377050c51a77SMatthias Ringwald                         break;
377150c51a77SMatthias Ringwald                 }
377250c51a77SMatthias Ringwald                 if (!done) break;
3773afd4e962S[email protected]             }
3774de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
3775afd4e962S[email protected]             break;
3776afd4e962S[email protected] 
37777fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
3778308eeaffSMatthias Ringwald #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY
377963c0b2fdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
378063c0b2fdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
378163c0b2fdSMatthias Ringwald             if (!conn) break;
378263c0b2fdSMatthias Ringwald 
378363c0b2fdSMatthias Ringwald             // lookup link key in db if not cached
378463c0b2fdSMatthias Ringwald             if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){
378563c0b2fdSMatthias Ringwald                 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type);
378663c0b2fdSMatthias Ringwald             }
378763c0b2fdSMatthias Ringwald 
378863c0b2fdSMatthias Ringwald             // response sent by hci_run()
378963c0b2fdSMatthias Ringwald             conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST;
379063c0b2fdSMatthias Ringwald #endif
3791608f51bbSMatthias Ringwald             break;
37927fde4af9Smatthias.ringwald 
37939ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
37941714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
3795f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
37969ab95c90S[email protected]             if (!conn) break;
37971714cbbdSMatthias Ringwald 
37981714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
37991714cbbdSMatthias Ringwald 
38003817f9dfSMatthias Ringwald             // CVE-2020-26555: ignore NULL link key
38013817f9dfSMatthias Ringwald             // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption
38023817f9dfSMatthias Ringwald             if (btstack_is_null(&packet[8], 16)) break;
38033817f9dfSMatthias Ringwald 
38047bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
38059ab95c90S[email protected]             // Change Connection Encryption keeps link key type
38069ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
38079ab95c90S[email protected]                 conn->link_key_type = link_key_type;
38089ab95c90S[email protected]             }
38093817f9dfSMatthias Ringwald 
3810e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
3811e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
3812e9f98c4aSMatthias Ringwald 
3813bec5f683SMatthias Ringwald             // only store link key:
3814bec5f683SMatthias Ringwald             // - if bondable enabled
3815bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
38166edaed7fSMatthias Ringwald             // - if security level sufficient
38176edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
381855597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
38197fde4af9Smatthias.ringwald             break;
38209ab95c90S[email protected]         }
38217fde4af9Smatthias.ringwald 
38227fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
38231714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
38241714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
38251714cbbdSMatthias Ringwald             if (!conn) break;
38261714cbbdSMatthias Ringwald 
38271714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
3828a800d95eSMatthias Ringwald             // abort pairing if: non-bondable mode (pin code request is not forwarded to app)
38293a9fb326S[email protected]             if (!hci_stack->bondable ){
38308daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
38311714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
3832f8fb5f6eS[email protected]                 hci_run();
3833f8fb5f6eS[email protected]                 return;
38344c57c146S[email protected]             }
3835a800d95eSMatthias Ringwald             // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app)
3836a800d95eSMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){
3837a800d95eSMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
383850dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
383950dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
384050dcc63cSMatthias Ringwald                 hci_run();
384150dcc63cSMatthias Ringwald                 return;
384250dcc63cSMatthias Ringwald             }
38437fde4af9Smatthias.ringwald             break;
38447fde4af9Smatthias.ringwald 
384550d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
384650d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
384750d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
384850d7398cSMatthias Ringwald             if (!conn) break;
38491714cbbdSMatthias Ringwald 
38508daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
38511714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
385250d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
3853e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
3854d22b82d6SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3855d22b82d6SMatthias Ringwald             conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet);
3856d22b82d6SMatthias Ringwald #endif
385750d7398cSMatthias Ringwald             break;
385850d7398cSMatthias Ringwald 
38591d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
38601714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
38611714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
38621714cbbdSMatthias Ringwald             if (!conn) break;
38631714cbbdSMatthias Ringwald 
3864c950c316SMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
38659671e615SMatthias Ringwald             hci_connection_timestamp(conn);
38661714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
3867dbe1a790S[email protected]             break;
3868dbe1a790S[email protected] 
38691849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
38701849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
38717ca4a7edSMatthias Ringwald             hci_event_remote_oob_data_request_get_bd_addr(packet, addr);
38727ca4a7edSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
38737ca4a7edSMatthias Ringwald             if (!conn) break;
38747ca4a7edSMatthias Ringwald 
38757ca4a7edSMatthias Ringwald             hci_connection_timestamp(conn);
38767ca4a7edSMatthias Ringwald 
38777ca4a7edSMatthias Ringwald             hci_pairing_started(conn, true);
38787ca4a7edSMatthias Ringwald 
38797ca4a7edSMatthias Ringwald             connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
38801849becdSMatthias Ringwald             break;
38811849becdSMatthias Ringwald #endif
38821849becdSMatthias Ringwald 
3883dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
388417c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
3885367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3886367aedc0SMatthias Ringwald             if (!conn) break;
3887367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
3888367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
38898daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
3890367aedc0SMatthias Ringwald                 };
3891367aedc0SMatthias Ringwald             } else {
3892367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
3893367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
3894367aedc0SMatthias Ringwald                 // don't forward event to app
3895367aedc0SMatthias Ringwald                 hci_run();
3896367aedc0SMatthias Ringwald                 return;
3897367aedc0SMatthias Ringwald             }
3898dbe1a790S[email protected]             break;
3899dbe1a790S[email protected] 
3900dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
3901367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
3902367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
39038daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
3904367aedc0SMatthias Ringwald             };
39051d6b20aeS[email protected]             break;
39061849becdSMatthias Ringwald 
39073dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
39083dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
39093dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
39103dce6128SMatthias Ringwald             if (!conn) break;
39113dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
39123dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
39133dce6128SMatthias Ringwald             break;
391435454696SMatthias Ringwald #endif
39151d6b20aeS[email protected] 
3916f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
3917a355334eSMatthias Ringwald         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
3918254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
3919f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
3920f0944df2S[email protected]             if (!conn) break;
3921db3c1f89SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == ERROR_CODE_SUCCESS) {
3922254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
3923254b78eeSMatthias Ringwald                 if (encryption_enabled){
3924573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
3925573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
39268daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
3927573897a0SMatthias Ringwald                     }
3928573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
3929573897a0SMatthias Ringwald                     else {
3930fcaf38b9SMatthias Ringwald 
3931254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
393236c3546bSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type);
3933254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
3934edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
3935813a09c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
3936813a09c6SMatthias Ringwald                             // The following tests require to reject L2CAP connection as SC has been disabled on the remote
3937813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-31-C
3938813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-32-C
3939813a09c6SMatthias Ringwald                             // - GAP/SEC/SEM/BI-33-C
3940813a09c6SMatthias Ringwald 
3941813a09c6SMatthias Ringwald                             // Our release code (aggressively) disconnects the HCI connection, without a chance to respond to PTS
3942813a09c6SMatthias Ringwald                             // To pass the tests, we only downgrade the link key type instead of the more secure disconnect
394329d4766dSMatthias Ringwald                             link_key_type_t new_link_key_type = UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
394429d4766dSMatthias Ringwald                             if (conn->link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256){
3945813a09c6SMatthias Ringwald                                 new_link_key_type = AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192;
3946813a09c6SMatthias Ringwald                             }
3947813a09c6SMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> downgrade link key type from %u to %u",
3948813a09c6SMatthias Ringwald                                      conn->link_key_type, new_link_key_type);
3949813a09c6SMatthias Ringwald                             conn->link_key_type = new_link_key_type;
3950813a09c6SMatthias Ringwald #else
3951254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
39529ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3953254b78eeSMatthias Ringwald                             break;
3954813a09c6SMatthias Ringwald #endif
3955254b78eeSMatthias Ringwald                         }
3956254b78eeSMatthias Ringwald 
3957aa2fe986SMatthias Ringwald                         // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication
3958aa2fe986SMatthias Ringwald                         if (connected_uses_aes_ccm){
3959aa2fe986SMatthias Ringwald                             conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3960aa2fe986SMatthias Ringwald                         }
3961aa2fe986SMatthias Ringwald 
3962aa2fe986SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
3963aa2fe986SMatthias Ringwald                         // work around for issue with PTS dongle
3964aa2fe986SMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
3965aa2fe986SMatthias Ringwald #endif
3966a355334eSMatthias Ringwald                         // validate encryption key size
3967a355334eSMatthias Ringwald                         if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) {
3968a355334eSMatthias Ringwald                             uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet);
3969a355334eSMatthias Ringwald                             // already got encryption key size
3970a355334eSMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, encryption_key_size);
3971a355334eSMatthias Ringwald                         } else {
39721ffa425cSMatthias Ringwald                             if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) {
39736e058d3fSMatthias Ringwald                                 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
3974573897a0SMatthias Ringwald                                 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
39756e058d3fSMatthias Ringwald                             } else {
39766e058d3fSMatthias Ringwald                                 // if not, pretend everything is perfect
39779866fdc7SMatthias Ringwald                                 hci_handle_read_encryption_key_size_complete(conn, 16);
39786e058d3fSMatthias Ringwald                             }
3979573897a0SMatthias Ringwald                         }
3980a355334eSMatthias Ringwald                     }
3981573897a0SMatthias Ringwald #endif
3982f0944df2S[email protected]                 } else {
39838daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
3984f0944df2S[email protected]                 }
39855999ee11SMatthias Ringwald             } else {
39868eae094cSMatthias Ringwald #ifdef ENABLE_CLASSIC
39878eae094cSMatthias Ringwald                 if (!hci_is_le_connection(conn)){
39885999ee11SMatthias Ringwald                     uint8_t status = hci_event_encryption_change_get_status(packet);
39895999ee11SMatthias Ringwald                     if ((conn->bonding_flags & BONDING_DEDICATED) != 0){
39905999ee11SMatthias Ringwald                         conn->bonding_flags &= ~BONDING_DEDICATED;
39915999ee11SMatthias Ringwald                         conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
39925999ee11SMatthias Ringwald                         conn->bonding_status = status;
39935999ee11SMatthias Ringwald                     }
399427b992efSMatthias Ringwald                     // trigger security update -> level 0
399527b992efSMatthias Ringwald                     hci_handle_mutual_authentication_completed(conn);
3996ad83dc6aS[email protected]                 }
39978eae094cSMatthias Ringwald #endif
39988eae094cSMatthias Ringwald             }
3999573897a0SMatthias Ringwald 
4000f0944df2S[email protected]             break;
4001f0944df2S[email protected] 
400235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
40031eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
4004abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
40051eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
40061eb2563eS[email protected]             if (!conn) break;
4007ad83dc6aS[email protected] 
4008dbd5dcc3SMatthias Ringwald             // clear authentication active flag
4009dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
40101714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
4011dbd5dcc3SMatthias Ringwald 
4012abdad579SMatthias Ringwald             // authenticated only if auth status == 0
4013abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
4014abdad579SMatthias Ringwald                 // authenticated
40158daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4016abdad579SMatthias Ringwald 
4017131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
40188daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
40191eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4020ad83dc6aS[email protected]                     break;
4021ad83dc6aS[email protected]                 }
4022abdad579SMatthias Ringwald             }
4023abdad579SMatthias Ringwald 
40244aa2f135SMatthias Ringwald             // emit updated security level (will be 0 if not authenticated)
40254aa2f135SMatthias Ringwald             hci_handle_mutual_authentication_completed(conn);
40261eb2563eS[email protected]             break;
40271714cbbdSMatthias Ringwald 
40281714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
40291714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
40301714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
40311714cbbdSMatthias Ringwald             if (!conn) break;
40321714cbbdSMatthias Ringwald 
4033aa2fe986SMatthias Ringwald             // treat successfully paired connection as authenticated
4034aa2fe986SMatthias Ringwald             if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){
4035f3aafff1SMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
4036aa2fe986SMatthias Ringwald             }
4037aa2fe986SMatthias Ringwald 
40381714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
40391714cbbdSMatthias Ringwald             break;
404035454696SMatthias Ringwald #endif
404134d2123cS[email protected] 
404286805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
4043ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
4044ccda6e14S[email protected]         // see end of function, too.
4045a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
4046a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
4047f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
404881d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
40494ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
4050c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
40514ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
405281d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
4053c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
4054c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
405581d2bdb2SMatthias Ringwald                     if (release_buffer){
405681d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
405781d2bdb2SMatthias Ringwald                     }
4058c6a37cfdSMatthias Ringwald                 }
4059c6a37cfdSMatthias Ringwald             }
406035454696SMatthias Ringwald 
40614ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4062098c2716SMatthias Ringwald             // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active
4063098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size > 0u) {
4064098c2716SMatthias Ringwald                 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
4065098c2716SMatthias Ringwald                     int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u;
4066098c2716SMatthias Ringwald                     log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer);
4067098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_total_size = 0;
4068098c2716SMatthias Ringwald                     hci_stack->iso_fragmentation_pos = 0;
4069098c2716SMatthias Ringwald                     if (release_buffer){
4070098c2716SMatthias Ringwald                         hci_release_packet_buffer();
4071098c2716SMatthias Ringwald                     }
4072098c2716SMatthias Ringwald                 }
4073098c2716SMatthias Ringwald             }
4074098c2716SMatthias Ringwald 
40756fd1d2c8SMatthias Ringwald             // finalize iso stream for CIS handle
407615a15be3SMatthias Ringwald             iso_stream = hci_iso_stream_for_con_handle(handle);
40774ae8623eSMatthias Ringwald             if (iso_stream != NULL){
40784ae8623eSMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
40794ae8623eSMatthias Ringwald                 break;
40804ae8623eSMatthias Ringwald             }
40816fd1d2c8SMatthias Ringwald 
40826fd1d2c8SMatthias Ringwald             // finalize iso stream(s) for ACL handle
40836fd1d2c8SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
40846fd1d2c8SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
40856fd1d2c8SMatthias Ringwald                 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
40866fd1d2c8SMatthias Ringwald                 if (iso_stream->acl_handle == handle ) {
40876fd1d2c8SMatthias Ringwald                     hci_iso_stream_finalize(iso_stream);
40886fd1d2c8SMatthias Ringwald                 }
40896fd1d2c8SMatthias Ringwald             }
40904ae8623eSMatthias Ringwald #endif
40914ae8623eSMatthias Ringwald 
4092c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
4093c6a37cfdSMatthias Ringwald             if (!conn) break;
40941714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
40951714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
40961714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
40971714cbbdSMatthias Ringwald #endif
4098046ec007SMatthias Ringwald 
4099046ec007SMatthias Ringwald             // emit dedicatd bonding event
4100046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
4101046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
4102046ec007SMatthias Ringwald             }
4103046ec007SMatthias Ringwald 
4104459d27b9SMatthias Ringwald             // mark connection for shutdown, stop timers, reset state
4105459d27b9SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
4106459d27b9SMatthias Ringwald             hci_connection_stop_timer(conn);
4107459d27b9SMatthias Ringwald             hci_connection_init(conn);
4108459d27b9SMatthias Ringwald 
410935454696SMatthias Ringwald #ifdef ENABLE_BLE
4110d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4111046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
41122b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
4113bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
41149a2e4658SMatthias Ringwald             }
411535454696SMatthias Ringwald #endif
4116d70217a2SMatthias Ringwald #endif
4117ccda6e14S[email protected]             break;
41186772a24cSmatthias.ringwald 
4119c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
4120313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
4121d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
4122c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
41237586ee35S[email protected]             } else {
41247586ee35S[email protected]                 // if no special requests, just reboot stack
41257586ee35S[email protected]                 hci_power_control_off();
41267586ee35S[email protected]                 hci_power_control_on();
4127c68bdf90Smatthias.ringwald             }
4128c68bdf90Smatthias.ringwald             break;
4129c68bdf90Smatthias.ringwald 
41300e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
41315cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
41325cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
4133c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
4134f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
4135c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4136c4c88f1bSJakob Krantz             if (!conn) break;
413788f925b1SMatthias Ringwald             conn->role = (hci_role_t) packet[9];
41385cf766e8SMatthias Ringwald             break;
41390e6f3837SMatthias Ringwald #endif
41405cf766e8SMatthias Ringwald 
414163fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
4142098c2716SMatthias Ringwald             // release packet buffer only for asynchronous transport and if there are not further fragments
41434fa24b5fS[email protected]             if (hci_transport_synchronous()) {
414463fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
41454fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
41464fa24b5fS[email protected]             }
414781d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
4148098c2716SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4149098c2716SMatthias Ringwald             hci_stack->iso_fragmentation_tx_active = 0;
4150098c2716SMatthias Ringwald             if (hci_stack->iso_fragmentation_total_size) break;
4151098c2716SMatthias Ringwald #endif
4152d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
4153d051460cS[email protected]             hci_release_packet_buffer();
4154701e3307SMatthias Ringwald 
41555ade6657SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
41565ade6657SMatthias Ringwald             hci_iso_notify_can_send_now();
41575ade6657SMatthias Ringwald #endif
415863fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
415963fa3374SMatthias Ringwald 
416035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
416163fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
4162701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
416335454696SMatthias Ringwald #endif
41646b4af23dS[email protected]             break;
41656b4af23dS[email protected] 
416635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
416763fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
416863fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
41691972f31fSMatthias Ringwald             hci_stack->sco_can_send_now = true;
417063fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
417163fa3374SMatthias Ringwald             return;
41721cfb383eSMatthias Ringwald 
41731cfb383eSMatthias Ringwald         // explode inquriy results for easier consumption
41741cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
41751cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
41761cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
41779784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
41781cfb383eSMatthias Ringwald             break;
417935454696SMatthias Ringwald #endif
418063fa3374SMatthias Ringwald 
4181a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
41825909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
41835909f7f2Smatthias.ringwald             switch (packet[2]){
4184d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
418557c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
41866fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
418757c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
41887bdc6798S[email protected]                     break;
4189a0698cb4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4190a0698cb4SMatthias Ringwald                 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT:
4191a0698cb4SMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
4192a0698cb4SMatthias Ringwald                     le_handle_extended_advertisement_report(packet, size);
4193a0698cb4SMatthias Ringwald                     break;
4194ce56b945SMatthias Ringwald                 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT:
4195ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
4196ce56b945SMatthias Ringwald                     hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE;
4197ce56b945SMatthias Ringwald                     break;
419889254d99SMatthias Ringwald                 case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
419989254d99SMatthias Ringwald                     advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
420089254d99SMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
420189254d99SMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it)) {
420289254d99SMatthias Ringwald                         le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
420389254d99SMatthias Ringwald                         if (advertising_set->advertising_handle == advertising_handle){
420489254d99SMatthias Ringwald                             advertising_set->state &= ~(LE_ADVERTISEMENT_STATE_ACTIVE | LE_ADVERTISEMENT_STATE_ENABLED);
420589254d99SMatthias Ringwald                         }
420689254d99SMatthias Ringwald                     }
420789254d99SMatthias Ringwald                     break;
4208a0698cb4SMatthias Ringwald #endif
4209d70217a2SMatthias Ringwald #endif
42105909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
421160fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V1:
421260fb273dSMatthias Ringwald                 case HCI_SUBEVENT_LE_ENHANCED_CONNECTION_COMPLETE_V2:
42130ce3f217SMatthias Ringwald 					event_handle_le_connection_complete(packet);
42145909f7f2Smatthias.ringwald                     break;
42155909f7f2Smatthias.ringwald 
4216f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
4217c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
4218c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
4219c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
4220c9db5c21SMilanka Ringwald                     if (!conn) break;
4221c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
4222c9db5c21SMilanka Ringwald                     break;
422365a46ef3S[email protected] 
422473cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
422573cd8a2aSMatthias Ringwald                     // connection
422673cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
422773cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
422873cd8a2aSMatthias Ringwald                     if (conn) {
422973cd8a2aSMatthias Ringwald                         // read arguments
423073cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
423173cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
423273cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
423373cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
423473cd8a2aSMatthias Ringwald 
423573cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
423673cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
423773cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
423873cd8a2aSMatthias 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);
423973cd8a2aSMatthias Ringwald                         if (update_parameter){
424073cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
424173cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
424273cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
424373cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
424473cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
424573cd8a2aSMatthias Ringwald                         } else {
4246c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
424773cd8a2aSMatthias Ringwald                         }
424873cd8a2aSMatthias Ringwald                     }
424973cd8a2aSMatthias Ringwald                     break;
42500f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
42510f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
42520f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
42530f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
42540f3b27c5SMatthias Ringwald                     if (conn) {
42550f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
42560f3b27c5SMatthias Ringwald                     }
42570f3b27c5SMatthias Ringwald                     break;
42580f3b27c5SMatthias Ringwald #endif
42594ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
42606fd1d2c8SMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_REQUEST:
42616fd1d2c8SMatthias Ringwald                     // incoming CIS request, allocate iso stream object and cache metadata
42626fd1d2c8SMatthias Ringwald                     iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS, HCI_ISO_STREAM_W4_USER,
42636fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cig_id(packet),
42646fd1d2c8SMatthias Ringwald                                                        hci_subevent_le_cis_request_get_cis_id(packet));
42656fd1d2c8SMatthias Ringwald                     // if there's no memory, gap_cis_accept/gap_cis_reject will fail
42666fd1d2c8SMatthias Ringwald                     if (iso_stream != NULL){
42676fd1d2c8SMatthias Ringwald                         iso_stream->cis_handle = hci_subevent_le_cis_request_get_cis_connection_handle(packet);
42686fd1d2c8SMatthias Ringwald                         iso_stream->acl_handle = hci_subevent_le_cis_request_get_acl_connection_handle(packet);
42696fd1d2c8SMatthias Ringwald                     }
42706fd1d2c8SMatthias Ringwald                     break;
42714ae8623eSMatthias Ringwald                 case HCI_SUBEVENT_LE_CIS_ESTABLISHED:
42728e58e4f7SMatthias Ringwald                     if (hci_stack->iso_active_operation_type == HCI_ISO_TYPE_CIS){
42734ae8623eSMatthias Ringwald                         handle = hci_subevent_le_cis_established_get_connection_handle(packet);
42744ae8623eSMatthias Ringwald                         uint8_t status = hci_subevent_le_cis_established_get_status(packet);
42758e58e4f7SMatthias Ringwald                         iso_stream = hci_iso_stream_for_con_handle(handle);
42768e58e4f7SMatthias Ringwald                         btstack_assert(iso_stream != NULL);
427726b93350SMatthias Ringwald                         // track SDU
427826b93350SMatthias Ringwald                         iso_stream->max_sdu_c_to_p = hci_subevent_le_cis_established_get_max_pdu_c_to_p(packet);
427926b93350SMatthias Ringwald                         iso_stream->max_sdu_p_to_c = hci_subevent_le_cis_established_get_max_pdu_p_to_c(packet);
428026b93350SMatthias Ringwald                         if (hci_stack->iso_active_operation_group_id == HCI_ISO_GROUP_ID_SINGLE_CIS){
428126b93350SMatthias Ringwald                             // CIS Accept by Peripheral
428226b93350SMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
428326b93350SMatthias Ringwald                                 if (iso_stream->max_sdu_p_to_c > 0){
428426b93350SMatthias Ringwald                                     // we're peripheral and we will send data
428526b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT;
428626b93350SMatthias Ringwald                                 } else {
428726b93350SMatthias Ringwald                                     // we're peripheral and we will only receive data
428826b93350SMatthias Ringwald                                     iso_stream->state = HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT;
428926b93350SMatthias Ringwald                                 }
429026b93350SMatthias Ringwald                             } else {
429114045fdbSMatthias Ringwald                                 hci_cis_handle_created(iso_stream, status);
429226b93350SMatthias Ringwald                             }
429326b93350SMatthias Ringwald                             hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
429426b93350SMatthias Ringwald                         } else {
429526b93350SMatthias Ringwald                             // CIG Setup by Central
429626b93350SMatthias Ringwald                             le_audio_cig_t * cig = hci_cig_for_id(hci_stack->iso_active_operation_group_id);
429726b93350SMatthias Ringwald                             btstack_assert(cig != NULL);
429826b93350SMatthias Ringwald                             // update iso stream state
42994ae8623eSMatthias Ringwald                             if (status == ERROR_CODE_SUCCESS){
43004ae8623eSMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
43014ae8623eSMatthias Ringwald                             } else {
43028e58e4f7SMatthias Ringwald                                 iso_stream->state = HCI_ISO_STREAM_STATE_IDLE;
43034ae8623eSMatthias Ringwald                             }
43048e58e4f7SMatthias Ringwald                             // update cig state
4305f06bb90fSMatthias Ringwald                             uint8_t i;
4306f06bb90fSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
4307f06bb90fSMatthias Ringwald                                 if (cig->cis_con_handles[i] == handle){
43083abcd16cSMatthias Ringwald                                     cig->cis_setup_active[i] = false;
4309f9306a1aSMatthias Ringwald                                     if (status == ERROR_CODE_SUCCESS){
4310f9306a1aSMatthias Ringwald                                         cig->cis_established[i] = true;
4311f9306a1aSMatthias Ringwald                                     } else {
431214045fdbSMatthias Ringwald                                         hci_cis_handle_created(iso_stream, status);
4313f06bb90fSMatthias Ringwald                                     }
4314f06bb90fSMatthias Ringwald                                 }
4315f06bb90fSMatthias Ringwald                             }
43168e58e4f7SMatthias Ringwald 
43178e58e4f7SMatthias Ringwald                             // trigger iso path setup if complete
43180f0ba168SMatthias Ringwald                             bool cis_setup_active = false;
4319f9306a1aSMatthias Ringwald                             for (i=0;i<cig->num_cis;i++){
43200f0ba168SMatthias Ringwald                                 cis_setup_active |= cig->cis_setup_active[i];
4321f9306a1aSMatthias Ringwald                             }
43220f0ba168SMatthias Ringwald                             if (cis_setup_active == false){
4323f9306a1aSMatthias Ringwald                                 cig->state_vars.next_cis = 0;
4324f9306a1aSMatthias Ringwald                                 cig->state = LE_AUDIO_CIG_STATE_SETUP_ISO_PATH;
432526b93350SMatthias Ringwald                                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
432626b93350SMatthias Ringwald                             }
4327f06bb90fSMatthias Ringwald                         }
43284ae8623eSMatthias Ringwald                     }
43297aa35f6aSMatthias Ringwald                     break;
43307aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE:
433126b93350SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
43327aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(packet[4]);
43337aa35f6aSMatthias Ringwald                     if (big != NULL){
43347aa35f6aSMatthias Ringwald                         uint8_t status = packet[3];
43357aa35f6aSMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
43367aa35f6aSMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
43377aa35f6aSMatthias Ringwald                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]);
43387aa35f6aSMatthias Ringwald                             uint8_t i;
43397aa35f6aSMatthias Ringwald                             for (i=0;i<num_bis;i++){
4340fb16346aSMatthias Ringwald                                 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i));
4341fb16346aSMatthias Ringwald                                 big->bis_con_handles[i] = bis_handle;
4342fb16346aSMatthias Ringwald                                 // assign bis handle
4343fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_t it;
4344fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4345fb16346aSMatthias Ringwald                                 while (btstack_linked_list_iterator_has_next(&it)){
4346fb16346aSMatthias Ringwald                                     hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
4347fb16346aSMatthias Ringwald                                     if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
43488d72db10SMatthias Ringwald                                         (iso_stream->group_id == big->big_handle)){
4349969d876aSMatthias Ringwald                                         iso_stream->cis_handle = bis_handle;
4350fb16346aSMatthias Ringwald                                         iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED;
4351cd1139aaSMatthias Ringwald                                         break;
4352fb16346aSMatthias Ringwald                                     }
4353fb16346aSMatthias Ringwald                                 }
43547aa35f6aSMatthias Ringwald                             }
43552a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
43567aa35f6aSMatthias Ringwald                                 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
43577aa35f6aSMatthias Ringwald                                 big->state_vars.next_bis = 0;
43582a6c0f82SMatthias Ringwald                             }
43597aa35f6aSMatthias Ringwald                         } else {
43602a6c0f82SMatthias Ringwald                             // create BIG failed or has been stopped by us
4361778463d0SMatthias Ringwald                             hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big->big_handle);
43627aa35f6aSMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
43632a6c0f82SMatthias Ringwald                             if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){
43647aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, status);
43652a6c0f82SMatthias Ringwald                             } else {
43662a6c0f82SMatthias Ringwald                                 hci_emit_big_terminated(big);
43672a6c0f82SMatthias Ringwald                             }
43687aa35f6aSMatthias Ringwald                         }
43697aa35f6aSMatthias Ringwald                     }
43707aa35f6aSMatthias Ringwald                     break;
43717aa35f6aSMatthias Ringwald                 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE:
4372c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
43737aa35f6aSMatthias Ringwald                     big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet));
43747aa35f6aSMatthias Ringwald                     if (big != NULL){
4375fb16346aSMatthias Ringwald                         // finalize associated ISO streams
4376fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_t it;
4377fb16346aSMatthias Ringwald                         btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
4378fb16346aSMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&it)){
4379fb16346aSMatthias Ringwald                             hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
43808d72db10SMatthias Ringwald                             if (iso_stream->group_id == big->big_handle){
4381969d876aSMatthias Ringwald                                 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->group_id, iso_stream->cis_handle);
4382fb16346aSMatthias Ringwald                                 btstack_linked_list_iterator_remove(&it);
4383fb16346aSMatthias Ringwald                                 btstack_memory_hci_iso_stream_free(iso_stream);
4384fb16346aSMatthias Ringwald                             }
4385fb16346aSMatthias Ringwald                         }
43867aa35f6aSMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
43877aa35f6aSMatthias Ringwald                         switch (big->state){
43887aa35f6aSMatthias Ringwald                             case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED:
43897aa35f6aSMatthias Ringwald                                 hci_emit_big_created(big, big->state_vars.status);
43907aa35f6aSMatthias Ringwald                                 break;
43917aa35f6aSMatthias Ringwald                             default:
43927aa35f6aSMatthias Ringwald                                 hci_emit_big_terminated(big);
43937aa35f6aSMatthias Ringwald                                 break;
43947aa35f6aSMatthias Ringwald                         }
43957aa35f6aSMatthias Ringwald                     }
43967aa35f6aSMatthias Ringwald                     break;
43972a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED:
4398c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
43992a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
44002a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
44012a6c0f82SMatthias Ringwald                         uint8_t status = packet[3];
4402d04a9afcSMatthias Ringwald                         uint8_t big_handle = packet[4];
44032a6c0f82SMatthias Ringwald                         if (status == ERROR_CODE_SUCCESS){
44042a6c0f82SMatthias Ringwald                             // store bis_con_handles and trigger iso path setup
44052a6c0f82SMatthias Ringwald                             uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]);
44062a6c0f82SMatthias Ringwald                             uint8_t i;
44072a6c0f82SMatthias Ringwald                             for (i=0;i<num_bis;i++){
44082a6c0f82SMatthias Ringwald                                 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i));
44092a6c0f82SMatthias Ringwald                             }
44102a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
44112a6c0f82SMatthias Ringwald                                 // trigger iso path setup
44122a6c0f82SMatthias Ringwald                                 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH;
44132a6c0f82SMatthias Ringwald                                 big_sync->state_vars.next_bis = 0;
44142a6c0f82SMatthias Ringwald                             }
44152a6c0f82SMatthias Ringwald                         } else {
44162a6c0f82SMatthias Ringwald                             // create BIG Sync failed or has been stopped by us
44172a6c0f82SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
44182a6c0f82SMatthias Ringwald                             if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) {
44192a6c0f82SMatthias Ringwald                                 hci_emit_big_sync_created(big_sync, status);
44202a6c0f82SMatthias Ringwald                             } else {
4421d04a9afcSMatthias Ringwald                                 hci_emit_big_sync_stopped(big_handle);
44222a6c0f82SMatthias Ringwald                             }
44232a6c0f82SMatthias Ringwald                         }
44242a6c0f82SMatthias Ringwald                     }
44252a6c0f82SMatthias Ringwald                     break;
44262a6c0f82SMatthias Ringwald                 case HCI_SUBEVENT_LE_BIG_SYNC_LOST:
4427c45ca112SMatthias Ringwald                     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
44282a6c0f82SMatthias Ringwald                     big_sync = hci_big_sync_for_handle(packet[4]);
44292a6c0f82SMatthias Ringwald                     if (big_sync != NULL){
4430d04a9afcSMatthias Ringwald                         uint8_t big_handle = packet[4];
44312a6c0f82SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
4432d04a9afcSMatthias Ringwald                         hci_emit_big_sync_stopped(big_handle);
44332a6c0f82SMatthias Ringwald                     }
44342a6c0f82SMatthias Ringwald                     break;
44354ae8623eSMatthias Ringwald #endif
44365909f7f2Smatthias.ringwald                 default:
44375909f7f2Smatthias.ringwald                     break;
44385909f7f2Smatthias.ringwald             }
44395909f7f2Smatthias.ringwald             break;
44405909f7f2Smatthias.ringwald #endif
44410b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
44420b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
44430b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
44440b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
44450b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
44460b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
44470b36101dSMatthias Ringwald                     break;
44480b36101dSMatthias Ringwald                 default:
44490b36101dSMatthias Ringwald                     break;
44500b36101dSMatthias Ringwald             }
44510b36101dSMatthias Ringwald             break;
44526772a24cSmatthias.ringwald         default:
44536772a24cSmatthias.ringwald             break;
4454fe1ed1b8Smatthias.ringwald     }
4455fe1ed1b8Smatthias.ringwald 
445667c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
445789db417bSmatthias.ringwald 
445886805605S[email protected]     // notify upper stack
4459d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
446094ab26f8Smatthias.ringwald 
446186805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
4462797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
4463f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
446405ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
4465046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
4466797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
446705ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
4468b0136355SMatthias Ringwald 		}
44698ad9cf99SMatthias Ringwald #ifdef ENABLE_CONTROLLER_DUMP_PACKETS
44708ad9cf99SMatthias Ringwald         hci_controller_dump_packets();
44718ad9cf99SMatthias Ringwald #endif
447286805605S[email protected]     }
447386805605S[email protected] 
447494ab26f8Smatthias.ringwald 	// execute main loop
447594ab26f8Smatthias.ringwald 	hci_run();
447616833f0aSmatthias.ringwald }
447716833f0aSmatthias.ringwald 
447835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
44796f28d2eeSMatthias Ringwald 
4480c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
44810b3f95dfSMatthias Ringwald     // lookup connection struct
44822b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
44832b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
44840b3f95dfSMatthias Ringwald     if (!conn) return;
44850b3f95dfSMatthias Ringwald 
44866be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
4487760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
4488760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
4489a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
4490760b20efSMatthias Ringwald             packet[2] = 0x3c;
4491760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
4492760b20efSMatthias Ringwald             size = 63;
44930b3f95dfSMatthias Ringwald         }
44940b3f95dfSMatthias Ringwald     }
4495760b20efSMatthias Ringwald 
4496f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
4497f234b250SMatthias Ringwald         // Nothing to do
4498f234b250SMatthias Ringwald     } else {
449949205f5dSMatthias 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);
4500760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
4501fa7f2dfdSMatthias Ringwald             // ignore received SCO packets for the first 10 ms, then allow for max two HCI_SCO_2EV3_SIZE packets
4502fa7f2dfdSMatthias Ringwald             uint16_t max_sco_packets = btstack_min(2 * HCI_SCO_2EV3_SIZE / conn->sco_payload_length, hci_stack->sco_packets_total_num);
4503fa7f2dfdSMatthias Ringwald             if (conn->sco_tx_active == 0){
4504fa7f2dfdSMatthias Ringwald                 if (btstack_time_delta(btstack_run_loop_get_time_ms(), conn->sco_established_ms) > 10){
4505fa7f2dfdSMatthias Ringwald                     conn->sco_tx_active = 1;
4506fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready = max_sco_packets;
4507fa7f2dfdSMatthias Ringwald                     log_info("Start SCO sending, %u packets", conn->sco_tx_ready);
4508fa7f2dfdSMatthias Ringwald                     hci_notify_if_sco_can_send_now();
450959c33575SMatthias Ringwald                 }
451059c33575SMatthias Ringwald             } else {
4511fa7f2dfdSMatthias Ringwald                 if (conn->sco_tx_ready < max_sco_packets){
4512fa7f2dfdSMatthias Ringwald                     conn->sco_tx_ready++;
451359c33575SMatthias Ringwald                 }
4514fa7f2dfdSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
45156f28d2eeSMatthias Ringwald             }
4516760b20efSMatthias Ringwald         }
4517f234b250SMatthias Ringwald     }
45186be3cf7fSMatthias Ringwald #endif
45196be3cf7fSMatthias Ringwald 
45200b3f95dfSMatthias Ringwald     // deliver to app
45210b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
45220b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
45230b3f95dfSMatthias Ringwald     }
45240b3f95dfSMatthias Ringwald 
4525ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4526ed325439SMatthias Ringwald     // We can send one packet for each received packet
4527ed325439SMatthias Ringwald     conn->sco_tx_ready++;
4528ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
4529ed325439SMatthias Ringwald #endif
4530ed325439SMatthias Ringwald 
45310b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
45322b838201SMatthias Ringwald     conn->num_packets_completed++;
45332b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
45342b838201SMatthias Ringwald     hci_run();
45352b838201SMatthias Ringwald #endif
4536c91d150bS[email protected] }
453735454696SMatthias Ringwald #endif
4538c91d150bS[email protected] 
45390a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
45405bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
454110e830c9Smatthias.ringwald     switch (packet_type) {
454210e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
454310e830c9Smatthias.ringwald             event_handler(packet, size);
454410e830c9Smatthias.ringwald             break;
454510e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
454610e830c9Smatthias.ringwald             acl_handler(packet, size);
454710e830c9Smatthias.ringwald             break;
454835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4549c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
4550c91d150bS[email protected]             sco_handler(packet, size);
4551202c8a4cSMatthias Ringwald             break;
455235454696SMatthias Ringwald #endif
45530a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
45545027c498SMatthias Ringwald         case HCI_ISO_DATA_PACKET:
4555d39e4f95SMatthias Ringwald             hci_iso_packet_handler(packet, size);
45565027c498SMatthias Ringwald             break;
45575027c498SMatthias Ringwald #endif
455810e830c9Smatthias.ringwald         default:
455910e830c9Smatthias.ringwald             break;
456010e830c9Smatthias.ringwald     }
456110e830c9Smatthias.ringwald }
456210e830c9Smatthias.ringwald 
4563d6b06661SMatthias Ringwald /**
4564d6b06661SMatthias Ringwald  * @brief Add event packet handler.
4565d6b06661SMatthias Ringwald  */
4566d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4567d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
4568d6b06661SMatthias Ringwald }
4569d6b06661SMatthias Ringwald 
457067f708e0SMatthias Ringwald /**
457167f708e0SMatthias Ringwald  * @brief Remove event packet handler.
457267f708e0SMatthias Ringwald  */
457367f708e0SMatthias Ringwald void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
457467f708e0SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
457567f708e0SMatthias Ringwald }
4576d6b06661SMatthias Ringwald 
4577fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
45783d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
4579fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
458016833f0aSmatthias.ringwald }
458116833f0aSmatthias.ringwald 
458235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
45838abbe8b5SMatthias Ringwald /**
45848abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
45858abbe8b5SMatthias Ringwald  */
45863d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
45878abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
45888abbe8b5SMatthias Ringwald }
458935454696SMatthias Ringwald #endif
45908abbe8b5SMatthias Ringwald 
45910a8cccd5SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
45925027c498SMatthias Ringwald void hci_register_iso_packet_handler(btstack_packet_handler_t handler){
45935027c498SMatthias Ringwald     hci_stack->iso_packet_handler = handler;
45945027c498SMatthias Ringwald }
45955027c498SMatthias Ringwald #endif
45965027c498SMatthias Ringwald 
459771de195eSMatthias Ringwald static void hci_state_reset(void){
4598595bdbfbS[email protected]     // no connections yet
4599595bdbfbS[email protected]     hci_stack->connections = NULL;
460074308b23Smatthias.ringwald 
460174308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
460274308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
460374308b23Smatthias.ringwald     // hci_stack->connectable = 0;
460474308b23Smatthias.ringwald     // hci_stack->bondable = 1;
4605b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
4606595bdbfbS[email protected] 
460744935e40S[email protected]     // buffer is free
460802c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
460944935e40S[email protected] 
4610595bdbfbS[email protected]     // no pending cmds
4611595bdbfbS[email protected]     hci_stack->decline_reason = 0;
4612595bdbfbS[email protected] 
4613c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
4614c214d65bSMatthias Ringwald 
4615bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
4616496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
461732a12730SMatthias Ringwald     hci_stack->page_timeout = 0x6000;  // ca. 15 sec
461832a12730SMatthias Ringwald 
4619baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic =
462059d59ecfSMatthias Ringwald             GAP_TASK_SET_DEFAULT_LINK_POLICY |
462159d59ecfSMatthias Ringwald             GAP_TASK_SET_CLASS_OF_DEVICE |
462259d59ecfSMatthias Ringwald             GAP_TASK_SET_LOCAL_NAME |
4623bc2dcc03SMatthias Ringwald             GAP_TASK_SET_EIR_DATA |
462432a12730SMatthias Ringwald             GAP_TASK_WRITE_SCAN_ENABLE |
462532a12730SMatthias Ringwald             GAP_TASK_WRITE_PAGE_TIMEOUT;
4626bea424a5SMatthias Ringwald #endif
4627bea424a5SMatthias Ringwald 
4628cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
46298d5f0979SMatthias Ringwald     hci_stack->classic_read_local_oob_data = false;
46301ae74bf3SMatthias Ringwald     hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID;
4631cf01e888SMatthias Ringwald #endif
4632cf01e888SMatthias Ringwald 
4633595bdbfbS[email protected]     // LE
4634b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
4635b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
4636b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
4637d70217a2SMatthias Ringwald #endif
4638d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4639a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
464073799937SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
4641b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4642d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
4643e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
46444bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
46454bafedd5SMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
46464bafedd5SMatthias Ringwald #endif
4647d70217a2SMatthias Ringwald #endif
4648a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4649935aa76eSMatthias Ringwald     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
46506bf435a6SMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){
4651a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4652a61834b6SMatthias Ringwald     }
4653a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
4654a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4655a61834b6SMatthias Ringwald     }
4656a61834b6SMatthias Ringwald #endif
4657d320e123SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4658d320e123SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION;
4659d320e123SMatthias Ringwald #endif
466040f86dfdSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
466126b93350SMatthias Ringwald     hci_stack->iso_active_operation_type = HCI_ISO_TYPE_INVALID;
4662d75a6bbfSMatthias Ringwald     hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_INVALID;
466340f86dfdSMatthias Ringwald #endif
4664595bdbfbS[email protected] }
4665595bdbfbS[email protected] 
466635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
46672d5e09d6SMatthias Ringwald /**
46682d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
46692d5e09d6SMatthias Ringwald  */
46702d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
46712d5e09d6SMatthias Ringwald     // store and open remote device db
46722d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
46732d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
46742d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
46752d5e09d6SMatthias Ringwald     }
46762d5e09d6SMatthias Ringwald }
467735454696SMatthias Ringwald #endif
46782d5e09d6SMatthias Ringwald 
46792d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
4680475c8125Smatthias.ringwald 
46813a9fb326S[email protected] #ifdef HAVE_MALLOC
46823a9fb326S[email protected]     if (!hci_stack) {
46833a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
46843a9fb326S[email protected]     }
46853a9fb326S[email protected] #else
46863a9fb326S[email protected]     hci_stack = &hci_stack_static;
46873a9fb326S[email protected] #endif
468866fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
46893a9fb326S[email protected] 
4690475c8125Smatthias.ringwald     // reference to use transport layer implementation
46913a9fb326S[email protected]     hci_stack->hci_transport = transport;
4692475c8125Smatthias.ringwald 
469311e23e5fSmatthias.ringwald     // reference to used config
46943a9fb326S[email protected]     hci_stack->config = config;
469511e23e5fSmatthias.ringwald 
469626a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
469726a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
469826a9b6daSMatthias Ringwald 
46998fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
47003a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
47018fcba05dSmatthias.ringwald 
470216833f0aSmatthias.ringwald     // register packet handlers with transport
470310e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
4704f5454fc6Smatthias.ringwald 
47053a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
4706e2386ba1S[email protected] 
4707e2386ba1S[email protected]     // class of device
47083a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
4709a45d6b9fS[email protected] 
4710f20168b8Smatthias.ringwald     // bondable by default
4711f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
4712f20168b8Smatthias.ringwald 
4713e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
471463168530SMatthias Ringwald     // classic name
471563168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
4716c4c88f1bSJakob Krantz 
4717c4c88f1bSJakob Krantz     // Master slave policy
4718c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
4719170fafaeSMatthias Ringwald 
4720b4eb4420SMatthias Ringwald     // Allow Role Switch
4721b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
4722b4eb4420SMatthias Ringwald 
472378315a58SMatthias Ringwald     // Default / minimum security level = 2
472478315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
472578315a58SMatthias Ringwald 
47265dbec6b3SMatthias Ringwald     // Default Security Mode 4
47275dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
47285dbec6b3SMatthias Ringwald 
4729cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
4730cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
4731d821984bSMatthias Ringwald 
4732d821984bSMatthias Ringwald     // Link Supervision Timeout
4733d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
4734d821984bSMatthias Ringwald 
4735e9f343c8SMatthias Ringwald #endif
473663168530SMatthias Ringwald 
473763048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
47383a9fb326S[email protected]     hci_stack->ssp_enable = 1;
47393a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
47403a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
47413a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
474269a97523S[email protected] 
47435d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
47445d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
47455d23aae8SMatthias Ringwald 
4746fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
4747fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
4748d950d659SMatthias Ringwald 
47490c2c5f79SMatthias Ringwald #ifdef ENABLE_BLE
4750cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   //    60 ms
4751cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window   = 0x0030;    //   30 ms
4752831711daSMatthias Ringwald     hci_stack->le_connection_interval_min  = 0x0008;    //   10 ms
4753831711daSMatthias Ringwald     hci_stack->le_connection_interval_max  = 0x0018;    //   30 ms
4754831711daSMatthias Ringwald     hci_stack->le_connection_latency       =      4;    //    4
4755831711daSMatthias Ringwald     hci_stack->le_supervision_timeout      = 0x0048;    //  720 ms
475624d14ae3SMatthias Ringwald     hci_stack->le_minimum_ce_length        =      0;    //    0 ms
475724d14ae3SMatthias Ringwald     hci_stack->le_maximum_ce_length        =      0;    //    0 ms
47580c2c5f79SMatthias Ringwald #endif
47590c2c5f79SMatthias Ringwald 
47600c2c5f79SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
47617eb5b27eSMatthias Ringwald     hci_stack->le_connection_phys          =   0x01;    // LE 1M PHY
47627261e5d8SMatthias Ringwald 
47637261e5d8SMatthias Ringwald     // default LE Scanning
47647eb5b27eSMatthias Ringwald     hci_stack->le_scan_type     =  0x01; // active
47658b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
47668b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
47677eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys     =  0x01; // LE 1M PHY
4768831711daSMatthias Ringwald #endif
4769831711daSMatthias Ringwald 
47702b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
47712b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
4772ee605458SMatthias Ringwald 
4773ee605458SMatthias Ringwald     // default advertising parameters from Core v5.4 -- needed to use random address without prior adv setup
4774ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_min =                         0x0800;
4775ee605458SMatthias Ringwald     hci_stack->le_advertisements_interval_max =                         0x0800;
4776ee605458SMatthias Ringwald     hci_stack->le_advertisements_type =                                      0;
4777ee605458SMatthias Ringwald     hci_stack->le_own_addr_type =                       BD_ADDR_TYPE_LE_PUBLIC;
4778ee605458SMatthias Ringwald     hci_stack->le_advertisements_direct_address_type =  BD_ADDR_TYPE_LE_PUBLIC;
4779ee605458SMatthias Ringwald     hci_stack->le_advertisements_channel_map =                            0x07;
4780ee605458SMatthias Ringwald     hci_stack->le_advertisements_filter_policy =                             0;
47812b6ab3e6SMatthias Ringwald #endif
47822b6ab3e6SMatthias Ringwald 
4783831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
4784831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
4785831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
4786831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
4787831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
4788831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
4789831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
4790831711daSMatthias Ringwald 
479101d4f05fSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
479201d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = 1;
479301d4f05fSMatthias Ringwald #endif
479401d4f05fSMatthias Ringwald 
4795c3d19a30SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4796c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = LE_PRIVACY_MODE_DEVICE;
4797c3d19a30SMatthias Ringwald #endif
4798c3d19a30SMatthias Ringwald 
4799595bdbfbS[email protected]     hci_state_reset();
4800475c8125Smatthias.ringwald }
4801475c8125Smatthias.ringwald 
48024688f216SMatthias Ringwald void hci_deinit(void){
4803b02cfc15SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
48044688f216SMatthias Ringwald #ifdef HAVE_MALLOC
48054688f216SMatthias Ringwald     if (hci_stack) {
48064688f216SMatthias Ringwald         free(hci_stack);
48074688f216SMatthias Ringwald     }
48084688f216SMatthias Ringwald #endif
48094688f216SMatthias Ringwald     hci_stack = NULL;
4810b5bbcbf4SMatthias Ringwald 
4811b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
48124688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
4813b5bbcbf4SMatthias Ringwald #endif
48144688f216SMatthias Ringwald }
48154688f216SMatthias Ringwald 
48163fb36a29SMatthias Ringwald /**
48173fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
48183fb36a29SMatthias Ringwald  */
48193fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
48203fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
48213fb36a29SMatthias Ringwald 
48223fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
48233fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
48243fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
48253fb36a29SMatthias Ringwald     }
48263fb36a29SMatthias Ringwald }
48273fb36a29SMatthias Ringwald 
48286fe16221SMatthias Ringwald void hci_enable_custom_pre_init(void){
48296fe16221SMatthias Ringwald     hci_stack->chipset_pre_init = true;
48306fe16221SMatthias Ringwald }
48316fe16221SMatthias Ringwald 
4832fb55bd0aSMatthias Ringwald /**
4833d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
4834fb55bd0aSMatthias Ringwald  */
4835fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
4836fb55bd0aSMatthias Ringwald     // references to used control implementation
4837fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
4838d0b87befSMatthias Ringwald     // init with transport config
4839d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
4840fb55bd0aSMatthias Ringwald }
4841fb55bd0aSMatthias Ringwald 
48421f9eb2ccSMatthias Ringwald static void hci_discard_connections(void){
4843346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_t it;
4844346f8c2cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4845346f8c2cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
48461f9eb2ccSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
4847346f8c2cSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
48481f9eb2ccSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
48491f9eb2ccSMatthias Ringwald         hci_shutdown_connection(connection);
48501f9eb2ccSMatthias Ringwald     }
4851346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
4852346f8c2cSMatthias Ringwald     while (hci_stack->iso_streams != NULL){
4853346f8c2cSMatthias Ringwald         hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams);
4854346f8c2cSMatthias Ringwald     }
4855346f8c2cSMatthias Ringwald #endif
48561f9eb2ccSMatthias Ringwald }
48571f9eb2ccSMatthias Ringwald 
485871de195eSMatthias Ringwald void hci_close(void){
4859e6d6524dSMatthias Ringwald 
4860e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
4861404843c1Smatthias.ringwald     // close remote device db
4862a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
4863a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
4864404843c1Smatthias.ringwald     }
4865e6d6524dSMatthias Ringwald #endif
48667224be7eSMatthias Ringwald 
48671f9eb2ccSMatthias Ringwald     hci_discard_connections();
48687224be7eSMatthias Ringwald 
4869f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
48703a9fb326S[email protected] 
48713a9fb326S[email protected] #ifdef HAVE_MALLOC
48723a9fb326S[email protected]     free(hci_stack);
48733a9fb326S[email protected] #endif
48743a9fb326S[email protected]     hci_stack = NULL;
4875404843c1Smatthias.ringwald }
4876404843c1Smatthias.ringwald 
4877cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
4878cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
4879cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
4880cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
4881cb70c5abSMatthias Ringwald }
4882cb70c5abSMatthias Ringwald #endif
4883cb70c5abSMatthias Ringwald 
488435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4885170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
4886170fafaeSMatthias Ringwald     // validate ranage and set
4887170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
4888170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
4889170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
4890170fafaeSMatthias Ringwald }
489178315a58SMatthias Ringwald 
4892137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
4893137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
48945dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
4895137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
4896137715ebSMatthias Ringwald     } else {
4897137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
4898137715ebSMatthias Ringwald     }
48995dbec6b3SMatthias Ringwald }
49005dbec6b3SMatthias Ringwald 
49015dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
49025dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
49035dbec6b3SMatthias Ringwald }
49045dbec6b3SMatthias Ringwald 
490578315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
490678315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
490778315a58SMatthias Ringwald }
490878315a58SMatthias Ringwald 
490978315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
4910d7387af3SMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode){
4911d7387af3SMatthias Ringwald         return LEVEL_4;
4912d7387af3SMatthias Ringwald     }
491378315a58SMatthias Ringwald     return hci_stack->gap_security_level;
491478315a58SMatthias Ringwald }
491530cdf3c6SMatthias Ringwald 
49168ad4dfffSMatthias Ringwald void gap_set_minimal_service_security_level(gap_security_level_t security_level){
49178ad4dfffSMatthias Ringwald     hci_stack->gap_minimal_service_security_level = security_level;
49188ad4dfffSMatthias Ringwald }
49198ad4dfffSMatthias Ringwald 
492030cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
492130cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
492230cdf3c6SMatthias Ringwald }
492330cdf3c6SMatthias Ringwald 
492430cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
492530cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
492630cdf3c6SMatthias Ringwald }
4927170fafaeSMatthias Ringwald #endif
4928170fafaeSMatthias Ringwald 
4929170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
493060b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
49319e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
4932baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE;
493359d59ecfSMatthias Ringwald     hci_run();
49349e61646fS[email protected] }
493576f27cffSMatthias Ringwald 
4936c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
4937c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
4938baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY;
493959d59ecfSMatthias Ringwald     hci_run();
4940c33e56d3SMatthias Ringwald }
4941c33e56d3SMatthias Ringwald 
4942b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
4943b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
4944b4eb4420SMatthias Ringwald }
4945b4eb4420SMatthias Ringwald 
4946b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
4947b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
4948b4eb4420SMatthias Ringwald }
4949b4eb4420SMatthias Ringwald 
49500c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
49510c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
49520c3eb48dSMatthias Ringwald }
49530c3eb48dSMatthias Ringwald 
49549afaa4d4SMatthias Ringwald void gap_enable_link_watchdog(uint16_t timeout_ms){
49559afaa4d4SMatthias Ringwald     hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625
49569afaa4d4SMatthias Ringwald }
49579afaa4d4SMatthias Ringwald 
49589afaa4d4SMatthias Ringwald uint16_t hci_automatic_flush_timeout(void){
49599afaa4d4SMatthias Ringwald     return hci_stack->automatic_flush_timeout;
49609afaa4d4SMatthias Ringwald }
49619afaa4d4SMatthias Ringwald 
496276f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
496376f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
496476f27cffSMatthias Ringwald }
496535454696SMatthias Ringwald #endif
49669e61646fS[email protected] 
49676fad2c37SMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
4968f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
4969f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
49706535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
4971f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
4972f456b2d0S[email protected] }
497376f27cffSMatthias Ringwald #endif
4974f456b2d0S[email protected] 
49758d213e1aSmatthias.ringwald // State-Module-Driver overview
49768d213e1aSmatthias.ringwald // state                    module  low-level
49778d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
49788d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
49798d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
49808d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
4981d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
4982d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
4983c7e0c5f6Smatthias.ringwald 
498440d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
49857301ad89Smatthias.ringwald 
4986038bc64cSmatthias.ringwald     // power on
4987f9a30166Smatthias.ringwald     int err = 0;
49883a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
4989d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
4990f9a30166Smatthias.ringwald     }
4991038bc64cSmatthias.ringwald     if (err){
49929da54300S[email protected]         log_error( "POWER_ON failed");
4993038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
4994038bc64cSmatthias.ringwald         return err;
4995038bc64cSmatthias.ringwald     }
4996038bc64cSmatthias.ringwald 
499724b3c629SMatthias Ringwald     // int chipset driver
49983fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
49993fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
50003fb36a29SMatthias Ringwald     }
50013fb36a29SMatthias Ringwald 
500224b3c629SMatthias Ringwald     // init transport
500324b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
500424b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
500524b3c629SMatthias Ringwald     }
500624b3c629SMatthias Ringwald 
500724b3c629SMatthias Ringwald     // open transport
500824b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
5009038bc64cSmatthias.ringwald     if (err){
50109da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
50113a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5012d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5013f9a30166Smatthias.ringwald         }
5014038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
5015038bc64cSmatthias.ringwald         return err;
5016038bc64cSmatthias.ringwald     }
50178d213e1aSmatthias.ringwald     return 0;
50188d213e1aSmatthias.ringwald }
5019038bc64cSmatthias.ringwald 
502040d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
50218d213e1aSmatthias.ringwald 
50229da54300S[email protected]     log_info("hci_power_control_off");
50239418f9c9Smatthias.ringwald 
50248d213e1aSmatthias.ringwald     // close low-level device
502524b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
50268d213e1aSmatthias.ringwald 
50279da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
50289418f9c9Smatthias.ringwald 
50298d213e1aSmatthias.ringwald     // power off
50303a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
5031d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
50328d213e1aSmatthias.ringwald     }
50339418f9c9Smatthias.ringwald 
50349da54300S[email protected]     log_info("hci_power_control_off - control closed");
50359418f9c9Smatthias.ringwald 
50363a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
503772ea5239Smatthias.ringwald }
503872ea5239Smatthias.ringwald 
503940d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
504072ea5239Smatthias.ringwald 
50419da54300S[email protected]     log_info("hci_power_control_sleep");
50423144bce4Smatthias.ringwald 
5043b429b9b7Smatthias.ringwald #if 0
5044b429b9b7Smatthias.ringwald     // don't close serial port during sleep
5045b429b9b7Smatthias.ringwald 
504672ea5239Smatthias.ringwald     // close low-level device
50473a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
5048b429b9b7Smatthias.ringwald #endif
504972ea5239Smatthias.ringwald 
505072ea5239Smatthias.ringwald     // sleep mode
50513a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
5052d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
505372ea5239Smatthias.ringwald     }
5054b429b9b7Smatthias.ringwald 
50553a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
50568d213e1aSmatthias.ringwald }
50578d213e1aSmatthias.ringwald 
505840d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
5059b429b9b7Smatthias.ringwald 
50609da54300S[email protected]     log_info("hci_power_control_wake");
5061b429b9b7Smatthias.ringwald 
5062b429b9b7Smatthias.ringwald     // wake on
50633a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
5064d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
5065b429b9b7Smatthias.ringwald     }
5066b429b9b7Smatthias.ringwald 
5067b429b9b7Smatthias.ringwald #if 0
5068b429b9b7Smatthias.ringwald     // open low-level device
50693a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
5070b429b9b7Smatthias.ringwald     if (err){
50719da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
50723a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
5073d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
5074b429b9b7Smatthias.ringwald         }
5075b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
5076b429b9b7Smatthias.ringwald         return err;
5077b429b9b7Smatthias.ringwald     }
5078b429b9b7Smatthias.ringwald #endif
5079b429b9b7Smatthias.ringwald 
5080b429b9b7Smatthias.ringwald     return 0;
5081b429b9b7Smatthias.ringwald }
5082b429b9b7Smatthias.ringwald 
50830c88d5efSMatthias Ringwald static void hci_power_enter_initializing_state(void){
508444935e40S[email protected]     // set up state machine
508544935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
508602c7fc01SMatthias Ringwald     hci_stack->hci_packet_buffer_reserved = false;
508744935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
50886fe16221SMatthias Ringwald 
50890535e08cSMatthias Ringwald #ifndef HAVE_HOST_CONTROLLER_API
50906fe16221SMatthias Ringwald     if (hci_stack->chipset_pre_init) {
50916fe16221SMatthias Ringwald         hci_stack->substate = HCI_INIT_CUSTOM_PRE_INIT;
50920535e08cSMatthias Ringwald     } else
50930535e08cSMatthias Ringwald #endif
50940535e08cSMatthias Ringwald     {
50955c363727SMatthias Ringwald         hci_stack->substate = HCI_INIT_SEND_RESET;
509644935e40S[email protected]     }
50976fe16221SMatthias Ringwald }
5098b429b9b7Smatthias.ringwald 
50990c88d5efSMatthias Ringwald static void hci_power_enter_halting_state(void){
51000c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
51011e907691SMatthias Ringwald     // drop entries scheduled for removal, mark others for re-adding
51021e907691SMatthias Ringwald     btstack_linked_list_iterator_t it;
51031e907691SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
51041e907691SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
51051e907691SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
51061e907691SMatthias Ringwald         if ((entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)) == LE_WHITELIST_REMOVE_FROM_CONTROLLER){
51071e907691SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
51081e907691SMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
51091e907691SMatthias Ringwald         } else {
51101e907691SMatthias Ringwald             entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
51111e907691SMatthias Ringwald         }
51121e907691SMatthias Ringwald     }
5113a2c9d908SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5114e8d160b3SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
5115e8d160b3SMatthias Ringwald     const uint8_t mask = LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
5116e8d160b3SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5117e8d160b3SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
5118e8d160b3SMatthias Ringwald         if ((entry->state & mask) == LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER) {
5119e8d160b3SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
5120e8d160b3SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
5121e8d160b3SMatthias Ringwald         } else {
5122e8d160b3SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
5123e8d160b3SMatthias Ringwald             continue;
5124e8d160b3SMatthias Ringwald         }
5125e8d160b3SMatthias Ringwald     }
5126a2c9d908SMatthias Ringwald #endif
51270c88d5efSMatthias Ringwald #endif
5128184dbe2fSMatthias Ringwald     // see hci_run
5129184dbe2fSMatthias Ringwald     hci_stack->state = HCI_STATE_HALTING;
51300c88d5efSMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLASSIC_STOP;
5131184dbe2fSMatthias Ringwald     // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore
5132184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer(&hci_stack->timeout, 1000);
5133184dbe2fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5134184dbe2fSMatthias Ringwald     btstack_run_loop_add_timer(&hci_stack->timeout);
5135184dbe2fSMatthias Ringwald }
5136184dbe2fSMatthias Ringwald 
513742bd3d77SMatthias Ringwald // returns error
513842bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
513942bd3d77SMatthias Ringwald     int err;
51408d213e1aSmatthias.ringwald     switch (power_mode){
51418d213e1aSmatthias.ringwald         case HCI_POWER_ON:
51428d213e1aSmatthias.ringwald             err = hci_power_control_on();
514342bd3d77SMatthias Ringwald             if (err != 0) {
5144f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
514597b61c7bS[email protected]                 return err;
514697b61c7bS[email protected]             }
51470c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
51488d213e1aSmatthias.ringwald             break;
51498d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
51508d213e1aSmatthias.ringwald             // do nothing
51518d213e1aSmatthias.ringwald             break;
51528d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5153b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
51548d213e1aSmatthias.ringwald             break;
51557bbeb3adSMilanka Ringwald         default:
51567bbeb3adSMilanka Ringwald             btstack_assert(false);
51577bbeb3adSMilanka Ringwald             break;
51588d213e1aSmatthias.ringwald     }
515942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
516042bd3d77SMatthias Ringwald }
51617301ad89Smatthias.ringwald 
516242bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
51638d213e1aSmatthias.ringwald     switch (power_mode){
51648d213e1aSmatthias.ringwald         case HCI_POWER_ON:
51658d213e1aSmatthias.ringwald             // do nothing
51668d213e1aSmatthias.ringwald             break;
51678d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
51688d213e1aSmatthias.ringwald             // no connections yet, just turn it off
51698d213e1aSmatthias.ringwald             hci_power_control_off();
51708d213e1aSmatthias.ringwald             break;
51718d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5172b546ac54Smatthias.ringwald             // no connections yet, just turn it off
517372ea5239Smatthias.ringwald             hci_power_control_sleep();
51748d213e1aSmatthias.ringwald             break;
51757bbeb3adSMilanka Ringwald         default:
51767bbeb3adSMilanka Ringwald             btstack_assert(false);
51777bbeb3adSMilanka Ringwald             break;
51788d213e1aSmatthias.ringwald     }
517942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
518042bd3d77SMatthias Ringwald }
51817301ad89Smatthias.ringwald 
518242bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
51838d213e1aSmatthias.ringwald     switch (power_mode){
51848d213e1aSmatthias.ringwald         case HCI_POWER_ON:
51858d213e1aSmatthias.ringwald             // do nothing
51868d213e1aSmatthias.ringwald             break;
51878d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
51880c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
51898d213e1aSmatthias.ringwald             break;
51908d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5191b546ac54Smatthias.ringwald             // see hci_run
51923a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
519374b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
51948d213e1aSmatthias.ringwald             break;
51957bbeb3adSMilanka Ringwald         default:
51967bbeb3adSMilanka Ringwald             btstack_assert(false);
51977bbeb3adSMilanka Ringwald             break;
51988d213e1aSmatthias.ringwald     }
519942bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
520042bd3d77SMatthias Ringwald }
52017301ad89Smatthias.ringwald 
520242bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
52038d213e1aSmatthias.ringwald     switch (power_mode){
52048d213e1aSmatthias.ringwald         case HCI_POWER_ON:
52050c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
52068d213e1aSmatthias.ringwald             break;
52078d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
52088d213e1aSmatthias.ringwald             // do nothing
52098d213e1aSmatthias.ringwald             break;
52108d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5211b546ac54Smatthias.ringwald             // see hci_run
52123a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
521374b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
52148d213e1aSmatthias.ringwald             break;
52157bbeb3adSMilanka Ringwald         default:
52167bbeb3adSMilanka Ringwald             btstack_assert(false);
52177bbeb3adSMilanka Ringwald             break;
52188d213e1aSmatthias.ringwald     }
521900278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
522042bd3d77SMatthias Ringwald }
52218d213e1aSmatthias.ringwald 
522242bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
52238d213e1aSmatthias.ringwald     switch (power_mode){
52248d213e1aSmatthias.ringwald         case HCI_POWER_ON:
52250c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
52268d213e1aSmatthias.ringwald             break;
52278d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
52280c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
52298d213e1aSmatthias.ringwald             break;
52308d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5231b546ac54Smatthias.ringwald             // do nothing
52328d213e1aSmatthias.ringwald             break;
52337bbeb3adSMilanka Ringwald         default:
52347bbeb3adSMilanka Ringwald             btstack_assert(false);
52357bbeb3adSMilanka Ringwald             break;
52368d213e1aSmatthias.ringwald     }
523742bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
523842bd3d77SMatthias Ringwald }
52398d213e1aSmatthias.ringwald 
524042bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
524142bd3d77SMatthias Ringwald     int err;
52428d213e1aSmatthias.ringwald     switch (power_mode){
52438d213e1aSmatthias.ringwald         case HCI_POWER_ON:
52443144bce4Smatthias.ringwald             err = hci_power_control_wake();
52453144bce4Smatthias.ringwald             if (err) return err;
52460c88d5efSMatthias Ringwald             hci_power_enter_initializing_state();
52478d213e1aSmatthias.ringwald             break;
52488d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
52490c88d5efSMatthias Ringwald             hci_power_enter_halting_state();
52508d213e1aSmatthias.ringwald             break;
52518d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
5252b546ac54Smatthias.ringwald             // do nothing
52538d213e1aSmatthias.ringwald             break;
52547bbeb3adSMilanka Ringwald         default:
52557bbeb3adSMilanka Ringwald             btstack_assert(false);
52567bbeb3adSMilanka Ringwald             break;
52578d213e1aSmatthias.ringwald     }
525842bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
525942bd3d77SMatthias Ringwald }
52607bbeb3adSMilanka Ringwald 
526142bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
526242bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
5263bef627f1SMatthias Ringwald     btstack_run_loop_remove_timer(&hci_stack->timeout);
526424f87726SMatthias Ringwald     int err = 0;
526542bd3d77SMatthias Ringwald     switch (hci_stack->state){
526642bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
526742bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
526842bd3d77SMatthias Ringwald             break;
526942bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
527042bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
527142bd3d77SMatthias Ringwald             break;
527242bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
527342bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
527442bd3d77SMatthias Ringwald             break;
527542bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
527642bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
527742bd3d77SMatthias Ringwald             break;
527842bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
527942bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
528042bd3d77SMatthias Ringwald             break;
528142bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
528242bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
528342bd3d77SMatthias Ringwald             break;
52847bbeb3adSMilanka Ringwald         default:
52857bbeb3adSMilanka Ringwald             btstack_assert(false);
52867bbeb3adSMilanka Ringwald             break;
528711e23e5fSmatthias.ringwald     }
528824f87726SMatthias Ringwald     if (err != 0){
528942bd3d77SMatthias Ringwald         return err;
529042bd3d77SMatthias Ringwald     }
529168d92d03Smatthias.ringwald 
5292038bc64cSmatthias.ringwald     // create internal event
5293ee8bf225Smatthias.ringwald 	hci_emit_state();
5294ee8bf225Smatthias.ringwald 
529568d92d03Smatthias.ringwald 	// trigger next/first action
529668d92d03Smatthias.ringwald 	hci_run();
529768d92d03Smatthias.ringwald 
5298475c8125Smatthias.ringwald     return 0;
5299475c8125Smatthias.ringwald }
5300475c8125Smatthias.ringwald 
530135454696SMatthias Ringwald 
5302091e35e3SMatthias Ringwald static void hci_halting_run(void) {
5303091e35e3SMatthias Ringwald 
5304091e35e3SMatthias Ringwald     log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
5305091e35e3SMatthias Ringwald 
5306091e35e3SMatthias Ringwald     hci_connection_t *connection;
5307d5f71a7eSMatthias Ringwald #ifdef ENABLE_BLE
5308d5f71a7eSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5309911801caSMatthias Ringwald     bool stop_advertismenets;
5310d5f71a7eSMatthias Ringwald #endif
5311d5f71a7eSMatthias Ringwald #endif
5312091e35e3SMatthias Ringwald 
5313091e35e3SMatthias Ringwald     switch (hci_stack->substate) {
53140c88d5efSMatthias Ringwald         case HCI_HALTING_CLASSIC_STOP:
53150c88d5efSMatthias Ringwald #ifdef ENABLE_CLASSIC
5316911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5317911801caSMatthias Ringwald 
53180c88d5efSMatthias Ringwald             if (hci_stack->connectable || hci_stack->discoverable){
53190c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
53200c88d5efSMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, 0);
53210c88d5efSMatthias Ringwald                 return;
53220c88d5efSMatthias Ringwald             }
53230c88d5efSMatthias Ringwald #endif
53240c88d5efSMatthias Ringwald             /* fall through */
53250c88d5efSMatthias Ringwald 
53260c88d5efSMatthias Ringwald         case HCI_HALTING_LE_ADV_STOP:
53270c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_ADV_STOP;
53280c88d5efSMatthias Ringwald 
53290c88d5efSMatthias Ringwald #ifdef ENABLE_BLE
53300c88d5efSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5331911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5332911801caSMatthias Ringwald 
5333911801caSMatthias Ringwald             stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0;
5334911801caSMatthias Ringwald 
5335911801caSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5336911801caSMatthias Ringwald             if (hci_extended_advertising_supported()){
5337c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
5338911801caSMatthias Ringwald                 btstack_linked_list_iterator_t it;
5339911801caSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
5340911801caSMatthias Ringwald                 // stop all periodic advertisements and check if an extended set is active
5341911801caSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
5342911801caSMatthias Ringwald                     le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
5343911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
5344911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
5345911801caSMatthias Ringwald                         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle);
53460c88d5efSMatthias Ringwald                         return;
53470c88d5efSMatthias Ringwald                     }
5348911801caSMatthias Ringwald                     if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
5349911801caSMatthias Ringwald                         stop_advertismenets = true;
5350911801caSMatthias Ringwald                         advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5351911801caSMatthias Ringwald                     }
5352911801caSMatthias Ringwald                 }
5353c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
5354911801caSMatthias Ringwald                 if (stop_advertismenets){
5355911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5356911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL);
5357911801caSMatthias Ringwald                     return;
5358911801caSMatthias Ringwald                 }
5359d935373dSMatthias Ringwald             } else
5360a2c9d908SMatthias Ringwald #else /* ENABLE_LE_PERIPHERAL */
5361911801caSMatthias Ringwald             {
5362911801caSMatthias Ringwald                 if (stop_advertismenets) {
5363911801caSMatthias Ringwald                     hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
5364911801caSMatthias Ringwald                     hci_send_cmd(&hci_le_set_advertise_enable, 0);
5365911801caSMatthias Ringwald                     return;
5366911801caSMatthias Ringwald                 }
5367911801caSMatthias Ringwald             }
5368911801caSMatthias Ringwald #endif  /* ENABLE_LE_EXTENDED_ADVERTISING*/
5369911801caSMatthias Ringwald #endif  /* ENABLE_LE_PERIPHERAL */
5370911801caSMatthias Ringwald #endif  /* ENABLE_BLE */
5371911801caSMatthias Ringwald 
53720c88d5efSMatthias Ringwald             /* fall through */
53730c88d5efSMatthias Ringwald 
53740c88d5efSMatthias Ringwald         case HCI_HALTING_LE_SCAN_STOP:
53750c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_LE_SCAN_STOP;
5376911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
5377091e35e3SMatthias Ringwald 
5378091e35e3SMatthias Ringwald #ifdef ENABLE_BLE
5379091e35e3SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
53800c88d5efSMatthias Ringwald             if (hci_stack->le_scanning_active){
5381c42da3bcSMatthias Ringwald                 hci_le_scan_stop();
53820c88d5efSMatthias Ringwald                 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
53830c88d5efSMatthias Ringwald                 return;
53840c88d5efSMatthias Ringwald             }
5385091e35e3SMatthias Ringwald #endif
5386091e35e3SMatthias Ringwald #endif
53870c88d5efSMatthias Ringwald 
53880c88d5efSMatthias Ringwald             /* fall through */
53890c88d5efSMatthias Ringwald 
53900c88d5efSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL:
53910c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL;
5392911801caSMatthias Ringwald             if (!hci_can_send_command_packet_now()) return;
53930c88d5efSMatthias Ringwald 
5394091e35e3SMatthias Ringwald             // close all open connections
5395091e35e3SMatthias Ringwald             connection = (hci_connection_t *) hci_stack->connections;
5396091e35e3SMatthias Ringwald             if (connection) {
5397091e35e3SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
5398091e35e3SMatthias Ringwald 
539903270f05SMatthias Ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u, state %u", connection, con_handle, connection->state);
5400091e35e3SMatthias Ringwald 
540103270f05SMatthias Ringwald                 // check state
540203270f05SMatthias Ringwald                 switch(connection->state) {
540303270f05SMatthias Ringwald                     case SENT_DISCONNECT:
540403270f05SMatthias Ringwald                     case RECEIVED_DISCONNECTION_COMPLETE:
540503270f05SMatthias Ringwald                         // wait until connection is gone
540603270f05SMatthias Ringwald                         return;
540703270f05SMatthias Ringwald                     default:
540803270f05SMatthias Ringwald                         break;
540903270f05SMatthias Ringwald                 }
5410091e35e3SMatthias Ringwald 
5411091e35e3SMatthias Ringwald                 // finally, send the disconnect command
541203270f05SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
5413091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5414091e35e3SMatthias Ringwald                 return;
5415091e35e3SMatthias Ringwald             }
5416091e35e3SMatthias Ringwald 
5417346f8c2cSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
5418346f8c2cSMatthias Ringwald             // stop BIGs and BIG Syncs
5419346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_bigs != NULL){
5420346f8c2cSMatthias Ringwald                 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs;
5421346f8c2cSMatthias Ringwald                 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5422346f8c2cSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5423346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle);
5424346f8c2cSMatthias Ringwald                 return;
5425346f8c2cSMatthias Ringwald             }
5426346f8c2cSMatthias Ringwald             if (hci_stack->le_audio_big_syncs != NULL){
5427346f8c2cSMatthias Ringwald                 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs;
5428346f8c2cSMatthias Ringwald                 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return;
5429346f8c2cSMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
5430346f8c2cSMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
5431346f8c2cSMatthias Ringwald                 return;
5432346f8c2cSMatthias Ringwald             }
5433346f8c2cSMatthias Ringwald #endif
5434346f8c2cSMatthias Ringwald 
5435091e35e3SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
5436091e35e3SMatthias Ringwald 
5437091e35e3SMatthias Ringwald             // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
5438091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING: wait 50 ms");
54390c88d5efSMatthias Ringwald             hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER;
5440091e35e3SMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 50);
5441091e35e3SMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
5442091e35e3SMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
5443091e35e3SMatthias Ringwald             break;
5444091e35e3SMatthias Ringwald 
5445b188b5fcSMatthias Ringwald         case HCI_HALTING_W4_CLOSE_TIMER:
5446b188b5fcSMatthias Ringwald             // keep waiting
5447b188b5fcSMatthias Ringwald             break;
5448b188b5fcSMatthias Ringwald 
5449091e35e3SMatthias Ringwald         case HCI_HALTING_CLOSE:
5450091e35e3SMatthias Ringwald             // close left over connections (that had not been properly closed before)
5451b188b5fcSMatthias Ringwald             hci_stack->substate = HCI_HALTING_CLOSE_DISCARDING_CONNECTIONS;
5452091e35e3SMatthias Ringwald             hci_discard_connections();
5453091e35e3SMatthias Ringwald 
5454091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, calling off");
5455091e35e3SMatthias Ringwald 
5456091e35e3SMatthias Ringwald             // switch mode
5457091e35e3SMatthias Ringwald             hci_power_control_off();
5458091e35e3SMatthias Ringwald 
5459091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, emitting state");
5460091e35e3SMatthias Ringwald             hci_emit_state();
5461091e35e3SMatthias Ringwald             log_info("HCI_STATE_HALTING, done");
5462091e35e3SMatthias Ringwald             break;
5463091e35e3SMatthias Ringwald 
5464091e35e3SMatthias Ringwald         default:
5465091e35e3SMatthias Ringwald             break;
5466091e35e3SMatthias Ringwald     }
5467091e35e3SMatthias Ringwald };
5468091e35e3SMatthias Ringwald 
5469091e35e3SMatthias Ringwald static void hci_falling_asleep_run(void){
5470091e35e3SMatthias Ringwald     hci_connection_t * connection;
5471091e35e3SMatthias Ringwald     switch(hci_stack->substate) {
5472091e35e3SMatthias Ringwald         case HCI_FALLING_ASLEEP_DISCONNECT:
5473091e35e3SMatthias Ringwald             log_info("HCI_STATE_FALLING_ASLEEP");
5474091e35e3SMatthias Ringwald             // close all open connections
5475091e35e3SMatthias Ringwald             connection =  (hci_connection_t *) hci_stack->connections;
5476091e35e3SMatthias Ringwald             if (connection){
5477091e35e3SMatthias Ringwald 
5478091e35e3SMatthias Ringwald                 // send disconnect
5479091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5480091e35e3SMatthias Ringwald 
5481091e35e3SMatthias Ringwald                 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
5482091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
5483091e35e3SMatthias Ringwald 
5484091e35e3SMatthias Ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
5485091e35e3SMatthias Ringwald                 hci_shutdown_connection(connection);
5486091e35e3SMatthias Ringwald                 return;
5487091e35e3SMatthias Ringwald             }
5488091e35e3SMatthias Ringwald 
5489091e35e3SMatthias Ringwald             if (hci_classic_supported()){
5490091e35e3SMatthias Ringwald                 // disable page and inquiry scan
5491091e35e3SMatthias Ringwald                 if (!hci_can_send_command_packet_now()) return;
5492091e35e3SMatthias Ringwald 
5493091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, disabling inq scans");
5494091e35e3SMatthias Ringwald                 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
5495091e35e3SMatthias Ringwald 
5496091e35e3SMatthias Ringwald                 // continue in next sub state
5497091e35e3SMatthias Ringwald                 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
5498091e35e3SMatthias Ringwald                 break;
5499091e35e3SMatthias Ringwald             }
5500091e35e3SMatthias Ringwald 
5501091e35e3SMatthias Ringwald             /* fall through */
5502091e35e3SMatthias Ringwald 
5503091e35e3SMatthias Ringwald             case HCI_FALLING_ASLEEP_COMPLETE:
5504091e35e3SMatthias Ringwald                 log_info("HCI_STATE_HALTING, calling sleep");
5505091e35e3SMatthias Ringwald                 // switch mode
5506091e35e3SMatthias Ringwald                 hci_power_control_sleep();  // changes hci_stack->state to SLEEP
5507091e35e3SMatthias Ringwald                 hci_emit_state();
5508091e35e3SMatthias Ringwald                 break;
5509091e35e3SMatthias Ringwald 
5510091e35e3SMatthias Ringwald                 default:
5511091e35e3SMatthias Ringwald                     break;
5512091e35e3SMatthias Ringwald     }
5513091e35e3SMatthias Ringwald }
5514091e35e3SMatthias Ringwald 
551535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
551635454696SMatthias Ringwald 
5517758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
5518758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
5519a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
5520baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE;
5521758b46ceSmatthias.ringwald     hci_run();
5522758b46ceSmatthias.ringwald }
5523758b46ceSmatthias.ringwald 
552415a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
5525381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
5526381fbed8Smatthias.ringwald 
55273a9fb326S[email protected]     if (hci_stack->discoverable == enable){
552871fd255dSMatthias Ringwald         hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable);
5529381fbed8Smatthias.ringwald         return;
5530381fbed8Smatthias.ringwald     }
5531381fbed8Smatthias.ringwald 
55323a9fb326S[email protected]     hci_stack->discoverable = enable;
5533758b46ceSmatthias.ringwald     hci_update_scan_enable();
5534758b46ceSmatthias.ringwald }
5535b031bebbSmatthias.ringwald 
553615a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
5537758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
5538758b46ceSmatthias.ringwald 
5539758b46ceSmatthias.ringwald     // don't emit event
55403a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
5541758b46ceSmatthias.ringwald 
55423a9fb326S[email protected]     hci_stack->connectable = enable;
5543758b46ceSmatthias.ringwald     hci_update_scan_enable();
5544381fbed8Smatthias.ringwald }
554535454696SMatthias Ringwald #endif
5546381fbed8Smatthias.ringwald 
554715a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
55486535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
55495061f3afS[email protected] }
55505061f3afS[email protected] 
55512b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
55522b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
55532b838201SMatthias Ringwald 
55542b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
55552b838201SMatthias Ringwald     hci_reserve_packet_buffer();
55562b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
55572b838201SMatthias Ringwald 
55582b838201SMatthias Ringwald     uint16_t size = 0;
55592b838201SMatthias Ringwald     uint16_t num_handles = 0;
55602b838201SMatthias Ringwald     packet[size++] = 0x35;
55612b838201SMatthias Ringwald     packet[size++] = 0x0c;
55622b838201SMatthias Ringwald     size++;  // skip param len
55632b838201SMatthias Ringwald     size++;  // skip num handles
55642b838201SMatthias Ringwald 
55652b838201SMatthias Ringwald     // add { handle, packets } entries
55662b838201SMatthias Ringwald     btstack_linked_item_t * it;
55672b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
55682b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
55692b838201SMatthias Ringwald         if (connection->num_packets_completed){
55702b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
55712b838201SMatthias Ringwald             size += 2;
55722b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
55732b838201SMatthias Ringwald             size += 2;
55742b838201SMatthias Ringwald             //
55752b838201SMatthias Ringwald             num_handles++;
55762b838201SMatthias Ringwald             connection->num_packets_completed = 0;
55772b838201SMatthias Ringwald         }
55782b838201SMatthias Ringwald     }
55792b838201SMatthias Ringwald 
55802b838201SMatthias Ringwald     packet[2] = size - 3;
55812b838201SMatthias Ringwald     packet[3] = num_handles;
55822b838201SMatthias Ringwald 
55832b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
55842b838201SMatthias Ringwald 
55852b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
55862b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
55872b838201SMatthias Ringwald 
55882b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
55892b838201SMatthias Ringwald     if (hci_transport_synchronous()){
5590e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5591068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
55922b838201SMatthias Ringwald     }
55932b838201SMatthias Ringwald }
55942b838201SMatthias Ringwald #endif
55952b838201SMatthias Ringwald 
559626fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
559726fe9592SMatthias Ringwald     UNUSED(ds);
559826fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
5599f021201aSMatthias Ringwald     hci_halting_run();
560026fe9592SMatthias Ringwald }
560126fe9592SMatthias Ringwald 
5602f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
56034ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
5604b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
5605b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
5606b5d8b22bS[email protected]         if (connection) {
560728a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
5608b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
5609f30077b7SMatthias Ringwald                 return true;
5610b5d8b22bS[email protected]             }
561128a0332dSMatthias Ringwald         } else {
5612b5d8b22bS[email protected]             // connection gone -> discard further fragments
561328a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
5614b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
5615b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
5616b5d8b22bS[email protected]         }
5617b5d8b22bS[email protected]     }
5618f30077b7SMatthias Ringwald     return false;
56192b838201SMatthias Ringwald }
5620b031bebbSmatthias.ringwald 
562168ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
562268ab6207SMatthias Ringwald static bool hci_run_iso_fragments(void){
562368ab6207SMatthias Ringwald     if (hci_stack->iso_fragmentation_total_size > 0u) {
562468ab6207SMatthias Ringwald         // TODO: flow control
562568ab6207SMatthias Ringwald         if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){
562668ab6207SMatthias Ringwald             hci_send_iso_packet_fragments();
562768ab6207SMatthias Ringwald             return true;
562868ab6207SMatthias Ringwald         }
562968ab6207SMatthias Ringwald     }
563068ab6207SMatthias Ringwald     return false;
563168ab6207SMatthias Ringwald }
563268ab6207SMatthias Ringwald #endif
563368ab6207SMatthias Ringwald 
563435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
56356c0d5426SMatthias Ringwald 
56366c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
56376c0d5426SMatthias Ringwald static bool hci_classic_operation_active(void) {
56386c0d5426SMatthias Ringwald     if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){
56396c0d5426SMatthias Ringwald         return true;
56406c0d5426SMatthias Ringwald     }
56416c0d5426SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
56426c0d5426SMatthias Ringwald         return true;
56436c0d5426SMatthias Ringwald     }
56446c0d5426SMatthias Ringwald     btstack_linked_item_t * it;
56456c0d5426SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) {
56466c0d5426SMatthias Ringwald         hci_connection_t *connection = (hci_connection_t *) it;
56476c0d5426SMatthias Ringwald         switch (connection->state) {
56486c0d5426SMatthias Ringwald             case SENT_CREATE_CONNECTION:
56496c0d5426SMatthias Ringwald             case SENT_CANCEL_CONNECTION:
56506c0d5426SMatthias Ringwald             case SENT_DISCONNECT:
56516c0d5426SMatthias Ringwald                 return true;
56526c0d5426SMatthias Ringwald             default:
56536c0d5426SMatthias Ringwald                 break;
56546c0d5426SMatthias Ringwald         }
56556c0d5426SMatthias Ringwald     }
56566c0d5426SMatthias Ringwald     return false;
56576c0d5426SMatthias Ringwald }
56586c0d5426SMatthias Ringwald #endif
56596c0d5426SMatthias Ringwald 
5660f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
5661f30077b7SMatthias Ringwald 
566259d59ecfSMatthias Ringwald     // assert stack is working and classic is active
566359d59ecfSMatthias Ringwald     if (hci_classic_supported() == false)      return false;
566459d59ecfSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
566559d59ecfSMatthias Ringwald 
5666b031bebbSmatthias.ringwald     // decline incoming connections
56673a9fb326S[email protected]     if (hci_stack->decline_reason){
56683a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
56693a9fb326S[email protected]         hci_stack->decline_reason = 0;
56703a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
5671f30077b7SMatthias Ringwald         return true;
5672ce4c8fabSmatthias.ringwald     }
567359d59ecfSMatthias Ringwald 
5674baa4881eSMatthias Ringwald     if (hci_stack->gap_tasks_classic != 0){
5675ab4831a3SMatthias Ringwald         hci_run_gap_tasks_classic();
5676f30077b7SMatthias Ringwald         return true;
5677b031bebbSmatthias.ringwald     }
567827741fe7SMatthias Ringwald 
5679f5875de5SMatthias Ringwald     // start/stop inquiry
5680a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
56816c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
56826c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
56836c0d5426SMatthias Ringwald #endif
56846c0d5426SMatthias Ringwald         {
5685f5875de5SMatthias Ringwald             uint8_t duration = hci_stack->inquiry_state;
5686beb3c81dSMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
568730199e24SMatthias Ringwald             if (hci_stack->inquiry_max_period_length != 0){
568830199e24SMatthias 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);
568930199e24SMatthias Ringwald             } else {
5690496bb884SMatthias Ringwald                 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
569130199e24SMatthias Ringwald             }
5692f30077b7SMatthias Ringwald             return true;
5693f5875de5SMatthias Ringwald         }
56946c0d5426SMatthias Ringwald     }
5695f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
5696f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
5697f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
5698f30077b7SMatthias Ringwald         return true;
5699f5875de5SMatthias Ringwald     }
570030199e24SMatthias Ringwald 
570130199e24SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){
5702bc06f564SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
570330199e24SMatthias Ringwald         hci_send_cmd(&hci_exit_periodic_inquiry_mode);
570430199e24SMatthias Ringwald         return true;
570530199e24SMatthias Ringwald     }
570630199e24SMatthias Ringwald 
5707b7f1ee76SMatthias Ringwald     // remote name request
5708b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
57096c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
57106c0d5426SMatthias Ringwald         if (hci_classic_operation_active() == false)
57116c0d5426SMatthias Ringwald #endif
57126c0d5426SMatthias Ringwald         {
5713b7f1ee76SMatthias Ringwald             hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
5714b7f1ee76SMatthias Ringwald             hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
5715ee8a36c8SMatthias Ringwald                          hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
5716f30077b7SMatthias Ringwald             return true;
5717b7f1ee76SMatthias Ringwald         }
57186c0d5426SMatthias Ringwald     }
5719cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
5720cf01e888SMatthias Ringwald     // Local OOB data
572159d59ecfSMatthias Ringwald     if (hci_stack->classic_read_local_oob_data){
5722cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
57231e83575aSMatthias Ringwald         if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){
5724cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
5725cf01e888SMatthias Ringwald         } else {
5726cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
5727cf01e888SMatthias Ringwald         }
5728cf01e888SMatthias Ringwald     }
5729cf01e888SMatthias Ringwald #endif
57300a51f88bSMatthias Ringwald     // pairing
57310a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
57320a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
57333f659ee4SMilanka Ringwald         uint8_t pin_code[16];
57340a51f88bSMatthias Ringwald         switch (state){
57350a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
5736cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
57373f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
57383f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
57393f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
57400a51f88bSMatthias Ringwald                 break;
57410a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
5742cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
57430a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
57440a51f88bSMatthias Ringwald                 break;
57450a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
5746cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
5747d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
57480a51f88bSMatthias Ringwald                 break;
57490a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
5750cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
57510a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
57520a51f88bSMatthias Ringwald                 break;
57530a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
5754cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
57550a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
57560a51f88bSMatthias Ringwald                 break;
57570a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
5758cc15bb2cSMatthias Ringwald                 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE;
57590a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
57600a51f88bSMatthias Ringwald                 break;
57610a51f88bSMatthias Ringwald             default:
57620a51f88bSMatthias Ringwald                 break;
57630a51f88bSMatthias Ringwald         }
5764f30077b7SMatthias Ringwald         return true;
5765f30077b7SMatthias Ringwald     }
5766f30077b7SMatthias Ringwald     return false;
57670a51f88bSMatthias Ringwald }
576835454696SMatthias Ringwald #endif
5769b031bebbSmatthias.ringwald 
5770a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
5771be7ef9d8SMatthias Ringwald 
57727eb5b27eSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
57737eb5b27eSMatthias Ringwald static uint8_t hci_le_num_phys(uint8_t phys){
57747eb5b27eSMatthias Ringwald     const uint8_t num_bits_set[] = { 0, 1, 1, 2, 1, 2, 2, 3 };
57757eb5b27eSMatthias Ringwald     btstack_assert(phys);
57767eb5b27eSMatthias Ringwald     return num_bits_set[phys];
57777eb5b27eSMatthias Ringwald }
57787eb5b27eSMatthias Ringwald #endif
57797eb5b27eSMatthias Ringwald 
5780c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5781c42da3bcSMatthias Ringwald static void hci_le_scan_stop(void){
5782c42da3bcSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5783c42da3bcSMatthias Ringwald     if (hci_extended_advertising_supported()) {
5784c42da3bcSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0);
5785c42da3bcSMatthias Ringwald     } else
5786c42da3bcSMatthias Ringwald #endif
5787c42da3bcSMatthias Ringwald     {
5788c42da3bcSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
5789c42da3bcSMatthias Ringwald     }
5790c42da3bcSMatthias Ringwald }
5791327f7f07SMatthias Ringwald 
5792f346015eSMatthias Ringwald static void
5793f346015eSMatthias Ringwald hci_send_le_create_connection(uint8_t initiator_filter_policy, bd_addr_type_t address_type, uint8_t *address) {
5794327f7f07SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5795327f7f07SMatthias Ringwald     if (hci_extended_advertising_supported()) {
57967eb5b27eSMatthias Ringwald         // prepare arrays for all phys (LE Coded, LE 1M, LE 2M PHY)
57977eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_interval[3];
57987eb5b27eSMatthias Ringwald         uint16_t le_connection_scan_window[3];
57997eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_min[3];
58007eb5b27eSMatthias Ringwald         uint16_t le_connection_interval_max[3];
58017eb5b27eSMatthias Ringwald         uint16_t le_connection_latency[3];
58027eb5b27eSMatthias Ringwald         uint16_t le_supervision_timeout[3];
58037eb5b27eSMatthias Ringwald         uint16_t le_minimum_ce_length[3];
58047eb5b27eSMatthias Ringwald         uint16_t le_maximum_ce_length[3];
58057eb5b27eSMatthias Ringwald 
58067eb5b27eSMatthias Ringwald         uint8_t i;
58077eb5b27eSMatthias Ringwald         uint8_t num_phys = hci_le_num_phys(hci_stack->le_connection_phys);
58087eb5b27eSMatthias Ringwald         for (i=0;i<num_phys;i++){
58097eb5b27eSMatthias Ringwald             le_connection_scan_interval[i] = hci_stack->le_connection_scan_interval;
58107eb5b27eSMatthias Ringwald             le_connection_scan_window[i]   = hci_stack->le_connection_scan_window;
58117eb5b27eSMatthias Ringwald             le_connection_interval_min[i]  = hci_stack->le_connection_interval_min;
58127eb5b27eSMatthias Ringwald             le_connection_interval_max[i]  = hci_stack->le_connection_interval_max;
58137eb5b27eSMatthias Ringwald             le_connection_latency[i]       = hci_stack->le_connection_latency;
58147eb5b27eSMatthias Ringwald             le_supervision_timeout[i]      = hci_stack->le_supervision_timeout;
58157eb5b27eSMatthias Ringwald             le_minimum_ce_length[i]        = hci_stack->le_minimum_ce_length;
58167eb5b27eSMatthias Ringwald             le_maximum_ce_length[i]        = hci_stack->le_maximum_ce_length;
58177eb5b27eSMatthias Ringwald         }
5818327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_extended_create_connection,
5819f346015eSMatthias Ringwald                      initiator_filter_policy,
5820327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
5821f346015eSMatthias Ringwald                      address_type,                  // peer address type
5822f346015eSMatthias Ringwald                      address,                       // peer bd addr
58237eb5b27eSMatthias Ringwald                      hci_stack->le_connection_phys, // initiating PHY
5824327f7f07SMatthias Ringwald                      le_connection_scan_interval,   // conn scan interval
5825327f7f07SMatthias Ringwald                      le_connection_scan_window,     // conn scan windows
5826327f7f07SMatthias Ringwald                      le_connection_interval_min,    // conn interval min
5827327f7f07SMatthias Ringwald                      le_connection_interval_max,    // conn interval max
5828327f7f07SMatthias Ringwald                      le_connection_latency,         // conn latency
5829327f7f07SMatthias Ringwald                      le_supervision_timeout,        // conn latency
5830327f7f07SMatthias Ringwald                      le_minimum_ce_length,          // min ce length
5831327f7f07SMatthias Ringwald                      le_maximum_ce_length           // max ce length
5832327f7f07SMatthias Ringwald         );
5833d935373dSMatthias Ringwald     } else
5834327f7f07SMatthias Ringwald #endif
5835327f7f07SMatthias Ringwald     {
5836327f7f07SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
5837327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_interval,  // conn scan interval
5838327f7f07SMatthias Ringwald                      hci_stack->le_connection_scan_window,    // conn scan windows
5839f346015eSMatthias Ringwald                      initiator_filter_policy,                 // don't use whitelist
5840f346015eSMatthias Ringwald                      address_type,                            // peer address type
5841f346015eSMatthias Ringwald                      address,                                 // peer bd addr
5842327f7f07SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,  // our addr type:
5843327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_min,   // conn interval min
5844327f7f07SMatthias Ringwald                      hci_stack->le_connection_interval_max,   // conn interval max
5845327f7f07SMatthias Ringwald                      hci_stack->le_connection_latency,        // conn latency
5846327f7f07SMatthias Ringwald                      hci_stack->le_supervision_timeout,       // conn latency
5847327f7f07SMatthias Ringwald                      hci_stack->le_minimum_ce_length,         // min ce length
5848327f7f07SMatthias Ringwald                      hci_stack->le_maximum_ce_length          // max ce length
5849327f7f07SMatthias Ringwald         );
5850327f7f07SMatthias Ringwald     }
5851327f7f07SMatthias Ringwald }
5852c42da3bcSMatthias Ringwald #endif
5853c42da3bcSMatthias Ringwald 
5854be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5855be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5856be7ef9d8SMatthias Ringwald uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){
5857be7ef9d8SMatthias Ringwald     uint8_t  operation = 0;
5858be7ef9d8SMatthias Ringwald     if (pos == 0){
5859be7ef9d8SMatthias Ringwald         // first fragment or complete data
5860be7ef9d8SMatthias Ringwald         operation |= 1;
5861be7ef9d8SMatthias Ringwald     }
5862be7ef9d8SMatthias Ringwald     if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){
5863be7ef9d8SMatthias Ringwald         // last fragment or complete data
5864be7ef9d8SMatthias Ringwald         operation |= 2;
5865be7ef9d8SMatthias Ringwald     }
5866be7ef9d8SMatthias Ringwald     return operation;
5867be7ef9d8SMatthias Ringwald }
5868be7ef9d8SMatthias Ringwald #endif
5869be7ef9d8SMatthias Ringwald #endif
5870be7ef9d8SMatthias Ringwald 
5871f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
5872f30077b7SMatthias Ringwald 
5873f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t lit;
5874f40c73b4SMatthias Ringwald 
58752052d96cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
58762052d96cSMatthias Ringwald     if (hci_stack->le_resolvable_private_address_update_s > 0){
58772052d96cSMatthias Ringwald         uint16_t update_s = hci_stack->le_resolvable_private_address_update_s;
58782052d96cSMatthias Ringwald         hci_stack->le_resolvable_private_address_update_s = 0;
58792052d96cSMatthias Ringwald         hci_send_cmd(&hci_le_set_resolvable_private_address_timeout, update_s);
58802052d96cSMatthias Ringwald         return true;
58812052d96cSMatthias Ringwald     }
58822052d96cSMatthias Ringwald #endif
58832052d96cSMatthias Ringwald 
5884a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
5885a41310b7SMatthias Ringwald 
588649a6c69cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5887a41310b7SMatthias Ringwald     bool scanning_stop = false;
5888a41310b7SMatthias Ringwald     bool connecting_stop = false;
5889be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
5890c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
58914bafedd5SMatthias Ringwald     bool periodic_sync_stop = false;
58924bafedd5SMatthias Ringwald #endif
5893be7ef9d8SMatthias Ringwald #endif
5894c814a904SMatthias Ringwald #endif
5895be7ef9d8SMatthias Ringwald 
589649a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
589749a6c69cSMatthias Ringwald     bool advertising_stop = false;
589849a6c69cSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
589949a6c69cSMatthias Ringwald     le_advertising_set_t * advertising_stop_set = NULL;
590049a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
590149a6c69cSMatthias Ringwald     bool periodic_advertising_stop = false;
5902a41310b7SMatthias Ringwald #endif
590349a6c69cSMatthias Ringwald #endif
5904a41310b7SMatthias Ringwald #endif
5905a41310b7SMatthias Ringwald 
59069136bde8SMatthias Ringwald     // check if own address changes
59079ce6dfa1SMatthias Ringwald     uint8_t address_change_mask = LE_ADVERTISEMENT_TASKS_SET_ADDRESS | LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
59089ce6dfa1SMatthias Ringwald     bool random_address_change = (hci_stack->le_advertisements_todo & address_change_mask) != 0;
59099136bde8SMatthias Ringwald 
591029c24bebSMatthias Ringwald     // check if whitelist needs modification
591129c24bebSMatthias Ringwald     bool whitelist_modification_pending = false;
591229c24bebSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
591329c24bebSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
591429c24bebSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
591529c24bebSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
591629c24bebSMatthias Ringwald             whitelist_modification_pending = true;
591729c24bebSMatthias Ringwald             break;
591829c24bebSMatthias Ringwald         }
591929c24bebSMatthias Ringwald     }
5920f40c73b4SMatthias Ringwald 
592121debf25SMatthias Ringwald     // check if resolving list needs modification
592221debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
592321debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
59241ffa425cSMatthias Ringwald     bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE);
5925ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
592621debf25SMatthias Ringwald         resolving_list_modification_pending = true;
592721debf25SMatthias Ringwald     }
592821debf25SMatthias Ringwald #endif
592929c24bebSMatthias Ringwald 
5930f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
593149a6c69cSMatthias Ringwald 
5932f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
593349a6c69cSMatthias Ringwald     // check if periodic advertiser list needs modification
5934f40c73b4SMatthias Ringwald     bool periodic_list_modification_pending = false;
5935f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
5936f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
5937f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
5938f40c73b4SMatthias Ringwald         if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){
5939f40c73b4SMatthias Ringwald             periodic_list_modification_pending = true;
5940f40c73b4SMatthias Ringwald             break;
5941f40c73b4SMatthias Ringwald         }
5942f40c73b4SMatthias Ringwald     }
5943f40c73b4SMatthias Ringwald #endif
5944f40c73b4SMatthias Ringwald 
5945fde725feSMatthias Ringwald     // scanning control
59463251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
594729c24bebSMatthias Ringwald         // stop if:
594829c24bebSMatthias Ringwald         // - parameter change required
594929c24bebSMatthias Ringwald         // - it's disabled
595029c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
595121debf25SMatthias Ringwald         // - resolving list modified
595251e51a58SMatthias Ringwald         // - own address changes
595329c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
595421debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
595521debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
5956d54b2c94SMatthias Ringwald             (scanning_uses_whitelist && whitelist_modification_pending) ||
595751e51a58SMatthias Ringwald             resolving_list_modification_pending ||
595851e51a58SMatthias Ringwald             random_address_change){
595921debf25SMatthias Ringwald 
59602d5c2a27SMatthias Ringwald             scanning_stop = true;
5961fde725feSMatthias Ringwald         }
5962fde725feSMatthias Ringwald     }
5963fde725feSMatthias Ringwald 
596429c24bebSMatthias Ringwald     // connecting control
5965f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
5966f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
5967f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
5968f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
5969af64f147SMatthias Ringwald             // stop connecting if:
5970af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
5971af64f147SMatthias Ringwald             // - if it got disabled
597221debf25SMatthias Ringwald             // - resolving list modified
597351e51a58SMatthias Ringwald             // - own address changes
5974f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
5975f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
597621debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
597751e51a58SMatthias Ringwald                 resolving_list_modification_pending ||
597851e51a58SMatthias Ringwald                 random_address_change) {
597921debf25SMatthias Ringwald 
598029c24bebSMatthias Ringwald                 connecting_stop = true;
598129c24bebSMatthias Ringwald             }
5982f496d06eSMatthias Ringwald             break;
5983f496d06eSMatthias Ringwald         default:
5984f496d06eSMatthias Ringwald             break;
598529c24bebSMatthias Ringwald     }
598649a6c69cSMatthias Ringwald 
59874bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
598849a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
59894bafedd5SMatthias Ringwald     // periodic sync control
59904bafedd5SMatthias Ringwald     bool sync_with_advertiser_list;
59914bafedd5SMatthias Ringwald     switch(hci_stack->le_periodic_sync_state){
59924bafedd5SMatthias Ringwald         case LE_CONNECTING_DIRECT:
59934bafedd5SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
599449a6c69cSMatthias Ringwald             // stop sync if:
59954bafedd5SMatthias Ringwald             // - sync with advertiser list and advertiser list modification pending
599649a6c69cSMatthias Ringwald             // - if it got disabled
59974bafedd5SMatthias Ringwald             sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST;
59984bafedd5SMatthias Ringwald             if ((sync_with_advertiser_list && periodic_list_modification_pending) ||
59994bafedd5SMatthias Ringwald                     (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){
60004bafedd5SMatthias Ringwald                 periodic_sync_stop = true;
60014bafedd5SMatthias Ringwald             }
60024bafedd5SMatthias Ringwald             break;
60034bafedd5SMatthias Ringwald         default:
60044bafedd5SMatthias Ringwald             break;
60054bafedd5SMatthias Ringwald     }
60064bafedd5SMatthias Ringwald #endif
6007d70217a2SMatthias Ringwald #endif
600829c24bebSMatthias Ringwald 
600949a6c69cSMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
601049a6c69cSMatthias Ringwald 
6011d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
601245c102fdSMatthias Ringwald     // le advertisement control
6013935aa76eSMatthias Ringwald     if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){
601429c24bebSMatthias Ringwald         // stop if:
601529c24bebSMatthias Ringwald         // - parameter change required
60169136bde8SMatthias Ringwald         // - random address used in advertising and changes
601729c24bebSMatthias Ringwald         // - it's disabled
6018ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
601921debf25SMatthias Ringwald         // - resolving list modified
602051e51a58SMatthias Ringwald         // - own address changes
6021a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
60229136bde8SMatthias Ringwald         bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC;
60234e5d21eaSMatthias Ringwald         bool advertising_change    = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS)  != 0;
6024a61834b6SMatthias Ringwald         if (advertising_change ||
60259136bde8SMatthias Ringwald             (advertising_uses_random_address && random_address_change) ||
6026a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
60279136bde8SMatthias Ringwald             (advertising_uses_whitelist && whitelist_modification_pending) ||
602851e51a58SMatthias Ringwald             resolving_list_modification_pending ||
602951e51a58SMatthias Ringwald             random_address_change) {
603021debf25SMatthias Ringwald 
6031fde725feSMatthias Ringwald             advertising_stop = true;
6032fde725feSMatthias Ringwald         }
6033fde725feSMatthias Ringwald     }
6034be7ef9d8SMatthias Ringwald 
6035be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6036be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported() && (advertising_stop == false)){
6037be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6038be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6039be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6040be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
604153f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) {
6042be7ef9d8SMatthias Ringwald                 // stop if:
6043be7ef9d8SMatthias Ringwald                 // - parameter change required
6044be7ef9d8SMatthias Ringwald                 // - random address used in connectable advertising and changes
6045be7ef9d8SMatthias Ringwald                 // - it's disabled
6046be7ef9d8SMatthias Ringwald                 // - whitelist change required but used for advertisement filter policy
6047be7ef9d8SMatthias Ringwald                 // - resolving list modified
6048be7ef9d8SMatthias Ringwald                 // - own address changes
6049be7ef9d8SMatthias Ringwald                 // - advertisement set will be removed
605057a04237SMatthias Ringwald                 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0;
605157a04237SMatthias Ringwald                 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0;
605253f240c0SMatthias Ringwald                 bool advertising_uses_random_address =
605353f240c0SMatthias Ringwald                         (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) &&
605453f240c0SMatthias Ringwald                         advertising_connectable;
6055be7ef9d8SMatthias Ringwald                 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
6056be7ef9d8SMatthias Ringwald                 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0;
605753f240c0SMatthias Ringwald                 bool advertising_set_random_address_change =
605853f240c0SMatthias Ringwald                         (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0;
605953f240c0SMatthias Ringwald                 bool advertising_set_will_be_removed =
606053f240c0SMatthias Ringwald                         (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0;
6061be7ef9d8SMatthias Ringwald                 if (advertising_parameter_change ||
6062be7ef9d8SMatthias Ringwald                     (advertising_uses_random_address && advertising_set_random_address_change) ||
6063be7ef9d8SMatthias Ringwald                     (advertising_enabled == false) ||
6064be7ef9d8SMatthias Ringwald                     (advertising_uses_whitelist && whitelist_modification_pending) ||
6065be7ef9d8SMatthias Ringwald                     resolving_list_modification_pending ||
6066be7ef9d8SMatthias Ringwald                     advertising_set_will_be_removed) {
6067be7ef9d8SMatthias Ringwald 
6068be7ef9d8SMatthias Ringwald                     advertising_stop = true;
6069be7ef9d8SMatthias Ringwald                     advertising_stop_set = advertising_set;
6070be7ef9d8SMatthias Ringwald                     break;
6071be7ef9d8SMatthias Ringwald                 }
6072be7ef9d8SMatthias Ringwald             }
6073c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
607453f240c0SMatthias Ringwald             if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) {
607553f240c0SMatthias Ringwald                 // stop if:
607653f240c0SMatthias Ringwald                 // - it's disabled
607753f240c0SMatthias Ringwald                 // - parameter change required
607853f240c0SMatthias Ringwald                 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0;
607953f240c0SMatthias Ringwald                 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0;
608053f240c0SMatthias Ringwald                 if ((periodic_enabled == false) || periodic_parameter_change){
608149a6c69cSMatthias Ringwald                     periodic_advertising_stop = true;
608253f240c0SMatthias Ringwald                     advertising_stop_set = advertising_set;
608353f240c0SMatthias Ringwald                 }
608453f240c0SMatthias Ringwald             }
608549a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
608653f240c0SMatthias Ringwald         }
6087be7ef9d8SMatthias Ringwald     }
6088be7ef9d8SMatthias Ringwald #endif
6089be7ef9d8SMatthias Ringwald 
6090a41310b7SMatthias Ringwald #endif
6091fde725feSMatthias Ringwald 
6092a41310b7SMatthias Ringwald 
6093a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
6094a41310b7SMatthias Ringwald 
6095131d4778SMatthias Ringwald 
6096131d4778SMatthias Ringwald     // 2.1 Outgoing connection
6097131d4778SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6098131d4778SMatthias Ringwald     if (connecting_stop){
6099131d4778SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
6100131d4778SMatthias Ringwald         return true;
6101131d4778SMatthias Ringwald     }
6102131d4778SMatthias Ringwald #endif
6103131d4778SMatthias Ringwald 
6104131d4778SMatthias Ringwald     // 2.2 Scanning
6105a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6106a41310b7SMatthias Ringwald     if (scanning_stop){
61075226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
6108c42da3bcSMatthias Ringwald         hci_le_scan_stop();
6109a41310b7SMatthias Ringwald         return true;
6110a41310b7SMatthias Ringwald     }
6111a41310b7SMatthias Ringwald 
6112131d4778SMatthias Ringwald     // 2.3 Periodic Sync
61134bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
611449a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
611549a6c69cSMatthias Ringwald         uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle;
611649a6c69cSMatthias Ringwald         hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID;
611749a6c69cSMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle);
611849a6c69cSMatthias Ringwald         return true;
611949a6c69cSMatthias Ringwald     }
612049a6c69cSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
61214bafedd5SMatthias Ringwald     if (periodic_sync_stop){
61224bafedd5SMatthias Ringwald         hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL;
61234bafedd5SMatthias Ringwald         hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel);
61244bafedd5SMatthias Ringwald         return true;
61254bafedd5SMatthias Ringwald     }
612649a6c69cSMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6127a8016f96SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6128a8016f96SMatthias Ringwald #endif /* ENABLE_LE_CENTRAL */
6129a41310b7SMatthias Ringwald 
6130131d4778SMatthias Ringwald     // 2.4 Advertising: legacy, extended, periodic
6131a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6132fde725feSMatthias Ringwald     if (advertising_stop){
6133e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6134e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()) {
6135be7ef9d8SMatthias Ringwald             uint8_t advertising_stop_handle;
6136be7ef9d8SMatthias Ringwald             if (advertising_stop_set != NULL){
6137be7ef9d8SMatthias Ringwald                 advertising_stop_handle = advertising_stop_set->advertising_handle;
6138be7ef9d8SMatthias Ringwald                 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6139be7ef9d8SMatthias Ringwald             } else {
6140be7ef9d8SMatthias Ringwald                 advertising_stop_handle = 0;
6141be7ef9d8SMatthias Ringwald                 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
6142be7ef9d8SMatthias Ringwald             }
6143be7ef9d8SMatthias Ringwald             const uint8_t advertising_handles[] = { advertising_stop_handle };
6144e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6145e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6146e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events);
6147e464cd48SMatthias Ringwald         } else
6148e464cd48SMatthias Ringwald #endif
6149e464cd48SMatthias Ringwald         {
6150be7ef9d8SMatthias Ringwald             hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE;
615145c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
6152e464cd48SMatthias Ringwald         }
6153f30077b7SMatthias Ringwald         return true;
615445c102fdSMatthias Ringwald     }
615553f240c0SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6156c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
615749a6c69cSMatthias Ringwald     if (periodic_advertising_stop){
615853f240c0SMatthias Ringwald         advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
615953f240c0SMatthias Ringwald         hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle);
616053f240c0SMatthias Ringwald         return true;
616153f240c0SMatthias Ringwald     }
6162c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6163c814a904SMatthias Ringwald #endif /* ENABLE_LE_EXTENDED_ADVERTISING */
6164a8016f96SMatthias Ringwald #endif /* ENABLE_LE_PERIPHERAL */
6165fde725feSMatthias Ringwald 
6166131d4778SMatthias Ringwald 
6167a41310b7SMatthias Ringwald     // Phase 3: modify
6168a41310b7SMatthias Ringwald 
616964f9dabaSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS){
61709136bde8SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
61719136bde8SMatthias Ringwald         hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address);
6172ae35a99cSMatthias Ringwald #ifdef ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE
6173ae35a99cSMatthias Ringwald         // workaround: on some Controllers, address in advertisements is updated only after next dv params set
6174ae35a99cSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6175ae35a99cSMatthias Ringwald #endif
61769136bde8SMatthias Ringwald         return true;
61779136bde8SMatthias Ringwald     }
61789136bde8SMatthias Ringwald 
6179a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6180a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
6181a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
618263671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
618363671e69SMatthias Ringwald         if (hci_extended_advertising_supported()){
61847eb5b27eSMatthias Ringwald             // prepare arrays for all phys (LE Coded and LE 1M PHY)
61857eb5b27eSMatthias Ringwald             uint8_t  scan_types[2];
61867eb5b27eSMatthias Ringwald             uint16_t scan_intervals[2];
61877eb5b27eSMatthias Ringwald             uint16_t scan_windows[2];
61887eb5b27eSMatthias Ringwald 
61897eb5b27eSMatthias Ringwald             uint8_t i;
61907eb5b27eSMatthias Ringwald             uint8_t num_phys = hci_le_num_phys(hci_stack->le_scan_phys);
61917eb5b27eSMatthias Ringwald             for (i=0;i<num_phys;i++){
61927eb5b27eSMatthias Ringwald                 scan_types[i]     = hci_stack->le_scan_type;
61937eb5b27eSMatthias Ringwald                 scan_intervals[i] = hci_stack->le_scan_interval;
61947eb5b27eSMatthias Ringwald                 scan_windows[i]   = hci_stack->le_scan_window;
61957eb5b27eSMatthias Ringwald             }
619663671e69SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type,
61977eb5b27eSMatthias Ringwald                          hci_stack->le_scan_filter_policy, hci_stack->le_scan_phys, scan_types, scan_intervals, scan_windows);
619863671e69SMatthias Ringwald         } else
619963671e69SMatthias Ringwald #endif
620063671e69SMatthias Ringwald         {
6201a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
6202a41310b7SMatthias Ringwald                          hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
620363671e69SMatthias Ringwald         }
6204a41310b7SMatthias Ringwald         return true;
6205a41310b7SMatthias Ringwald     }
6206a41310b7SMatthias Ringwald #endif
6207a41310b7SMatthias Ringwald 
6208a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
620945c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
621045c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
62116bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
6212e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6213e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
6214e464cd48SMatthias Ringwald             // map advertisment type to advertising event properties
6215e464cd48SMatthias Ringwald             uint16_t adv_event_properties = 0;
6216e464cd48SMatthias Ringwald             const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000};
6217e464cd48SMatthias Ringwald             if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){
6218e464cd48SMatthias Ringwald                 adv_event_properties = mapping[hci_stack->le_advertisements_type];
6219e464cd48SMatthias Ringwald             }
6220174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6221e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6222e464cd48SMatthias Ringwald                          0,
6223e464cd48SMatthias Ringwald                          adv_event_properties,
6224e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
6225e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
6226e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
6227e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
6228e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
6229e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
6230e464cd48SMatthias Ringwald                          hci_stack->le_advertisements_filter_policy,
6231e464cd48SMatthias Ringwald                          0x7f,  // tx power: no preference
6232e464cd48SMatthias Ringwald                          0x01,  // primary adv phy: LE 1M
6233e464cd48SMatthias Ringwald                          0,     // secondary adv max skip
62345375ad13SMatthias Ringwald                          0x01,  // secondary adv phy
6235e464cd48SMatthias Ringwald                          0,     // adv sid
6236e464cd48SMatthias Ringwald                          0      // scan request notification
6237e464cd48SMatthias Ringwald                          );
6238d935373dSMatthias Ringwald         } else
6239e464cd48SMatthias Ringwald #endif
6240e464cd48SMatthias Ringwald         {
624145c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
624245c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_min,
624345c102fdSMatthias Ringwald                          hci_stack->le_advertisements_interval_max,
624445c102fdSMatthias Ringwald                          hci_stack->le_advertisements_type,
62456bcfa632SMatthias Ringwald                          hci_stack->le_advertisements_own_addr_type,
624645c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address_type,
624745c102fdSMatthias Ringwald                          hci_stack->le_advertisements_direct_address,
624845c102fdSMatthias Ringwald                          hci_stack->le_advertisements_channel_map,
624945c102fdSMatthias Ringwald                          hci_stack->le_advertisements_filter_policy);
6250e464cd48SMatthias Ringwald         }
6251f30077b7SMatthias Ringwald         return true;
625245c102fdSMatthias Ringwald     }
6253be7ef9d8SMatthias Ringwald 
62549ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
62559ce6dfa1SMatthias Ringwald     // assumption: only set if extended advertising is supported
62569ce6dfa1SMatthias Ringwald     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0) != 0){
62579ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
62589ce6dfa1SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address);
62599ce6dfa1SMatthias Ringwald         return true;
62609ce6dfa1SMatthias Ringwald     }
62619ce6dfa1SMatthias Ringwald #endif
62629ce6dfa1SMatthias Ringwald 
6263501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
6264501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
62657a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
62667a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
62676535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
62686535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
62693c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
6270e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6271e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
6272174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6273e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean);
6274e464cd48SMatthias Ringwald         } else
6275e464cd48SMatthias Ringwald #endif
6276e464cd48SMatthias Ringwald         {
62777a85e4f5SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
6278e464cd48SMatthias Ringwald         }
6279f30077b7SMatthias Ringwald         return true;
628045c102fdSMatthias Ringwald     }
6281be7ef9d8SMatthias Ringwald 
6282501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
6283501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6284f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
6285f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
62866535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
62876535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
62883c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
6289e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6290e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
6291174b4d21SMatthias Ringwald             hci_stack->le_advertising_set_in_current_command = 0;
6292e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean);
6293e464cd48SMatthias Ringwald         } else
6294e464cd48SMatthias Ringwald #endif
6295e464cd48SMatthias Ringwald         {
6296214bfd60SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
6297e464cd48SMatthias Ringwald         }
6298f30077b7SMatthias Ringwald         return true;
6299501f56b3SMatthias Ringwald     }
6300be7ef9d8SMatthias Ringwald 
6301be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6302be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported()) {
6303be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6304be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6305be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
6306be7ef9d8SMatthias Ringwald             le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it);
6307be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) {
6308be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET;
6309174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6310be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle);
6311be7ef9d8SMatthias Ringwald                 return true;
6312be7ef9d8SMatthias Ringwald             }
6313be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){
6314be7ef9d8SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
6315174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
6316be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_parameters,
6317be7ef9d8SMatthias Ringwald                              advertising_set->advertising_handle,
631857a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_event_properties,
631957a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_min,
632057a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_interval_max,
632157a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_channel_map,
632257a04237SMatthias Ringwald                              advertising_set->extended_params.own_address_type,
632357a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address_type,
632457a04237SMatthias Ringwald                              advertising_set->extended_params.peer_address,
632557a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_filter_policy,
632657a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_tx_power,
632757a04237SMatthias Ringwald                              advertising_set->extended_params.primary_advertising_phy,
632857a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_max_skip,
632957a04237SMatthias Ringwald                              advertising_set->extended_params.secondary_advertising_phy,
633057a04237SMatthias Ringwald                              advertising_set->extended_params.advertising_sid,
633157a04237SMatthias Ringwald                              advertising_set->extended_params.scan_request_notification_enable
6332be7ef9d8SMatthias Ringwald                 );
6333be7ef9d8SMatthias Ringwald                 return true;
6334be7ef9d8SMatthias Ringwald             }
63350f54aa8dSMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){
63360f54aa8dSMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
63370f54aa8dSMatthias Ringwald                 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address);
63380f54aa8dSMatthias Ringwald                 return true;
63390f54aa8dSMatthias Ringwald             }
6340be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) {
6341be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->adv_data_pos;
6342be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len);
6343be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6344be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6345be7ef9d8SMatthias Ringwald                     // last fragment or complete data
6346be7ef9d8SMatthias Ringwald                     operation |= 2;
6347be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos = 0;
6348be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
6349be7ef9d8SMatthias Ringwald                 } else {
6350be7ef9d8SMatthias Ringwald                     advertising_set->adv_data_pos += data_to_upload;
6351be7ef9d8SMatthias Ringwald                 }
6352174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
63530cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]);
6354be7ef9d8SMatthias Ringwald                 return true;
6355be7ef9d8SMatthias Ringwald             }
6356be7ef9d8SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) {
6357be7ef9d8SMatthias Ringwald                 uint16_t pos = advertising_set->scan_data_pos;
6358be7ef9d8SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len);
6359be7ef9d8SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
6360be7ef9d8SMatthias Ringwald                 if ((operation & 0x02) != 0){
6361be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos = 0;
6362be7ef9d8SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
6363be7ef9d8SMatthias Ringwald                 } else {
6364be7ef9d8SMatthias Ringwald                     advertising_set->scan_data_pos += data_to_upload;
6365be7ef9d8SMatthias Ringwald                 }
6366174b4d21SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
63678ef6d15fSMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_scan_response_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->scan_data[pos]);
6368be7ef9d8SMatthias Ringwald                 return true;
6369be7ef9d8SMatthias Ringwald             }
6370c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
637153f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){
637253f240c0SMatthias Ringwald                 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
637353f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
637453f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_parameters,
637553f240c0SMatthias Ringwald                              advertising_set->advertising_handle,
637653f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_min,
637753f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_interval_max,
637853f240c0SMatthias Ringwald                              advertising_set->periodic_params.periodic_advertising_properties);
637953f240c0SMatthias Ringwald                 return true;
638053f240c0SMatthias Ringwald             }
638153f240c0SMatthias Ringwald             if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) {
63820cbe4690SMatthias Ringwald                 uint16_t pos = advertising_set->periodic_data_pos;
638353f240c0SMatthias Ringwald                 uint8_t  operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len);
638453f240c0SMatthias Ringwald                 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN);
638553f240c0SMatthias Ringwald                 if ((operation & 0x02) != 0){
638653f240c0SMatthias Ringwald                     // last fragment or complete data
638753f240c0SMatthias Ringwald                     operation |= 2;
63880cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos = 0;
638953f240c0SMatthias Ringwald                     advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
639053f240c0SMatthias Ringwald                 } else {
63910cbe4690SMatthias Ringwald                     advertising_set->periodic_data_pos += data_to_upload;
639253f240c0SMatthias Ringwald                 }
639353f240c0SMatthias Ringwald                 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle;
63940cbe4690SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]);
639553f240c0SMatthias Ringwald                 return true;
639653f240c0SMatthias Ringwald             }
6397c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6398be7ef9d8SMatthias Ringwald         }
6399be7ef9d8SMatthias Ringwald     }
6400be7ef9d8SMatthias Ringwald #endif
6401be7ef9d8SMatthias Ringwald 
6402d70217a2SMatthias Ringwald #endif
64039956955bSMatthias Ringwald 
6404057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6405a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
6406a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
64074bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
64084bafedd5SMatthias Ringwald     // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time
64094bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false;
64104bafedd5SMatthias Ringwald #endif
6411057ab60cSMatthias Ringwald #endif
6412057ab60cSMatthias Ringwald 
6413a41310b7SMatthias Ringwald     // LE Whitelist Management
6414a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
64159956955bSMatthias Ringwald         // add/remove entries
6416665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6417665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
6418665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
6419453459ddSMatthias Ringwald 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
6420453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
6421334e35acSMatthias Ringwald                 entry->state &= ~LE_WHITELIST_ON_CONTROLLER;
6422334e35acSMatthias Ringwald                 bd_addr_type_t address_type = entry->address_type;
6423334e35acSMatthias Ringwald                 bd_addr_t address;
6424334e35acSMatthias Ringwald                 memcpy(address, entry->address, 6);
6425334e35acSMatthias Ringwald                 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) == 0){
6426334e35acSMatthias Ringwald                     // remove from whitelist if not scheduled for re-addition
6427334e35acSMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
6428334e35acSMatthias Ringwald                     btstack_memory_whitelist_entry_free(entry);
6429334e35acSMatthias Ringwald                 }
6430334e35acSMatthias Ringwald 				hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
6431453459ddSMatthias Ringwald 				return true;
6432453459ddSMatthias Ringwald 			}
64339956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
6434453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
6435453459ddSMatthias Ringwald                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
64369956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
6437f30077b7SMatthias Ringwald                 return true;
64389956955bSMatthias Ringwald             }
64399956955bSMatthias Ringwald         }
644091915b0bSMatthias Ringwald     }
64419956955bSMatthias Ringwald 
644221debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
644321debf25SMatthias Ringwald     // LE Resolving List Management
6444ea151974SMatthias Ringwald     if (resolving_list_supported) {
644521debf25SMatthias Ringwald 		uint16_t i;
644621debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
644721debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
644821debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
644921debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
645021debf25SMatthias Ringwald 				return true;
645121debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
645221debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
645321debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
645421debf25SMatthias Ringwald 				return true;
645521debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
64565f3ccd83SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
6457ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
6458ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
6459e8ca66c6SMatthias Ringwald                 (void) memset(hci_stack->le_resolving_list_set_privacy_mode, 0xff,
6460e8ca66c6SMatthias Ringwald                               sizeof(hci_stack->le_resolving_list_set_privacy_mode));
6461ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
6462ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
646321debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
646421debf25SMatthias Ringwald 				return true;
64655f3ccd83SMatthias Ringwald 			case LE_RESOLVING_LIST_UPDATES_ENTRIES:
64665f3ccd83SMatthias Ringwald                 // first remove old entries
646702b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
646802b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
646902b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
647002b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
647102b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
647202b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
647302b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
647402b02cffSMatthias Ringwald 					sm_key_t peer_irk;
647502b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
647602b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6477f5228c62SMatthias Ringwald 
6478f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
6479f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
6480f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
6481f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
6482f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
6483f5228c62SMatthias Ringwald 						if (entry->address_type != peer_identity_addr_type) continue;
6484f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
6485f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
6486f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
6487f5228c62SMatthias Ringwald 					}
6488f5228c62SMatthias Ringwald #endif
6489f5228c62SMatthias Ringwald 
6490ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
6491ea151974SMatthias Ringwald 								 peer_identity_addreses);
649202b02cffSMatthias Ringwald 					return true;
649302b02cffSMatthias Ringwald 				}
649402b02cffSMatthias Ringwald 
64955f3ccd83SMatthias Ringwald                 // then add new entries
649621debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
649721debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
649821debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
649902b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
650002b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
650121debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
650221debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
650321debf25SMatthias Ringwald 					sm_key_t peer_irk;
650421debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
650521debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6506e938c062SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
650721debf25SMatthias Ringwald 					const uint8_t *local_irk = gap_get_persistent_irk();
650821debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
650921debf25SMatthias Ringwald 					uint8_t local_irk_flipped[16];
651021debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
651121debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
651221debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
6513ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
6514ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
651521debf25SMatthias Ringwald 					return true;
651621debf25SMatthias Ringwald 				}
6517e8ca66c6SMatthias Ringwald 
6518e8ca66c6SMatthias Ringwald                 // finally, set privacy mode
6519e8ca66c6SMatthias Ringwald                 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
6520e8ca66c6SMatthias Ringwald                     uint8_t offset = i >> 3;
6521e8ca66c6SMatthias Ringwald                     uint8_t mask = 1 << (i & 7);
6522e8ca66c6SMatthias Ringwald                     if ((hci_stack->le_resolving_list_set_privacy_mode[offset] & mask) == 0) continue;
6523e8ca66c6SMatthias Ringwald                     hci_stack->le_resolving_list_set_privacy_mode[offset] &= ~mask;
6524e8ca66c6SMatthias Ringwald                     if (hci_stack->le_privacy_mode == LE_PRIVACY_MODE_NETWORK) {
6525e8ca66c6SMatthias Ringwald                         // Network Privacy Mode is default
6526e8ca66c6SMatthias Ringwald                         continue;
6527e8ca66c6SMatthias Ringwald                     }
6528e8ca66c6SMatthias Ringwald                     bd_addr_t peer_identity_address;
6529e8ca66c6SMatthias Ringwald                     int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
6530e8ca66c6SMatthias Ringwald                     sm_key_t peer_irk;
6531e8ca66c6SMatthias Ringwald                     le_device_db_info(i, &peer_identity_addr_type, peer_identity_address, peer_irk);
6532e8ca66c6SMatthias Ringwald                     if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
6533e8ca66c6SMatthias Ringwald                     if (btstack_is_null(peer_irk, 16)) continue;
6534e8ca66c6SMatthias Ringwald                     // command uses format specifier 'P' that stores 16-byte value without flip
6535e8ca66c6SMatthias Ringwald                     uint8_t peer_irk_flipped[16];
6536e8ca66c6SMatthias Ringwald                     reverse_128(peer_irk, peer_irk_flipped);
6537e8ca66c6SMatthias Ringwald                     hci_send_cmd(&hci_le_set_privacy_mode, peer_identity_addr_type, peer_identity_address, hci_stack->le_privacy_mode);
6538e8ca66c6SMatthias Ringwald                     return true;
6539e8ca66c6SMatthias Ringwald                 }
654002b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
654121debf25SMatthias Ringwald 				break;
654202b02cffSMatthias Ringwald 
654321debf25SMatthias Ringwald 			default:
654421debf25SMatthias Ringwald 				break;
654521debf25SMatthias Ringwald 		}
6546ea151974SMatthias Ringwald 	}
654721debf25SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
654821debf25SMatthias Ringwald #endif
6549a41310b7SMatthias Ringwald 
6550f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6551f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6552f40c73b4SMatthias Ringwald     // LE Whitelist Management
6553f40c73b4SMatthias Ringwald     if (periodic_list_modification_pending){
6554f40c73b4SMatthias Ringwald         // add/remove entries
6555f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list);
6556f40c73b4SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
6557f40c73b4SMatthias Ringwald             periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit);
6558f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){
6559f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
6560f40c73b4SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address);
6561f40c73b4SMatthias Ringwald                 return true;
6562f40c73b4SMatthias Ringwald             }
6563f40c73b4SMatthias Ringwald             if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){
6564f40c73b4SMatthias Ringwald                 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
6565f40c73b4SMatthias Ringwald                 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER;
65669e88556bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid);
6567f40c73b4SMatthias Ringwald                 return true;
6568f40c73b4SMatthias Ringwald             }
6569f40c73b4SMatthias Ringwald             if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){
6570f40c73b4SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry);
6571f40c73b4SMatthias Ringwald                 btstack_memory_periodic_advertiser_list_entry_free(entry);
6572f40c73b4SMatthias Ringwald             }
6573f40c73b4SMatthias Ringwald         }
6574f40c73b4SMatthias Ringwald     }
6575f40c73b4SMatthias Ringwald #endif
6576f40c73b4SMatthias Ringwald #endif
6577f40c73b4SMatthias Ringwald 
657898aa715fSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
657998aa715fSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
658098aa715fSMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
658198aa715fSMatthias Ringwald     if (hci_stack->le_past_set_default_params){
658298aa715fSMatthias Ringwald         hci_stack->le_past_set_default_params = false;
658398aa715fSMatthias Ringwald         hci_send_cmd(&hci_le_set_default_periodic_advertising_sync_transfer_parameters,
658498aa715fSMatthias Ringwald                      hci_stack->le_past_mode,
658598aa715fSMatthias Ringwald                      hci_stack->le_past_skip,
658698aa715fSMatthias Ringwald                      hci_stack->le_past_sync_timeout,
658798aa715fSMatthias Ringwald                      hci_stack->le_past_cte_type);
658898aa715fSMatthias Ringwald         return true;
658998aa715fSMatthias Ringwald     }
659098aa715fSMatthias Ringwald #endif
659198aa715fSMatthias Ringwald #endif
659298aa715fSMatthias Ringwald #endif
659398aa715fSMatthias Ringwald 
659473799937SMatthias Ringwald     // post-pone all actions until stack is fully working
659573799937SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
659673799937SMatthias Ringwald 
659773799937SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
659873799937SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
659973799937SMatthias Ringwald 
6600a41310b7SMatthias Ringwald     // Phase 4: restore state
660129c24bebSMatthias Ringwald 
660229c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6603af64f147SMatthias Ringwald     // re-start scanning
660429c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
660529c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
660663671e69SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
660763671e69SMatthias Ringwald         if (hci_extended_advertising_supported()){
66084856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_scan_enable, 1, hci_stack->le_scan_filter_duplicates, 0, 0);
660963671e69SMatthias Ringwald         } else
661063671e69SMatthias Ringwald #endif
661163671e69SMatthias Ringwald         {
66124856283bSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_enable, 1, hci_stack->le_scan_filter_duplicates);
661363671e69SMatthias Ringwald         }
661429c24bebSMatthias Ringwald         return true;
661529c24bebSMatthias Ringwald     }
661629c24bebSMatthias Ringwald #endif
661729c24bebSMatthias Ringwald 
661813eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6619af64f147SMatthias Ringwald     // re-start connecting
6620af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
66219956955bSMatthias Ringwald         bd_addr_t null_addr;
66229956955bSMatthias Ringwald         memset(null_addr, 0, 6);
66236bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
66246bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
66256f34e9d6SMatthias Ringwald         hci_send_le_create_connection(1, 0, null_addr);
6626f30077b7SMatthias Ringwald         return true;
66279956955bSMatthias Ringwald     }
66284bafedd5SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
66294bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){
66304bafedd5SMatthias Ringwald         switch(hci_stack->le_periodic_sync_request){
66314bafedd5SMatthias Ringwald             case LE_CONNECTING_DIRECT:
66324bafedd5SMatthias Ringwald             case LE_CONNECTING_WHITELIST:
66334bafedd5SMatthias Ringwald                 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
66344bafedd5SMatthias Ringwald                 hci_send_cmd(&hci_le_periodic_advertising_create_sync,
66354bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_options,
66364bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertising_sid,
66374bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address_type,
66384bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_advertiser_address,
66394bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_skip,
66404bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_timeout,
66414bafedd5SMatthias Ringwald                              hci_stack->le_periodic_sync_cte_type);
66424bafedd5SMatthias Ringwald                 return true;
66434bafedd5SMatthias Ringwald             default:
66444bafedd5SMatthias Ringwald                 break;
66454bafedd5SMatthias Ringwald         }
66464bafedd5SMatthias Ringwald     }
66474bafedd5SMatthias Ringwald #endif
6648d70217a2SMatthias Ringwald #endif
6649a41310b7SMatthias Ringwald 
6650a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
6651a41310b7SMatthias Ringwald     // re-start advertising
6652935aa76eSMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
6653a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
6654935aa76eSMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6655b892db1cSMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address);
6656e464cd48SMatthias Ringwald 
6657e464cd48SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6658e464cd48SMatthias Ringwald         if (hci_extended_advertising_supported()){
6659e464cd48SMatthias Ringwald             const uint8_t advertising_handles[] = { 0 };
6660e464cd48SMatthias Ringwald             const uint16_t durations[] = { 0 };
6661e464cd48SMatthias Ringwald             const uint16_t max_events[] = { 0 };
6662e464cd48SMatthias Ringwald             hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6663e464cd48SMatthias Ringwald         } else
6664e464cd48SMatthias Ringwald #endif
6665e464cd48SMatthias Ringwald         {
6666a41310b7SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
6667e464cd48SMatthias Ringwald         }
6668a41310b7SMatthias Ringwald         return true;
6669a41310b7SMatthias Ringwald     }
6670be7ef9d8SMatthias Ringwald 
6671be7ef9d8SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
6672be7ef9d8SMatthias Ringwald     if (hci_extended_advertising_supported()) {
6673be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_t it;
6674be7ef9d8SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
6675be7ef9d8SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)) {
6676be7ef9d8SMatthias Ringwald             le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
6677be7ef9d8SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){
66788caa405cSMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE;
6679be7ef9d8SMatthias Ringwald                 const uint8_t advertising_handles[] = { advertising_set->advertising_handle };
6680be7ef9d8SMatthias Ringwald                 const uint16_t durations[] = { advertising_set->enable_timeout };
6681be7ef9d8SMatthias Ringwald                 const uint16_t max_events[] = { advertising_set->enable_max_scan_events };
6682be7ef9d8SMatthias Ringwald                 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events);
6683be7ef9d8SMatthias Ringwald                 return true;
6684be7ef9d8SMatthias Ringwald             }
6685c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
668653f240c0SMatthias Ringwald             if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){
668753f240c0SMatthias Ringwald                 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE;
668853f240c0SMatthias Ringwald                 uint8_t enable = 1;
668953f240c0SMatthias Ringwald                 if (advertising_set->periodic_include_adi){
669053f240c0SMatthias Ringwald                     enable |= 2;
669153f240c0SMatthias Ringwald                 }
669253f240c0SMatthias Ringwald                 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle);
669353f240c0SMatthias Ringwald                 return true;
669453f240c0SMatthias Ringwald             }
6695c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
6696be7ef9d8SMatthias Ringwald         }
6697be7ef9d8SMatthias Ringwald     }
6698be7ef9d8SMatthias Ringwald #endif
6699a41310b7SMatthias Ringwald #endif
6700a41310b7SMatthias Ringwald 
6701f30077b7SMatthias Ringwald     return false;
67027bdc6798S[email protected] }
67037aa35f6aSMatthias Ringwald 
67047aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
67057aa35f6aSMatthias Ringwald static bool hci_run_iso_tasks(void){
67067aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
67072a6c0f82SMatthias Ringwald 
670826b93350SMatthias Ringwald     if (hci_stack->iso_active_operation_type != HCI_ISO_TYPE_INVALID) {
670940f86dfdSMatthias Ringwald         return false;
671040f86dfdSMatthias Ringwald     }
671140f86dfdSMatthias Ringwald 
67122a6c0f82SMatthias Ringwald     // BIG
67137aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
67147aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
67157aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
67167aa35f6aSMatthias Ringwald         switch (big->state){
67177aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
671840f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big->params->big_handle;
671940f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
67207aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
67217aa35f6aSMatthias Ringwald                 hci_send_cmd(&hci_le_create_big,
67227aa35f6aSMatthias Ringwald                              big->params->big_handle,
67237aa35f6aSMatthias Ringwald                              big->params->advertising_handle,
67247aa35f6aSMatthias Ringwald                              big->params->num_bis,
67257aa35f6aSMatthias Ringwald                              big->params->sdu_interval_us,
67267aa35f6aSMatthias Ringwald                              big->params->max_sdu,
67277aa35f6aSMatthias Ringwald                              big->params->max_transport_latency_ms,
67287aa35f6aSMatthias Ringwald                              big->params->rtn,
67297aa35f6aSMatthias Ringwald                              big->params->phy,
67307aa35f6aSMatthias Ringwald                              big->params->packing,
67317aa35f6aSMatthias Ringwald                              big->params->framing,
67327aa35f6aSMatthias Ringwald                              big->params->encryption,
67337aa35f6aSMatthias Ringwald                              big->params->broadcast_code);
67347aa35f6aSMatthias Ringwald                 return true;
67357aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
67367aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
673785dc435bSDirk Helbig                 hci_send_cmd(&hci_le_setup_iso_data_path, big->bis_con_handles[big->state_vars.next_bis], 0, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0,  0, 0, NULL);
67387aa35f6aSMatthias Ringwald                 return true;
67397aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
67407aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
67412a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status);
6742c1f83111SMatthias Ringwald                 return true;
67437aa35f6aSMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
67447aa35f6aSMatthias Ringwald                 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
67452a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS);
67467aa35f6aSMatthias Ringwald                 return true;
67477aa35f6aSMatthias Ringwald             default:
67487aa35f6aSMatthias Ringwald                 break;
67497aa35f6aSMatthias Ringwald         }
67507aa35f6aSMatthias Ringwald     }
67512a6c0f82SMatthias Ringwald 
67522a6c0f82SMatthias Ringwald     // BIG Sync
67532a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
67542a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
67552a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
67562a6c0f82SMatthias Ringwald         switch (big_sync->state){
67572a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_CREATE:
675840f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_group_id = big_sync->params->big_handle;
675940f86dfdSMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_BIS;
67602a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED;
67612a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_create_sync,
67622a6c0f82SMatthias Ringwald                              big_sync->params->big_handle,
67632a6c0f82SMatthias Ringwald                              big_sync->params->sync_handle,
67642a6c0f82SMatthias Ringwald                              big_sync->params->encryption,
67652a6c0f82SMatthias Ringwald                              big_sync->params->broadcast_code,
67662a6c0f82SMatthias Ringwald                              big_sync->params->mse,
67672a6c0f82SMatthias Ringwald                              big_sync->params->big_sync_timeout_10ms,
67682a6c0f82SMatthias Ringwald                              big_sync->params->num_bis,
67692a6c0f82SMatthias Ringwald                              big_sync->params->bis_indices);
67702a6c0f82SMatthias Ringwald                 return true;
67712a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
67722a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH;
677385dc435bSDirk Helbig                 hci_send_cmd(&hci_le_setup_iso_data_path, big_sync->bis_con_handles[big_sync->state_vars.next_bis], 1, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
67742a6c0f82SMatthias Ringwald                 return true;
67752a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED:
67762a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED;
67772a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
6778c1f83111SMatthias Ringwald                 return true;
67792a6c0f82SMatthias Ringwald             case LE_AUDIO_BIG_STATE_TERMINATE:
67802a6c0f82SMatthias Ringwald                 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED;
67812a6c0f82SMatthias Ringwald                 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle);
67822a6c0f82SMatthias Ringwald                 return true;
67832a6c0f82SMatthias Ringwald             default:
67842a6c0f82SMatthias Ringwald                 break;
67852a6c0f82SMatthias Ringwald         }
67862a6c0f82SMatthias Ringwald     }
67872a6c0f82SMatthias Ringwald 
6788d3a89d91SMatthias Ringwald     // CIG
6789d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
6790d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
6791d3a89d91SMatthias Ringwald         le_audio_cig_t *cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
6792d3a89d91SMatthias Ringwald         uint8_t i;
6793444e371eSMatthias Ringwald         // Set CIG Parameters
6794d3a89d91SMatthias Ringwald         uint8_t cis_id[MAX_NR_CIS];
6795d3a89d91SMatthias Ringwald         uint16_t max_sdu_c_to_p[MAX_NR_CIS];
6796d3a89d91SMatthias Ringwald         uint16_t max_sdu_p_to_c[MAX_NR_CIS];
6797d3a89d91SMatthias Ringwald         uint8_t phy_c_to_p[MAX_NR_CIS];
6798d3a89d91SMatthias Ringwald         uint8_t phy_p_to_c[MAX_NR_CIS];
6799d3a89d91SMatthias Ringwald         uint8_t rtn_c_to_p[MAX_NR_CIS];
6800d3a89d91SMatthias Ringwald         uint8_t rtn_p_to_c[MAX_NR_CIS];
6801d3a89d91SMatthias Ringwald         switch (cig->state) {
6802d3a89d91SMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE:
6803d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6804d3a89d91SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6805d3a89d91SMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_ESTABLISHED;
6806d3a89d91SMatthias Ringwald                 le_audio_cig_params_t * params = cig->params;
6807d3a89d91SMatthias Ringwald                 for (i = 0; i < params->num_cis; i++) {
6808d3a89d91SMatthias Ringwald                     le_audio_cis_params_t * cis_params = &cig->params->cis_params[i];
6809d3a89d91SMatthias Ringwald                     cis_id[i]         = cis_params->cis_id;
6810d3a89d91SMatthias Ringwald                     max_sdu_c_to_p[i] = cis_params->max_sdu_c_to_p;
6811d3a89d91SMatthias Ringwald                     max_sdu_p_to_c[i] = cis_params->max_sdu_p_to_c;
6812d3a89d91SMatthias Ringwald                     phy_c_to_p[i]     = cis_params->phy_c_to_p;
6813d3a89d91SMatthias Ringwald                     phy_p_to_c[i]     = cis_params->phy_p_to_c;
6814d3a89d91SMatthias Ringwald                     rtn_c_to_p[i]     = cis_params->rtn_c_to_p;
6815d3a89d91SMatthias Ringwald                     rtn_p_to_c[i]     = cis_params->rtn_p_to_c;
6816d3a89d91SMatthias Ringwald                 }
6817d3a89d91SMatthias Ringwald                 hci_send_cmd(&hci_le_set_cig_parameters,
6818d3a89d91SMatthias Ringwald                              cig->cig_id,
6819d3a89d91SMatthias Ringwald                              params->sdu_interval_c_to_p,
6820d3a89d91SMatthias Ringwald                              params->sdu_interval_p_to_c,
6821d3a89d91SMatthias Ringwald                              params->worst_case_sca,
6822d3a89d91SMatthias Ringwald                              params->packing,
6823d3a89d91SMatthias Ringwald                              params->framing,
6824d3a89d91SMatthias Ringwald                              params->max_transport_latency_c_to_p,
6825d3a89d91SMatthias Ringwald                              params->max_transport_latency_p_to_c,
6826d3a89d91SMatthias Ringwald                              params->num_cis,
6827d3a89d91SMatthias Ringwald                              cis_id,
6828d3a89d91SMatthias Ringwald                              max_sdu_c_to_p,
6829d3a89d91SMatthias Ringwald                              max_sdu_p_to_c,
6830d3a89d91SMatthias Ringwald                              phy_c_to_p,
6831d3a89d91SMatthias Ringwald                              phy_p_to_c,
6832d3a89d91SMatthias Ringwald                              rtn_c_to_p,
6833d3a89d91SMatthias Ringwald                              rtn_p_to_c
6834d3a89d91SMatthias Ringwald                 );
6835bb42b5c0SMatthias Ringwald                 return true;
6836444e371eSMatthias Ringwald             case LE_AUDIO_CIG_STATE_CREATE_CIS:
6837bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6838bb42b5c0SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6839444e371eSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_W4_CREATE_CIS;
68403abcd16cSMatthias Ringwald                 for (i=0;i<cig->num_cis;i++){
68413abcd16cSMatthias Ringwald                     cig->cis_setup_active[i] = true;
68423abcd16cSMatthias Ringwald                 }
6843444e371eSMatthias Ringwald                 hci_send_cmd(&hci_le_create_cis, cig->num_cis, cig->cis_con_handles, cig->acl_con_handles);
6844bb42b5c0SMatthias Ringwald                 return true;
6845f9306a1aSMatthias Ringwald             case LE_AUDIO_CIG_STATE_SETUP_ISO_PATH:
6846f9306a1aSMatthias Ringwald                 while (cig->state_vars.next_cis < (cig->num_cis * 2)){
6847f9306a1aSMatthias Ringwald                     // find next path to setup
6848f9306a1aSMatthias Ringwald                     uint8_t cis_index = cig->state_vars.next_cis >> 1;
6849f9306a1aSMatthias Ringwald                     if (cig->cis_established[cis_index] == false) {
6850f9306a1aSMatthias Ringwald                         continue;
6851f9306a1aSMatthias Ringwald                     }
6852f9306a1aSMatthias Ringwald                     uint8_t cis_direction = cig->state_vars.next_cis & 1;
6853f9306a1aSMatthias Ringwald                     bool setup = true;
68548e58e4f7SMatthias Ringwald                     if (cis_direction == 0){
6855f9306a1aSMatthias Ringwald                         // 0 - input - host to controller
6856f9306a1aSMatthias Ringwald                         // we are central => central to peripheral
6857f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_c_to_p > 0;
6858f9306a1aSMatthias Ringwald                     } else {
6859f9306a1aSMatthias Ringwald                         // 1 - output - controller to host
6860f9306a1aSMatthias Ringwald                         // we are central => peripheral to central
6861f9306a1aSMatthias Ringwald                         setup &= cig->params->cis_params[cis_index].max_sdu_p_to_c > 0;
6862f9306a1aSMatthias Ringwald                     }
6863f9306a1aSMatthias Ringwald                     if (setup){
6864f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_group_id = cig->params->cig_id;
6865f9306a1aSMatthias Ringwald                         hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
6866f9306a1aSMatthias Ringwald                         cig->state = LE_AUDIO_CIG_STATE_W4_SETUP_ISO_PATH;
686785dc435bSDirk Helbig                         hci_send_cmd(&hci_le_setup_iso_data_path, cig->cis_con_handles[cis_index], cis_direction, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
6868f9306a1aSMatthias Ringwald                         return true;
6869f9306a1aSMatthias Ringwald                     }
68708e58e4f7SMatthias Ringwald                     cig->state_vars.next_cis++;
6871f9306a1aSMatthias Ringwald                 }
6872f9306a1aSMatthias Ringwald                 // emit done
6873f9306a1aSMatthias Ringwald                 cig->state = LE_AUDIO_CIG_STATE_ACTIVE;
6874d3a89d91SMatthias Ringwald             default:
6875d3a89d91SMatthias Ringwald                 break;
6876d3a89d91SMatthias Ringwald         }
6877d3a89d91SMatthias Ringwald     }
6878d3a89d91SMatthias Ringwald 
687926b93350SMatthias Ringwald     // CIS Accept/Reject
688026b93350SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
688126b93350SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
688226b93350SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
688326b93350SMatthias Ringwald         hci_con_handle_t con_handle;
688426b93350SMatthias Ringwald         switch (iso_stream->state){
688526b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_ACCEPT:
688626b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
688726b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
688826b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
6889969d876aSMatthias Ringwald                 hci_send_cmd(&hci_le_accept_cis_request, iso_stream->cis_handle);
689026b93350SMatthias Ringwald                 return true;
689126b93350SMatthias Ringwald             case HCI_ISO_STREAM_W2_REJECT:
6892969d876aSMatthias Ringwald                 con_handle = iso_stream->cis_handle;
689326b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
689426b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
689526b93350SMatthias Ringwald                 hci_iso_stream_finalize(iso_stream);
689626b93350SMatthias Ringwald                 hci_send_cmd(&hci_le_reject_cis_request, con_handle, ERROR_CODE_REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES);
689726b93350SMatthias Ringwald                 return true;
689826b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_INPUT:
689926b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
690026b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
690126b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_INPUT;
690285dc435bSDirk Helbig                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->cis_handle, 0, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
690326b93350SMatthias Ringwald                 break;
690426b93350SMatthias Ringwald             case HCI_ISO_STREAM_STATE_W2_SETUP_ISO_OUTPUT:
690526b93350SMatthias Ringwald                 hci_stack->iso_active_operation_group_id = HCI_ISO_GROUP_ID_SINGLE_CIS;
690626b93350SMatthias Ringwald                 hci_stack->iso_active_operation_type = HCI_ISO_TYPE_CIS;
690726b93350SMatthias Ringwald                 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ISO_SETUP_OUTPUT;
690885dc435bSDirk Helbig                 hci_send_cmd(&hci_le_setup_iso_data_path, iso_stream->cis_handle, 1, 0, HCI_AUDIO_CODING_FORMAT_TRANSPARENT, 0, 0, 0, 0, NULL);
690926b93350SMatthias Ringwald                 break;
691026b93350SMatthias Ringwald             default:
691126b93350SMatthias Ringwald                 break;
691226b93350SMatthias Ringwald         }
691326b93350SMatthias Ringwald     }
691426b93350SMatthias Ringwald 
69157aa35f6aSMatthias Ringwald     return false;
69167aa35f6aSMatthias Ringwald }
69177aa35f6aSMatthias Ringwald #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */
6918b2f949feS[email protected] #endif
69197bdc6798S[email protected] 
692088a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
6921f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
6922a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
692305ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
692432ab9390Smatthias.ringwald 
69250bf6344aS[email protected]         switch(connection->state){
69260bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
69274f3229d8S[email protected]                 switch(connection->address_type){
692835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6929f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
69309da54300S[email protected]                         log_info("sending hci_create_connection");
6931b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
69324f3229d8S[email protected]                         break;
693335454696SMatthias Ringwald #endif
69344f3229d8S[email protected]                     default:
6935a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
6936d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
69379da54300S[email protected]                         log_info("sending hci_le_create_connection");
69386bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
69396bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
6940f346015eSMatthias Ringwald                         hci_send_le_create_connection(0, connection->address_type, connection->address);
69414f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
6942b2f949feS[email protected] #endif
6943d70217a2SMatthias Ringwald #endif
69444f3229d8S[email protected]                         break;
69454f3229d8S[email protected]                 }
6946f30077b7SMatthias Ringwald                 return true;
6947ad83dc6aS[email protected] 
694835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
69490bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
6950f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
695176ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
6952895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
6953c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
6954f30077b7SMatthias Ringwald                     return true;
6955ee025741SMatthias Ringwald                 }
6956ee025741SMatthias Ringwald                 break;
695735454696SMatthias Ringwald #endif
69580bf6344aS[email protected]             case SEND_DISCONNECT:
69590bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
69606ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
6961f30077b7SMatthias Ringwald                 return true;
69620bf6344aS[email protected] 
69630bf6344aS[email protected]             default:
69640bf6344aS[email protected]                 break;
6965c7e0c5f6Smatthias.ringwald         }
6966c7e0c5f6Smatthias.ringwald 
6967cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
6968cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
6969cabf004eSMatthias Ringwald 
697094418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
697194418890SMatthias Ringwald 
6972ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
697350f49832SMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){
6974608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
69758daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
697630e72d78SMatthias Ringwald 
6977e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
6978e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
697930e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
6980e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
698132ab9390Smatthias.ringwald             } else {
698232ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
698332ab9390Smatthias.ringwald             }
6984f30077b7SMatthias Ringwald             return true;
698532ab9390Smatthias.ringwald         }
69861d6b20aeS[email protected] 
69878daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
69889da54300S[email protected]             log_info("denying to pin request");
69898daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
699034d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
6991f30077b7SMatthias Ringwald             return true;
69924c57c146S[email protected]         }
69934c57c146S[email protected] 
6994c950c316SMatthias Ringwald         // security assessment requires remote features
69952dd8985bSMatthias Ringwald         if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){
6996c950c316SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST);
6997c950c316SMatthias Ringwald             hci_ssp_assess_security_on_io_cap_request(connection);
6998c950c316SMatthias 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
6999c950c316SMatthias Ringwald         }
7000c950c316SMatthias Ringwald 
70018daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
70028daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
7003a8d20135SMatthias Ringwald             // set authentication requirements:
7004a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
7005532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
7006a8d20135SMatthias Ringwald             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
70079faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
70089faad3abS[email protected]                 authreq |= 1;
7009106d6d11S[email protected]             }
7010532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
70118daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
7012532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
7013532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7014532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
7015532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
7016532454f9SMatthias Ringwald                     bonding = false;
7017532454f9SMatthias Ringwald                 }
7018532454f9SMatthias Ringwald             }
7019532454f9SMatthias Ringwald             if (bonding){
7020a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
7021a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
7022532454f9SMatthias Ringwald                 } else {
7023a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
7024a8d20135SMatthias Ringwald                 }
7025532454f9SMatthias Ringwald             }
70261849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
70271849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
70281849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
70291849becdSMatthias Ringwald                     have_oob_data |= 1;
70301849becdSMatthias Ringwald             }
70311849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
70321849becdSMatthias Ringwald                 have_oob_data |= 2;
70331849becdSMatthias Ringwald             }
70341849becdSMatthias Ringwald #endif
70351849becdSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
703611b03efaSMatthias Ringwald             return true;
7037f8fb5f6eS[email protected]         }
703811b03efaSMatthias Ringwald 
70398daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
70408daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
704111b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
7042f30077b7SMatthias Ringwald             return true;
704332ab9390Smatthias.ringwald         }
704432ab9390Smatthias.ringwald 
70451849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
70467ca4a7edSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){
70477ca4a7edSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY);
70481849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
70491849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
70501849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
70511849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
70521849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
70531849becdSMatthias Ringwald             // verify P-256 OOB
70541e83575aSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) {
70551849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
70561849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
70571849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
70581849becdSMatthias Ringwald                 }
70591849becdSMatthias Ringwald             }
70601849becdSMatthias Ringwald             // verify P-192 OOB
70611849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
70621849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
70631849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
70641849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
70651849becdSMatthias Ringwald                 }
70661849becdSMatthias Ringwald             }
70677ca4a7edSMatthias Ringwald 
70687ca4a7edSMatthias Ringwald             // assess security
70697ca4a7edSMatthias Ringwald             bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4);
70707ca4a7edSMatthias Ringwald             bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL);
70717ca4a7edSMatthias Ringwald             if (need_level_4 && !can_reach_level_4){
70727ca4a7edSMatthias Ringwald                 log_info("Level 4 required, but not possible -> abort");
70737ca4a7edSMatthias Ringwald                 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY);
70747ca4a7edSMatthias Ringwald                 // send oob negative reply
70757ca4a7edSMatthias Ringwald                 c_256 = NULL;
70767ca4a7edSMatthias Ringwald                 c_192 = NULL;
70777ca4a7edSMatthias Ringwald             }
70787ca4a7edSMatthias Ringwald 
70791849becdSMatthias Ringwald             // Reply
70801849becdSMatthias Ringwald             if (c_256 != zero) {
70811849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
70821849becdSMatthias Ringwald             } else if (c_192 != zero){
70831849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
70841849becdSMatthias Ringwald             } else {
70851ae74bf3SMatthias Ringwald                 hci_stack->classic_oob_con_handle = connection->con_handle;
70861849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
70871849becdSMatthias Ringwald             }
70881849becdSMatthias Ringwald             return true;
70891849becdSMatthias Ringwald         }
70901849becdSMatthias Ringwald #endif
70911849becdSMatthias Ringwald 
70928daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
70938daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
709434d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
7095f30077b7SMatthias Ringwald             return true;
7096dbe1a790S[email protected]         }
7097dbe1a790S[email protected] 
7098367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
7099367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
7100367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
7101367aedc0SMatthias Ringwald             return true;
7102367aedc0SMatthias Ringwald         }
7103367aedc0SMatthias Ringwald 
71048daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
71058daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
710634d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
7107f30077b7SMatthias Ringwald             return true;
7108dbe1a790S[email protected]         }
7109afd4e962S[email protected] 
7110ab0c69a9SMatthias Ringwald         if ((connection->bonding_flags & (BONDING_DISCONNECT_DEDICATED_DONE | BONDING_DEDICATED_DEFER_DISCONNECT)) == BONDING_DISCONNECT_DEDICATED_DONE){
7111ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
71121bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
71136ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
71146ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
7115f30077b7SMatthias Ringwald             return true;
7116ad83dc6aS[email protected]         }
711776f27cffSMatthias Ringwald 
71182a75353aSMatthias Ringwald         if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
711934d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
7120abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
712134d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
7122f30077b7SMatthias Ringwald             return true;
7123afd4e962S[email protected]         }
712476f27cffSMatthias Ringwald 
7125dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
7126dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
7127dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
7128f30077b7SMatthias Ringwald             return true;
7129dce78009S[email protected]         }
7130447016ffSMatthias Ringwald 
7131573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
7132573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
7133573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
7134f30077b7SMatthias Ringwald             return true;
7135573897a0SMatthias Ringwald         }
7136447016ffSMatthias Ringwald 
7137447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
7138447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7139447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
7140447016ffSMatthias Ringwald             return true;
7141447016ffSMatthias Ringwald         }
7142447016ffSMatthias Ringwald 
7143447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
7144447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
7145447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
7146447016ffSMatthias Ringwald             return true;
7147447016ffSMatthias Ringwald         }
7148447016ffSMatthias Ringwald 
7149447016ffSMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
7150447016ffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
7151447016ffSMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
7152447016ffSMatthias Ringwald             return true;
7153447016ffSMatthias Ringwald         }
715476f27cffSMatthias Ringwald #endif
715576f27cffSMatthias Ringwald 
715676f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
715776f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
71581714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
71591714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
71601714cbbdSMatthias Ringwald #endif
71616ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
71626ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
71636ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
7164f30077b7SMatthias Ringwald                 return true;
716576f27cffSMatthias Ringwald             }
71666ef3696aSMatthias Ringwald         }
7167da886c03S[email protected] 
71686cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
7169f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
7170f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
7171f8ee3071SMatthias Ringwald             case 0:
7172f8ee3071SMatthias Ringwald                 break;
7173f8ee3071SMatthias Ringwald             case 0xffff:
7174f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7175f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
7176f30077b7SMatthias Ringwald                 return true;
7177f8ee3071SMatthias Ringwald             default:
7178f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
7179f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
7180f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
7181f30077b7SMatthias Ringwald                 return true;
7182f8ee3071SMatthias Ringwald         }
718388a03c8dSMatthias Ringwald 
7184140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
7185140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
7186140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
7187140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
7188140c0557SMatthias Ringwald             return true;
7189140c0557SMatthias Ringwald         }
7190140c0557SMatthias Ringwald 
7191965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
7192278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
7193965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
7194278ff8a9SMatthias 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);
7195278ff8a9SMatthias Ringwald             return true;
7196278ff8a9SMatthias Ringwald         }
7197278ff8a9SMatthias Ringwald 
719888a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
719988a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
720088a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
720188a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
720288a03c8dSMatthias Ringwald             return true;
720388a03c8dSMatthias Ringwald         }
720422df2fe2SMatthias Ringwald #endif
72059afaa4d4SMatthias Ringwald 
72069afaa4d4SMatthias Ringwald         if (connection->gap_connection_tasks != 0){
720722df2fe2SMatthias Ringwald #ifdef ENABLE_CLASSIC
72089afaa4d4SMatthias Ringwald             if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){
72099afaa4d4SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT;
72109afaa4d4SMatthias Ringwald                 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout);
72119afaa4d4SMatthias Ringwald                 return true;
72129afaa4d4SMatthias Ringwald             }
721322df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){
721422df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT;
721522df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
721622df2fe2SMatthias Ringwald                 return true;
72179afaa4d4SMatthias Ringwald             }
72186cdc2862SMatthias Ringwald #endif
721922df2fe2SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){
722022df2fe2SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI;
722122df2fe2SMatthias Ringwald                 hci_send_cmd(&hci_read_rssi, connection->con_handle);
722222df2fe2SMatthias Ringwald                 return true;
722322df2fe2SMatthias Ringwald             }
7224ac0f6b83SMatthias Ringwald #ifdef ENABLE_BLE
7225ac0f6b83SMatthias Ringwald             if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES){
7226ac0f6b83SMatthias Ringwald                 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_LE_READ_REMOTE_FEATURES;
7227ac0f6b83SMatthias Ringwald                 hci_send_cmd(&hci_le_read_remote_used_features, connection->con_handle);
7228ac0f6b83SMatthias Ringwald                 return true;
7229ac0f6b83SMatthias Ringwald             }
7230ac0f6b83SMatthias Ringwald #endif
723122df2fe2SMatthias Ringwald         }
7232f8ee3071SMatthias Ringwald 
7233a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
723473cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
723573cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
723673cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
7237da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
723873cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
7239c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7240d4876126SMatthias Ringwald                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7241f30077b7SMatthias Ringwald                 return true;
724273cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
724373cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
724473cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
724573cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
7246d4876126SMatthias Ringwald                              hci_stack->le_minimum_ce_length, hci_stack->le_maximum_ce_length);
7247f30077b7SMatthias Ringwald                 return true;
724873cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
724973cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
72501e0338ebSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle,
72511e0338ebSMatthias Ringwald                              ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS);
7252f30077b7SMatthias Ringwald                 return true;
725373cd8a2aSMatthias Ringwald             default:
725473cd8a2aSMatthias Ringwald                 break;
7255c37a3166S[email protected]         }
72564ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
7257b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
7258b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
7259b90f6e0aSMatthias 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);
7260f30077b7SMatthias Ringwald             return true;
7261b90f6e0aSMatthias Ringwald         }
72623bd96807SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
72633bd96807SMatthias Ringwald         if (connection->le_past_sync_handle != HCI_CON_HANDLE_INVALID){
72643bd96807SMatthias Ringwald             hci_con_handle_t sync_handle = connection->le_past_sync_handle;
72653bd96807SMatthias Ringwald             connection->le_past_sync_handle = HCI_CON_HANDLE_INVALID;
72663bd96807SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_sync_transfer, connection->con_handle, connection->le_past_service_data, sync_handle);
72673bd96807SMatthias Ringwald             return true;
72683bd96807SMatthias Ringwald         }
7269027f4677SMatthias Ringwald         if (connection->le_past_advertising_handle != 0xff){
7270027f4677SMatthias Ringwald             uint8_t advertising_handle = connection->le_past_advertising_handle;
7271027f4677SMatthias Ringwald             connection->le_past_advertising_handle = 0xff;
7272027f4677SMatthias Ringwald             hci_send_cmd(&hci_le_periodic_advertising_set_info_transfer, connection->con_handle, connection->le_past_service_data, advertising_handle);
7273027f4677SMatthias Ringwald             return true;
7274027f4677SMatthias Ringwald         }
72753bd96807SMatthias Ringwald #endif
7276c37a3166S[email protected] #endif
7277dbe1a790S[email protected]     }
7278f30077b7SMatthias Ringwald     return false;
7279f30077b7SMatthias Ringwald }
7280c7e0c5f6Smatthias.ringwald 
7281f30077b7SMatthias Ringwald static void hci_run(void){
7282f30077b7SMatthias Ringwald 
7283df9e2780SMatthias Ringwald     // stack state sub statemachines
7284df9e2780SMatthias Ringwald     switch (hci_stack->state) {
7285df9e2780SMatthias Ringwald         case HCI_STATE_INITIALIZING:
7286df9e2780SMatthias Ringwald             hci_initializing_run();
7287d0dea5fbSMatthias Ringwald             break;
7288df9e2780SMatthias Ringwald         case HCI_STATE_HALTING:
7289df9e2780SMatthias Ringwald             hci_halting_run();
7290d0dea5fbSMatthias Ringwald             break;
7291df9e2780SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
7292df9e2780SMatthias Ringwald             hci_falling_asleep_run();
7293d0dea5fbSMatthias Ringwald             break;
7294df9e2780SMatthias Ringwald         default:
7295df9e2780SMatthias Ringwald             break;
7296df9e2780SMatthias Ringwald     }
7297df9e2780SMatthias Ringwald 
7298d0dea5fbSMatthias Ringwald     // allow to run after initialization to working transition
7299d0dea5fbSMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING){
7300d0dea5fbSMatthias Ringwald         return;
7301d0dea5fbSMatthias Ringwald     }
7302d0dea5fbSMatthias Ringwald 
7303f30077b7SMatthias Ringwald     bool done;
7304f30077b7SMatthias Ringwald 
7305f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
7306f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
7307f30077b7SMatthias Ringwald     if (done) return;
7308f30077b7SMatthias Ringwald 
730968ab6207SMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
731068ab6207SMatthias Ringwald     done = hci_run_iso_fragments();
731168ab6207SMatthias Ringwald     if (done) return;
731268ab6207SMatthias Ringwald #endif
731368ab6207SMatthias Ringwald 
7314f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
7315f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
7316f30077b7SMatthias Ringwald     if (!hci_can_send_comand_packet_transport()) return;
7317f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
7318f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
7319f30077b7SMatthias Ringwald         return;
7320f30077b7SMatthias Ringwald     }
7321f30077b7SMatthias Ringwald #endif
7322f30077b7SMatthias Ringwald 
7323f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
7324f30077b7SMatthias Ringwald 
7325f30077b7SMatthias Ringwald     // global/non-connection oriented commands
7326f30077b7SMatthias Ringwald 
7327f30077b7SMatthias Ringwald 
7328f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
7329f30077b7SMatthias Ringwald     // general gap classic
7330f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
7331f30077b7SMatthias Ringwald     if (done) return;
7332f30077b7SMatthias Ringwald #endif
7333f30077b7SMatthias Ringwald 
7334f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
7335f30077b7SMatthias Ringwald     // general gap le
7336f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
7337f30077b7SMatthias Ringwald     if (done) return;
73387aa35f6aSMatthias Ringwald 
73397aa35f6aSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
73407aa35f6aSMatthias Ringwald     // ISO related tasks, e.g. BIG create/terminate/sync
73417aa35f6aSMatthias Ringwald     done = hci_run_iso_tasks();
73427aa35f6aSMatthias Ringwald     if (done) return;
73437aa35f6aSMatthias Ringwald #endif
7344f30077b7SMatthias Ringwald #endif
7345f30077b7SMatthias Ringwald 
7346f30077b7SMatthias Ringwald     // send pending HCI commands
7347df9e2780SMatthias Ringwald     hci_run_general_pending_commands();
73483429f56bSmatthias.ringwald }
734916833f0aSmatthias.ringwald 
73500f076adeSMatthias Ringwald #ifdef ENABLE_CLASSIC
7351d7891039SMatthias Ringwald static void hci_set_sco_payload_length_for_flipped_packet_types(hci_connection_t * hci_connection, uint16_t flipped_packet_types){
7352d7891039SMatthias Ringwald     // bits 6-9 are 'don't use'
7353d7891039SMatthias Ringwald     uint16_t packet_types = flipped_packet_types ^ 0x03c0;
7354d7891039SMatthias Ringwald 
7355d7891039SMatthias Ringwald     // restrict packet types to local and remote supported
7356d7891039SMatthias Ringwald     packet_types &= hci_connection->remote_supported_sco_packets & hci_stack->usable_packet_types_sco;
7357d7891039SMatthias Ringwald     hci_connection->sco_payload_length = hci_sco_payload_length_for_packet_types(packet_types);
7358d7891039SMatthias Ringwald     log_info("Possible SCO packet types 0x%04x => payload length %u", packet_types, hci_connection->sco_payload_length);
7359d7891039SMatthias Ringwald }
73600f076adeSMatthias Ringwald #endif
7361d7891039SMatthias Ringwald 
73623e2050f7SMatthias Ringwald uint8_t hci_send_cmd_packet(uint8_t *packet, int size){
736335454696SMatthias Ringwald     // house-keeping
736435454696SMatthias Ringwald 
736535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7366c8e4258aSmatthias.ringwald     bd_addr_t addr;
7367c8e4258aSmatthias.ringwald     hci_connection_t * conn;
7368c123d999SMatthias Ringwald #endif
7369c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
73706f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
73719cbd2215SMatthias Ringwald #endif
7372c8e4258aSmatthias.ringwald 
73736f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
73746f35bb46SMatthias Ringwald     switch (opcode) {
73759cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
73769cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
73779cbd2215SMatthias Ringwald             break;
73789cbd2215SMatthias Ringwald 
73799cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
73806f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
7381724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
73829da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
7383c8e4258aSmatthias.ringwald 
738472cf8859SMatthias Ringwald             // CVE-2020-26555: reject outgoing connection to device with same BD ADDR
738572cf8859SMatthias Ringwald             if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) {
738679e0fa07SMatthias Ringwald                 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR);
73873e2050f7SMatthias Ringwald                 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
738872cf8859SMatthias Ringwald             }
738972cf8859SMatthias Ringwald 
7390f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
7391ad83dc6aS[email protected]             if (!conn) {
739288f925b1SMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
739317f1ba2aSmatthias.ringwald                 if (!conn) {
739417f1ba2aSmatthias.ringwald                     // notify client that alloc failed
73952deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
73963e2050f7SMatthias Ringwald                     return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller
739717f1ba2aSmatthias.ringwald                 }
7398ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
7399ad83dc6aS[email protected]             }
7400aee5d5c1SMatthias Ringwald 
7401ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
74023e2050f7SMatthias Ringwald             // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used
7403ad83dc6aS[email protected]             switch (conn->state) {
7404ad83dc6aS[email protected]                 // if connection active exists
7405ad83dc6aS[email protected]                 case OPEN:
7406f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
740772cf8859SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS);
74083e2050f7SMatthias Ringwald                     // packet not sent to controller
74093e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7410672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
7411672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
7412672e36abSMatthias Ringwald                     break;
7413ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
74146c0d5426SMatthias Ringwald #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS
74156c0d5426SMatthias Ringwald                     if (hci_classic_operation_active()){
74166c0d5426SMatthias Ringwald                         return ERROR_CODE_SUCCESS;
74176c0d5426SMatthias Ringwald                     }
74186c0d5426SMatthias Ringwald #endif
7419532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
7420532f91a5SMatthias Ringwald                     break;
7421ad83dc6aS[email protected]                 default:
7422ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
74233e2050f7SMatthias Ringwald                     // packet not sent to controller
74243e2050f7SMatthias Ringwald                     return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
7425ad83dc6aS[email protected]             }
7426c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
7427229331c6SMatthias Ringwald 
7428229331c6SMatthias Ringwald             // track outgoing connection
7429f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
74306535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
74316f35bb46SMatthias Ringwald             break;
7432ee752bb8SMatthias Ringwald 
74336f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
74349071873aSMatthias Ringwald             conn = hci_connection_for_handle(little_endian_read_16(packet, 3));
74359071873aSMatthias Ringwald             if (conn == NULL) {
74369071873aSMatthias Ringwald                 // neither SCO nor ACL connection for con handle
74379071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
74389071873aSMatthias Ringwald             } else {
7439d7891039SMatthias Ringwald                 uint16_t remote_supported_sco_packets;
74409071873aSMatthias Ringwald                 switch (conn->address_type){
74419071873aSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
74429071873aSMatthias Ringwald                         // assert SCO connection does not exit
7443d9290e95SMatthias Ringwald                         if (hci_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO) != NULL){
74449071873aSMatthias Ringwald                             return ERROR_CODE_COMMAND_DISALLOWED;
74459071873aSMatthias Ringwald                         }
7446d7891039SMatthias Ringwald                         // cache remote sco packet types
7447d7891039SMatthias Ringwald                         remote_supported_sco_packets = conn->remote_supported_sco_packets;
7448d7891039SMatthias Ringwald 
74499071873aSMatthias Ringwald                         // allocate connection struct
745088f925b1SMatthias Ringwald                         conn = create_connection_for_bd_addr_and_type(conn->address, BD_ADDR_TYPE_SCO,
745188f925b1SMatthias Ringwald                                                                       HCI_ROLE_MASTER);
74529071873aSMatthias Ringwald                         if (!conn) {
74539071873aSMatthias Ringwald                             return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
74549071873aSMatthias Ringwald                         }
7455d7891039SMatthias Ringwald                         conn->remote_supported_sco_packets = remote_supported_sco_packets;
74569071873aSMatthias Ringwald                         break;
74579071873aSMatthias Ringwald                     case BD_ADDR_TYPE_SCO:
74589071873aSMatthias Ringwald                         // update of existing SCO connection
74599071873aSMatthias Ringwald                         break;
74609071873aSMatthias Ringwald                     default:
74619071873aSMatthias Ringwald                         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
74629071873aSMatthias Ringwald                 }
74639071873aSMatthias Ringwald             }
7464d9290e95SMatthias Ringwald 
7465d9290e95SMatthias Ringwald             // conn refers to hci connection of type sco now
7466d9290e95SMatthias Ringwald 
74679071873aSMatthias Ringwald             conn->state = SENT_CREATE_CONNECTION;
74689071873aSMatthias Ringwald 
74699071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
74709071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
74719071873aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
74729071873aSMatthias Ringwald 
7473ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
7474ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7475ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
7476d7891039SMatthias Ringwald 
7477d7891039SMatthias Ringwald             // derive sco payload length from packet types
7478d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 18));
74796f35bb46SMatthias Ringwald             break;
74809071873aSMatthias Ringwald 
74816f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
74829071873aSMatthias Ringwald             // get SCO connection
74839071873aSMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
74849071873aSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
74859071873aSMatthias Ringwald             if (conn == NULL){
74869071873aSMatthias Ringwald                 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
74879071873aSMatthias Ringwald             }
74889071873aSMatthias Ringwald 
74899071873aSMatthias Ringwald             conn->state = ACCEPTED_CONNECTION_REQUEST;
74909071873aSMatthias Ringwald 
74919071873aSMatthias Ringwald             // track outgoing connection to handle command status with error
74929071873aSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO;
74939071873aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
74949071873aSMatthias Ringwald 
7495c91e6e4fSMatthias Ringwald             // accept_synchronous_connection? Voice setting at offset 18
7496ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
7497ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
7498d7891039SMatthias Ringwald 
7499d7891039SMatthias Ringwald             // derive sco payload length from packet types
7500d7891039SMatthias Ringwald             hci_set_sco_payload_length_for_flipped_packet_types(conn, little_endian_read_16(packet, 22));
75016f35bb46SMatthias Ringwald             break;
7502ee752bb8SMatthias Ringwald #endif
75034b3e1e19SMatthias Ringwald 
7504a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
7505d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
75066f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
7507b04dfa37SMatthias Ringwald             // white list used?
75086f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
7509b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
7510b04dfa37SMatthias Ringwald                 case 0:
7511b04dfa37SMatthias Ringwald                     // whitelist not used
7512b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
7513b04dfa37SMatthias Ringwald                     break;
7514b04dfa37SMatthias Ringwald                 case 1:
7515b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
7516b04dfa37SMatthias Ringwald                     break;
7517b04dfa37SMatthias Ringwald                 default:
7518b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
7519b04dfa37SMatthias Ringwald                     break;
7520b04dfa37SMatthias Ringwald             }
7521c163146eSMatthias Ringwald             // track outgoing connection
75228f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer address type
7523c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
75246f35bb46SMatthias Ringwald             break;
75258f7da641SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
75268f7da641SMatthias Ringwald         case HCI_OPCODE_HCI_LE_EXTENDED_CREATE_CONNECTION:
75278f7da641SMatthias Ringwald             // white list used?
75288f7da641SMatthias Ringwald             initiator_filter_policy = packet[3];
75298f7da641SMatthias Ringwald             switch (initiator_filter_policy) {
75308f7da641SMatthias Ringwald                 case 0:
75318f7da641SMatthias Ringwald                     // whitelist not used
75328f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
75338f7da641SMatthias Ringwald                     break;
75348f7da641SMatthias Ringwald                 case 1:
75358f7da641SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
75368f7da641SMatthias Ringwald                     break;
75378f7da641SMatthias Ringwald                 default:
75388f7da641SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
75398f7da641SMatthias Ringwald                     break;
75408f7da641SMatthias Ringwald             }
75418f7da641SMatthias Ringwald             // track outgoing connection
75428f7da641SMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[5]; // peer address type
75438f7da641SMatthias Ringwald             reverse_bd_addr( &packet[6], hci_stack->outgoing_addr); // peer address
75448f7da641SMatthias Ringwald             break;
75458f7da641SMatthias Ringwald #endif
75466f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
75476ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
75486f35bb46SMatthias Ringwald             break;
75499cbd2215SMatthias Ringwald #endif
75504ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
75516f35bb46SMatthias Ringwald         default:
75526f35bb46SMatthias Ringwald             break;
7553b04dfa37SMatthias Ringwald     }
755469a97523S[email protected] 
75553a9fb326S[email protected]     hci_stack->num_cmd_packets--;
75565bb5bc3eS[email protected] 
75575bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
75583e2050f7SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
75593e2050f7SMatthias Ringwald     if (err != 0){
75603e2050f7SMatthias Ringwald         return ERROR_CODE_HARDWARE_FAILURE;
75613e2050f7SMatthias Ringwald     }
75623e2050f7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
756331452debSmatthias.ringwald }
75648adf0ddaSmatthias.ringwald 
75652bd8b7e7S[email protected] // disconnect because of security block
75662bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
75672bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
75682bd8b7e7S[email protected]     if (!connection) return;
75692bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
75702bd8b7e7S[email protected] }
75712bd8b7e7S[email protected] 
75722bd8b7e7S[email protected] 
7573dbe1a790S[email protected] // Configure Secure Simple Pairing
7574dbe1a790S[email protected] 
757535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
757635454696SMatthias Ringwald 
7577dbe1a790S[email protected] // enable will enable SSP during init
757815a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
75793a9fb326S[email protected]     hci_stack->ssp_enable = enable;
7580dbe1a790S[email protected] }
7581dbe1a790S[email protected] 
758295d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
758315a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
75842bd8b7e7S[email protected] }
75852bd8b7e7S[email protected] 
7586dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
758715a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
75883a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
7589dbe1a790S[email protected] }
759015a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
75913a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
7592dbe1a790S[email protected] }
7593dbe1a790S[email protected] 
7594dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
759515a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
75963a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
7597dbe1a790S[email protected] }
75985d23aae8SMatthias Ringwald 
75995d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
76005d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
76015d23aae8SMatthias Ringwald }
760222d445d8SMatthias Ringwald bool gap_secure_connections_active(void){
7603eaf85bc8SMatthias Ringwald     return hci_stack->secure_connections_active;
760422d445d8SMatthias Ringwald }
76055d23aae8SMatthias Ringwald 
760635454696SMatthias Ringwald #endif
7607dbe1a790S[email protected] 
760894be1a66SMatthias Ringwald // va_list part of hci_send_cmd
76093e2050f7SMatthias Ringwald uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
7610d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
76119d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
76123e2050f7SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
76139d14b626S[email protected]     }
76149d14b626S[email protected] 
76155127cc62S[email protected]     // for HCI INITIALIZATION
76169da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
76175127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
76185127cc62S[email protected] 
76199d14b626S[email protected]     hci_reserve_packet_buffer();
76209d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
762194be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
76223e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_packet(packet, size);
7623bfea0222SMatthias Ringwald 
7624593702caSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
76253e2050f7SMatthias Ringwald     if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){
7626e2d22487SMatthias Ringwald         hci_release_packet_buffer();
7627068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
7628bfea0222SMatthias Ringwald     }
7629bfea0222SMatthias Ringwald 
76303e2050f7SMatthias Ringwald     return status;
763194be1a66SMatthias Ringwald }
76329d14b626S[email protected] 
763394be1a66SMatthias Ringwald /**
763494be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
763594be1a66SMatthias Ringwald  */
76363e2050f7SMatthias Ringwald uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){
76371cd208adSmatthias.ringwald     va_list argptr;
76381cd208adSmatthias.ringwald     va_start(argptr, cmd);
76393e2050f7SMatthias Ringwald     uint8_t status = hci_send_cmd_va_arg(cmd, argptr);
76401cd208adSmatthias.ringwald     va_end(argptr);
76413e2050f7SMatthias Ringwald     return status;
764293b8dc03Smatthias.ringwald }
7643c8e4258aSmatthias.ringwald 
7644ee091cf1Smatthias.ringwald // Create various non-HCI events.
7645ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
7646ee091cf1Smatthias.ringwald 
7647d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
7648fb37a842SMatthias Ringwald     // dump packet
7649d6b06661SMatthias Ringwald     if (dump) {
765092da54c4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
7651d6b06661SMatthias Ringwald     }
76521ef6bb52SMatthias Ringwald 
7653fb37a842SMatthias Ringwald     // dispatch to all event handlers
76541ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
76551ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
76561ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
76571ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
7658d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
76591ef6bb52SMatthias Ringwald     }
7660d6b06661SMatthias Ringwald }
7661d6b06661SMatthias Ringwald 
7662d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
7663fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
76643d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
7665d6b06661SMatthias Ringwald }
7666d6b06661SMatthias Ringwald 
766735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
7668701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
76693bc639ceSMatthias Ringwald     // notify SCO sender if waiting
7670701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
7671701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
76723bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
7673701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
7674701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
76753d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
76763bc639ceSMatthias Ringwald     }
76773bc639ceSMatthias Ringwald }
76781cfb383eSMatthias Ringwald 
76791cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
76809784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
7681ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
76821cfb383eSMatthias Ringwald 
76831cfb383eSMatthias Ringwald     uint8_t * eir_data;
76841cfb383eSMatthias Ringwald     ad_context_t context;
76851cfb383eSMatthias Ringwald     const uint8_t * name;
76861cfb383eSMatthias Ringwald     uint8_t         name_len;
76871cfb383eSMatthias Ringwald 
76889784dac1SMatthias Ringwald     if (size < 3) return;
76899784dac1SMatthias Ringwald 
76901cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
7691a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
76921cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
76931cfb383eSMatthias Ringwald 
76949784dac1SMatthias Ringwald     switch (event_type){
76959784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
76969784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
76979784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
76989784dac1SMatthias Ringwald             break;
76999784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
77009784dac1SMatthias Ringwald             if (size != 257) return;
77019784dac1SMatthias Ringwald             if (num_responses != 1) return;
77029784dac1SMatthias Ringwald             break;
77039784dac1SMatthias Ringwald         default:
77049784dac1SMatthias Ringwald             return;
77059784dac1SMatthias Ringwald     }
77069784dac1SMatthias Ringwald 
77071cfb383eSMatthias Ringwald     // event[1] is set at the end
77081cfb383eSMatthias Ringwald     int i;
77091cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
77101cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
77111cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
7712ac973fd6SMatthias Ringwald         uint8_t event_size = 27;    // if name is not set by EIR
77131cfb383eSMatthias Ringwald 
77146535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
77150e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
77166535961aSMatthias Ringwald         (void)memcpy(&event[9],
77176535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
77186535961aSMatthias Ringwald                      3); // class of device
77196535961aSMatthias Ringwald         (void)memcpy(&event[12],
77206535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
77216535961aSMatthias Ringwald                      2); // clock offset
77221cfb383eSMatthias Ringwald 
77231cfb383eSMatthias Ringwald         switch (event_type){
77241cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
77251cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
77261cfb383eSMatthias Ringwald                 break;
77271cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
77281cfb383eSMatthias Ringwald                 event[14] = 1;
7729a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
77301cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
77311cfb383eSMatthias Ringwald                 break;
77321cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
77331cfb383eSMatthias Ringwald                 event[14] = 1;
7734a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
773579186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
77361cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
77371cfb383eSMatthias Ringwald                 name = NULL;
7738a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
7739a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
77401cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
77411cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
77421cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
7743ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
77441cfb383eSMatthias Ringwald                     switch (data_type){
77451cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
77461cfb383eSMatthias Ringwald                             if (name) continue;
7747cf373d3aSMatthias Ringwald                             /* fall through */
77481cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
77491cfb383eSMatthias Ringwald                             name = data;
77501cfb383eSMatthias Ringwald                             name_len = data_size;
77511cfb383eSMatthias Ringwald                             break;
7752ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
7753ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
7754ac9136ccSMatthias Ringwald                             event[16] = 1;
77553c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
7756ac9136ccSMatthias Ringwald                             break;
77571cfb383eSMatthias Ringwald                         default:
77581cfb383eSMatthias Ringwald                             break;
77591cfb383eSMatthias Ringwald                     }
77601cfb383eSMatthias Ringwald                 }
77611cfb383eSMatthias Ringwald                 if (name){
7762ac9136ccSMatthias Ringwald                     event[25] = 1;
77631cfb383eSMatthias Ringwald                     // truncate name if needed
77641cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
7765ac9136ccSMatthias Ringwald                     event[26] = len;
7766ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
77671cfb383eSMatthias Ringwald                     event_size += len;
77681cfb383eSMatthias Ringwald                 }
77691cfb383eSMatthias Ringwald                 break;
77707bbeb3adSMilanka Ringwald             default:
77717bbeb3adSMilanka Ringwald                 return;
77721cfb383eSMatthias Ringwald         }
77731cfb383eSMatthias Ringwald         event[1] = event_size - 2;
77741cfb383eSMatthias Ringwald         hci_emit_event(event, event_size, 1);
77751cfb383eSMatthias Ringwald     }
77761cfb383eSMatthias Ringwald }
777735454696SMatthias Ringwald #endif
77783bc639ceSMatthias Ringwald 
777971de195eSMatthias Ringwald void hci_emit_state(void){
77803a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
7781425d1371Smatthias.ringwald     uint8_t event[3];
778280d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
77834ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
77843a9fb326S[email protected]     event[2] = hci_stack->state;
7785d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7786c8e4258aSmatthias.ringwald }
7787c8e4258aSmatthias.ringwald 
778835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
77892deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
7790425d1371Smatthias.ringwald     uint8_t event[13];
7791c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
7792425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
779317f1ba2aSmatthias.ringwald     event[2] = status;
77942deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
77952deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
7796c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
7797c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
7798d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7799c8e4258aSmatthias.ringwald }
780052db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
780152db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
780252db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
780352db98b2SMatthias Ringwald     uint8_t event[4];
780452db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
780552db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
780652db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
780752db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
780852db98b2SMatthias Ringwald }
780935454696SMatthias Ringwald #endif
7810c8e4258aSmatthias.ringwald 
781135454696SMatthias Ringwald #ifdef ENABLE_BLE
7812d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7813667ba9d1SMatthias 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){
78144f3229d8S[email protected]     uint8_t event[21];
78154f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
78164ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
78174f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
78184f3229d8S[email protected]     event[3] = status;
7819fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
78204f3229d8S[email protected]     event[6] = 0; // TODO: role
78216e2e9a6bS[email protected]     event[7] = address_type;
7822724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
7823f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
7824f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
7825f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
78264f3229d8S[email protected]     event[20] = 0; // master clock accuracy
7827d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
78284f3229d8S[email protected] }
782935454696SMatthias Ringwald #endif
7830d70217a2SMatthias Ringwald #endif
78314f3229d8S[email protected] 
7832fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
7833fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
7834fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
7835fd43c0e0SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
7836fd43c0e0SMatthias Ringwald }
7837fd43c0e0SMatthias Ringwald 
7838fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
7839425d1371Smatthias.ringwald     uint8_t event[6];
78403c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
78414ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
78423c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
7843fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
78443c4d4b90Smatthias.ringwald     event[5] = reason;
7845d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
78463c4d4b90Smatthias.ringwald }
78473c4d4b90Smatthias.ringwald 
7848b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
7849e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
7850425d1371Smatthias.ringwald     uint8_t event[3];
785180d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
78524ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
785343bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
7854d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
785543bfb1bdSmatthias.ringwald }
7856038bc64cSmatthias.ringwald 
7857b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
7858e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
7859425d1371Smatthias.ringwald     uint8_t event[2];
786080d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
78614ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
7862d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7863038bc64cSmatthias.ringwald }
78641b0e3922Smatthias.ringwald 
786535454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
786635454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
786735454696SMatthias Ringwald     uint8_t event[9];
786835454696SMatthias Ringwald     int pos = 0;
786935454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
78704ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
787135454696SMatthias Ringwald     event[pos++] = status;
787235454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
7873d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7874381fbed8Smatthias.ringwald }
7875458bf4e8S[email protected] 
787635454696SMatthias Ringwald 
787735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
787835454696SMatthias Ringwald 
7879b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
7880df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
7881a00031e2S[email protected]     uint8_t event[5];
7882e00caf9cS[email protected]     int pos = 0;
78835611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
7884e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
7885f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
7886e00caf9cS[email protected]     pos += 2;
7887e00caf9cS[email protected]     event[pos++] = level;
7888d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7889e00caf9cS[email protected] }
7890e00caf9cS[email protected] 
789135454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
789235454696SMatthias Ringwald     if (!connection) return LEVEL_0;
78938daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
7894fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
78958daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
7896170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
78974051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
7898170fafaeSMatthias Ringwald     // LEVEL 4 always requires 128 bit encrytion key size
78990e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
7900170fafaeSMatthias Ringwald         security_level = LEVEL_3;
7901170fafaeSMatthias Ringwald     }
7902170fafaeSMatthias Ringwald     return security_level;
790335454696SMatthias Ringwald }
790435454696SMatthias Ringwald 
790571fd255dSMatthias Ringwald static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){
790671fd255dSMatthias Ringwald     uint8_t event[4];
790771fd255dSMatthias Ringwald     event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED;
790835454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
790971fd255dSMatthias Ringwald     event[2] = discoverable;
791071fd255dSMatthias Ringwald     event[3] = connectable;
7911d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
7912ad83dc6aS[email protected] }
7913ad83dc6aS[email protected] 
791498a2fd1cSMatthias Ringwald // query if remote side supports eSCO
791520dcdd22SMatthias Ringwald bool hci_remote_esco_supported(hci_con_handle_t con_handle){
791698a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
791720dcdd22SMatthias Ringwald     if (!connection) return false;
791876ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
791998a2fd1cSMatthias Ringwald }
792098a2fd1cSMatthias Ringwald 
79210b78a447SMatthias Ringwald uint16_t hci_remote_sco_packet_types(hci_con_handle_t con_handle){
79220b78a447SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
79230b78a447SMatthias Ringwald     if (!connection) return 0;
79240b78a447SMatthias Ringwald     return connection->remote_supported_sco_packets;
79250b78a447SMatthias Ringwald }
79260b78a447SMatthias Ringwald 
792767aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
792867aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
792967aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
793067aae551SMatthias Ringwald }
793167aae551SMatthias Ringwald 
79322bd8b7e7S[email protected] // query if remote side supports SSP
793320dcdd22SMatthias Ringwald bool hci_remote_ssp_supported(hci_con_handle_t con_handle){
79342bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
793520dcdd22SMatthias Ringwald     if (!connection) return false;
793667aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
79372bd8b7e7S[email protected] }
79382bd8b7e7S[email protected] 
793920dcdd22SMatthias Ringwald bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
7940df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
7941df3354fcS[email protected] }
7942df3354fcS[email protected] 
79436ffc78ceSMatthias Ringwald /**
79446ffc78ceSMatthias Ringwald  * Check if remote supported features query has completed
79456ffc78ceSMatthias Ringwald  */
79466ffc78ceSMatthias Ringwald bool hci_remote_features_available(hci_con_handle_t handle){
79476ffc78ceSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(handle);
79486ffc78ceSMatthias Ringwald     if (!connection) return false;
79496ffc78ceSMatthias Ringwald     return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0;
79506ffc78ceSMatthias Ringwald }
79516ffc78ceSMatthias Ringwald 
7952d6596031SMatthias Ringwald /**
7953d6596031SMatthias Ringwald  * Trigger remote supported features query
7954d6596031SMatthias Ringwald  */
7955c9742cd1SMatthias Ringwald 
7956c9742cd1SMatthias Ringwald static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){
7957c9742cd1SMatthias Ringwald     if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){
7958c9742cd1SMatthias Ringwald         connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
7959c9742cd1SMatthias Ringwald     }
7960c9742cd1SMatthias Ringwald }
7961c9742cd1SMatthias Ringwald 
7962d6596031SMatthias Ringwald void hci_remote_features_query(hci_con_handle_t con_handle){
7963d6596031SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
7964d6596031SMatthias Ringwald     if (!connection) return;
7965c9742cd1SMatthias Ringwald     hci_trigger_remote_features_for_connection(connection);
7966d6596031SMatthias Ringwald     hci_run();
7967d6596031SMatthias Ringwald }
7968d6596031SMatthias Ringwald 
7969458bf4e8S[email protected] // GAP API
7970458bf4e8S[email protected] /**
7971458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
7972458bf4e8S[email protected]  * @praram enabled
7973458bf4e8S[email protected]  */
79744c57c146S[email protected] void gap_set_bondable_mode(int enable){
79753a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
7976458bf4e8S[email protected] }
79774ef6443cSMatthias Ringwald /**
79784ef6443cSMatthias Ringwald  * @brief Get bondable mode.
79794ef6443cSMatthias Ringwald  * @return 1 if bondable
79804ef6443cSMatthias Ringwald  */
79814ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
79824ef6443cSMatthias Ringwald     return hci_stack->bondable;
79834ef6443cSMatthias Ringwald }
7984cb230b9dS[email protected] 
7985cb230b9dS[email protected] /**
798634d2123cS[email protected]  * @brief map link keys to security levels
7987cb230b9dS[email protected]  */
798834d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
798934d2123cS[email protected]     switch (link_key_type){
79903c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
79913c68dfa9S[email protected]             return LEVEL_4;
79923c68dfa9S[email protected]         case COMBINATION_KEY:
79933c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
79943c68dfa9S[email protected]             return LEVEL_3;
79953c68dfa9S[email protected]         default:
79963c68dfa9S[email protected]             return LEVEL_2;
79973c68dfa9S[email protected]     }
7998cb230b9dS[email protected] }
7999cb230b9dS[email protected] 
80008b35e16aSMatthias Ringwald /**
80018b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
80028b35e16aSMatthias Ringwald  */
800336c3546bSMatthias Ringwald bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
80048b35e16aSMatthias Ringwald     switch (link_key_type){
80058b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
80068b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
800736c3546bSMatthias Ringwald             return true;
80088b35e16aSMatthias Ringwald         default:
800936c3546bSMatthias Ringwald             return false;
80108b35e16aSMatthias Ringwald     }
80118b35e16aSMatthias Ringwald }
80128b35e16aSMatthias Ringwald 
80138b35e16aSMatthias Ringwald /**
80148b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
80158b35e16aSMatthias Ringwald  */
80167040ba26SMatthias Ringwald bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
80178b35e16aSMatthias Ringwald     switch (link_key_type){
80188b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
80198b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
80207040ba26SMatthias Ringwald             return true;
80218b35e16aSMatthias Ringwald         default:
80227040ba26SMatthias Ringwald             return false;
80238b35e16aSMatthias Ringwald     }
80248b35e16aSMatthias Ringwald }
80258b35e16aSMatthias Ringwald 
8026552b9260SMatthias Ringwald bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){
80275127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
8028106d6d11S[email protected]     return level > LEVEL_2;
8029106d6d11S[email protected] }
8030106d6d11S[email protected] 
803134d2123cS[email protected] /**
803234d2123cS[email protected]  * @brief get current security level
803334d2123cS[email protected]  */
803434d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
803534d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
803634d2123cS[email protected]     if (!connection) return LEVEL_0;
803734d2123cS[email protected]     return gap_security_level_for_connection(connection);
803834d2123cS[email protected] }
803934d2123cS[email protected] 
8040cb230b9dS[email protected] /**
8041cb230b9dS[email protected]  * @brief request connection to device to
8042cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
8043cb230b9dS[email protected]  */
804434d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
804534d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
804634d2123cS[email protected]     if (!connection){
8047a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
804834d2123cS[email protected]         return;
804934d2123cS[email protected]     }
8050defbf200SMatthias Ringwald 
8051defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
8052defbf200SMatthias Ringwald 
8053bc00e12cSMatthias 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)
8054bc00e12cSMatthias Ringwald     // available on the BR/EDR physical transport require Security Mode 4, Level 4 "
8055bc00e12cSMatthias Ringwald     if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){
8056bc00e12cSMatthias Ringwald         requested_level = LEVEL_4;
8057bc00e12cSMatthias Ringwald     }
8058bc00e12cSMatthias Ringwald 
805934d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
806083d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
806183d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
806283d08d7cSMatthias Ringwald 
8063dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
8064dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
8065dbd5dcc3SMatthias Ringwald     if (authentication_active){
80661cf0a6c8SMatthias Ringwald         // authentication already active
806783d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
806883d08d7cSMatthias Ringwald             // increase requested level as new level is higher
806983d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
807083d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
807183d08d7cSMatthias Ringwald         }
80721cf0a6c8SMatthias Ringwald     } else {
807383d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
807483d08d7cSMatthias Ringwald         if (requested_level <= current_level){
8075a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
807634d2123cS[email protected]             return;
807734d2123cS[email protected]         }
8078a00031e2S[email protected] 
8079e060c07dSMatthias Ringwald         // store request
808034d2123cS[email protected]         connection->requested_security_level = requested_level;
8081a00031e2S[email protected] 
80821cf0a6c8SMatthias Ringwald         // start to authenticate connection
80831eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
80847fdbaf79SMatthias Ringwald 
80857fdbaf79SMatthias Ringwald         // request remote features if not already active, also trigger hci_run
80867fdbaf79SMatthias Ringwald         hci_remote_features_query(con_handle);
8087e00caf9cS[email protected]     }
80881cf0a6c8SMatthias Ringwald }
8089ad83dc6aS[email protected] 
8090ad83dc6aS[email protected] /**
8091ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
8092ad83dc6aS[email protected]  * @param device
8093ad83dc6aS[email protected]  * @param request MITM protection
8094ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
8095ad83dc6aS[email protected]  */
8096ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
8097ad83dc6aS[email protected] 
8098ad83dc6aS[email protected]     // create connection state machine
809988f925b1SMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL, HCI_ROLE_MASTER);
8100ad83dc6aS[email protected] 
8101ad83dc6aS[email protected]     if (!connection){
8102ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
8103ad83dc6aS[email protected]     }
8104ad83dc6aS[email protected] 
81054cd03f8aSMatthias Ringwald     // delete link key
810615a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
8107ad83dc6aS[email protected] 
8108ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
8109ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
8110ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
8111f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
8112ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
8113ad83dc6aS[email protected] 
8114ad83dc6aS[email protected]     hci_run();
8115ad83dc6aS[email protected] 
8116ad83dc6aS[email protected]     return 0;
8117ad83dc6aS[email protected] }
81188e618f72S[email protected] 
8119f82b8f4bSMatthias Ringwald uint8_t hci_dedicated_bonding_defer_disconnect(hci_con_handle_t con_handle, bool defer){
8120ab0c69a9SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8121ab0c69a9SMatthias Ringwald     if (connection == NULL){
8122ab0c69a9SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8123ab0c69a9SMatthias Ringwald     }
8124ab0c69a9SMatthias Ringwald     if (defer){
8125ab0c69a9SMatthias Ringwald         connection->bonding_flags |= BONDING_DEDICATED_DEFER_DISCONNECT;
8126ab0c69a9SMatthias Ringwald     } else {
8127ab0c69a9SMatthias Ringwald         connection->bonding_flags &= ~BONDING_DEDICATED_DEFER_DISCONNECT;
8128ab0c69a9SMatthias Ringwald         // trigger disconnect
8129ab0c69a9SMatthias Ringwald         hci_run();
8130ab0c69a9SMatthias Ringwald     }
8131ab0c69a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8132ab0c69a9SMatthias Ringwald }
8133ab0c69a9SMatthias Ringwald 
81348e618f72S[email protected] void gap_set_local_name(const char * local_name){
81358e618f72S[email protected]     hci_stack->local_name = local_name;
8136baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME;
813759d59ecfSMatthias Ringwald     // also update EIR if not set by user
813859d59ecfSMatthias Ringwald     if (hci_stack->eir_data == NULL){
8139baa4881eSMatthias Ringwald         hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
814059d59ecfSMatthias Ringwald     }
814159d59ecfSMatthias Ringwald     hci_run();
81428e618f72S[email protected] }
81431aeec2ebSMatthias Ringwald #endif
81448e618f72S[email protected] 
814535454696SMatthias Ringwald 
814635454696SMatthias Ringwald #ifdef ENABLE_BLE
814735454696SMatthias Ringwald 
8148d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8149d8e8f12aSMatthias Ringwald void gap_start_scan(void){
8150fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
81517bdc6798S[email protected]     hci_run();
81527bdc6798S[email protected] }
81538e618f72S[email protected] 
8154d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
8155fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
81567bdc6798S[email protected]     hci_run();
81577bdc6798S[email protected] }
81584f3229d8S[email protected] 
8159a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
8160ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
8161a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
8162ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
8163ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
81648b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
8165ef11999fSmatthias.ringwald     hci_run();
8166ef11999fSmatthias.ringwald }
81674f3229d8S[email protected] 
8168a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
8169a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
8170a7a719e9SMatthias Ringwald }
8171a7a719e9SMatthias Ringwald 
81724856283bSMatthias Ringwald void gap_set_scan_duplicate_filter(bool enabled){
81734856283bSMatthias Ringwald     hci_stack->le_scan_filter_duplicates = enabled ? 1 : 0;
81744856283bSMatthias Ringwald }
81754856283bSMatthias Ringwald 
81767eb5b27eSMatthias Ringwald void gap_set_scan_phys(uint8_t phys){
81777eb5b27eSMatthias Ringwald     // LE Coded and LE 1M PHY
81787eb5b27eSMatthias Ringwald     hci_stack->le_scan_phys = phys & 0x05;
81797eb5b27eSMatthias Ringwald }
81807eb5b27eSMatthias Ringwald 
8181667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
81824f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
81834f3229d8S[email protected]     if (!conn){
8184d32b3f05SMatthias Ringwald         // disallow if le connection is already outgoing
8185d32b3f05SMatthias Ringwald         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
8186d32b3f05SMatthias Ringwald             log_error("le connection already active");
8187d32b3f05SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
8188d32b3f05SMatthias Ringwald         }
8189d32b3f05SMatthias Ringwald 
8190d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
819188f925b1SMatthias Ringwald         conn = create_connection_for_bd_addr_and_type(addr, addr_type, HCI_ROLE_MASTER);
81924f3229d8S[email protected]         if (!conn){
81934f3229d8S[email protected]             // notify client that alloc failed
81946e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
8195d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
8196472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
81974f3229d8S[email protected]         }
8198d5b1a89eSMatthias Ringwald 
8199d5b1a89eSMatthias Ringwald         // set le connecting state
8200d5b1a89eSMatthias Ringwald         if (hci_is_le_connection_type(addr_type)){
8201d5b1a89eSMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
8202d5b1a89eSMatthias Ringwald         }
8203d5b1a89eSMatthias Ringwald 
82044f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
8205d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
8206564fca32S[email protected]         hci_run();
8207b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
82084f3229d8S[email protected]     }
82090bf6344aS[email protected] 
82100bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
8211a1df452eSMatthias Ringwald         (conn->state == SEND_CREATE_CONNECTION) ||
82120e588213SMatthias Ringwald         (conn->state == SENT_CREATE_CONNECTION)) {
82132e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
8214d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
8215616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
82160bf6344aS[email protected]     }
82170bf6344aS[email protected] 
8218b0136355SMatthias Ringwald     // check if connection was just disconnected
8219b0136355SMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
8220b0136355SMatthias Ringwald         log_info("gap_connect: send create connection (again)");
8221b0136355SMatthias Ringwald         conn->state = SEND_CREATE_CONNECTION;
8222b0136355SMatthias Ringwald         hci_run();
8223b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
8224b0136355SMatthias Ringwald     }
8225b0136355SMatthias Ringwald 
8226d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
8227d5b1a89eSMatthias Ringwald     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
82284f3229d8S[email protected]     hci_run();
8229b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
82304f3229d8S[email protected] }
82314f3229d8S[email protected] 
82327851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
8233d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
8234665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
8235a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
82360bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
82370bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
82380bf6344aS[email protected]         switch (conn->state){
8239a6725849S[email protected]             case SEND_CREATE_CONNECTION:
82407851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
82417851196eSmatthias.ringwald                 return conn;
82427851196eSmatthias.ringwald             default:
82437851196eSmatthias.ringwald                 break;
82447851196eSmatthias.ringwald         };
82457851196eSmatthias.ringwald     }
82467851196eSmatthias.ringwald     return NULL;
82477851196eSmatthias.ringwald }
82487851196eSmatthias.ringwald 
8249d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
825014f2d8f0SMatthias Ringwald     hci_connection_t * conn;
825114f2d8f0SMatthias Ringwald     switch (hci_stack->le_connecting_request){
825214f2d8f0SMatthias Ringwald         case LE_CONNECTING_IDLE:
825314f2d8f0SMatthias Ringwald             break;
825414f2d8f0SMatthias Ringwald         case LE_CONNECTING_WHITELIST:
825514f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
825614f2d8f0SMatthias Ringwald             hci_run();
825714f2d8f0SMatthias Ringwald             break;
825814f2d8f0SMatthias Ringwald         case LE_CONNECTING_DIRECT:
825914f2d8f0SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
826014f2d8f0SMatthias Ringwald             conn = gap_get_outgoing_connection();
826114f2d8f0SMatthias Ringwald             if (conn == NULL){
826214f2d8f0SMatthias Ringwald                 hci_run();
826314f2d8f0SMatthias Ringwald             } else {
82647851196eSmatthias.ringwald                 switch (conn->state){
82657851196eSmatthias.ringwald                     case SEND_CREATE_CONNECTION:
82667851196eSmatthias.ringwald                         // skip sending create connection and emit event instead
82672e77e513S[email protected]                         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
8268665d90f2SMatthias Ringwald                         btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
82697851196eSmatthias.ringwald                         btstack_memory_hci_connection_free( conn );
82700bf6344aS[email protected]                         break;
8271a6725849S[email protected]                     case SENT_CREATE_CONNECTION:
8272ea04fbd8SMatthias Ringwald                         // let hci_run_general_gap_le cancel outgoing connection
82730bf6344aS[email protected]                         hci_run();
82740bf6344aS[email protected]                         break;
82750bf6344aS[email protected]                     default:
82760bf6344aS[email protected]                         break;
82770bf6344aS[email protected]                 }
827814f2d8f0SMatthias Ringwald             }
827914f2d8f0SMatthias Ringwald             break;
828043dfd98aSMatthias Ringwald         default:
828114f2d8f0SMatthias Ringwald             btstack_unreachable();
828214f2d8f0SMatthias Ringwald             break;
828314f2d8f0SMatthias Ringwald     }
828414f2d8f0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8285e31f89a7S[email protected] }
82864f3229d8S[email protected] 
8287c37a3166S[email protected] /**
82886012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
8289cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
8290cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
82916012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
82926012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
82936012052bSMatthias Ringwald  * @param conn_latency, default: 4
82946012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
82956012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
82966012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
82976012052bSMatthias Ringwald  */
82986012052bSMatthias Ringwald 
82990c2c5f79SMatthias Ringwald void gap_set_connection_phys(uint8_t phys){
83000c2c5f79SMatthias Ringwald     // LE Coded, LE 1M, LE 2M PHY
83010c2c5f79SMatthias Ringwald     hci_stack->le_connection_phys = phys & 7;
83020c2c5f79SMatthias Ringwald }
83030c2c5f79SMatthias Ringwald 
83040c2c5f79SMatthias Ringwald #endif
83050c2c5f79SMatthias Ringwald 
8306cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
8307cbe54ab2SJakob Krantz                                    uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
8308cbe54ab2SJakob Krantz                                    uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
8309cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
8310cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
83116012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
83126012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
83136012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
83146012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
83156012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
83166012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
83176012052bSMatthias Ringwald }
83187eb5b27eSMatthias Ringwald 
83196012052bSMatthias Ringwald /**
8320c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
8321c37a3166S[email protected]  * @param handle
8322c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
8323c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
8324c37a3166S[email protected]  * @param conn_latency
8325c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
83266b65794dSMilanka Ringwald  * @return 0 if ok
8327c37a3166S[email protected]  */
8328c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8329c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8330c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8331c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8332c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
8333c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
8334c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
8335c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
833684cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
8337cfc59f1bSMatthias Ringwald     hci_run();
8338c37a3166S[email protected]     return 0;
8339c37a3166S[email protected] }
8340c37a3166S[email protected] 
834145c102fdSMatthias Ringwald /**
8342b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
8343b68d7bc3SMatthias Ringwald  * @param handle
8344b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
8345b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
8346b68d7bc3SMatthias Ringwald  * @param conn_latency
8347b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
83486b65794dSMilanka Ringwald  * @return 0 if ok
8349b68d7bc3SMatthias Ringwald  */
8350b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
8351b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
8352b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
8353b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8354b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
8355b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
8356b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
8357b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
8358b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
835909c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
836009c9c963SMatthias Ringwald     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
8361b68d7bc3SMatthias Ringwald     return 0;
8362b68d7bc3SMatthias Ringwald }
8363b68d7bc3SMatthias Ringwald 
8364d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
8365d70217a2SMatthias Ringwald 
8366b68d7bc3SMatthias Ringwald /**
836745c102fdSMatthias Ringwald  * @brief Set Advertisement Data
836845c102fdSMatthias Ringwald  * @param advertising_data_length
836945c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
837045c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
837145c102fdSMatthias Ringwald  */
837245c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
837345c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
837445c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
8375501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8376bbc366e6SMatthias Ringwald     hci_run();
837745c102fdSMatthias Ringwald }
8378501f56b3SMatthias Ringwald 
8379501f56b3SMatthias Ringwald /**
8380501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
8381501f56b3SMatthias Ringwald  * @param advertising_data_length
8382501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
8383501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
8384501f56b3SMatthias Ringwald  */
8385501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
8386501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
8387501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
8388501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8389bbc366e6SMatthias Ringwald     hci_run();
839045c102fdSMatthias Ringwald }
839145c102fdSMatthias Ringwald 
839245c102fdSMatthias Ringwald /**
839345c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
839445c102fdSMatthias Ringwald  * @param adv_int_min
839545c102fdSMatthias Ringwald  * @param adv_int_max
839645c102fdSMatthias Ringwald  * @param adv_type
839745c102fdSMatthias Ringwald  * @param direct_address_type
839845c102fdSMatthias Ringwald  * @param direct_address
839945c102fdSMatthias Ringwald  * @param channel_map
840045c102fdSMatthias Ringwald  * @param filter_policy
840145c102fdSMatthias Ringwald  *
840245c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
840345c102fdSMatthias Ringwald  */
840445c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
8405b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
840645c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
840745c102fdSMatthias Ringwald 
840845c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
840945c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
841045c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
841145c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
841245c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
841345c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
84146535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
84156535961aSMatthias Ringwald                  6);
841645c102fdSMatthias Ringwald 
84176bf435a6SMatthias Ringwald     hci_stack->le_advertisements_todo  |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
84186bf435a6SMatthias Ringwald     hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET;
8419bbc366e6SMatthias Ringwald     hci_run();
842045c102fdSMatthias Ringwald  }
842145c102fdSMatthias Ringwald 
842245c102fdSMatthias Ringwald /**
842345c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
842445c102fdSMatthias Ringwald  * @param enabled
842545c102fdSMatthias Ringwald  */
842645c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
8427a408e724SMatthias Ringwald     if (enabled == 0){
8428a408e724SMatthias Ringwald         hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8429a408e724SMatthias Ringwald     } else {
8430a408e724SMatthias Ringwald         hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED;
8431a408e724SMatthias Ringwald     }
8432bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
8433cfc59f1bSMatthias Ringwald     hci_run();
843445c102fdSMatthias Ringwald }
843545c102fdSMatthias Ringwald 
8436a5770ecbSMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
8437a5770ecbSMatthias Ringwald static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){
8438a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_t it;
8439a5770ecbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets);
8440a5770ecbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8441a5770ecbSMatthias Ringwald         le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it);
8442a5770ecbSMatthias Ringwald         if ( item->advertising_handle == advertising_handle ) {
8443a5770ecbSMatthias Ringwald             return item;
8444a5770ecbSMatthias Ringwald         }
8445a5770ecbSMatthias Ringwald     }
8446a5770ecbSMatthias Ringwald     return NULL;
8447a5770ecbSMatthias Ringwald }
8448a5770ecbSMatthias Ringwald 
84492052d96cSMatthias Ringwald uint8_t gap_extended_advertising_set_resolvable_private_address_update(uint16_t update_s){
84502052d96cSMatthias Ringwald     hci_stack->le_resolvable_private_address_update_s = update_s;
84512052d96cSMatthias Ringwald     hci_run();
84522052d96cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
84532052d96cSMatthias Ringwald }
84542052d96cSMatthias Ringwald 
8455a5770ecbSMatthias 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){
8456a5770ecbSMatthias Ringwald     // find free advertisement handle
8457a5770ecbSMatthias Ringwald     uint8_t advertisement_handle;
8458a5770ecbSMatthias Ringwald     for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){
8459a5770ecbSMatthias Ringwald         if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break;
8460a5770ecbSMatthias Ringwald     }
8461a5770ecbSMatthias Ringwald     if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
8462a5770ecbSMatthias Ringwald     // clear
8463a5770ecbSMatthias Ringwald     memset(storage, 0, sizeof(le_advertising_set_t));
8464a5770ecbSMatthias Ringwald     // copy params
84650cbe4690SMatthias Ringwald     storage->advertising_handle = advertisement_handle;
846657a04237SMatthias Ringwald     memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8467a5770ecbSMatthias Ringwald     // add to list
8468a5770ecbSMatthias Ringwald     bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage);
8469a5770ecbSMatthias Ringwald     if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
84700cbe4690SMatthias Ringwald     *out_advertising_handle = advertisement_handle;
8471a5770ecbSMatthias Ringwald     // set tasks and start
8472a5770ecbSMatthias Ringwald     storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8473a5770ecbSMatthias Ringwald     hci_run();
8474a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8475a5770ecbSMatthias Ringwald }
8476a5770ecbSMatthias Ringwald 
8477a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){
8478a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8479a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
848057a04237SMatthias Ringwald     memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t));
8481a5770ecbSMatthias Ringwald     // set tasks and start
8482a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8483a5770ecbSMatthias Ringwald     hci_run();
8484a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8485a5770ecbSMatthias Ringwald }
8486a5770ecbSMatthias Ringwald 
8487a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){
8488a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8489a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
849057a04237SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t));
8491a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8492a5770ecbSMatthias Ringwald }
8493a5770ecbSMatthias Ringwald 
8494a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){
8495a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8496a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8497a5770ecbSMatthias Ringwald     memcpy(advertising_set->random_address, random_address, 6);
8498a5770ecbSMatthias Ringwald     // set tasks and start
8499a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
8500a5770ecbSMatthias Ringwald     hci_run();
8501a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8502a5770ecbSMatthias Ringwald }
8503a5770ecbSMatthias Ringwald 
85042e4aaf70SMatthias Ringwald uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){
8505a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8506a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8507a5770ecbSMatthias Ringwald     advertising_set->adv_data = advertising_data;
8508a5770ecbSMatthias Ringwald     advertising_set->adv_data_len = advertising_data_length;
8509a5770ecbSMatthias Ringwald     // set tasks and start
8510a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
8511a5770ecbSMatthias Ringwald     hci_run();
8512a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8513a5770ecbSMatthias Ringwald }
8514a5770ecbSMatthias Ringwald 
85152e4aaf70SMatthias 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){
8516a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8517a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8518a5770ecbSMatthias Ringwald     advertising_set->scan_data = scan_response_data;
8519a5770ecbSMatthias Ringwald     advertising_set->scan_data_len = scan_response_data_length;
8520a5770ecbSMatthias Ringwald     // set tasks and start
8521a5770ecbSMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
8522a5770ecbSMatthias Ringwald     hci_run();
8523a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8524a5770ecbSMatthias Ringwald }
8525a5770ecbSMatthias Ringwald 
8526a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){
8527a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8528a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8529a5770ecbSMatthias Ringwald     advertising_set->enable_timeout = timeout;
8530a5770ecbSMatthias Ringwald     advertising_set->enable_max_scan_events = num_extended_advertising_events;
8531a5770ecbSMatthias Ringwald     // set tasks and start
8532a5770ecbSMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED;
8533a5770ecbSMatthias Ringwald     hci_run();
8534a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8535a5770ecbSMatthias Ringwald }
8536a5770ecbSMatthias Ringwald 
8537a5770ecbSMatthias Ringwald uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){
8538a5770ecbSMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8539a5770ecbSMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8540a5770ecbSMatthias Ringwald     // set tasks and start
8541a5770ecbSMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED;
8542a5770ecbSMatthias Ringwald     hci_run();
8543a5770ecbSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8544a5770ecbSMatthias Ringwald }
8545a5770ecbSMatthias Ringwald 
8546c814a904SMatthias Ringwald uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){
8547c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8548c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8549c814a904SMatthias Ringwald     // set tasks and start
8550c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET;
8551c814a904SMatthias Ringwald     hci_run();
8552c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8553c814a904SMatthias Ringwald }
8554c814a904SMatthias Ringwald 
8555c814a904SMatthias Ringwald #ifdef ENABLE_LE_PERIODIC_ADVERTISING
8556c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){
8557c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8558c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8559c814a904SMatthias Ringwald     // periodic advertising requires neither connectable, scannable, legacy or anonymous
8560c814a904SMatthias Ringwald     if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8561c814a904SMatthias Ringwald     memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t));
8562c814a904SMatthias Ringwald     // set tasks and start
8563c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS;
8564c814a904SMatthias Ringwald     hci_run();
8565c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8566c814a904SMatthias Ringwald }
8567c814a904SMatthias Ringwald 
8568c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){
8569c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8570c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8571c814a904SMatthias Ringwald     memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t));
8572c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8573c814a904SMatthias Ringwald }
8574c814a904SMatthias Ringwald 
8575c814a904SMatthias Ringwald uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){
8576c814a904SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
8577c814a904SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8578c814a904SMatthias Ringwald     advertising_set->periodic_data = periodic_data;
8579c814a904SMatthias Ringwald     advertising_set->periodic_data_len = periodic_data_length;
8580c814a904SMatthias Ringwald     // set tasks and start
8581c814a904SMatthias Ringwald     advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA;
8582c814a904SMatthias Ringwald     hci_run();
8583c814a904SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8584c814a904SMatthias Ringwald }
8585c814a904SMatthias Ringwald 
858653f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){
858753f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
858853f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
858953f240c0SMatthias Ringwald     // set tasks and start
859053f240c0SMatthias Ringwald     advertising_set->periodic_include_adi = include_adi;
859153f240c0SMatthias Ringwald     advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
859253f240c0SMatthias Ringwald     hci_run();
859353f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
859453f240c0SMatthias Ringwald }
859553f240c0SMatthias Ringwald 
859653f240c0SMatthias Ringwald uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){
859753f240c0SMatthias Ringwald     le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle);
859853f240c0SMatthias Ringwald     if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
859953f240c0SMatthias Ringwald     // set tasks and start
860053f240c0SMatthias Ringwald     advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED;
860153f240c0SMatthias Ringwald     hci_run();
860253f240c0SMatthias Ringwald     return ERROR_CODE_SUCCESS;
860353f240c0SMatthias Ringwald }
860498aa715fSMatthias Ringwald 
860598aa715fSMatthias Ringwald uint8_t gap_periodic_advertising_sync_transfer_set_default_parameters(uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type){
860698aa715fSMatthias Ringwald     hci_stack->le_past_mode = mode;
860798aa715fSMatthias Ringwald     hci_stack->le_past_skip = skip;
860898aa715fSMatthias Ringwald     hci_stack->le_past_sync_timeout = sync_timeout;
860998aa715fSMatthias Ringwald     hci_stack->le_past_cte_type = cte_type;
861098aa715fSMatthias Ringwald     hci_stack->le_past_set_default_params = true;
861198aa715fSMatthias Ringwald     hci_run();
861298aa715fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
861398aa715fSMatthias Ringwald }
861498aa715fSMatthias Ringwald 
86153bd96807SMatthias Ringwald uint8_t gap_periodic_advertising_sync_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, hci_con_handle_t sync_handle){
86163bd96807SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
86173bd96807SMatthias Ringwald     if (hci_connection == NULL){
86183bd96807SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
86193bd96807SMatthias Ringwald     }
86203bd96807SMatthias Ringwald     hci_connection->le_past_sync_handle = sync_handle;
86213bd96807SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
86223bd96807SMatthias Ringwald     hci_run();
86233bd96807SMatthias Ringwald     return ERROR_CODE_SUCCESS;
86243bd96807SMatthias Ringwald }
86253bd96807SMatthias Ringwald 
8626027f4677SMatthias Ringwald uint8_t gap_periodic_advertising_set_info_transfer_send(hci_con_handle_t con_handle, uint16_t service_data, uint8_t advertising_handle){
8627027f4677SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8628027f4677SMatthias Ringwald     if (hci_connection == NULL){
8629027f4677SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8630027f4677SMatthias Ringwald     }
8631027f4677SMatthias Ringwald     hci_connection->le_past_advertising_handle = advertising_handle;
8632027f4677SMatthias Ringwald     hci_connection->le_past_service_data = service_data;
8633027f4677SMatthias Ringwald     hci_run();
8634027f4677SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8635027f4677SMatthias Ringwald }
8636027f4677SMatthias Ringwald 
8637c814a904SMatthias Ringwald #endif /* ENABLE_LE_PERIODIC_ADVERTISING */
863853f240c0SMatthias Ringwald 
8639a5770ecbSMatthias Ringwald #endif
8640a5770ecbSMatthias Ringwald 
864135454696SMatthias Ringwald #endif
864206e5cf96SMatthias Ringwald 
864306e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
864406e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
864506e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
864606e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
864706e5cf96SMatthias Ringwald 
864864068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
864906e5cf96SMatthias Ringwald     // update advertisement parameters, too
865006e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
8651bbc366e6SMatthias Ringwald     hci_run();
865264068776SMatthias Ringwald #endif
865364068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
865406e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
865564068776SMatthias Ringwald #endif
865606e5cf96SMatthias Ringwald }
865706e5cf96SMatthias Ringwald 
86589136bde8SMatthias Ringwald void hci_le_random_address_set(const bd_addr_t random_address){
86599136bde8SMatthias Ringwald     memcpy(hci_stack->le_random_address, random_address, 6);
86609136bde8SMatthias Ringwald     hci_stack->le_random_address_set = true;
86619136bde8SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS;
86629ce6dfa1SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
86639ce6dfa1SMatthias Ringwald     if (hci_extended_advertising_supported()){
86649ce6dfa1SMatthias Ringwald         // force advertising set creation for LE Set Advertising Set Random Address
86659ce6dfa1SMatthias Ringwald         if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) == 0){
86669ce6dfa1SMatthias Ringwald             hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
86679ce6dfa1SMatthias Ringwald         }
86689ce6dfa1SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS_SET_0;
86699ce6dfa1SMatthias Ringwald     }
86709ce6dfa1SMatthias Ringwald #endif
86719136bde8SMatthias Ringwald     hci_run();
86729136bde8SMatthias Ringwald }
86739136bde8SMatthias Ringwald 
8674d70217a2SMatthias Ringwald #endif
867545c102fdSMatthias Ringwald 
8676616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
86775917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
86785917a5c5S[email protected]     if (!conn){
86797851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
8680616edd56SMatthias Ringwald         return 0;
86815917a5c5S[email protected]     }
86827fd7aa6fSMatthias Ringwald     // ignore if already disconnected
86837fd7aa6fSMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
86847fd7aa6fSMatthias Ringwald         return 0;
86857fd7aa6fSMatthias Ringwald     }
86865917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
86875917a5c5S[email protected]     hci_run();
8688616edd56SMatthias Ringwald     return 0;
86894f3229d8S[email protected] }
869004a6ef8cSmatthias.ringwald 
8691228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
8692228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
8693228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
869422df2fe2SMatthias Ringwald     hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI;
8695228e430cSMatthias Ringwald     hci_run();
8696228e430cSMatthias Ringwald     return 1;
8697228e430cSMatthias Ringwald }
8698228e430cSMatthias Ringwald 
8699a1bf5ae7SMatthias Ringwald /**
8700a1bf5ae7SMatthias Ringwald  * @brief Get connection type
8701a1bf5ae7SMatthias Ringwald  * @param con_handle
8702a1bf5ae7SMatthias Ringwald  * @result connection_type
8703a1bf5ae7SMatthias Ringwald  */
8704a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
8705a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
8706a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
8707a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
8708a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
8709a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
8710a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
8711a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
8712a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
8713f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
8714a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
8715a1bf5ae7SMatthias Ringwald         default:
8716a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
8717a1bf5ae7SMatthias Ringwald     }
8718a1bf5ae7SMatthias Ringwald }
8719a1bf5ae7SMatthias Ringwald 
87202dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
87212dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
87222dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
87232dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
87242dceb1d6SMatthias Ringwald }
87252dceb1d6SMatthias Ringwald 
87262dceb1d6SMatthias Ringwald 
872744f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
8728667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
872988a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
873088a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
873188a03c8dSMatthias Ringwald     conn->request_role = role;
873288a03c8dSMatthias Ringwald     hci_run();
8733d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
873488a03c8dSMatthias Ringwald }
873544f858f3SMatthias Ringwald #endif
873688a03c8dSMatthias Ringwald 
8737a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
87384f551432SMatthias Ringwald 
87399d8be771SMatthias Ringwald uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options){
8740b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8741b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
8742b90f6e0aSMatthias Ringwald 
8743b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
8744b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
8745b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
87469d8be771SMatthias Ringwald     conn->le_phy_update_phy_options = (uint8_t) phy_options;
8747b90f6e0aSMatthias Ringwald 
8748b90f6e0aSMatthias Ringwald     hci_run();
8749b90f6e0aSMatthias Ringwald 
8750b90f6e0aSMatthias Ringwald     return 0;
8751b90f6e0aSMatthias Ringwald }
8752b90f6e0aSMatthias Ringwald 
8753667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
87547a92a9dbSMatthias Ringwald     // check if already in list
87557a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
87567a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
87577a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
87587a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
87597a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
87607a92a9dbSMatthias Ringwald             continue;
87617a92a9dbSMatthias Ringwald         }
87627a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
87637a92a9dbSMatthias Ringwald             continue;
87647a92a9dbSMatthias Ringwald         }
8765caaf5151SMilanka Ringwald 
8766caaf5151SMilanka Ringwald         // if already on controller:
8767caaf5151SMilanka Ringwald         if ((entry->state & LE_WHITELIST_ON_CONTROLLER) != 0){
8768caaf5151SMilanka Ringwald             if ((entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER) != 0){
8769caaf5151SMilanka Ringwald                 // drop remove request
8770caaf5151SMilanka Ringwald                 entry->state = LE_WHITELIST_ON_CONTROLLER;
8771caaf5151SMilanka Ringwald                 return ERROR_CODE_SUCCESS;
8772caaf5151SMilanka Ringwald             } else {
8773caaf5151SMilanka Ringwald                 // disallow as already on controller
87747a92a9dbSMatthias Ringwald                 return ERROR_CODE_COMMAND_DISALLOWED;
87757a92a9dbSMatthias Ringwald             }
8776287379ccSMatthias Ringwald         }
8777caaf5151SMilanka Ringwald 
8778caaf5151SMilanka Ringwald         // assume scheduled to add
8779caaf5151SMilanka Ringwald 		return ERROR_CODE_COMMAND_DISALLOWED;
8780caaf5151SMilanka Ringwald     }
8781caaf5151SMilanka Ringwald 
87827a92a9dbSMatthias Ringwald     // alloc and add to list
8783e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
8784e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
8785e83201bcSMatthias Ringwald     entry->address_type = address_type;
87866535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
8787e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
8788665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
8789226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8790ac9c45e0SMatthias Ringwald }
8791ac9c45e0SMatthias Ringwald 
8792667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8793665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
8794665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8795665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8796665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
87977a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
87987a92a9dbSMatthias Ringwald             continue;
87997a92a9dbSMatthias Ringwald         }
88007a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
88017a92a9dbSMatthias Ringwald             continue;
88027a92a9dbSMatthias Ringwald         }
8803e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8804e83201bcSMatthias Ringwald             // remove from controller if already present
8805e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8806a3b69fdeSMatthias Ringwald         }  else {
8807226db5efSMatthias Ringwald             // directly remove entry from whitelist
8808665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
8809e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
8810e83201bcSMatthias Ringwald         }
8811a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
8812a3b69fdeSMatthias Ringwald     }
8813a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
881442ff5ba1SMatthias Ringwald }
881542ff5ba1SMatthias Ringwald 
8816226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
8817665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
8818665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
8819665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
8820665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
8821e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
8822e83201bcSMatthias Ringwald             // remove from controller if already present
8823e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
8824e83201bcSMatthias Ringwald             continue;
8825e83201bcSMatthias Ringwald         }
882691915b0bSMatthias Ringwald         // directly remove entry from whitelist
8827665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
8828e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
8829e83201bcSMatthias Ringwald     }
8830226db5efSMatthias Ringwald }
8831226db5efSMatthias Ringwald 
8832a3b69fdeSMatthias Ringwald /**
8833a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
88346b65794dSMilanka Ringwald  * @return 0 if ok
8835a3b69fdeSMatthias Ringwald  */
8836a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
8837a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
8838a3b69fdeSMatthias Ringwald     hci_run();
8839a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8840a3b69fdeSMatthias Ringwald }
8841a3b69fdeSMatthias Ringwald 
8842a3b69fdeSMatthias Ringwald /**
8843a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
8844a3b69fdeSMatthias Ringwald  * @param address_typ
8845a3b69fdeSMatthias Ringwald  * @param address
88466b65794dSMilanka Ringwald  * @return 0 if ok
8847a3b69fdeSMatthias Ringwald  */
8848667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
8849a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
8850a3b69fdeSMatthias Ringwald     if (status){
8851a3b69fdeSMatthias Ringwald         return status;
8852a3b69fdeSMatthias Ringwald     }
8853a3b69fdeSMatthias Ringwald     hci_run();
8854a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8855a3b69fdeSMatthias Ringwald }
8856a3b69fdeSMatthias Ringwald 
8857a3b69fdeSMatthias Ringwald /**
8858a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
8859a3b69fdeSMatthias Ringwald  * @param address_typ
8860a3b69fdeSMatthias Ringwald  * @param address
88616b65794dSMilanka Ringwald  * @return 0 if ok
8862a3b69fdeSMatthias Ringwald  */
8863667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
8864a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
8865a3b69fdeSMatthias Ringwald     if (status){
8866a3b69fdeSMatthias Ringwald         return status;
8867a3b69fdeSMatthias Ringwald     }
8868a3b69fdeSMatthias Ringwald     hci_run();
8869a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
8870a3b69fdeSMatthias Ringwald }
8871a3b69fdeSMatthias Ringwald 
8872226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
8873226db5efSMatthias Ringwald /**
887495e257d9SMatthias Ringwald  * @brief Connect with Whitelist
887595e257d9SMatthias Ringwald  * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
88766b65794dSMilanka Ringwald  * @return - if ok
887795e257d9SMatthias Ringwald  */
887895e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
887995e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
888095e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
888195e257d9SMatthias Ringwald     }
888295e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
888395e257d9SMatthias Ringwald     hci_run();
888495e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
888595e257d9SMatthias Ringwald }
888695e257d9SMatthias Ringwald 
888795e257d9SMatthias Ringwald /**
8888226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
8889226db5efSMatthias Ringwald  * @param address_typ
8890226db5efSMatthias Ringwald  * @param address
88916b65794dSMilanka Ringwald  * @return 0 if ok
8892226db5efSMatthias Ringwald  */
8893667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
889495e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
8895226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
8896226db5efSMatthias Ringwald     }
8897226db5efSMatthias Ringwald 
8898226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
889963f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
8900226db5efSMatthias Ringwald         return status;
8901226db5efSMatthias Ringwald     }
8902226db5efSMatthias Ringwald 
8903226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
8904226db5efSMatthias Ringwald 
8905226db5efSMatthias Ringwald     hci_run();
890695e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8907226db5efSMatthias Ringwald }
8908226db5efSMatthias Ringwald 
8909226db5efSMatthias Ringwald /**
8910226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
8911226db5efSMatthias Ringwald  * @param address_typ
8912226db5efSMatthias Ringwald  * @param address
89136b65794dSMilanka Ringwald  * @return 0 if ok
8914226db5efSMatthias Ringwald  */
8915667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
891695e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
891795e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
891895e257d9SMatthias Ringwald     }
891995e257d9SMatthias Ringwald 
8920226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
892195e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
892295e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
892395e257d9SMatthias Ringwald     }
8924226db5efSMatthias Ringwald     hci_run();
8925226db5efSMatthias Ringwald     return 0;
8926226db5efSMatthias Ringwald }
8927226db5efSMatthias Ringwald 
8928226db5efSMatthias Ringwald /**
8929226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
8930226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
8931226db5efSMatthias Ringwald  */
893295e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
893395e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
893495e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
893595e257d9SMatthias Ringwald     }
8936226db5efSMatthias Ringwald     hci_whitelist_clear();
8937226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
8938e83201bcSMatthias Ringwald     hci_run();
893995e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
8940ac9c45e0SMatthias Ringwald }
8941c9db5c21SMilanka Ringwald 
8942b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
8943b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
8944c9db5c21SMilanka Ringwald     if (!conn) return 0;
8945c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
8946c9db5c21SMilanka Ringwald }
8947d70217a2SMatthias Ringwald #endif
89484f551432SMatthias Ringwald #endif
89494f551432SMatthias Ringwald 
895035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
8951ac9c45e0SMatthias Ringwald /**
8952ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
8953a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
8954ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
8955ff00ed1cSMatthias Ringwald  */
8956ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
8957ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
8958baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA;
895959d59ecfSMatthias Ringwald     hci_run();
8960ff00ed1cSMatthias Ringwald }
8961ff00ed1cSMatthias Ringwald 
8962ff00ed1cSMatthias Ringwald /**
8963f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
8964f5875de5SMatthias Ringwald  * @param duration in 1.28s units
8965f5875de5SMatthias Ringwald  * @return 0 if ok
8966f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
8967f5875de5SMatthias Ringwald  */
8968f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
896999449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
8970f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
8971a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
8972f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
8973f5875de5SMatthias Ringwald     }
8974f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
897530199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = 0;
897630199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = 0;
897730199e24SMatthias Ringwald     hci_run();
897830199e24SMatthias Ringwald     return 0;
897930199e24SMatthias Ringwald }
898030199e24SMatthias Ringwald 
898130199e24SMatthias Ringwald uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){
898230199e24SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING)                return ERROR_CODE_COMMAND_DISALLOWED;
898330199e24SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE)   return ERROR_CODE_COMMAND_DISALLOWED;
898430199e24SMatthias Ringwald     if (duration < GAP_INQUIRY_DURATION_MIN)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
898530199e24SMatthias Ringwald     if (duration > GAP_INQUIRY_DURATION_MAX)                  return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
898630199e24SMatthias Ringwald     if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
898730199e24SMatthias Ringwald     if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;;
898830199e24SMatthias Ringwald 
898930199e24SMatthias Ringwald     hci_stack->inquiry_state = duration;
899030199e24SMatthias Ringwald     hci_stack->inquiry_max_period_length = max_period_length;
899130199e24SMatthias Ringwald     hci_stack->inquiry_min_period_length = min_period_length;
8992f5875de5SMatthias Ringwald     hci_run();
8993f5875de5SMatthias Ringwald     return 0;
8994f5875de5SMatthias Ringwald }
8995f5875de5SMatthias Ringwald 
8996f5875de5SMatthias Ringwald /**
8997f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
89986b65794dSMilanka Ringwald  * @return 0 if ok
8999f5875de5SMatthias Ringwald  */
9000f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
9001a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
9002f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
9003f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
9004f5875de5SMatthias Ringwald         hci_emit_event(event, sizeof(event), 1);
9005f5875de5SMatthias Ringwald         return 0;
9006f5875de5SMatthias Ringwald     }
900730199e24SMatthias Ringwald     switch (hci_stack->inquiry_state){
900830199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_ACTIVE:
9009f5875de5SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
9010f5875de5SMatthias Ringwald             hci_run();
901130199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
901230199e24SMatthias Ringwald         case GAP_INQUIRY_STATE_PERIODIC:
901330199e24SMatthias Ringwald             hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC;
901430199e24SMatthias Ringwald             hci_run();
901530199e24SMatthias Ringwald             return ERROR_CODE_SUCCESS;
901630199e24SMatthias Ringwald         default:
901730199e24SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
901830199e24SMatthias Ringwald     }
9019f5875de5SMatthias Ringwald }
9020f5875de5SMatthias Ringwald 
9021496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
9022496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
9023496bb884SMatthias Ringwald }
9024496bb884SMatthias Ringwald 
90251dc973e7SMatthias Ringwald void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){
9026c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_interval = inquiry_scan_interval;
9027c0c8a829SMatthias Ringwald     hci_stack->inquiry_scan_window   = inquiry_scan_window;
9028baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY;
9029c0c8a829SMatthias Ringwald     hci_run();
9030c0c8a829SMatthias Ringwald }
9031c0c8a829SMatthias Ringwald 
9032f50ed5acSAndrey Fominykh void gap_inquiry_set_transmit_power_level(int8_t tx_power)
9033f50ed5acSAndrey Fominykh {
9034f50ed5acSAndrey Fominykh     hci_stack->inquiry_tx_power_level = tx_power;
9035f50ed5acSAndrey Fominykh     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_TX_POWER_LEVEL;
9036f50ed5acSAndrey Fominykh     hci_run();
9037f50ed5acSAndrey Fominykh }
9038f50ed5acSAndrey Fominykh 
9039b7f1ee76SMatthias Ringwald 
9040b7f1ee76SMatthias Ringwald /**
9041b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
9042b7f1ee76SMatthias Ringwald  * @param addr
9043b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
9044b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
9045b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
9046b7f1ee76SMatthias Ringwald  */
9047667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
9048b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
90496535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
9050b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
9051b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
9052b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
9053b7f1ee76SMatthias Ringwald     hci_run();
9054b7f1ee76SMatthias Ringwald     return 0;
9055b7f1ee76SMatthias Ringwald }
9056b7f1ee76SMatthias Ringwald 
9057667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
90580a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
90596535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
90600a51f88bSMatthias Ringwald     hci_run();
90610a51f88bSMatthias Ringwald     return 0;
90620a51f88bSMatthias Ringwald }
90630a51f88bSMatthias Ringwald 
90640a51f88bSMatthias Ringwald /**
9065aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
9066aad97216SMatthias Ringwald  * @param addr
9067aad97216SMatthias Ringwald  * @param pin_data
9068aad97216SMatthias Ringwald  * @param pin_len
9069aad97216SMatthias Ringwald  * @return 0 if ok
9070aad97216SMatthias Ringwald  */
9071667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
9072aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9073aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
9074aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
9075aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
9076aad97216SMatthias Ringwald }
9077aad97216SMatthias Ringwald 
9078aad97216SMatthias Ringwald /**
90790a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
90800a51f88bSMatthias Ringwald  * @param addr
90810a51f88bSMatthias Ringwald  * @param pin
90820a51f88bSMatthias Ringwald  * @return 0 if ok
90830a51f88bSMatthias Ringwald  */
9084667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
90859d78a7ecSMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin));
90860a51f88bSMatthias Ringwald }
90870a51f88bSMatthias Ringwald 
90880a51f88bSMatthias Ringwald /**
90890a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
90900a51f88bSMatthias Ringwald  * @param addr
90910a51f88bSMatthias Ringwald  * @param pin
90920a51f88bSMatthias Ringwald  * @return 0 if ok
90930a51f88bSMatthias Ringwald  */
90940a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
9095cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
90960a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
90970a51f88bSMatthias Ringwald }
90980a51f88bSMatthias Ringwald 
90990a51f88bSMatthias Ringwald /**
91000a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
91010a51f88bSMatthias Ringwald  * @param addr
91020a51f88bSMatthias Ringwald  * @param passkey
91030a51f88bSMatthias Ringwald  * @return 0 if ok
91040a51f88bSMatthias Ringwald  */
9105667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
9106cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
9107d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
91080a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
91090a51f88bSMatthias Ringwald }
91100a51f88bSMatthias Ringwald 
91110a51f88bSMatthias Ringwald /**
91120a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
91130a51f88bSMatthias Ringwald  * @param addr
91140a51f88bSMatthias Ringwald  * @param pin
91150a51f88bSMatthias Ringwald  * @return 0 if ok
91160a51f88bSMatthias Ringwald  */
9117667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
9118cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
91190a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
91200a51f88bSMatthias Ringwald }
91210a51f88bSMatthias Ringwald 
91220a51f88bSMatthias Ringwald /**
91230a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
91240a51f88bSMatthias Ringwald  * @param addr
91250a51f88bSMatthias Ringwald  * @param passkey
91260a51f88bSMatthias Ringwald  * @return 0 if ok
91270a51f88bSMatthias Ringwald  */
9128667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
9129cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
91300a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
91310a51f88bSMatthias Ringwald }
91320a51f88bSMatthias Ringwald 
91330a51f88bSMatthias Ringwald /**
91340a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
91350a51f88bSMatthias Ringwald  * @param addr
91360a51f88bSMatthias Ringwald  * @param pin
91370a51f88bSMatthias Ringwald  * @return 0 if ok
91380a51f88bSMatthias Ringwald  */
9139667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
9140cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
91410a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
91420a51f88bSMatthias Ringwald }
91430a51f88bSMatthias Ringwald 
9144308eeaffSMatthias Ringwald #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY)
914544565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
914644565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
914744565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
914844565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
914944565b0cSMatthias Ringwald     hci_run();
915044565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
915144565b0cSMatthias Ringwald }
9152308eeaffSMatthias Ringwald #endif
915344565b0cSMatthias Ringwald 
9154308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
915544565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
91567ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
915744565b0cSMatthias Ringwald }
915844565b0cSMatthias Ringwald 
915944565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
91607ca4a7edSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
916144565b0cSMatthias Ringwald }
916244565b0cSMatthias Ringwald #endif
916344565b0cSMatthias Ringwald 
91641849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
91651849becdSMatthias Ringwald /**
91661849becdSMatthias Ringwald  * @brief Report Remote OOB Data
91671849becdSMatthias Ringwald  * @param bd_addr
91681849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
91691849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
91701849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
91711849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
91721849becdSMatthias Ringwald  */
91731849becdSMatthias 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){
91741849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
91751849becdSMatthias Ringwald     if (connection == NULL) {
91761849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
91771849becdSMatthias Ringwald     }
91781849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
91791849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
9180204e8f1dSMatthias Ringwald 
9181204e8f1dSMatthias Ringwald     // ignore P-256 if not supported by us
9182204e8f1dSMatthias Ringwald     if (hci_stack->secure_connections_active){
91831849becdSMatthias Ringwald         connection->classic_oob_c_256 = c_256;
91841849becdSMatthias Ringwald         connection->classic_oob_r_256 = r_256;
9185204e8f1dSMatthias Ringwald     }
9186204e8f1dSMatthias Ringwald 
91871849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
91881849becdSMatthias Ringwald }
9189cf01e888SMatthias Ringwald /**
9190cf01e888SMatthias Ringwald  * @brief Generate new OOB data
9191cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
9192cf01e888SMatthias Ringwald  */
9193cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
9194cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
9195cf01e888SMatthias Ringwald     hci_run();
9196cf01e888SMatthias Ringwald }
9197cf01e888SMatthias Ringwald 
91981849becdSMatthias Ringwald #endif
91991849becdSMatthias Ringwald 
9200308eeaffSMatthias Ringwald #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY
9201308eeaffSMatthias Ringwald uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){
9202308eeaffSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
9203308eeaffSMatthias Ringwald     if (connection == NULL) {
9204308eeaffSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9205308eeaffSMatthias Ringwald     }
9206308eeaffSMatthias Ringwald 
9207308eeaffSMatthias Ringwald     memcpy(connection->link_key, link_key, sizeof(link_key_t));
9208308eeaffSMatthias Ringwald     connection->link_key_type = type;
9209308eeaffSMatthias Ringwald 
9210308eeaffSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
9211308eeaffSMatthias Ringwald }
9212308eeaffSMatthias Ringwald 
9213308eeaffSMatthias Ringwald #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY
9214f5875de5SMatthias Ringwald /**
9215f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
9216f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
9217f6858d14SMatthias Ringwald  */
9218b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
9219b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
9220f6858d14SMatthias Ringwald }
9221f6858d14SMatthias Ringwald 
9222f6858d14SMatthias Ringwald /**
9223d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
9224d950d659SMatthias Ringwald  */
9225d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
9226d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
9227d950d659SMatthias Ringwald }
9228d950d659SMatthias Ringwald 
9229d950d659SMatthias Ringwald /**
9230d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
9231d950d659SMatthias Ringwald  * @return current voice setting
9232d950d659SMatthias Ringwald  */
92330cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
9234d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
9235d950d659SMatthias Ringwald }
9236d950d659SMatthias Ringwald 
9237400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
9238400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
9239400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
9240400ff5abSMatthias Ringwald     if (!transport_name) return 0;
9241400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
9242400ff5abSMatthias Ringwald }
9243400ff5abSMatthias Ringwald 
92449427aeb5SMatthias Ringwald static uint16_t hci_sco_packet_length_for_payload_length(uint16_t payload_size){
924520dcdd22SMatthias Ringwald     uint16_t sco_packet_length = 0;
9246cf119f3bSMatthias Ringwald 
924791dfed7eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
92486f28d2eeSMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
924973f498e7SMatthias Ringwald     int multiplier;
925073f498e7SMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) &&
925173f498e7SMatthias Ringwald         ((hci_stack->sco_voice_setting_active & 0x20) == 0x20)) {
925273f498e7SMatthias Ringwald         multiplier = 2;
925373f498e7SMatthias Ringwald     } else {
925473f498e7SMatthias Ringwald         multiplier = 1;
925573f498e7SMatthias Ringwald     }
925691dfed7eSMatthias Ringwald #endif
925791dfed7eSMatthias Ringwald 
92589427aeb5SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
9259400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
9260400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
9261cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
92629427aeb5SMatthias Ringwald         // @note multiple sco connections not supported currently
92639427aeb5SMatthias Ringwald         sco_packet_length = 3 + 24 * multiplier;
9264400ff5abSMatthias Ringwald     } else {
92659427aeb5SMatthias Ringwald         // 3 byte SCO header + SCO packet length over the air
92669427aeb5SMatthias Ringwald         sco_packet_length = 3 + payload_size * multiplier;
9267d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
9268ad915196SMatthias Ringwald         if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
92699427aeb5SMatthias Ringwald             sco_packet_length = 3 + hci_stack->sco_data_packet_length;
9270d966a453SMatthias Ringwald         }
9271400ff5abSMatthias Ringwald     }
9272a3069afeSMatthias Ringwald #endif
92735b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
92749427aeb5SMatthias Ringwald     // 3 byte SCO header + SCO packet length over the air
92759427aeb5SMatthias Ringwald     sco_packet_length = 3 + payload_size * multiplier;
92769427aeb5SMatthias Ringwald     // assert that it still fits inside an SCO buffer
92779427aeb5SMatthias Ringwald     if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){
92789427aeb5SMatthias Ringwald         sco_packet_length = 3 + hci_stack->sco_data_packet_length;
92799427aeb5SMatthias Ringwald     }
92805b7087c7SMatthias Ringwald #endif
9281a3069afeSMatthias Ringwald     return sco_packet_length;
9282b3aad8daSMatthias Ringwald }
9283b3aad8daSMatthias Ringwald 
92849427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length_for_connection(hci_con_handle_t sco_con_handle){
92859427aeb5SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(sco_con_handle);
92869427aeb5SMatthias Ringwald     if (connection != NULL){
92879427aeb5SMatthias Ringwald         return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);
92889427aeb5SMatthias Ringwald     }
92899427aeb5SMatthias Ringwald     return 0;
92909427aeb5SMatthias Ringwald }
92919427aeb5SMatthias Ringwald 
92929427aeb5SMatthias Ringwald uint16_t hci_get_sco_packet_length(void){
92939427aeb5SMatthias Ringwald     btstack_linked_list_iterator_t it;
92949427aeb5SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
92959427aeb5SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
92969427aeb5SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
92979427aeb5SMatthias Ringwald         if ( connection->address_type == BD_ADDR_TYPE_SCO ) {
92989427aeb5SMatthias Ringwald             return hci_sco_packet_length_for_payload_length(connection->sco_payload_length);;
92999427aeb5SMatthias Ringwald         }
93009427aeb5SMatthias Ringwald     }
93019427aeb5SMatthias Ringwald     return 0;
93029427aeb5SMatthias Ringwald }
93039427aeb5SMatthias Ringwald 
9304c4c88f1bSJakob Krantz /**
9305c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
9306c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
9307c4c88f1bSJakob Krantz */
9308c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
9309c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
9310c4c88f1bSJakob Krantz }
9311c4c88f1bSJakob Krantz 
9312c4c88f1bSJakob Krantz #endif
9313ec111c8bSMatthias Ringwald 
9314ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
9315ec111c8bSMatthias Ringwald     return hci_stack->state;
9316ec111c8bSMatthias Ringwald }
9317ec111c8bSMatthias Ringwald 
931807e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
93195e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
932007e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
932107e010b6SMilanka Ringwald }
932207e010b6SMilanka Ringwald #endif
9323ec111c8bSMatthias Ringwald 
9324d950d659SMatthias Ringwald /**
9325d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
9326d23838ecSMatthias Ringwald  */
9327c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
9328d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
9329d23838ecSMatthias Ringwald }
9330d23838ecSMatthias Ringwald 
933171de195eSMatthias Ringwald void hci_disconnect_all(void){
9332665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9333665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
9334665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9335665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
933604a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
933704a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
933804a6ef8cSmatthias.ringwald     }
9339d31fba26S[email protected]     hci_run();
934004a6ef8cSmatthias.ringwald }
934133373e40SMatthias Ringwald 
934233373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
934333373e40SMatthias Ringwald     return hci_stack->manufacturer;
934433373e40SMatthias Ringwald }
93459c6e867eSMatthias Ringwald 
93463e329ddfSandryblack #ifdef ENABLE_BLE
93479c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
93489c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
93499c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
93509c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
93519c6e867eSMatthias Ringwald }
93529c6e867eSMatthias Ringwald 
93539c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
93549c6e867eSMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
93556a79f6baSMatthias Ringwald #endif
93569c6e867eSMatthias Ringwald 
93576d105c71SMatthias Ringwald uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){
9358c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9359c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
9360c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
93616a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
9362c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
9363c5fb5ca4SMatthias Ringwald         if (sm_conn->sm_connection_encrypted) {
93649c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
93659c6e867eSMatthias Ringwald         }
93666a79f6baSMatthias Ringwald #endif
93676a79f6baSMatthias Ringwald     } else {
9368c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
93698daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
9370c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
9371c5fb5ca4SMatthias Ringwald         }
9372c5fb5ca4SMatthias Ringwald #endif
93736a79f6baSMatthias Ringwald     }
9374c5fb5ca4SMatthias Ringwald     return 0;
9375c5fb5ca4SMatthias Ringwald }
93769c6e867eSMatthias Ringwald 
9377ff3f1026SMatthias Ringwald bool gap_authenticated(hci_con_handle_t con_handle){
9378c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9379ff3f1026SMatthias Ringwald     if (hci_connection == NULL) return false;
93805f3981bfSMatthias Ringwald 
9381c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
93826a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
93835f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
93845f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9385c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
9386ff3f1026SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated != 0;
93876a79f6baSMatthias Ringwald #endif
938859a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
93895f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9390f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9391ff3f1026SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
939259a1a47aSMatthias Ringwald #endif
93935f3981bfSMatthias Ringwald         default:
9394ff3f1026SMatthias Ringwald             return false;
93955f3981bfSMatthias Ringwald     }
93969c6e867eSMatthias Ringwald }
93979c6e867eSMatthias Ringwald 
9398f461b3dfSMatthias Ringwald bool gap_secure_connection(hci_con_handle_t con_handle){
9399c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
9400c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
94018b35e16aSMatthias Ringwald 
9402c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
94036a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
94048b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
94058b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
9406f461b3dfSMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated
9407f461b3dfSMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc != 0;
94086a79f6baSMatthias Ringwald #endif
940959a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
94108b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
9411f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
9412f461b3dfSMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
941359a1a47aSMatthias Ringwald #endif
94148b35e16aSMatthias Ringwald         default:
9415f461b3dfSMatthias Ringwald             return false;
94168b35e16aSMatthias Ringwald     }
9417f1dfbe18SMatthias Ringwald }
9418f1dfbe18SMatthias Ringwald 
94191e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
94201e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
94211e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
94221e122704SMatthias Ringwald 
942348f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
94241e122704SMatthias Ringwald 	link_key_t link_key;
94251e122704SMatthias Ringwald 	link_key_type_t link_key_type;
942648f33f37SMatthias Ringwald #endif
94271e122704SMatthias Ringwald 	switch (hci_connection->address_type){
94286a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
94291e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
94301e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
94311e122704SMatthias Ringwald 			return hci_connection->sm_connection.sm_le_db_index >= 0;
94326a79f6baSMatthias Ringwald #endif
94331e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
94341e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
94351e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
94361e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
94371e122704SMatthias Ringwald #endif
94381e122704SMatthias Ringwald 		default:
94391e122704SMatthias Ringwald 			return false;
94401e122704SMatthias Ringwald 	}
94411e122704SMatthias Ringwald }
94421e122704SMatthias Ringwald 
94436a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
94449c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
94459c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
94469c6e867eSMatthias Ringwald     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
94479c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
94489c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
94499c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
94509c6e867eSMatthias Ringwald }
94519c6e867eSMatthias Ringwald #endif
9452f8ee3071SMatthias Ringwald 
9453f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
9454f8ee3071SMatthias 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){
9455f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
94567f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9457f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
9458f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
9459f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
9460f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
9461f8ee3071SMatthias Ringwald     hci_run();
9462f8ee3071SMatthias Ringwald     return 0;
9463f8ee3071SMatthias Ringwald }
9464f8ee3071SMatthias Ringwald 
9465f8ee3071SMatthias Ringwald /**
9466f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
9467f8ee3071SMatthias Ringwald  * @param con_handle
9468f8ee3071SMatthias Ringwald  @ @return 0 if ok
9469f8ee3071SMatthias Ringwald  */
9470f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
9471f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
94727f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9473f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
9474f8ee3071SMatthias Ringwald     hci_run();
9475f8ee3071SMatthias Ringwald     return 0;
9476f8ee3071SMatthias Ringwald }
9477bea424a5SMatthias Ringwald 
9478140c0557SMatthias 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){
9479140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
94807f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9481140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
9482140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
9483140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
9484140c0557SMatthias Ringwald     hci_run();
9485dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9486140c0557SMatthias Ringwald }
9487140c0557SMatthias Ringwald 
9488278ff8a9SMatthias 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){
9489278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
94907f839e2cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9491278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
9492278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
9493278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
9494278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
9495278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
9496278ff8a9SMatthias Ringwald     hci_run();
9497278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9498278ff8a9SMatthias Ringwald }
9499278ff8a9SMatthias Ringwald 
9500bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
9501bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
9502bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
9503baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY;
9504bea424a5SMatthias Ringwald     hci_run();
9505bea424a5SMatthias Ringwald }
9506bea424a5SMatthias Ringwald 
9507bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
9508bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
9509baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE;
9510bea424a5SMatthias Ringwald     hci_run();
9511bea424a5SMatthias Ringwald }
9512bea424a5SMatthias Ringwald 
951332a12730SMatthias Ringwald void gap_set_page_timeout(uint16_t page_timeout){
951432a12730SMatthias Ringwald     hci_stack->page_timeout = page_timeout;
9515baa4881eSMatthias Ringwald     hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT;
951632a12730SMatthias Ringwald     hci_run();
951732a12730SMatthias Ringwald }
951832a12730SMatthias Ringwald 
9519f8ee3071SMatthias Ringwald #endif
9520beceeddeSMatthias Ringwald 
952121debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
952221debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
952321debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
952421debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
952521debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
952621debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
952702b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
9528e8ca66c6SMatthias Ringwald     hci_stack->le_resolving_list_set_privacy_mode[offset] |= mask;
952921debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
953002b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
95315f3ccd83SMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
953202b02cffSMatthias Ringwald     }
953302b02cffSMatthias Ringwald }
953402b02cffSMatthias Ringwald 
953502b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
953602b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
953702b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
953802b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
953902b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
954002b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
954102b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
95425f3ccd83SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_UPDATES_ENTRIES;
954321debf25SMatthias Ringwald 	}
954421debf25SMatthias Ringwald }
9545cf38a091SMatthias Ringwald 
9546cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
95471ffa425cSMatthias Ringwald     if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){
9548cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
9549cf38a091SMatthias Ringwald 	}
9550cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
9551cf38a091SMatthias Ringwald 		// restart le resolving list update
9552cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
9553cf38a091SMatthias Ringwald 	}
9554cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
9555cf38a091SMatthias Ringwald }
9556c3d19a30SMatthias Ringwald 
9557c3d19a30SMatthias Ringwald void gap_set_peer_privacy_mode(le_privacy_mode_t privacy_mode ){
9558c3d19a30SMatthias Ringwald     hci_stack->le_privacy_mode = privacy_mode;
9559c3d19a30SMatthias Ringwald }
956021debf25SMatthias Ringwald #endif
956121debf25SMatthias Ringwald 
9562f40c73b4SMatthias Ringwald #ifdef ENABLE_BLE
9563f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
9564f40c73b4SMatthias Ringwald #ifdef ENABLE_LE_EXTENDED_ADVERTISING
9565f40c73b4SMatthias Ringwald 
9566f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9567f40c73b4SMatthias Ringwald     // check if already in list
9568f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
9569f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9570f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
9571f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it);
9572f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
9573f40c73b4SMatthias Ringwald             continue;
9574f40c73b4SMatthias Ringwald         }
9575f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
9576f40c73b4SMatthias Ringwald             continue;
9577f40c73b4SMatthias Ringwald         }
9578f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
9579f40c73b4SMatthias Ringwald             continue;
9580f40c73b4SMatthias Ringwald         }
9581f40c73b4SMatthias Ringwald         // disallow if already scheduled to add
9582f40c73b4SMatthias Ringwald         if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){
9583f40c73b4SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
9584f40c73b4SMatthias Ringwald         }
9585f40c73b4SMatthias Ringwald         // still on controller, but scheduled to remove -> re-add
9586f40c73b4SMatthias Ringwald         entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9587f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
9588f40c73b4SMatthias Ringwald     }
9589f40c73b4SMatthias Ringwald     // alloc and add to list
9590f40c73b4SMatthias Ringwald     periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get();
9591f40c73b4SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9592f40c73b4SMatthias Ringwald     entry->sid = advertising_sid;
9593f40c73b4SMatthias Ringwald     entry->address_type = address_type;
9594f40c73b4SMatthias Ringwald     (void)memcpy(entry->address, address, 6);
9595f40c73b4SMatthias Ringwald     entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER;
9596f40c73b4SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry);
9597f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9598f40c73b4SMatthias Ringwald }
9599f40c73b4SMatthias Ringwald 
9600f40c73b4SMatthias Ringwald static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9601f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
9602f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9603f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9604f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9605f40c73b4SMatthias Ringwald         if (entry->sid != advertising_sid) {
9606f40c73b4SMatthias Ringwald             continue;
9607f40c73b4SMatthias Ringwald         }
9608f40c73b4SMatthias Ringwald         if (entry->address_type != address_type) {
9609f40c73b4SMatthias Ringwald             continue;
9610f40c73b4SMatthias Ringwald         }
9611f40c73b4SMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
9612f40c73b4SMatthias Ringwald             continue;
9613f40c73b4SMatthias Ringwald         }
9614f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9615f40c73b4SMatthias Ringwald             // remove from controller if already present
9616f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9617f40c73b4SMatthias Ringwald         }  else {
9618f40c73b4SMatthias Ringwald             // directly remove entry from whitelist
9619f40c73b4SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
9620f40c73b4SMatthias Ringwald             btstack_memory_periodic_advertiser_list_entry_free(entry);
9621f40c73b4SMatthias Ringwald         }
9622f40c73b4SMatthias Ringwald         return ERROR_CODE_SUCCESS;
9623f40c73b4SMatthias Ringwald     }
9624f40c73b4SMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
9625f40c73b4SMatthias Ringwald }
9626f40c73b4SMatthias Ringwald 
9627f40c73b4SMatthias Ringwald static void hci_periodic_advertiser_list_clear(void){
9628f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_t it;
9629f40c73b4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list);
9630f40c73b4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9631f40c73b4SMatthias Ringwald         periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it);
9632f40c73b4SMatthias Ringwald         if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){
9633f40c73b4SMatthias Ringwald             // remove from controller if already present
9634f40c73b4SMatthias Ringwald             entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER;
9635f40c73b4SMatthias Ringwald             continue;
9636f40c73b4SMatthias Ringwald         }
9637f40c73b4SMatthias Ringwald         // directly remove entry from whitelist
9638f40c73b4SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
9639f40c73b4SMatthias Ringwald         btstack_memory_periodic_advertiser_list_entry_free(entry);
9640f40c73b4SMatthias Ringwald     }
9641f40c73b4SMatthias Ringwald }
9642f40c73b4SMatthias Ringwald 
9643f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_clear(void){
9644f40c73b4SMatthias Ringwald     hci_periodic_advertiser_list_clear();
9645f40c73b4SMatthias Ringwald     hci_run();
9646f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9647f40c73b4SMatthias Ringwald }
9648f40c73b4SMatthias Ringwald 
9649f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9650f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid);
9651f40c73b4SMatthias Ringwald     if (status){
9652f40c73b4SMatthias Ringwald         return status;
9653f40c73b4SMatthias Ringwald     }
9654f40c73b4SMatthias Ringwald     hci_run();
9655f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9656f40c73b4SMatthias Ringwald }
9657f40c73b4SMatthias Ringwald 
9658f40c73b4SMatthias Ringwald uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){
9659f40c73b4SMatthias Ringwald     uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid);
9660f40c73b4SMatthias Ringwald     if (status){
9661f40c73b4SMatthias Ringwald         return status;
9662f40c73b4SMatthias Ringwald     }
9663f40c73b4SMatthias Ringwald     hci_run();
9664f40c73b4SMatthias Ringwald     return ERROR_CODE_SUCCESS;
9665f40c73b4SMatthias Ringwald }
96664bafedd5SMatthias Ringwald 
96674bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type,
96684bafedd5SMatthias Ringwald                                              bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){
96694bafedd5SMatthias Ringwald     // abort if already active
96704bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) {
96714bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
96724bafedd5SMatthias Ringwald     }
96734bafedd5SMatthias Ringwald     // store request
96744bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT;
96754bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_options = options;
96764bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertising_sid = advertising_sid;
96774bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type;
96784bafedd5SMatthias Ringwald     memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6);
96794bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_skip = skip;
96804bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_timeout = sync_timeout;
96814bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_cte_type = sync_cte_type;
96824bafedd5SMatthias Ringwald 
96834bafedd5SMatthias Ringwald     hci_run();
96844bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
96854bafedd5SMatthias Ringwald }
96864bafedd5SMatthias Ringwald 
96874bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_create_sync_cancel(void){
96884bafedd5SMatthias Ringwald     // abort if not requested
96894bafedd5SMatthias Ringwald     if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) {
96904bafedd5SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
96914bafedd5SMatthias Ringwald     }
96924bafedd5SMatthias Ringwald     hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE;
96934bafedd5SMatthias Ringwald     hci_run();
96944bafedd5SMatthias Ringwald     return ERROR_CODE_SUCCESS;
96954bafedd5SMatthias Ringwald }
96964bafedd5SMatthias Ringwald 
96974bafedd5SMatthias Ringwald uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){
969849a6c69cSMatthias Ringwald     if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){
969949a6c69cSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
970049a6c69cSMatthias Ringwald     }
970149a6c69cSMatthias Ringwald     hci_stack->le_periodic_terminate_sync_handle = sync_handle;
970249a6c69cSMatthias Ringwald     hci_run();
970349a6c69cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
97044bafedd5SMatthias Ringwald }
97054bafedd5SMatthias Ringwald 
9706f40c73b4SMatthias Ringwald #endif
9707f40c73b4SMatthias Ringwald #endif
97084ae8623eSMatthias Ringwald #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS
9709969d876aSMatthias Ringwald static hci_iso_stream_t *
9710969d876aSMatthias Ringwald hci_iso_stream_create(hci_iso_type_t iso_type, hci_iso_stream_state_t state, uint8_t group_id, uint8_t stream_id) {
97114ae8623eSMatthias Ringwald     hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get();
9712969d876aSMatthias Ringwald     if (iso_stream != NULL){
97138d72db10SMatthias Ringwald         iso_stream->iso_type = iso_type;
971426b93350SMatthias Ringwald         iso_stream->state = state;
97158d72db10SMatthias Ringwald         iso_stream->group_id = group_id;
9716969d876aSMatthias Ringwald         iso_stream->stream_id = stream_id;
9717969d876aSMatthias Ringwald         iso_stream->cis_handle = HCI_CON_HANDLE_INVALID;
9718969d876aSMatthias Ringwald         iso_stream->acl_handle = HCI_CON_HANDLE_INVALID;
97194ae8623eSMatthias Ringwald         btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
97204ae8623eSMatthias Ringwald     }
9721969d876aSMatthias Ringwald     return iso_stream;
97224ae8623eSMatthias Ringwald }
97234ae8623eSMatthias Ringwald 
972415a15be3SMatthias Ringwald static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){
97254ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
97264ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
97274ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
97284ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9729969d876aSMatthias Ringwald         if (iso_stream->cis_handle == con_handle ) {
97304ae8623eSMatthias Ringwald             return iso_stream;
97314ae8623eSMatthias Ringwald         }
97324ae8623eSMatthias Ringwald     }
97334ae8623eSMatthias Ringwald     return NULL;
97344ae8623eSMatthias Ringwald }
97354ae8623eSMatthias Ringwald 
97364ae8623eSMatthias Ringwald static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){
9737969d876aSMatthias Ringwald     log_info("hci_iso_stream_finalize con_handle 0x%04x, group_id 0x%02x", iso_stream->cis_handle, iso_stream->group_id);
97384ae8623eSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream);
97394ae8623eSMatthias Ringwald     btstack_memory_hci_iso_stream_free(iso_stream);
97404ae8623eSMatthias Ringwald }
97414ae8623eSMatthias Ringwald 
9742778463d0SMatthias Ringwald static void hci_iso_stream_finalize_by_type_and_group_id(hci_iso_type_t iso_type, uint8_t group_id) {
9743778463d0SMatthias Ringwald     btstack_linked_list_iterator_t it;
9744778463d0SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
9745778463d0SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9746778463d0SMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9747778463d0SMatthias Ringwald         if ((iso_stream->group_id == group_id) &&
9748778463d0SMatthias Ringwald             (iso_stream->iso_type == iso_type)){
9749778463d0SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
9750778463d0SMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
9751778463d0SMatthias Ringwald         }
9752778463d0SMatthias Ringwald     }
9753778463d0SMatthias Ringwald }
9754778463d0SMatthias Ringwald 
97558d72db10SMatthias Ringwald static void hci_iso_stream_requested_finalize(uint8_t group_id) {
97564ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
97574ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
97584ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
97594ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
9760a90016deSMatthias Ringwald         if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) &&
97618d72db10SMatthias Ringwald             (iso_stream->group_id == group_id)){
97624ae8623eSMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
97634ae8623eSMatthias Ringwald             btstack_memory_hci_iso_stream_free(iso_stream);
97644ae8623eSMatthias Ringwald         }
97654ae8623eSMatthias Ringwald     }
97664ae8623eSMatthias Ringwald }
9767a90016deSMatthias Ringwald static void hci_iso_stream_requested_confirm(uint8_t big_handle){
97684ae8623eSMatthias Ringwald     btstack_linked_list_iterator_t it;
97694ae8623eSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
97704ae8623eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
97714ae8623eSMatthias Ringwald         hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
97724ae8623eSMatthias Ringwald         if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) {
97734ae8623eSMatthias Ringwald             iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED;
97744ae8623eSMatthias Ringwald         }
97754ae8623eSMatthias Ringwald     }
97764ae8623eSMatthias Ringwald }
9777d39e4f95SMatthias Ringwald 
9778d39e4f95SMatthias Ringwald static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){
9779d39e4f95SMatthias Ringwald     uint8_t  sdu_ts_flag = (packet[1] >> 6) & 1;
9780d39e4f95SMatthias Ringwald     uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4);
9781d39e4f95SMatthias Ringwald     uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff;
9782d39e4f95SMatthias Ringwald     return (sdu_len_offset + 2 + sdu_len) == size;
9783d39e4f95SMatthias Ringwald }
9784d39e4f95SMatthias Ringwald 
9785d39e4f95SMatthias Ringwald static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){
9786d39e4f95SMatthias Ringwald     if (hci_stack->iso_packet_handler == NULL) {
9787d39e4f95SMatthias Ringwald         return;
9788d39e4f95SMatthias Ringwald     }
9789d39e4f95SMatthias Ringwald     if (size < 4) {
9790d39e4f95SMatthias Ringwald         return;
9791d39e4f95SMatthias Ringwald     }
9792d39e4f95SMatthias Ringwald 
9793d39e4f95SMatthias Ringwald     // parse header
9794d39e4f95SMatthias Ringwald     uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0);
9795d39e4f95SMatthias Ringwald     uint16_t iso_data_len = little_endian_read_16(packet, 2);
9796d39e4f95SMatthias Ringwald     hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff);
979715a15be3SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
9798d39e4f95SMatthias Ringwald     uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3;
9799d39e4f95SMatthias Ringwald 
9800d39e4f95SMatthias Ringwald     // assert packet is complete
9801d39e4f95SMatthias Ringwald     if ((iso_data_len + 4u) != size){
9802d39e4f95SMatthias Ringwald         return;
9803d39e4f95SMatthias Ringwald     }
9804d39e4f95SMatthias Ringwald 
9805d39e4f95SMatthias Ringwald     if ((pb_flag & 0x01) == 0){
9806d39e4f95SMatthias Ringwald         if (pb_flag == 0x02){
9807d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and a complete SDU.
9808d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(packet, size)) {
9809d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size);
9810d39e4f95SMatthias Ringwald             }
9811d39e4f95SMatthias Ringwald         } else {
9812d39e4f95SMatthias Ringwald             // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU.
9813d39e4f95SMatthias Ringwald             if (iso_stream == NULL){
9814d39e4f95SMatthias Ringwald                 return;
9815d39e4f95SMatthias Ringwald             }
9816d39e4f95SMatthias Ringwald             if (size > HCI_ISO_PAYLOAD_SIZE){
9817d39e4f95SMatthias Ringwald                 return;
9818d39e4f95SMatthias Ringwald             }
9819d39e4f95SMatthias Ringwald             memcpy(iso_stream->reassembly_buffer, packet, size);
9820d39e4f95SMatthias Ringwald             // fix pb_flag
9821d39e4f95SMatthias Ringwald             iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20;
9822d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = size;
9823d39e4f95SMatthias Ringwald         }
9824d39e4f95SMatthias Ringwald     } else {
9825d39e4f95SMatthias Ringwald         // iso_data_load contains continuation or last fragment of an SDU
9826d39e4f95SMatthias Ringwald         uint8_t  ts_flag = (conn_handle_and_flags >> 14) & 1;
9827d39e4f95SMatthias Ringwald         if (ts_flag != 0){
9828d39e4f95SMatthias Ringwald            return;
9829d39e4f95SMatthias Ringwald         }
9830d39e4f95SMatthias Ringwald         // append fragment
9831d39e4f95SMatthias Ringwald         if (iso_stream == NULL){
9832d39e4f95SMatthias Ringwald             return;
9833d39e4f95SMatthias Ringwald         }
9834d39e4f95SMatthias Ringwald         if (iso_stream->reassembly_pos == 0){
9835d39e4f95SMatthias Ringwald             return;
9836d39e4f95SMatthias Ringwald         }
9837d39e4f95SMatthias Ringwald         if ((iso_stream->reassembly_pos + iso_data_len) > size){
9838d39e4f95SMatthias Ringwald             // reset reassembly buffer
9839d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
9840d39e4f95SMatthias Ringwald             return;
9841d39e4f95SMatthias Ringwald         }
9842d39e4f95SMatthias Ringwald         memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len);
9843d39e4f95SMatthias Ringwald         iso_stream->reassembly_pos += iso_data_len;
9844d39e4f95SMatthias Ringwald 
9845d39e4f95SMatthias Ringwald         // deliver if last fragment and SDU complete
9846d39e4f95SMatthias Ringwald         if (pb_flag == 0x03){
9847d39e4f95SMatthias Ringwald             if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){
9848d39e4f95SMatthias Ringwald                 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos);
9849d39e4f95SMatthias Ringwald             }
9850d39e4f95SMatthias Ringwald             iso_stream->reassembly_pos = 0;
9851d39e4f95SMatthias Ringwald         }
9852d39e4f95SMatthias Ringwald     }
9853d39e4f95SMatthias Ringwald }
9854d39e4f95SMatthias Ringwald 
98557aa35f6aSMatthias Ringwald static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){
98567aa35f6aSMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
98577aa35f6aSMatthias Ringwald     uint16_t pos = 0;
98587aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
98597aa35f6aSMatthias Ringwald     event[pos++] = 4 + (2 * big->num_bis);
98607aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_CREATED;
98617aa35f6aSMatthias Ringwald     event[pos++] = status;
98627aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
98637aa35f6aSMatthias Ringwald     event[pos++] = big->num_bis;
98647aa35f6aSMatthias Ringwald     uint8_t i;
98657aa35f6aSMatthias Ringwald     for (i=0;i<big->num_bis;i++){
98667aa35f6aSMatthias Ringwald         little_endian_store_16(event, pos, big->bis_con_handles[i]);
98677aa35f6aSMatthias Ringwald         pos += 2;
98687aa35f6aSMatthias Ringwald     }
98697aa35f6aSMatthias Ringwald     hci_emit_event(event, pos, 0);
98707aa35f6aSMatthias Ringwald }
98717aa35f6aSMatthias Ringwald 
9872d3a89d91SMatthias Ringwald static void hci_emit_cig_created(const le_audio_cig_t * cig, uint8_t status){
9873d3a89d91SMatthias Ringwald     uint8_t event [6 + (MAX_NR_CIS * 2)];
9874d3a89d91SMatthias Ringwald     uint16_t pos = 0;
9875d3a89d91SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
9876d3a89d91SMatthias Ringwald     event[pos++] = 4 + (2 * cig->num_cis);
9877d3a89d91SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIG_CREATED;
9878d3a89d91SMatthias Ringwald     event[pos++] = status;
9879d3a89d91SMatthias Ringwald     event[pos++] = cig->cig_id;
9880d3a89d91SMatthias Ringwald     event[pos++] = cig->num_cis;
9881d3a89d91SMatthias Ringwald     uint8_t i;
9882d3a89d91SMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
9883d3a89d91SMatthias Ringwald         little_endian_store_16(event, pos, cig->cis_con_handles[i]);
9884d3a89d91SMatthias Ringwald         pos += 2;
9885d3a89d91SMatthias Ringwald     }
9886d3a89d91SMatthias Ringwald     hci_emit_event(event, pos, 0);
9887d3a89d91SMatthias Ringwald }
9888f06bb90fSMatthias Ringwald 
9889*620553bdSMatthias Ringwald static uint16_t hci_setup_cis_created(uint8_t * event, hci_iso_stream_t * iso_stream, uint8_t status) {
9890f06bb90fSMatthias Ringwald     uint16_t pos = 0;
9891f06bb90fSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
9892cf439c63SMatthias Ringwald     event[pos++] = 8;
9893f06bb90fSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_CIS_CREATED;
9894f06bb90fSMatthias Ringwald     event[pos++] = status;
9895*620553bdSMatthias Ringwald     event[pos++] = iso_stream->group_id;
9896*620553bdSMatthias Ringwald     event[pos++] = iso_stream->stream_id;
9897*620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->cis_handle);
9898f06bb90fSMatthias Ringwald     pos += 2;
9899*620553bdSMatthias Ringwald     little_endian_store_16(event, pos, iso_stream->acl_handle);
9900cf439c63SMatthias Ringwald     pos += 2;
9901*620553bdSMatthias Ringwald     return pos;
9902f06bb90fSMatthias Ringwald }
9903f06bb90fSMatthias Ringwald 
990414045fdbSMatthias Ringwald // emits GAP_SUBEVENT_CIS_CREATED after calling hci_iso_finalize
990514045fdbSMatthias Ringwald static void hci_cis_handle_created(hci_iso_stream_t * iso_stream, uint8_t status){
990614045fdbSMatthias Ringwald     // cache data before finalizing struct
9907*620553bdSMatthias Ringwald     uint8_t event [10];
9908*620553bdSMatthias Ringwald     uint16_t pos = hci_setup_cis_created(event, iso_stream, status);
9909*620553bdSMatthias Ringwald     btstack_assert(pos <= sizeof(event));
991014045fdbSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
991114045fdbSMatthias Ringwald         hci_iso_stream_finalize(iso_stream);
991214045fdbSMatthias Ringwald     }
9913*620553bdSMatthias Ringwald     hci_emit_event(event, pos, 0);
991414045fdbSMatthias Ringwald }
991514045fdbSMatthias Ringwald 
99167aa35f6aSMatthias Ringwald static void hci_emit_big_terminated(const le_audio_big_t * big){
99177aa35f6aSMatthias Ringwald     uint8_t event [4];
99187aa35f6aSMatthias Ringwald     uint16_t pos = 0;
99197aa35f6aSMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
99207aa35f6aSMatthias Ringwald     event[pos++] = 2;
99217aa35f6aSMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_TERMINATED;
99227aa35f6aSMatthias Ringwald     event[pos++] = big->big_handle;
99237aa35f6aSMatthias Ringwald     hci_emit_event(event, pos, 0);
99247aa35f6aSMatthias Ringwald }
99257aa35f6aSMatthias Ringwald 
99262a6c0f82SMatthias Ringwald static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){
99272a6c0f82SMatthias Ringwald     uint8_t event [6 + (MAX_NR_BIS * 2)];
99282a6c0f82SMatthias Ringwald     uint16_t pos = 0;
99292a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
99302a6c0f82SMatthias Ringwald     event[pos++] = 4;
99312a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED;
99322a6c0f82SMatthias Ringwald     event[pos++] = status;
99332a6c0f82SMatthias Ringwald     event[pos++] = big_sync->big_handle;
99342a6c0f82SMatthias Ringwald     event[pos++] = big_sync->num_bis;
99352a6c0f82SMatthias Ringwald     uint8_t i;
99362a6c0f82SMatthias Ringwald     for (i=0;i<big_sync->num_bis;i++){
99372a6c0f82SMatthias Ringwald         little_endian_store_16(event, pos, big_sync->bis_con_handles[i]);
99382a6c0f82SMatthias Ringwald         pos += 2;
99392a6c0f82SMatthias Ringwald     }
99402a6c0f82SMatthias Ringwald     hci_emit_event(event, pos, 0);
99412a6c0f82SMatthias Ringwald }
99422a6c0f82SMatthias Ringwald 
9943d04a9afcSMatthias Ringwald static void hci_emit_big_sync_stopped(uint8_t big_handle){
99442a6c0f82SMatthias Ringwald     uint8_t event [4];
99452a6c0f82SMatthias Ringwald     uint16_t pos = 0;
99462a6c0f82SMatthias Ringwald     event[pos++] = HCI_EVENT_META_GAP;
99472a6c0f82SMatthias Ringwald     event[pos++] = 2;
99482a6c0f82SMatthias Ringwald     event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED;
9949d04a9afcSMatthias Ringwald     event[pos++] = big_handle;
99502a6c0f82SMatthias Ringwald     hci_emit_event(event, pos, 0);
99512a6c0f82SMatthias Ringwald }
99522a6c0f82SMatthias Ringwald 
99535ade6657SMatthias Ringwald static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) {
99545ade6657SMatthias Ringwald     uint8_t event[6];
99555ade6657SMatthias Ringwald     uint16_t pos = 0;
99565ade6657SMatthias Ringwald     event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW;
99575ade6657SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
99585ade6657SMatthias Ringwald     event[pos++] = big->big_handle;
99595ade6657SMatthias Ringwald     event[pos++] = bis_index;
99605ade6657SMatthias Ringwald     little_endian_store_16(event, pos, big->bis_con_handles[bis_index]);
99615ade6657SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
99625ade6657SMatthias Ringwald }
99635ade6657SMatthias Ringwald 
99642c077771SMatthias Ringwald static void hci_emit_cis_can_send_now(hci_con_handle_t cis_con_handle) {
99652c077771SMatthias Ringwald     uint8_t event[4];
99662c077771SMatthias Ringwald     uint16_t pos = 0;
99672c077771SMatthias Ringwald     event[pos++] = HCI_EVENT_CIS_CAN_SEND_NOW;
99682c077771SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
99692c077771SMatthias Ringwald     little_endian_store_16(event, pos, cis_con_handle);
99702c077771SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
99712c077771SMatthias Ringwald }
99722c077771SMatthias Ringwald 
99737aa35f6aSMatthias Ringwald static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){
99747aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_t it;
99757aa35f6aSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
99767aa35f6aSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
99777aa35f6aSMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
99787aa35f6aSMatthias Ringwald         if ( big->big_handle == big_handle ) {
99797aa35f6aSMatthias Ringwald             return big;
99807aa35f6aSMatthias Ringwald         }
99817aa35f6aSMatthias Ringwald     }
99827aa35f6aSMatthias Ringwald     return NULL;
99837aa35f6aSMatthias Ringwald }
99847aa35f6aSMatthias Ringwald 
99852a6c0f82SMatthias Ringwald static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){
99862a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_t it;
99872a6c0f82SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs);
99882a6c0f82SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
99892a6c0f82SMatthias Ringwald         le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it);
99902a6c0f82SMatthias Ringwald         if ( big_sync->big_handle == big_handle ) {
99912a6c0f82SMatthias Ringwald             return big_sync;
99922a6c0f82SMatthias Ringwald         }
99932a6c0f82SMatthias Ringwald     }
99942a6c0f82SMatthias Ringwald     return NULL;
99952a6c0f82SMatthias Ringwald }
99962a6c0f82SMatthias Ringwald 
999701d4f05fSMatthias Ringwald void hci_set_num_iso_packets_to_queue(uint8_t num_packets){
999801d4f05fSMatthias Ringwald     hci_stack->iso_packets_to_queue = num_packets;
999901d4f05fSMatthias Ringwald }
1000001d4f05fSMatthias Ringwald 
10001d3a89d91SMatthias Ringwald static le_audio_cig_t * hci_cig_for_id(uint8_t cig_id){
10002d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_t it;
10003d3a89d91SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_cigs);
10004d3a89d91SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10005d3a89d91SMatthias Ringwald         le_audio_cig_t * cig = (le_audio_cig_t *) btstack_linked_list_iterator_next(&it);
10006d3a89d91SMatthias Ringwald         if ( cig->cig_id == cig_id ) {
10007d3a89d91SMatthias Ringwald             return cig;
10008d3a89d91SMatthias Ringwald         }
10009d3a89d91SMatthias Ringwald     }
10010d3a89d91SMatthias Ringwald     return NULL;
10011d3a89d91SMatthias Ringwald }
10012d3a89d91SMatthias Ringwald 
100135ade6657SMatthias Ringwald static void hci_iso_notify_can_send_now(void){
100142c077771SMatthias Ringwald 
100152c077771SMatthias Ringwald     // BIG
100162c077771SMatthias Ringwald 
100175ade6657SMatthias Ringwald     btstack_linked_list_iterator_t it;
100185ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
100195ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
100205ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
10021aacb1081SMatthias Ringwald         // track number completed packet timestamps
10022aacb1081SMatthias Ringwald         if (big->num_completed_timestamp_current_valid){
10023aacb1081SMatthias Ringwald             big->num_completed_timestamp_current_valid = false;
10024aacb1081SMatthias Ringwald             if (big->num_completed_timestamp_previous_valid){
10025aacb1081SMatthias Ringwald                 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling
10026aacb1081SMatthias Ringwald                 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000;
10027aacb1081SMatthias Ringwald                 int32_t  num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms,
10028aacb1081SMatthias Ringwald                                                                                big->num_completed_timestamp_previous_ms);
10029aacb1081SMatthias Ringwald                 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){
10030aacb1081SMatthias Ringwald                     // to catch up, skip packet on all BIS
10031aacb1081SMatthias Ringwald                     uint8_t i;
10032aacb1081SMatthias Ringwald                     for (i=0;i<big->num_bis;i++){
10033aacb1081SMatthias Ringwald                         hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10034aacb1081SMatthias Ringwald                         if (iso_stream){
10035aacb1081SMatthias Ringwald                             iso_stream->num_packets_to_skip++;
10036aacb1081SMatthias Ringwald                         }
10037aacb1081SMatthias Ringwald                     }
10038aacb1081SMatthias Ringwald                 }
10039aacb1081SMatthias Ringwald             }
10040aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_valid = true;
10041aacb1081SMatthias Ringwald             big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms;
10042aacb1081SMatthias Ringwald         }
10043aacb1081SMatthias Ringwald 
100445ade6657SMatthias Ringwald         if (big->can_send_now_requested){
10045d4e5d4faSMatthias Ringwald             // check if no outgoing iso packets pending and no can send now have to be emitted
100465ade6657SMatthias Ringwald             uint8_t i;
100475ade6657SMatthias Ringwald             bool can_send = true;
10048aacb1081SMatthias Ringwald             uint8_t num_iso_queued_minimum = 0;
100495ade6657SMatthias Ringwald             for (i=0;i<big->num_bis;i++){
100505ade6657SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
10051aacb1081SMatthias Ringwald                 if (iso_stream == NULL) continue;
10052aacb1081SMatthias Ringwald                 // handle case where individual ISO packet was sent too late:
10053aacb1081SMatthias Ringwald                 // for each additionally queued packet, a new one needs to get skipped
10054aacb1081SMatthias Ringwald                 if (i==0){
10055aacb1081SMatthias Ringwald                     num_iso_queued_minimum = iso_stream->num_packets_sent;
10056aacb1081SMatthias Ringwald                 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){
10057aacb1081SMatthias Ringwald                     uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum;
10058aacb1081SMatthias Ringwald                     iso_stream->num_packets_to_skip += num_packets_to_skip;
10059aacb1081SMatthias Ringwald                     iso_stream->num_packets_sent    -= num_packets_to_skip;
10060aacb1081SMatthias Ringwald                 }
10061aacb1081SMatthias Ringwald                 // check if we can send now
10062aacb1081SMatthias Ringwald                 if  ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){
100635ade6657SMatthias Ringwald                     can_send = false;
100645ade6657SMatthias Ringwald                     break;
100655ade6657SMatthias Ringwald                 }
100665ade6657SMatthias Ringwald             }
100675ade6657SMatthias Ringwald             if (can_send){
100685ade6657SMatthias Ringwald                 // propagate can send now to individual streams
100695ade6657SMatthias Ringwald                 big->can_send_now_requested = false;
100705ade6657SMatthias Ringwald                 for (i=0;i<big->num_bis;i++){
100715ade6657SMatthias Ringwald                     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
100725ade6657SMatthias Ringwald                     iso_stream->emit_ready_to_send = true;
100735ade6657SMatthias Ringwald                 }
100745ade6657SMatthias Ringwald             }
100755ade6657SMatthias Ringwald         }
100765ade6657SMatthias Ringwald     }
100775ade6657SMatthias Ringwald 
100785ade6657SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return;
100795ade6657SMatthias Ringwald 
100805ade6657SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs);
100815ade6657SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
100825ade6657SMatthias Ringwald         le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it);
100835ade6657SMatthias Ringwald         // report bis ready
100845ade6657SMatthias Ringwald         uint8_t i;
100855ade6657SMatthias Ringwald         for (i=0;i<big->num_bis;i++){
100865ade6657SMatthias Ringwald             hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]);
100875ade6657SMatthias Ringwald             if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){
100885ade6657SMatthias Ringwald                 iso_stream->emit_ready_to_send = false;
100895ade6657SMatthias Ringwald                 hci_emit_bis_can_send_now(big, i);
100905ade6657SMatthias Ringwald                 break;
100915ade6657SMatthias Ringwald             }
100925ade6657SMatthias Ringwald         }
100935ade6657SMatthias Ringwald     }
100942c077771SMatthias Ringwald 
100952c077771SMatthias Ringwald     // CIS
100962c077771SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams);
100972c077771SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
100982c077771SMatthias Ringwald         hci_iso_stream_t *iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it);
100992c077771SMatthias Ringwald         if ((iso_stream->can_send_now_requested) &&
101002c077771SMatthias Ringwald             (iso_stream->num_packets_sent < hci_stack->iso_packets_to_queue)){
101012c077771SMatthias Ringwald             iso_stream->can_send_now_requested = false;
10102969d876aSMatthias Ringwald             hci_emit_cis_can_send_now(iso_stream->cis_handle);
101032c077771SMatthias Ringwald         }
101042c077771SMatthias Ringwald     }
101055ade6657SMatthias Ringwald }
101065ade6657SMatthias Ringwald 
101077aa35f6aSMatthias Ringwald uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){
101087aa35f6aSMatthias Ringwald     if (hci_big_for_handle(big_params->big_handle) != NULL){
101097aa35f6aSMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
101107aa35f6aSMatthias Ringwald     }
101117aa35f6aSMatthias Ringwald     if (big_params->num_bis == 0){
101127aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
101137aa35f6aSMatthias Ringwald     }
101147aa35f6aSMatthias Ringwald     if (big_params->num_bis > MAX_NR_BIS){
101157aa35f6aSMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
101167aa35f6aSMatthias Ringwald     }
101177aa35f6aSMatthias Ringwald 
10118fb16346aSMatthias Ringwald     // reserve ISO Streams
10119fb16346aSMatthias Ringwald     uint8_t i;
10120fb16346aSMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10121fb16346aSMatthias Ringwald     for (i=0;i<big_params->num_bis;i++){
10122969d876aSMatthias Ringwald         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_BIS, HCI_ISO_STREAM_STATE_REQUESTED, big_params->big_handle, i);
10123969d876aSMatthias Ringwald         if (iso_stream == NULL) {
10124969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10125fb16346aSMatthias Ringwald             break;
10126fb16346aSMatthias Ringwald         }
10127fb16346aSMatthias Ringwald     }
10128fb16346aSMatthias Ringwald 
10129fb16346aSMatthias Ringwald     // free structs on error
10130fb16346aSMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10131778463d0SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_BIS, big_params->big_handle);
10132fb16346aSMatthias Ringwald         return status;
10133fb16346aSMatthias Ringwald     }
10134fb16346aSMatthias Ringwald 
101357aa35f6aSMatthias Ringwald     le_audio_big_t * big = storage;
101367aa35f6aSMatthias Ringwald     big->big_handle = big_params->big_handle;
101377aa35f6aSMatthias Ringwald     big->params = big_params;
101387aa35f6aSMatthias Ringwald     big->state = LE_AUDIO_BIG_STATE_CREATE;
101397aa35f6aSMatthias Ringwald     big->num_bis = big_params->num_bis;
101407aa35f6aSMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
101417aa35f6aSMatthias Ringwald 
101427aa35f6aSMatthias Ringwald     hci_run();
101437aa35f6aSMatthias Ringwald 
101447aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
101457aa35f6aSMatthias Ringwald }
101467aa35f6aSMatthias Ringwald 
101472a6c0f82SMatthias Ringwald uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){
101482a6c0f82SMatthias Ringwald     if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){
101492a6c0f82SMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
101502a6c0f82SMatthias Ringwald     }
101512a6c0f82SMatthias Ringwald     if (big_sync_params->num_bis == 0){
101522a6c0f82SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
101532a6c0f82SMatthias Ringwald     }
101542a6c0f82SMatthias Ringwald     if (big_sync_params->num_bis > MAX_NR_BIS){
101552a6c0f82SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
101562a6c0f82SMatthias Ringwald     }
101572a6c0f82SMatthias Ringwald 
101582a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = storage;
101592a6c0f82SMatthias Ringwald     big_sync->big_handle = big_sync_params->big_handle;
101602a6c0f82SMatthias Ringwald     big_sync->params = big_sync_params;
101612a6c0f82SMatthias Ringwald     big_sync->state = LE_AUDIO_BIG_STATE_CREATE;
101622a6c0f82SMatthias Ringwald     big_sync->num_bis = big_sync_params->num_bis;
101632a6c0f82SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
101642a6c0f82SMatthias Ringwald 
101652a6c0f82SMatthias Ringwald     hci_run();
101662a6c0f82SMatthias Ringwald 
101672a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101682a6c0f82SMatthias Ringwald }
101692a6c0f82SMatthias Ringwald 
101707aa35f6aSMatthias Ringwald uint8_t gap_big_terminate(uint8_t big_handle){
101717aa35f6aSMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
101727aa35f6aSMatthias Ringwald     if (big == NULL){
101737aa35f6aSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
101747aa35f6aSMatthias Ringwald     }
101757aa35f6aSMatthias Ringwald     switch (big->state){
101767aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
101777aa35f6aSMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big);
101782a6c0f82SMatthias Ringwald             hci_emit_big_terminated(big);
101792a6c0f82SMatthias Ringwald             break;
101802a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
101812a6c0f82SMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
101827aa35f6aSMatthias Ringwald             break;
101837aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
101847aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
101857aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
101867aa35f6aSMatthias Ringwald             big->state = LE_AUDIO_BIG_STATE_TERMINATE;
101877aa35f6aSMatthias Ringwald             hci_run();
101887aa35f6aSMatthias Ringwald             break;
101892a6c0f82SMatthias Ringwald         default:
101902a6c0f82SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
101912a6c0f82SMatthias Ringwald     }
101922a6c0f82SMatthias Ringwald     return ERROR_CODE_SUCCESS;
101932a6c0f82SMatthias Ringwald }
101942a6c0f82SMatthias Ringwald 
101952a6c0f82SMatthias Ringwald uint8_t gap_big_sync_terminate(uint8_t big_handle){
101962a6c0f82SMatthias Ringwald     le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle);
101972a6c0f82SMatthias Ringwald     if (big_sync == NULL){
101982a6c0f82SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
101992a6c0f82SMatthias Ringwald     }
102002a6c0f82SMatthias Ringwald     switch (big_sync->state){
102012a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_CREATE:
102022a6c0f82SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync);
10203d04a9afcSMatthias Ringwald             hci_emit_big_sync_stopped(big_handle);
102042a6c0f82SMatthias Ringwald             break;
102057aa35f6aSMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH:
102062a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE;
102072a6c0f82SMatthias Ringwald             break;
102082a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_W4_ESTABLISHED:
102092a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH:
102102a6c0f82SMatthias Ringwald         case LE_AUDIO_BIG_STATE_ACTIVE:
102112a6c0f82SMatthias Ringwald             big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE;
102122a6c0f82SMatthias Ringwald             hci_run();
102137aa35f6aSMatthias Ringwald             break;
102147aa35f6aSMatthias Ringwald         default:
102157aa35f6aSMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
102167aa35f6aSMatthias Ringwald     }
102177aa35f6aSMatthias Ringwald     return ERROR_CODE_SUCCESS;
102187aa35f6aSMatthias Ringwald }
10219d39e4f95SMatthias Ringwald 
102205ade6657SMatthias Ringwald uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){
102215ade6657SMatthias Ringwald     le_audio_big_t * big = hci_big_for_handle(big_handle);
102225ade6657SMatthias Ringwald     if (big == NULL){
102235ade6657SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
102245ade6657SMatthias Ringwald     }
102255ade6657SMatthias Ringwald     if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){
102265ade6657SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
102275ade6657SMatthias Ringwald     }
102285ade6657SMatthias Ringwald     big->can_send_now_requested = true;
102295ade6657SMatthias Ringwald     hci_iso_notify_can_send_now();
102305ade6657SMatthias Ringwald     return ERROR_CODE_SUCCESS;
102315ade6657SMatthias Ringwald }
10232d3a89d91SMatthias Ringwald 
102332c077771SMatthias Ringwald uint8_t hci_request_cis_can_send_now_events(hci_con_handle_t cis_con_handle){
102342c077771SMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_con_handle);
102352c077771SMatthias Ringwald     if (iso_stream == NULL){
102362c077771SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
102372c077771SMatthias Ringwald     }
102382c077771SMatthias Ringwald     if ((iso_stream->iso_type != HCI_ISO_TYPE_CIS) && (iso_stream->state != HCI_ISO_STREAM_STATE_ESTABLISHED)) {
102392c077771SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
102402c077771SMatthias Ringwald     }
102412c077771SMatthias Ringwald     iso_stream->can_send_now_requested = true;
102422c077771SMatthias Ringwald     hci_iso_notify_can_send_now();
102432c077771SMatthias Ringwald     return ERROR_CODE_SUCCESS;
102442c077771SMatthias Ringwald }
102452c077771SMatthias Ringwald 
10246d3a89d91SMatthias Ringwald uint8_t gap_cig_create(le_audio_cig_t * storage, le_audio_cig_params_t * cig_params){
10247d3a89d91SMatthias Ringwald     if (hci_cig_for_id(cig_params->cig_id) != NULL){
10248d3a89d91SMatthias Ringwald         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
10249d3a89d91SMatthias Ringwald     }
10250d3a89d91SMatthias Ringwald     if (cig_params->num_cis == 0){
10251d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10252d3a89d91SMatthias Ringwald     }
10253d3a89d91SMatthias Ringwald     if (cig_params->num_cis > MAX_NR_BIS){
10254d3a89d91SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
10255d3a89d91SMatthias Ringwald     }
10256d3a89d91SMatthias Ringwald 
10257d3a89d91SMatthias Ringwald     // reserve ISO Streams
10258d3a89d91SMatthias Ringwald     uint8_t i;
10259d3a89d91SMatthias Ringwald     uint8_t status = ERROR_CODE_SUCCESS;
10260d3a89d91SMatthias Ringwald     for (i=0;i<cig_params->num_cis;i++){
10261969d876aSMatthias Ringwald         hci_iso_stream_t * iso_stream = hci_iso_stream_create(HCI_ISO_TYPE_CIS,HCI_ISO_STREAM_STATE_REQUESTED, cig_params->cig_id, i);
1026236468e6fSMatthias Ringwald         if (iso_stream == NULL) {
10263969d876aSMatthias Ringwald             status = ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
10264d3a89d91SMatthias Ringwald             break;
10265d3a89d91SMatthias Ringwald         }
10266d3a89d91SMatthias Ringwald     }
10267d3a89d91SMatthias Ringwald 
10268d3a89d91SMatthias Ringwald     // free structs on error
10269d3a89d91SMatthias Ringwald     if (status != ERROR_CODE_SUCCESS){
10270d3a89d91SMatthias Ringwald         hci_iso_stream_finalize_by_type_and_group_id(HCI_ISO_TYPE_CIS, cig_params->cig_id);
10271d3a89d91SMatthias Ringwald         return status;
10272d3a89d91SMatthias Ringwald     }
10273d3a89d91SMatthias Ringwald 
10274d3a89d91SMatthias Ringwald     le_audio_cig_t * cig = storage;
10275d3a89d91SMatthias Ringwald     cig->cig_id = cig_params->cig_id;
10276d3a89d91SMatthias Ringwald     cig->num_cis = cig_params->num_cis;
10277d3a89d91SMatthias Ringwald     cig->params = cig_params;
10278d3a89d91SMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE;
10279444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
10280444e371eSMatthias Ringwald         cig->cis_con_handles[i] = HCI_CON_HANDLE_INVALID;
10281444e371eSMatthias Ringwald         cig->acl_con_handles[i] = HCI_CON_HANDLE_INVALID;
102820f0ba168SMatthias Ringwald         cig->cis_setup_active[i] = false;
102830f0ba168SMatthias Ringwald         cig->cis_established[i] = false;
10284444e371eSMatthias Ringwald     }
10285d3a89d91SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_audio_cigs, (btstack_linked_item_t *) cig);
10286d3a89d91SMatthias Ringwald 
10287d3a89d91SMatthias Ringwald     hci_run();
10288d3a89d91SMatthias Ringwald 
10289d3a89d91SMatthias Ringwald     return ERROR_CODE_SUCCESS;
10290d3a89d91SMatthias Ringwald }
10291d3a89d91SMatthias Ringwald 
10292444e371eSMatthias Ringwald uint8_t gap_cis_create(uint8_t cig_handle, hci_con_handle_t cis_con_handles [], hci_con_handle_t acl_con_handles []){
10293444e371eSMatthias Ringwald     le_audio_cig_t * cig = hci_cig_for_id(cig_handle);
10294444e371eSMatthias Ringwald     if (cig == NULL){
10295444e371eSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10296444e371eSMatthias Ringwald     }
10297444e371eSMatthias Ringwald 
10298444e371eSMatthias Ringwald     if (cig->state != LE_AUDIO_CIG_STATE_W4_CIS_REQUEST){
10299444e371eSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
10300444e371eSMatthias Ringwald     }
10301444e371eSMatthias Ringwald 
10302444e371eSMatthias Ringwald     // store ACL Connection Handles
10303444e371eSMatthias Ringwald     uint8_t i;
10304444e371eSMatthias Ringwald     for (i=0;i<cig->num_cis;i++){
1030556bd2ec0SMatthias Ringwald         // check that all con handles exist and store
10306444e371eSMatthias Ringwald         hci_con_handle_t cis_handle = cis_con_handles[i];
1030736468e6fSMatthias Ringwald         if (cis_handle == HCI_CON_HANDLE_INVALID){
1030836468e6fSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1030936468e6fSMatthias Ringwald         }
10310444e371eSMatthias Ringwald         uint8_t j;
10311444e371eSMatthias Ringwald         bool found = false;
10312444e371eSMatthias Ringwald         for (j=0;j<cig->num_cis;j++){
10313444e371eSMatthias Ringwald             if (cig->cis_con_handles[j] == cis_handle){
10314444e371eSMatthias Ringwald                 cig->acl_con_handles[j] = acl_con_handles[j];
1031556bd2ec0SMatthias Ringwald                 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
1031656bd2ec0SMatthias Ringwald                 btstack_assert(iso_stream != NULL);
1031756bd2ec0SMatthias Ringwald                 iso_stream->acl_handle = acl_con_handles[j];
1031836468e6fSMatthias Ringwald                 found = true;
10319444e371eSMatthias Ringwald                 break;
10320444e371eSMatthias Ringwald             }
10321444e371eSMatthias Ringwald         }
10322444e371eSMatthias Ringwald         if (!found){
10323444e371eSMatthias Ringwald             return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
10324444e371eSMatthias Ringwald         }
10325444e371eSMatthias Ringwald     }
10326444e371eSMatthias Ringwald 
10327444e371eSMatthias Ringwald     cig->state = LE_AUDIO_CIG_STATE_CREATE_CIS;
10328444e371eSMatthias Ringwald     hci_run();
10329444e371eSMatthias Ringwald 
10330444e371eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
10331444e371eSMatthias Ringwald }
10332444e371eSMatthias Ringwald 
10333969d876aSMatthias Ringwald static uint8_t hci_cis_accept_or_reject(hci_con_handle_t cis_handle, hci_iso_stream_state_t state){
10334969d876aSMatthias Ringwald     hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle);
103356fd1d2c8SMatthias Ringwald     if (iso_stream == NULL){
103366fd1d2c8SMatthias Ringwald         // if we got a CIS Request but fail to allocate a hci_iso_stream_t object, we won't find it here
10337969d876aSMatthias Ringwald         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
1033826b93350SMatthias Ringwald     }
1033926b93350SMatthias Ringwald 
103406fd1d2c8SMatthias Ringwald     // set next state and continue
103416fd1d2c8SMatthias Ringwald     iso_stream->state = state;
1034226b93350SMatthias Ringwald     hci_run();
1034326b93350SMatthias Ringwald     return ERROR_CODE_SUCCESS;
1034426b93350SMatthias Ringwald }
1034526b93350SMatthias Ringwald 
1034626b93350SMatthias Ringwald uint8_t gap_cis_accept(hci_con_handle_t cis_con_handle){
1034726b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_ACCEPT);
1034826b93350SMatthias Ringwald }
1034926b93350SMatthias Ringwald 
1035026b93350SMatthias Ringwald uint8_t gap_cis_reject(hci_con_handle_t cis_con_handle){
1035126b93350SMatthias Ringwald     return hci_cis_accept_or_reject(cis_con_handle, HCI_ISO_STREAM_W2_REJECT);
1035226b93350SMatthias Ringwald }
1035326b93350SMatthias Ringwald 
1035426b93350SMatthias Ringwald 
10355f40c73b4SMatthias Ringwald #endif
103564ae8623eSMatthias Ringwald #endif /* ENABLE_BLE */
10357f40c73b4SMatthias Ringwald 
10358eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1035918976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
1036018976c74SMatthias Ringwald     hci_connection_t * conn;
1036118976c74SMatthias Ringwald 
1036218976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
1036318976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
1036418976c74SMatthias Ringwald 
103657d33cb26SMilanka Ringwald     // setup Controller info
103667d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
103677d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
103687d33cb26SMilanka Ringwald 
1036918976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
1037018976c74SMatthias Ringwald     addr[5] = 0x01;
1037117ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1037218976c74SMatthias Ringwald     conn->con_handle = addr[5];
1037318976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
103747d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1037518976c74SMatthias Ringwald 
1037618976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
1037718976c74SMatthias Ringwald     addr[5] = 0x02;
1037817ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1037918976c74SMatthias Ringwald     conn->con_handle = addr[5];
1038018976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
103817d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1038218976c74SMatthias Ringwald 
1038318976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
1038418976c74SMatthias Ringwald     addr[5] = 0x03;
1038517ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL, HCI_ROLE_SLAVE);
1038618976c74SMatthias Ringwald     conn->con_handle = addr[5];
1038718976c74SMatthias Ringwald     conn->state = OPEN;
103887d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1038918976c74SMatthias Ringwald 
1039018976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
1039118976c74SMatthias Ringwald     addr[5] = 0x04;
1039217ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO, HCI_ROLE_SLAVE);
1039318976c74SMatthias Ringwald     conn->con_handle = addr[5];
1039418976c74SMatthias Ringwald     conn->state = OPEN;
103957d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
1039618976c74SMatthias Ringwald 
1039718976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
1039818976c74SMatthias Ringwald     addr[5] = 0x05;
1039917ab8643SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC, HCI_ROLE_SLAVE);
1040018976c74SMatthias Ringwald     conn->con_handle = addr[5];
1040118976c74SMatthias Ringwald     conn->state = OPEN;
104027d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
104038046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
1040418976c74SMatthias Ringwald }
1040518976c74SMatthias Ringwald 
10406eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
10407eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
10408eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
10409eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10410eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
10411eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
10412eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
10413eddac615SMatthias Ringwald     }
10414eddac615SMatthias Ringwald }
104151470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
10416b6ffb67fSMatthias Ringwald     hci_stack->le_scanning_param_update = false;
104171470db0cSMatthias Ringwald     hci_init_done();
104181470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
104191470db0cSMatthias Ringwald }
10420eddac615SMatthias Ringwald #endif
10421