xref: /btstack/src/hci.c (revision 367aedc0e9bcd6a667a86fa0fe58d84dd974d1f4)
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
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD 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 
564a3574a1SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
57d0b87befSMatthias Ringwald #include "../port/ios/src/btstack_control_iphone.h"
584a3574a1SMatthias Ringwald #endif
594a3574a1SMatthias Ringwald 
60a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
61472a5742SMatthias Ringwald #include "gap.h"
6221debf25SMatthias Ringwald #include "ble/le_device_db.h"
6345c102fdSMatthias Ringwald #endif
6445c102fdSMatthias Ringwald 
6593b8dc03Smatthias.ringwald #include <stdarg.h>
6693b8dc03Smatthias.ringwald #include <string.h>
675838a2edSMatthias Ringwald #include <inttypes.h>
687f2435e6Smatthias.ringwald 
6916ece135SMatthias Ringwald #include "btstack_debug.h"
700e2df43fSMatthias Ringwald #include "btstack_event.h"
714a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
724a3574a1SMatthias Ringwald #include "btstack_memory.h"
7361f37892SMatthias Ringwald #include "bluetooth_company_id.h"
741cfb383eSMatthias Ringwald #include "bluetooth_data_types.h"
754a3574a1SMatthias Ringwald #include "gap.h"
764a3574a1SMatthias Ringwald #include "hci.h"
774a3574a1SMatthias Ringwald #include "hci_cmd.h"
78d8905019Smatthias.ringwald #include "hci_dump.h"
791cfb383eSMatthias Ringwald #include "ad_parser.h"
8093b8dc03Smatthias.ringwald 
812b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
822b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_NUM
832b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
842b838201SMatthias Ringwald #endif
852b838201SMatthias Ringwald #ifndef HCI_HOST_ACL_PACKET_LEN
862b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
872b838201SMatthias Ringwald #endif
882b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_NUM
892b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
902b838201SMatthias Ringwald #endif
912b838201SMatthias Ringwald #ifndef HCI_HOST_SCO_PACKET_LEN
922b838201SMatthias Ringwald #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
932b838201SMatthias Ringwald #endif
942b838201SMatthias Ringwald #endif
951b0e3922Smatthias.ringwald 
96aa81e641SMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM)
97aa81e641SMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM."
98aa81e641SMatthias Ringwald #endif
99aa81e641SMatthias Ringwald 
1001e20a53eSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT)
1011e20a53eSMatthias Ringwald #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT."
1021e20a53eSMatthias Ringwald #endif
1031e20a53eSMatthias Ringwald 
104169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
10562473419SMatthias Ringwald 
10662473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
107659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
10862473419SMatthias Ringwald #endif
109ee091cf1Smatthias.ringwald 
1101cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1111cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1121cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1131cfb383eSMatthias Ringwald #endif
1141cfb383eSMatthias Ringwald 
115f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
116f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN       0x01
117f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX       0x30
118beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE         0x00
119beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_ACTIVE    0x80
120beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE       0x81
121beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL    0x82
122beb3c81dSMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83
123f5875de5SMatthias Ringwald 
124b7f1ee76SMatthias Ringwald // GAP Remote Name Request
125b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
126b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
127b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
128b7f1ee76SMatthias Ringwald 
1290a51f88bSMatthias Ringwald // GAP Pairing
1300a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1310a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1320a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1330a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1340a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1350a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1360a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
1370a51f88bSMatthias Ringwald 
1380a51f88bSMatthias Ringwald 
139b83d5eabSMatthias Ringwald // prototypes
14035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
141758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
14235454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled);
14335454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
14435454696SMatthias Ringwald static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
14567aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
14635454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
14735454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
148a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
14935454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
150ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
15196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
15252db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
1539784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
15452db98b2SMatthias Ringwald #endif
1551cfb383eSMatthias Ringwald 
1567586ee35S[email protected] static int  hci_power_control_on(void);
1577586ee35S[email protected] static void hci_power_control_off(void);
1586da48142SSean Wilson static void hci_state_reset(void);
159fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
160fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
161b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
162b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
163b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
164b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
165b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
16695d71764SMatthias Ringwald static void hci_run(void);
16795d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
16895d71764SMatthias Ringwald static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
1696a5ffed8SMatthias Ringwald 
1706a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
171f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
1726a5ffed8SMatthias Ringwald #endif
1735d509858SMatthias Ringwald 
174a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
175e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
17639677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
177384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
178667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address);
1799c77c9dbSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void);
1805d509858SMatthias Ringwald #endif
181d70217a2SMatthias Ringwald #endif
182758b46ceSmatthias.ringwald 
18306b35ec0Smatthias.ringwald // the STACK is here
1843a9fb326S[email protected] #ifndef HAVE_MALLOC
1853a9fb326S[email protected] static hci_stack_t   hci_stack_static;
1863a9fb326S[email protected] #endif
1873a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
18816833f0aSmatthias.ringwald 
1891c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
19063168530SMatthias Ringwald // default name
19163168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
19263168530SMatthias Ringwald 
19366fb9560S[email protected] // test helper
19466fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
1951c9e5e9dSMatthias Ringwald #endif
19666fb9560S[email protected] 
19796a45072S[email protected] /**
19896a45072S[email protected]  * create connection for given address
19996a45072S[email protected]  *
20096a45072S[email protected]  * @return connection OR NULL, if no memory left
20196a45072S[email protected]  */
202667ba9d1SMatthias Ringwald static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){
2031a06f663S[email protected]     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
204bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
20596a45072S[email protected]     if (!conn) return NULL;
206058e3d6bSMatthias Ringwald     bd_addr_copy(conn->address, addr);
2072dceb1d6SMatthias Ringwald     conn->role = HCI_ROLE_INVALID;
20896a45072S[email protected]     conn->address_type = addr_type;
20996a45072S[email protected]     conn->con_handle = 0xffff;
2108daf94bcSMatthias Ringwald     conn->authentication_flags = AUTH_FLAG_NONE;
21196a45072S[email protected]     conn->bonding_flags = 0;
21296a45072S[email protected]     conn->requested_security_level = LEVEL_0;
21352db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
21488a03c8dSMatthias Ringwald     conn->request_role = HCI_ROLE_INVALID;
215140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = 0xffff;
216965a4ccfSMatthias Ringwald     conn->qos_service_type = HCI_SERVICE_TYPE_INVALID;
217e9f98c4aSMatthias Ringwald     conn->link_key_type = INVALID_LINK_KEY;
21891a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
21991a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
22096a45072S[email protected]     hci_connection_timestamp(conn);
22152db98b2SMatthias Ringwald #endif
22296a45072S[email protected]     conn->acl_recombination_length = 0;
22396a45072S[email protected]     conn->acl_recombination_pos = 0;
224ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
225760b20efSMatthias Ringwald 
226da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
227b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
228b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
229b90f6e0aSMatthias Ringwald #endif
2300f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2310f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
2320f3b27c5SMatthias Ringwald #endif
233665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
23496a45072S[email protected]     return conn;
23596a45072S[email protected] }
23666fb9560S[email protected] 
237da886c03S[email protected] 
238da886c03S[email protected] /**
239da886c03S[email protected]  * get le connection parameter range
240da886c03S[email protected] *
241da886c03S[email protected]  * @return le connection parameter range struct
242da886c03S[email protected]  */
2434ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
2444ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
245da886c03S[email protected] }
246da886c03S[email protected] 
247da886c03S[email protected] /**
248da886c03S[email protected]  * set le connection parameter range
249da886c03S[email protected]  *
250da886c03S[email protected]  */
251da886c03S[email protected] 
2524ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
2534ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
254da886c03S[email protected] }
255da886c03S[email protected] 
256da886c03S[email protected] /**
25773cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
25873cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
25973cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
26073cd8a2aSMatthias Ringwald  * @param conn_latency
26173cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
26273cd8a2aSMatthias Ringwald  * @returns 1 if included
26373cd8a2aSMatthias Ringwald  */
26473cd8a2aSMatthias 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){
26573cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
26673cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
26773cd8a2aSMatthias Ringwald 
26873cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
26973cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
27073cd8a2aSMatthias Ringwald 
27173cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
27273cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
27373cd8a2aSMatthias Ringwald 
27473cd8a2aSMatthias Ringwald     return 1;
27573cd8a2aSMatthias Ringwald }
27673cd8a2aSMatthias Ringwald 
27773cd8a2aSMatthias Ringwald /**
2782b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
2792b6ab3e6SMatthias Ringwald  * @note: default: 1
2802b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
2812b6ab3e6SMatthias Ringwald  */
282d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2832b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
2842b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
2852b6ab3e6SMatthias Ringwald }
286d4e4907bSMatthias Ringwald #endif
2872b6ab3e6SMatthias Ringwald 
2882b6ab3e6SMatthias Ringwald /**
289da886c03S[email protected]  * get hci connections iterator
290da886c03S[email protected]  *
291da886c03S[email protected]  * @return hci connections iterator
292da886c03S[email protected]  */
293da886c03S[email protected] 
294665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
295665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
296da886c03S[email protected] }
297da886c03S[email protected] 
29897addcc5Smatthias.ringwald /**
299ee091cf1Smatthias.ringwald  * get connection for a given handle
300ee091cf1Smatthias.ringwald  *
301ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
302ee091cf1Smatthias.ringwald  */
3035061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
304665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
305665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
306665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
307665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
3083ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
309da886c03S[email protected]             return item;
310ee091cf1Smatthias.ringwald         }
311ee091cf1Smatthias.ringwald     }
312ee091cf1Smatthias.ringwald     return NULL;
313ee091cf1Smatthias.ringwald }
314ee091cf1Smatthias.ringwald 
31596a45072S[email protected] /**
31696a45072S[email protected]  * get connection for given address
31796a45072S[email protected]  *
31896a45072S[email protected]  * @return connection OR NULL, if not found
31996a45072S[email protected]  */
320667ba9d1SMatthias Ringwald hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t  addr, bd_addr_type_t addr_type){
321665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
322665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
323665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
324665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
32596a45072S[email protected]         if (connection->address_type != addr_type)  continue;
32696a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
32762bda3fbS[email protected]         return connection;
32862bda3fbS[email protected]     }
32962bda3fbS[email protected]     return NULL;
33062bda3fbS[email protected] }
33162bda3fbS[email protected] 
3323e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
3333e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
3343e5e0926SMatthias Ringwald }
33552db98b2SMatthias Ringwald 
336228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
337228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
338228e430cSMatthias Ringwald }
339228e430cSMatthias Ringwald 
34052db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
34152db98b2SMatthias Ringwald 
342ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
343ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
344ee752bb8SMatthias Ringwald     int connections = 0;
345ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
346ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
347ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
348ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
349ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
350ee752bb8SMatthias Ringwald         connections++;
351ee752bb8SMatthias Ringwald     }
352ee752bb8SMatthias Ringwald     return connections;
353ee752bb8SMatthias Ringwald }
354ee752bb8SMatthias Ringwald #endif
355ee752bb8SMatthias Ringwald 
356ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
35791a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
358aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
359528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
360c785ef68Smatthias.ringwald         // connections might be timed out
361c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
362c785ef68Smatthias.ringwald     }
363f316a845SMatthias Ringwald #else
364c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
3655f26aadcSMatthias Ringwald         // connections might be timed out
3665f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
3675f26aadcSMatthias Ringwald     }
3685f26aadcSMatthias Ringwald #endif
369c785ef68Smatthias.ringwald }
370ee091cf1Smatthias.ringwald 
371ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
372aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
373528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
374f316a845SMatthias Ringwald #else
375528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
3765f26aadcSMatthias Ringwald #endif
377ee091cf1Smatthias.ringwald }
378ee091cf1Smatthias.ringwald 
37943bfb1bdSmatthias.ringwald /**
38080ca58a0Smatthias.ringwald  * add authentication flags and reset timer
38196a45072S[email protected]  * @note: assumes classic connection
3822e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
3837fde4af9Smatthias.ringwald  */
3847fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
3857fde4af9Smatthias.ringwald     bd_addr_t addr;
386724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
387f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3887fde4af9Smatthias.ringwald     if (conn) {
38928ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
39080ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
3917fde4af9Smatthias.ringwald     }
3927fde4af9Smatthias.ringwald }
3937fde4af9Smatthias.ringwald 
3941714cbbdSMatthias Ringwald static bool hci_pairing_active(hci_connection_t * hci_connection){
3958daf94bcSMatthias Ringwald     return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0;
3961714cbbdSMatthias Ringwald }
3971714cbbdSMatthias Ringwald 
3981714cbbdSMatthias Ringwald static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){
3991714cbbdSMatthias Ringwald     if (hci_pairing_active(hci_connection)) return;
4001714cbbdSMatthias Ringwald     if (ssp){
4018daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE;
4021714cbbdSMatthias Ringwald     } else {
4038daf94bcSMatthias Ringwald         hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE;
4041714cbbdSMatthias Ringwald     }
4051714cbbdSMatthias Ringwald     // if we are initiator, we have sent an HCI Authenticate Request
4061714cbbdSMatthias Ringwald     bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0;
4071714cbbdSMatthias Ringwald 
4081714cbbdSMatthias Ringwald     log_info("pairing started, ssp %u, initiator %u", (int) ssp, (int) initiator);
40977208d90SMatthias Ringwald 
41077208d90SMatthias Ringwald     uint8_t event[12];
41177208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_STARTED;
41277208d90SMatthias Ringwald     event[1] = 10;
41377208d90SMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[2]);
41477208d90SMatthias Ringwald     little_endian_store_16(event, 8, (uint16_t) hci_connection->con_handle);
41577208d90SMatthias Ringwald     event[10] = (uint8_t) ssp;
41677208d90SMatthias Ringwald     event[11] = (uint8_t) initiator;
41777208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4181714cbbdSMatthias Ringwald }
4191714cbbdSMatthias Ringwald 
4201714cbbdSMatthias Ringwald static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){
4211714cbbdSMatthias Ringwald     if (!hci_pairing_active(hci_connection)) return;
4228daf94bcSMatthias Ringwald     hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK;
4231714cbbdSMatthias Ringwald     log_info("pairing complete, status %02x", status);
42477208d90SMatthias Ringwald 
42577208d90SMatthias Ringwald     uint8_t event[12];
42677208d90SMatthias Ringwald     event[0] = GAP_EVENT_PAIRING_COMPLETE;
42777208d90SMatthias Ringwald     event[1] = 9;
42877208d90SMatthias Ringwald     reverse_bd_addr(hci_connection->address, &event[2]);
42977208d90SMatthias Ringwald     little_endian_store_16(event, 8, (uint16_t) hci_connection->con_handle);
43077208d90SMatthias Ringwald     event[10] = status;
43177208d90SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4321714cbbdSMatthias Ringwald }
4331714cbbdSMatthias Ringwald 
43480ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
4355061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
43680ca58a0Smatthias.ringwald     if (!conn) return 0;
4371714cbbdSMatthias Ringwald     return (int) hci_pairing_active(conn);
43880ca58a0Smatthias.ringwald }
43980ca58a0Smatthias.ringwald 
44015a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
44155597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
4422bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
443a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
444c12e46e7Smatthias.ringwald }
44555597469SMatthias Ringwald 
44655597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
44755597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
4482bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
44955597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
450c12e46e7Smatthias.ringwald }
4511b6fb31bSMatthias Ringwald 
452e8ad470fSMatthias Ringwald bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){
453e8ad470fSMatthias Ringwald 	if (!hci_stack->link_key_db) return false;
45476b0318eSMatthias Ringwald 	int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0;
45576b0318eSMatthias Ringwald 	log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type);
45676b0318eSMatthias Ringwald 	return result;
457e8ad470fSMatthias Ringwald }
458e8ad470fSMatthias Ringwald 
459ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
460ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
461ceecb9d9SMatthias Ringwald     link_key_t link_key;
462ceecb9d9SMatthias Ringwald     link_key_type_t type;
463ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
464ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
465ceecb9d9SMatthias Ringwald     if (!ok) {
466ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
467ceecb9d9SMatthias Ringwald         return;
468ceecb9d9SMatthias Ringwald     }
469ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
470ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
471ceecb9d9SMatthias Ringwald     }
472ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
473ceecb9d9SMatthias Ringwald }
474ceecb9d9SMatthias Ringwald 
4751b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
4761b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4771b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
4781b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
4791b6fb31bSMatthias Ringwald }
4801b6fb31bSMatthias 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){
4811b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4821b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
4831b6fb31bSMatthias Ringwald }
4841b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
4851b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
4861b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
4871b6fb31bSMatthias Ringwald }
48835454696SMatthias Ringwald #endif
489c12e46e7Smatthias.ringwald 
490eb8076ddSMatthias Ringwald static bool hci_is_le_connection_type(bd_addr_type_t address_type){
491eb8076ddSMatthias Ringwald     switch (address_type){
492ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
493ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
494ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
495ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
496eb8076ddSMatthias Ringwald             return true;
497ce41473eSMatthias Ringwald         default:
498eb8076ddSMatthias Ringwald             return false;
499ce41473eSMatthias Ringwald     }
5000bf6344aS[email protected] }
5010bf6344aS[email protected] 
502eb8076ddSMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
503eb8076ddSMatthias Ringwald     return hci_is_le_connection_type(connection->address_type);
504eb8076ddSMatthias Ringwald }
505eb8076ddSMatthias Ringwald 
5067fde4af9Smatthias.ringwald /**
50743bfb1bdSmatthias.ringwald  * count connections
50843bfb1bdSmatthias.ringwald  */
50940d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
51056c253c9Smatthias.ringwald     int count = 0;
511665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
512a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
51315a27967SMatthias Ringwald         count++;
51415a27967SMatthias Ringwald     }
51543bfb1bdSmatthias.ringwald     return count;
51643bfb1bdSmatthias.ringwald }
517c8e4258aSmatthias.ringwald 
51895d71764SMatthias Ringwald static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
519ee303eddS[email protected] 
520f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
521f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
522ee303eddS[email protected] 
523665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
524a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
525998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
526ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
527ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
528ce41473eSMatthias Ringwald         }
529f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
530ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
531ee303eddS[email protected]         }
532ee303eddS[email protected]     }
533d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
534ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
535ee303eddS[email protected]     int free_slots_le = 0;
536ee303eddS[email protected] 
537ee303eddS[email protected]     if (free_slots_classic < 0){
5389da54300S[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);
539998906cdSmatthias.ringwald         return 0;
540998906cdSmatthias.ringwald     }
541ee303eddS[email protected] 
542ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
543ee303eddS[email protected]         // if we have LE slots, they are used
544ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
545ee303eddS[email protected]         if (free_slots_le < 0){
5469da54300S[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);
547ee303eddS[email protected]             return 0;
548998906cdSmatthias.ringwald         }
549ee303eddS[email protected]     } else {
550ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
551ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
552ee303eddS[email protected]         if (free_slots_classic < 0){
5539da54300S[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);
554ee303eddS[email protected]             return 0;
555ee303eddS[email protected]         }
556ee303eddS[email protected]     }
557ee303eddS[email protected] 
558ee303eddS[email protected]     switch (address_type){
559ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
5602125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
561ee303eddS[email protected]             return 0;
562ee303eddS[email protected] 
563f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
564ee303eddS[email protected]             return free_slots_classic;
565ee303eddS[email protected] 
566ee303eddS[email protected]         default:
567cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
568ee303eddS[email protected]                return free_slots_le;
569ee303eddS[email protected]            }
570cb00d3aaS[email protected]            return free_slots_classic;
571cb00d3aaS[email protected]     }
572998906cdSmatthias.ringwald }
573998906cdSmatthias.ringwald 
5742125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
5752125de09SMatthias Ringwald     // get connection type
5762125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5772125de09SMatthias Ringwald     if (!connection){
5782125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
5792125de09SMatthias Ringwald         return 0;
5802125de09SMatthias Ringwald     }
5812125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
5822125de09SMatthias Ringwald }
5832125de09SMatthias Ringwald 
58435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
585701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
586f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
587665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
588760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
589760b20efSMatthias Ringwald         // explicit flow control
590665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
591e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
592ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
593ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
594e35edcc1S[email protected]         }
595e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
596701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
59744d0e3d5S[email protected]             return 0;
59844d0e3d5S[email protected]         }
599e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
60049205f5dSMatthias Ringwald     } else {
60149205f5dSMatthias Ringwald         // implicit flow control -- TODO
6026f28d2eeSMatthias Ringwald         int num_ready = 0;
6036f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
6046f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
6056f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
6066f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
6076f28d2eeSMatthias Ringwald             num_ready++;
60849205f5dSMatthias Ringwald         }
6096f28d2eeSMatthias Ringwald         return num_ready;
6106f28d2eeSMatthias Ringwald     }
611e35edcc1S[email protected] }
61235454696SMatthias Ringwald #endif
61344d0e3d5S[email protected] 
6142b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
6152b838201SMatthias Ringwald static int hci_can_send_comand_packet_transport(void){
616ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
617ac928cc2S[email protected] 
618ac928cc2S[email protected]     // check for async hci transport implementations
619ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
620ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
621ac928cc2S[email protected]             return 0;
622ac928cc2S[email protected]         }
623ac928cc2S[email protected]     }
6242b838201SMatthias Ringwald     return 1;
6252b838201SMatthias Ringwald }
626ac928cc2S[email protected] 
6272b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
6282b838201SMatthias Ringwald int hci_can_send_command_packet_now(void){
6292b838201SMatthias Ringwald     if (hci_can_send_comand_packet_transport() == 0) return 0;
6304ea43905SMatthias Ringwald     return hci_stack->num_cmd_packets > 0u;
631ac928cc2S[email protected] }
632ac928cc2S[email protected] 
6339d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
634ac928cc2S[email protected]     // check for async hci transport implementations
6359d04d3a7SMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
6369d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
637ac928cc2S[email protected] }
6389d04d3a7SMatthias Ringwald 
6399d04d3a7SMatthias Ringwald static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
6409d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
6419d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
642ac928cc2S[email protected] }
6439d04d3a7SMatthias Ringwald 
6449d04d3a7SMatthias Ringwald int hci_can_send_acl_le_packet_now(void){
6459d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
6469d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
6479d04d3a7SMatthias Ringwald }
6489d04d3a7SMatthias Ringwald 
6499d04d3a7SMatthias Ringwald int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
6509d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
651e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
652ac928cc2S[email protected] }
653ac928cc2S[email protected] 
654ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
655ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
656ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
6576b4af23dS[email protected] }
6586b4af23dS[email protected] 
65935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
66035454696SMatthias Ringwald int hci_can_send_acl_classic_packet_now(void){
66135454696SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
662f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
66335454696SMatthias Ringwald }
66435454696SMatthias Ringwald 
665701e3307SMatthias Ringwald int hci_can_send_prepared_sco_packet_now(void){
666d057580eSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
667f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
668f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
669f234b250SMatthias Ringwald     } else {
670701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
67144d0e3d5S[email protected]     }
672f234b250SMatthias Ringwald }
67344d0e3d5S[email protected] 
674701e3307SMatthias Ringwald int hci_can_send_sco_packet_now(void){
675d057580eSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
676701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
67744d0e3d5S[email protected] }
67844d0e3d5S[email protected] 
679d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
680d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
681d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
682d057580eSMatthias Ringwald }
68335454696SMatthias Ringwald #endif
684d057580eSMatthias Ringwald 
68595d71764SMatthias Ringwald // used for internal checks in l2cap.c
686c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
687c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
688c8b9416aS[email protected] }
689c8b9416aS[email protected] 
6906b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
6916b4af23dS[email protected] int hci_reserve_packet_buffer(void){
6929d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
6939d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
6949d14b626S[email protected]         return 0;
6959d14b626S[email protected]     }
6966b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
6976b4af23dS[email protected]     return 1;
6986b4af23dS[email protected] }
6996b4af23dS[email protected] 
70068a0fcf7S[email protected] void hci_release_packet_buffer(void){
70168a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
70268a0fcf7S[email protected] }
70368a0fcf7S[email protected] 
7046b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
7057f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
7066b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
7076b4af23dS[email protected] }
7086b4af23dS[email protected] 
709452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
710452cf3bbS[email protected] 
711452cf3bbS[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);
712452cf3bbS[email protected] 
713452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
714452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
7154ea43905SMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){
716452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
717452cf3bbS[email protected]     }
718452cf3bbS[email protected] 
7190f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
720fcf88f47SMatthias Ringwald     if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){
7210f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
7220f3b27c5SMatthias Ringwald     }
7230f3b27c5SMatthias Ringwald #endif
724452cf3bbS[email protected] 
725d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
726d999b54eSMatthias Ringwald 
727452cf3bbS[email protected]     int err;
728452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
729ff3cc4a5SMatthias Ringwald     while (true){
730452cf3bbS[email protected] 
731d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
732d999b54eSMatthias Ringwald 
733452cf3bbS[email protected]         // get current data
7344ea43905SMatthias Ringwald         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u;
735452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
7361979f09cSMatthias Ringwald         bool more_fragments = false;
737452cf3bbS[email protected] 
738452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
739452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
7401979f09cSMatthias Ringwald             more_fragments = true;
741452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
742452cf3bbS[email protected]         }
743452cf3bbS[email protected] 
744452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
7454ea43905SMatthias Ringwald         if (acl_header_pos > 0u){
746f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
7474ea43905SMatthias Ringwald             handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u);
748f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
749452cf3bbS[email protected]         }
750452cf3bbS[email protected] 
751452cf3bbS[email protected]         // update header len
7524ea43905SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length);
753452cf3bbS[email protected] 
754452cf3bbS[email protected]         // count packet
755ce41473eSMatthias Ringwald         connection->num_packets_sent++;
7561979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments);
757d999b54eSMatthias Ringwald 
758d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
759d999b54eSMatthias Ringwald         if (more_fragments){
760d999b54eSMatthias Ringwald             // update start of next fragment to send
761d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
762d999b54eSMatthias Ringwald         } else {
763d999b54eSMatthias Ringwald             // done
764d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
765d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
766d999b54eSMatthias Ringwald         }
767452cf3bbS[email protected] 
768452cf3bbS[email protected]         // send packet
769452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
770452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
7715bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
77281d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
773452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
774452cf3bbS[email protected] 
7751979f09cSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments);
776d999b54eSMatthias Ringwald 
777452cf3bbS[email protected]         // done yet?
778452cf3bbS[email protected]         if (!more_fragments) break;
779452cf3bbS[email protected] 
780452cf3bbS[email protected]         // can send more?
781452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
782452cf3bbS[email protected]     }
783452cf3bbS[email protected] 
784d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
785452cf3bbS[email protected] 
786d051460cS[email protected]     // release buffer now for synchronous transport
787203bace6S[email protected]     if (hci_transport_synchronous()){
78881d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
789452cf3bbS[email protected]         hci_release_packet_buffer();
790fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
791452cf3bbS[email protected]     }
792452cf3bbS[email protected] 
793452cf3bbS[email protected]     return err;
794452cf3bbS[email protected] }
795452cf3bbS[email protected] 
796826f7347S[email protected] // pre: caller has reserved the packet buffer
797826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
7987856c818Smatthias.ringwald 
799452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
800452cf3bbS[email protected] 
801826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
802826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
803826f7347S[email protected]         return 0;
804826f7347S[email protected]     }
805826f7347S[email protected] 
806d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
807d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
808d713a683S[email protected] 
809826f7347S[email protected]     // check for free places on Bluetooth module
810d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
811826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
81297b61c7bS[email protected]         hci_release_packet_buffer();
813068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
81497b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
81597b61c7bS[email protected]     }
8166218e6f1Smatthias.ringwald 
8175061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
81897b61c7bS[email protected]     if (!connection) {
8195fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
82097b61c7bS[email protected]         hci_release_packet_buffer();
821068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
82297b61c7bS[email protected]         return 0;
82397b61c7bS[email protected]     }
82452db98b2SMatthias Ringwald 
82552db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
82656cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
82752db98b2SMatthias Ringwald #endif
82856cf178bSmatthias.ringwald 
829452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
8307856c818Smatthias.ringwald 
831452cf3bbS[email protected]     // setup data
832452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
833452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
8346218e6f1Smatthias.ringwald 
835452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
836ee091cf1Smatthias.ringwald }
837ee091cf1Smatthias.ringwald 
83835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
83944d0e3d5S[email protected] // pre: caller has reserved the packet buffer
84044d0e3d5S[email protected] int hci_send_sco_packet_buffer(int size){
84144d0e3d5S[email protected] 
84244d0e3d5S[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
84344d0e3d5S[email protected] 
84444d0e3d5S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
84544d0e3d5S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
84644d0e3d5S[email protected]         return 0;
84744d0e3d5S[email protected]     }
84844d0e3d5S[email protected] 
84944d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
8504b3e1e19SMatthias Ringwald 
8514b3e1e19SMatthias Ringwald     // skip checks in loopback mode
8524b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
85344d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
85444d0e3d5S[email protected] 
85544d0e3d5S[email protected]         // check for free places on Bluetooth module
856701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
857cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
85844d0e3d5S[email protected]             hci_release_packet_buffer();
859068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
86044d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
86144d0e3d5S[email protected]         }
86244d0e3d5S[email protected] 
863e35edcc1S[email protected]         // track send packet in connection struct
864e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
865e35edcc1S[email protected]         if (!connection) {
866e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
867e35edcc1S[email protected]             hci_release_packet_buffer();
868068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
869e35edcc1S[email protected]             return 0;
870e35edcc1S[email protected]         }
871f234b250SMatthias Ringwald 
872f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
873f234b250SMatthias Ringwald             // token used
874f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 0;
875f234b250SMatthias Ringwald         } else {
876760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
877ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
8786f28d2eeSMatthias Ringwald             } else {
879e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
880760b20efSMatthias Ringwald             }
8814b3e1e19SMatthias Ringwald         }
882f234b250SMatthias Ringwald     }
88344d0e3d5S[email protected] 
88444d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
885543e835cSMatthias Ringwald 
88643149fc9SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
88743149fc9SMatthias Ringwald     hci_stack->sco_transport->send_packet(packet, size);
88843149fc9SMatthias Ringwald     hci_release_packet_buffer();
88943149fc9SMatthias Ringwald     hci_emit_transport_packet_sent();
89043149fc9SMatthias Ringwald 
89143149fc9SMatthias Ringwald     return 0;
89243149fc9SMatthias Ringwald #else
89343149fc9SMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
894543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
895543e835cSMatthias Ringwald         hci_release_packet_buffer();
896fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
897543e835cSMatthias Ringwald     }
898543e835cSMatthias Ringwald 
899543e835cSMatthias Ringwald     return err;
90043149fc9SMatthias Ringwald #endif
90144d0e3d5S[email protected] }
90235454696SMatthias Ringwald #endif
90344d0e3d5S[email protected] 
904c3b46f5aSMatthias Ringwald static void acl_handler(uint8_t *packet, uint16_t size){
905e76a89eeS[email protected] 
9067856c818Smatthias.ringwald     // get info
9077856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
9085061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
9097856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
9107856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
9117856c818Smatthias.ringwald 
9127856c818Smatthias.ringwald     // ignore non-registered handle
9137856c818Smatthias.ringwald     if (!conn){
914c3b46f5aSMatthias Ringwald         log_error("acl_handler called with non-registered handle %u!" , con_handle);
9157856c818Smatthias.ringwald         return;
9167856c818Smatthias.ringwald     }
9177856c818Smatthias.ringwald 
918e76a89eeS[email protected]     // assert packet is complete
9194ea43905SMatthias Ringwald     if ((acl_length + 4u) != size){
920c3b46f5aSMatthias Ringwald         log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
921e76a89eeS[email protected]         return;
922e76a89eeS[email protected]     }
923e76a89eeS[email protected] 
92452db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
9257856c818Smatthias.ringwald     // update idle timestamp
9267856c818Smatthias.ringwald     hci_connection_timestamp(conn);
92752db98b2SMatthias Ringwald #endif
9287856c818Smatthias.ringwald 
9292b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
9302b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
9312b838201SMatthias Ringwald     conn->num_packets_completed++;
9322b838201SMatthias Ringwald #endif
9332b838201SMatthias Ringwald 
9347856c818Smatthias.ringwald     // handle different packet types
9354ea43905SMatthias Ringwald     switch (acl_flags & 0x03u) {
9367856c818Smatthias.ringwald 
9377856c818Smatthias.ringwald         case 0x01: // continuation fragment
9387856c818Smatthias.ringwald 
9390ca847afS[email protected]             // sanity checks
9404ea43905SMatthias Ringwald             if (conn->acl_recombination_pos == 0u) {
9419da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
9427856c818Smatthias.ringwald                 return;
9437856c818Smatthias.ringwald             }
9444ea43905SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){
9450ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
9460ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
9470ca847afS[email protected]                 conn->acl_recombination_pos = 0;
9480ca847afS[email protected]                 return;
9490ca847afS[email protected]             }
9507856c818Smatthias.ringwald 
9517856c818Smatthias.ringwald             // append fragment payload (header already stored)
9526535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
9536535961aSMatthias Ringwald                          &packet[4], acl_length);
9547856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
9557856c818Smatthias.ringwald 
9567856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
9574ea43905SMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header
958d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
9597856c818Smatthias.ringwald                 // reset recombination buffer
9607856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
9617856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
9627856c818Smatthias.ringwald             }
9637856c818Smatthias.ringwald             break;
9647856c818Smatthias.ringwald 
9657856c818Smatthias.ringwald         case 0x02: { // first fragment
9667856c818Smatthias.ringwald 
96723a77e1aS[email protected]             // sanity check
96823a77e1aS[email protected]             if (conn->acl_recombination_pos) {
96923a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
97023a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
97123a77e1aS[email protected]             }
97223a77e1aS[email protected] 
9737856c818Smatthias.ringwald             // peek into L2CAP packet!
9747856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
9757856c818Smatthias.ringwald 
9767856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
9774ea43905SMatthias Ringwald             if (acl_length >= (l2cap_length + 4u)){
9787856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
9794ea43905SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4u);
9807856c818Smatthias.ringwald             } else {
9810ca847afS[email protected] 
9820ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
9830ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
9840ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
9850ca847afS[email protected]                     return;
9860ca847afS[email protected]                 }
9870ca847afS[email protected] 
9887856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
9896535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
9904ea43905SMatthias Ringwald                              packet, acl_length + 4u);
9914ea43905SMatthias Ringwald                 conn->acl_recombination_pos    = acl_length + 4u;
9927856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
9934ea43905SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u);
9947856c818Smatthias.ringwald             }
9957856c818Smatthias.ringwald             break;
9967856c818Smatthias.ringwald 
9977856c818Smatthias.ringwald         }
9987856c818Smatthias.ringwald         default:
999c3b46f5aSMatthias Ringwald             log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
10007856c818Smatthias.ringwald             return;
10017856c818Smatthias.ringwald     }
100294ab26f8Smatthias.ringwald 
100394ab26f8Smatthias.ringwald     // execute main loop
100494ab26f8Smatthias.ringwald     hci_run();
100516833f0aSmatthias.ringwald }
100622909952Smatthias.ringwald 
100767a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
10089da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
10093c4d4b90Smatthias.ringwald 
1010b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1011cb70c5abSMatthias Ringwald #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT)
1012cb70c5abSMatthias Ringwald     bd_addr_type_t addr_type = conn->address_type;
1013cb70c5abSMatthias Ringwald #endif
1014cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1015cb70c5abSMatthias Ringwald     hci_con_handle_t con_handle = conn->con_handle;
1016ee752bb8SMatthias Ringwald #endif
1017b3264428SMatthias Ringwald #endif
1018ee752bb8SMatthias Ringwald 
1019528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
1020c785ef68Smatthias.ringwald 
1021665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1022a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
10233c4d4b90Smatthias.ringwald 
10243c4d4b90Smatthias.ringwald     // now it's gone
1025c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
1026ee752bb8SMatthias Ringwald 
1027b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
1028034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1029ee752bb8SMatthias Ringwald     // update SCO
1030cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){
1031ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1032ee752bb8SMatthias Ringwald     }
1033034e9b53SMatthias Ringwald #endif
1034cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
1035cb70c5abSMatthias Ringwald     if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){
1036cb70c5abSMatthias Ringwald         hci_stack->sco_transport->close(con_handle);
1037cb70c5abSMatthias Ringwald     }
1038cb70c5abSMatthias Ringwald #endif
1039b3264428SMatthias Ringwald #endif
1040c7e0c5f6Smatthias.ringwald }
1041c7e0c5f6Smatthias.ringwald 
104235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
104335454696SMatthias Ringwald 
10440c042179S[email protected] static const uint16_t packet_type_sizes[] = {
10458f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
10468f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
10478f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
10488f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
10498f8108aaSmatthias.ringwald };
105065389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
105165389bfcS[email protected]      0, // 3 slot packets
105265389bfcS[email protected]      1, // 5 slot packets
105365389bfcS[email protected]     25, // EDR 2 mpbs
105465389bfcS[email protected]     26, // EDR 3 mbps
105565389bfcS[email protected]     39, // 3 slot EDR packts
105665389bfcS[email protected]     40, // 5 slot EDR packet
105765389bfcS[email protected] };
105865389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
105965389bfcS[email protected]     0x0f00, // 3 slot packets
106065389bfcS[email protected]     0xf000, // 5 slot packets
106165389bfcS[email protected]     0x1102, // EDR 2 mpbs
106265389bfcS[email protected]     0x2204, // EDR 3 mbps
106365389bfcS[email protected]     0x0300, // 3 slot EDR packts
106465389bfcS[email protected]     0x3000, // 5 slot EDR packet
106565389bfcS[email protected] };
10668f8108aaSmatthias.ringwald 
106765389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
106865389bfcS[email protected]     // enable packet types based on size
10698f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
1070f16a69bbS[email protected]     unsigned int i;
10718f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
10728f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
10738f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
10748f8108aaSmatthias.ringwald             packet_types |= 1 << i;
10758f8108aaSmatthias.ringwald         }
10768f8108aaSmatthias.ringwald     }
107765389bfcS[email protected]     // disable packet types due to missing local supported features
107865389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1079f04a0c31SMatthias Ringwald         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
108065389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
108165389bfcS[email protected]         if (feature_set) continue;
108265389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
108365389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
108465389bfcS[email protected]     }
10858f8108aaSmatthias.ringwald     // flip bits for "may not be used"
10868f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
10878f8108aaSmatthias.ringwald     return packet_types;
10888f8108aaSmatthias.ringwald }
10898f8108aaSmatthias.ringwald 
10908f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
10913a9fb326S[email protected]     return hci_stack->packet_types;
10928f8108aaSmatthias.ringwald }
109335454696SMatthias Ringwald #endif
10948f8108aaSmatthias.ringwald 
1095facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
10967dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
10973a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
10987dc17943Smatthias.ringwald }
10997dc17943Smatthias.ringwald 
1100f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
11013a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
11027dc17943Smatthias.ringwald }
11037dc17943Smatthias.ringwald 
110406b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
11053e68d23dSMatthias Ringwald int hci_extended_sco_link_supported(void){
11063e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
11073e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
11083e68d23dSMatthias Ringwald }
110906b9e820SMatthias Ringwald #endif
11103e68d23dSMatthias Ringwald 
11116ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
11126ac9a97eS[email protected]     // No. 54, byte 6, bit 6
11134ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u;
11146ac9a97eS[email protected] }
11156ac9a97eS[email protected] 
111615a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
11176ac9a97eS[email protected]     // No. 51, byte 6, bit 3
11184ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u;
1119f5d8d141S[email protected] }
1120f5d8d141S[email protected] 
11217f02f414SMatthias Ringwald static int hci_classic_supported(void){
112235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
11236ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
11243a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
112535454696SMatthias Ringwald #else
112635454696SMatthias Ringwald     return 0;
112735454696SMatthias Ringwald #endif
1128f5d8d141S[email protected] }
1129f5d8d141S[email protected] 
11307f02f414SMatthias Ringwald static int hci_le_supported(void){
1131a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
11326ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
11334ea43905SMatthias Ringwald     return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u;
1134f5d8d141S[email protected] #else
1135f5d8d141S[email protected]     return 0;
1136f5d8d141S[email protected] #endif
1137f5d8d141S[email protected] }
1138f5d8d141S[email protected] 
1139b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1140b95a5a35SMatthias Ringwald 
1141f5873674SMatthias Ringwald static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){
11426bcfa632SMatthias Ringwald     if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
11436bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->local_bd_addr, 6);
114469a97523S[email protected]     } else {
11456bcfa632SMatthias Ringwald         (void)memcpy(own_addr, hci_stack->le_random_address, 6);
114669a97523S[email protected]     }
114769a97523S[email protected] }
114869a97523S[email protected] 
11496bcfa632SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
11506bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
11516bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr);
11526bcfa632SMatthias Ringwald }
11536bcfa632SMatthias Ringwald 
11546bcfa632SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
11556bcfa632SMatthias Ringwald void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){
11566bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_advertisements_own_addr_type;
11576bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr);
11586bcfa632SMatthias Ringwald };
11596bcfa632SMatthias Ringwald #endif
11606bcfa632SMatthias Ringwald 
1161e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
11626bcfa632SMatthias Ringwald 
11636bcfa632SMatthias Ringwald /**
11646bcfa632SMatthias Ringwald  * @brief Get own addr type and address used for LE connections (Central)
11656bcfa632SMatthias Ringwald  */
11666bcfa632SMatthias Ringwald void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){
11676bcfa632SMatthias Ringwald     *addr_type = hci_stack->le_connection_own_addr_type;
11686bcfa632SMatthias Ringwald     hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr);
11696bcfa632SMatthias Ringwald }
11706bcfa632SMatthias Ringwald 
1171384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
11729ec2630cSMatthias Ringwald 
1173d1dc057bS[email protected]     int offset = 3;
1174d1dc057bS[email protected]     int num_reports = packet[offset];
1175d1dc057bS[email protected]     offset += 1;
1176d1dc057bS[email protected] 
117757c9da5bS[email protected]     int i;
11784f4e0224SMatthias Ringwald     // log_info("HCI: handle adv report with num reports: %d", num_reports);
117903fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1180a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
118133e6948bSMatthias Ringwald         // sanity checks on data_length:
118233e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
118333e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
11844ea43905SMatthias Ringwald         if ((offset + 9u + data_length + 1u) > size)    return;
118533e6948bSMatthias Ringwald         // setup event
11864ea43905SMatthias Ringwald         uint8_t event_size = 10u + data_length;
1187d1dc057bS[email protected]         int pos = 0;
1188045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
118957c9da5bS[email protected]         event[pos++] = event_size;
11906535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1191d1dc057bS[email protected]         offset += 8;
1192d1dc057bS[email protected]         pos += 8;
1193d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
119433e6948bSMatthias Ringwald         event[pos++] = data_length;
119533e6948bSMatthias Ringwald         offset++;
11966535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
119757c9da5bS[email protected]         pos +=    data_length;
11984ea43905SMatthias Ringwald         offset += data_length + 1u; // rssi
1199d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
120057c9da5bS[email protected]     }
120157c9da5bS[email protected] }
1202b2f949feS[email protected] #endif
1203e8c8828eSMatthias Ringwald #endif
120457c9da5bS[email protected] 
12052b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
12062b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1207bbc366e6SMatthias Ringwald static void hci_update_advertisements_enabled_for_current_roles(void){
1208bbc366e6SMatthias Ringwald     if (hci_stack->le_advertisements_enabled){
12092b6ab3e6SMatthias Ringwald         // get number of active le slave connections
12102b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
12112b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
12122b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
12132b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
12142b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
12152b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
12162b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
12172b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
12182b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
12192b6ab3e6SMatthias Ringwald             num_slave_connections++;
12202b6ab3e6SMatthias Ringwald         }
12212b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1222bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections;
1223bbc366e6SMatthias Ringwald     } else {
1224bbc366e6SMatthias Ringwald         hci_stack->le_advertisements_enabled_for_current_roles = false;
12252b6ab3e6SMatthias Ringwald     }
12262b6ab3e6SMatthias Ringwald }
12272b6ab3e6SMatthias Ringwald #endif
12282b6ab3e6SMatthias Ringwald #endif
12292b6ab3e6SMatthias Ringwald 
1230cd77dd38SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
123106b9e820SMatthias Ringwald 
123296b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
123396b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
12349796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
123596b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
1236a1df452eSMatthias Ringwald     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
123796b53536SMatthias Ringwald         baud_rate = 3000000;
123896b53536SMatthias Ringwald     }
123996b53536SMatthias Ringwald     return baud_rate;
124096b53536SMatthias Ringwald }
124196b53536SMatthias Ringwald 
1242ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
12439ec2630cSMatthias Ringwald     UNUSED(ds);
12449ec2630cSMatthias Ringwald 
12450305bdeaSMatthias Ringwald     switch (hci_stack->substate){
12460305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
12477b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
12480305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
12497b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
12500305bdeaSMatthias Ringwald             hci_run();
12510305bdeaSMatthias Ringwald             break;
12529f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
12539f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
12549f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
12559f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
12569f007422SMatthias Ringwald             }
1257cf373d3aSMatthias Ringwald 
1258cf373d3aSMatthias Ringwald             /* fall through */
1259cf373d3aSMatthias Ringwald 
1260e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1261e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1262e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1263e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1264e47e68c7SMatthias Ringwald             hci_run();
1265688c2635SMatthias Ringwald             break;
12667224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
12677224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
126896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1269cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate);
12707dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
12717224be7eSMatthias Ringwald             }
1272834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
127361f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1274834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1275834bce8cSMatthias Ringwald                     log_info("Link Reset");
1276834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1277834bce8cSMatthias Ringwald                 }
1278772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1279772a36d3SMatthias Ringwald                 hci_run();
1280772a36d3SMatthias Ringwald             }
12814696bddbSMatthias Ringwald             break;
1282559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1283559961d0SMatthias Ringwald             // otherwise continue
1284559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1285559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1286559961d0SMatthias Ringwald             break;
12870305bdeaSMatthias Ringwald         default:
12880305bdeaSMatthias Ringwald             break;
12890305bdeaSMatthias Ringwald     }
12900305bdeaSMatthias Ringwald }
129106b9e820SMatthias Ringwald #endif
12920305bdeaSMatthias Ringwald 
129371de195eSMatthias Ringwald static void hci_initializing_next_state(void){
129474b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
129574b323a9SMatthias Ringwald }
129674b323a9SMatthias Ringwald 
129774b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
129871de195eSMatthias Ringwald static void hci_initializing_run(void){
1299148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
130074b323a9SMatthias Ringwald     switch (hci_stack->substate){
130174b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
130274b323a9SMatthias Ringwald             hci_state_reset();
1303a0cf2f3fSMatthias Ringwald 
130406b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
13050305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1306659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1307528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1308528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1309a0cf2f3fSMatthias Ringwald #endif
13100305bdeaSMatthias Ringwald             // send command
131174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
13120305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
131374b323a9SMatthias Ringwald             break;
131476fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
131576fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
131676fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
131776fcb19bSMatthias Ringwald             break;
1318e90bae01SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
1319e90bae01SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
1320e90bae01SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1321e90bae01SMatthias Ringwald             break;
132206b9e820SMatthias Ringwald 
132306b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1324e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1325e47e68c7SMatthias Ringwald             hci_state_reset();
1326e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1327659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1328528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1329528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1330e47e68c7SMatthias Ringwald             // send command
1331e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1332e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1333e47e68c7SMatthias Ringwald             break;
13348d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
13358d29070eSMatthias Ringwald             hci_state_reset();
13368d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
13378d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
13388d29070eSMatthias Ringwald             break;
1339fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE: {
134096b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
13413fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1342f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
134374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
13444ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
13454696bddbSMatthias Ringwald             // STLC25000D: baudrate change happens within 0.5 s after command was send,
13464696bddbSMatthias Ringwald             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
134761f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1348659d758cSMatthias Ringwald                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1349528a4a3bSMatthias Ringwald                 btstack_run_loop_add_timer(&hci_stack->timeout);
13504696bddbSMatthias Ringwald             }
135174b323a9SMatthias Ringwald             break;
1352fab26ab3SMatthias Ringwald         }
1353fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
135496b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
13553fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1356f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1357eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
13584ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
1359eb3a5314SMatthias Ringwald             break;
1360fab26ab3SMatthias Ringwald         }
136174b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
136274b323a9SMatthias Ringwald             // Custom initialization
13633fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1364ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
13651979f09cSMatthias Ringwald                 bool send_cmd = false;
1366ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1367f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
13681979f09cSMatthias Ringwald                         send_cmd = true;
1369e47e68c7SMatthias Ringwald                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1370e47e68c7SMatthias Ringwald                         break;
1371f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
13721979f09cSMatthias Ringwald                         send_cmd = true;
1373f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1374e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1375659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1376528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1377528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
1378a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1379772a36d3SMatthias Ringwald                             && hci_stack->config
13803fb36a29SMatthias Ringwald                             && hci_stack->chipset
13813fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1382772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
13832caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
1384772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1385772a36d3SMatthias Ringwald                         } else {
13869f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1387772a36d3SMatthias Ringwald                         }
1388e47e68c7SMatthias Ringwald                         break;
1389f41911edSMatthias Ringwald                     default:
1390f41911edSMatthias Ringwald                         break;
1391e47e68c7SMatthias Ringwald                 }
1392ee720f3aSMatthias Ringwald 
1393ee720f3aSMatthias Ringwald                 if (send_cmd){
13944ea43905SMatthias Ringwald                     int size = 3u + hci_stack->hci_packet_buffer[2u];
1395ee720f3aSMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1396ee720f3aSMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
13970305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
139874b323a9SMatthias Ringwald                     break;
139974b323a9SMatthias Ringwald                 }
1400148ca237SMatthias Ringwald                 log_info("Init script done");
140192a0d36dSMatthias Ringwald 
1402559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1403ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1404a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1405a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1406e021ff1eSMatthias Ringwald 
1407559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
140892a0d36dSMatthias Ringwald                     int need_baud_change = hci_stack->config
14093fb36a29SMatthias Ringwald                         && hci_stack->chipset
14103fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
141192a0d36dSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
14129796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
141392a0d36dSMatthias Ringwald                     if (need_baud_change) {
14149796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1415cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate);
141692a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
141792a0d36dSMatthias Ringwald                     }
1418559961d0SMatthias Ringwald 
1419f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
1420f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1421f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
1422f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1423559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1424f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1425559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1426559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
1427559961d0SMatthias Ringwald                     break;
142892a0d36dSMatthias Ringwald                 }
142974b323a9SMatthias Ringwald             }
143074b323a9SMatthias Ringwald             // otherwise continue
1431a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1432a828a756SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1433a828a756SMatthias Ringwald             break;
143453860077SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
143553860077SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
14363fb36a29SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1437f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
143853860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
14394ea43905SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]);
144053860077SMatthias Ringwald             break;
144106b9e820SMatthias Ringwald #endif
144206b9e820SMatthias Ringwald 
144306b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
144406b9e820SMatthias Ringwald             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
144506b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
144606b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
144706b9e820SMatthias Ringwald             break;
144853860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
144953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
145053860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
145153860077SMatthias Ringwald             break;
145274b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
145374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
14540305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_buffer_size);
145574b323a9SMatthias Ringwald             break;
145653860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
145753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
14580305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
145974b323a9SMatthias Ringwald             break;
14602b838201SMatthias Ringwald 
14612b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
14622b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
14632b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
14642b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
14652b838201SMatthias Ringwald             break;
14662b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
14672b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
14682b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
14692b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
14702b838201SMatthias Ringwald             break;
14712b838201SMatthias Ringwald #endif
14722b838201SMatthias Ringwald 
147374b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
14740305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
147574b323a9SMatthias Ringwald             if (hci_le_supported()){
14765ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU);
147774b323a9SMatthias Ringwald             } else {
147874b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
14795ce1359eSMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU);
148074b323a9SMatthias Ringwald             }
148174b323a9SMatthias Ringwald             break;
14822b838201SMatthias Ringwald 
148335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
148474b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
148574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
14860305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
148774b323a9SMatthias Ringwald             break;
148874b323a9SMatthias Ringwald         case HCI_INIT_WRITE_PAGE_TIMEOUT:
148974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
14900305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
149174b323a9SMatthias Ringwald             break;
1492c33e56d3SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1493c33e56d3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1494c33e56d3SMatthias Ringwald             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1495c33e56d3SMatthias Ringwald             break;
149674b323a9SMatthias Ringwald         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
149774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
14980305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
149974b323a9SMatthias Ringwald             break;
15001c2a62f5SMatthias Ringwald         case HCI_INIT_WRITE_LOCAL_NAME: {
15010305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
15021c2a62f5SMatthias Ringwald             hci_reserve_packet_buffer();
15031c2a62f5SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
15041c2a62f5SMatthias Ringwald             // construct HCI Command and send
15051c2a62f5SMatthias Ringwald             uint16_t opcode = hci_write_local_name.opcode;
15061c2a62f5SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
15071c2a62f5SMatthias Ringwald             packet[0] = opcode & 0xff;
15081c2a62f5SMatthias Ringwald             packet[1] = opcode >> 8;
15091c2a62f5SMatthias Ringwald             packet[2] = DEVICE_NAME_LEN;
15101c2a62f5SMatthias Ringwald             memset(&packet[3], 0, DEVICE_NAME_LEN);
151179186815SMatthias Ringwald             uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
151279186815SMatthias Ringwald             uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
151379186815SMatthias Ringwald             // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
151479186815SMatthias Ringwald             (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
15151c2a62f5SMatthias Ringwald             // expand '00:00:00:00:00:00' in name with bd_addr
15163c9da642SMatthias Ringwald             btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
15171c2a62f5SMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
151874b323a9SMatthias Ringwald             break;
15191c2a62f5SMatthias Ringwald         }
152029af07f3SMatthias Ringwald         case HCI_INIT_WRITE_EIR_DATA: {
15218a114470SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
152229af07f3SMatthias Ringwald             hci_reserve_packet_buffer();
152329af07f3SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
152463873210SMatthias Ringwald             // construct HCI Command in-place and send
152529af07f3SMatthias Ringwald             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
152629af07f3SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
152763873210SMatthias Ringwald             uint16_t offset = 0;
152863873210SMatthias Ringwald             packet[offset++] = opcode & 0xff;
152963873210SMatthias Ringwald             packet[offset++] = opcode >> 8;
153063873210SMatthias Ringwald             packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
153163873210SMatthias Ringwald             packet[offset++] = 0;  // FEC not required
153263873210SMatthias Ringwald             memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1533ad0d1108SMatthias Ringwald             if (hci_stack->eir_data){
153463873210SMatthias Ringwald                 // copy items and expand '00:00:00:00:00:00' in name with bd_addr
153563873210SMatthias Ringwald                 ad_context_t context;
153663873210SMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
153763873210SMatthias Ringwald                     uint8_t data_type   = ad_iterator_get_data_type(&context);
153863873210SMatthias Ringwald                     uint8_t size        = ad_iterator_get_data_len(&context);
153963873210SMatthias Ringwald                     const uint8_t *data = ad_iterator_get_data(&context);
154063873210SMatthias Ringwald                     // copy item
154163873210SMatthias Ringwald                     packet[offset++] = size + 1;
154263873210SMatthias Ringwald                     packet[offset++] = data_type;
154363873210SMatthias Ringwald                     memcpy(&packet[offset], data, size);
154463873210SMatthias Ringwald                     // update name item
154563873210SMatthias Ringwald                     if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
15463c9da642SMatthias Ringwald                         btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
154763873210SMatthias Ringwald                     }
154863873210SMatthias Ringwald                     offset += size;
154963873210SMatthias Ringwald                 }
1550ad0d1108SMatthias Ringwald             } else {
155179186815SMatthias Ringwald                 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
155279186815SMatthias Ringwald                 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
155363873210SMatthias Ringwald                 packet[offset++] = bytes_to_copy + 1;
155463873210SMatthias Ringwald                 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
155579186815SMatthias Ringwald                 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
155629af07f3SMatthias Ringwald                 // expand '00:00:00:00:00:00' in name with bd_addr
15573c9da642SMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
155863873210SMatthias Ringwald             }
1559a8c4e5adSMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1560ff00ed1cSMatthias Ringwald             break;
156129af07f3SMatthias Ringwald         }
1562f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
1563f6858d14SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
15648a114470SMatthias Ringwald             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1565f6858d14SMatthias Ringwald             break;
15665d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
15675d23aae8SMatthias Ringwald             hci_send_cmd(&hci_write_secure_connections_host_support, 1);
1568c214d65bSMatthias Ringwald 			hci_stack->secure_connections_active = true;
15695d23aae8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
15705d23aae8SMatthias Ringwald             break;
157174b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SCAN_ENABLE:
157274b323a9SMatthias Ringwald             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
157374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
157474b323a9SMatthias Ringwald             break;
1575483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
1576729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1577729ed62eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1578729ed62eSMatthias Ringwald             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1579729ed62eSMatthias Ringwald             break;
1580483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1581483c5078SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1582483c5078SMatthias Ringwald             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1583483c5078SMatthias Ringwald             break;
15848051253fSMatthias Ringwald         // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined
1585a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1586a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
15878051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1588a42798c3SMatthias Ringwald             log_info("BCM: Route SCO data via HCI transport");
1589a42798c3SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
15908051253fSMatthias Ringwald #endif
15918051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
15928051253fSMatthias Ringwald             log_info("BCM: Route SCO data via PCM interface");
15931d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
15941d2bbd54SMatthias Ringwald             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
15951d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1);
15961d2bbd54SMatthias Ringwald #else
15971d2bbd54SMatthias Ringwald             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
15981d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1);
15991d2bbd54SMatthias Ringwald #endif
16008051253fSMatthias Ringwald #endif
1601a42798c3SMatthias Ringwald             break;
16024e821764SMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
16034e821764SMatthias Ringwald         case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
16044e821764SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
16054e821764SMatthias Ringwald             log_info("BCM: Config PCM interface for I2S");
16061d2bbd54SMatthias Ringwald #ifdef ENABLE_BCM_PCM_WBS
16071d2bbd54SMatthias Ringwald             // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz
16081d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2);
16091d2bbd54SMatthias Ringwald #else
16101d2bbd54SMatthias Ringwald             // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz
16111d2bbd54SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1);
16121d2bbd54SMatthias Ringwald #endif
16134e821764SMatthias Ringwald             break;
161435454696SMatthias Ringwald #endif
16154e821764SMatthias Ringwald #endif
16164e821764SMatthias Ringwald 
1617a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
161874b323a9SMatthias Ringwald         // LE INIT
161974b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
162074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
16210305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_read_buffer_size);
162274b323a9SMatthias Ringwald             break;
1623daabb8b8SMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
1624daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1625729710c0SMatthias Ringwald             hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1626daabb8b8SMatthias Ringwald             break;
162774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
162874b323a9SMatthias Ringwald             // LE Supported Host = 1, Simultaneous Host = 0
162974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
16300305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
163174b323a9SMatthias Ringwald             break;
1632b435e062SMatthias Ringwald #endif
1633b435e062SMatthias Ringwald 
1634b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1635dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1636dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1637dcd678baSMatthias Ringwald             hci_send_cmd(&hci_le_read_maximum_data_length);
1638dcd678baSMatthias Ringwald             break;
1639dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1640dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1641b435e062SMatthias 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);
1642dcd678baSMatthias Ringwald             break;
1643b435e062SMatthias Ringwald #endif
1644b435e062SMatthias Ringwald 
1645b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
16463b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
16473b6d4121SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
16483b6d4121SMatthias Ringwald             hci_send_cmd(&hci_le_read_white_list_size);
16493b6d4121SMatthias Ringwald             break;
165074b323a9SMatthias Ringwald         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
165174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
16528b69e4c7SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
165374b323a9SMatthias Ringwald             break;
165474b323a9SMatthias Ringwald #endif
165574b323a9SMatthias Ringwald         default:
165674b323a9SMatthias Ringwald             return;
165774b323a9SMatthias Ringwald     }
165855975f88SMatthias Ringwald }
165955975f88SMatthias Ringwald 
1660a650ba4dSMatthias Ringwald static void hci_init_done(void){
1661a650ba4dSMatthias Ringwald     // done. tell the app
1662a650ba4dSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1663a650ba4dSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1664a650ba4dSMatthias Ringwald     hci_emit_state();
1665a650ba4dSMatthias Ringwald     hci_run();
1666a650ba4dSMatthias Ringwald }
1667a650ba4dSMatthias Ringwald 
166807fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
166907fd2f31SMatthias Ringwald     bool command_completed = false;
16700e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1671f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
16726155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
167307fd2f31SMatthias Ringwald             command_completed = true;
1674148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
16756155b3d3S[email protected]         } else {
1676d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
16776155b3d3S[email protected]         }
16786155b3d3S[email protected]     }
16790f97eae7SMatthias Ringwald 
16800e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
16816155b3d3S[email protected]         uint8_t  status = packet[2];
1682f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
16836155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
16846155b3d3S[email protected]             if (status){
168507fd2f31SMatthias Ringwald                 command_completed = true;
1686148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
16876155b3d3S[email protected]             } else {
16886155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
16896155b3d3S[email protected]             }
16906155b3d3S[email protected]         } else {
1691148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
16926155b3d3S[email protected]         }
16936155b3d3S[email protected]     }
169406b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1695e47e68c7SMatthias Ringwald     // Vendor == CSR
16960e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1697e47e68c7SMatthias Ringwald         // TODO: track actual command
169807fd2f31SMatthias Ringwald         command_completed = true;
1699e47e68c7SMatthias Ringwald     }
1700a2481739S[email protected] 
17014e9daa6fSMatthias Ringwald     // Vendor == Toshiba
17020e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
17034e9daa6fSMatthias Ringwald         // TODO: track actual command
170407fd2f31SMatthias Ringwald         command_completed = true;
1705004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1706004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
17074e9daa6fSMatthias Ringwald     }
170807fd2f31SMatthias Ringwald #endif
170907fd2f31SMatthias Ringwald 
171007fd2f31SMatthias Ringwald     return command_completed;
171107fd2f31SMatthias Ringwald }
171207fd2f31SMatthias Ringwald 
171307fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
171407fd2f31SMatthias Ringwald 
171507fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
171607fd2f31SMatthias Ringwald 
171707fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
171807fd2f31SMatthias Ringwald 
171907fd2f31SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
17204e9daa6fSMatthias Ringwald 
17210f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
17220f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
17230f97eae7SMatthias Ringwald     //
17240f97eae7SMatthias Ringwald     // HCI Reset
17250f97eae7SMatthias Ringwald     // Timeout 100 ms
17260f97eae7SMatthias Ringwald     // HCI Reset
17270f97eae7SMatthias Ringwald     // Command Complete Reset
17280f97eae7SMatthias Ringwald     // HCI Read Local Version Information
17290f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
17300f97eae7SMatthias Ringwald     // hang...
17310f97eae7SMatthias Ringwald     //
17320f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
17330f97eae7SMatthias Ringwald     if (!command_completed
1734a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
17350e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
17360f97eae7SMatthias Ringwald 
1737f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
17380f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
17390f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
17400f97eae7SMatthias Ringwald             return;
17410f97eae7SMatthias Ringwald         }
17420f97eae7SMatthias Ringwald     }
17430f97eae7SMatthias Ringwald 
17449f007422SMatthias Ringwald     // CSR & H5
17459f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
17469f007422SMatthias Ringwald     if (!command_completed
1747a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
17480e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
17499f007422SMatthias Ringwald 
17509f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
17519f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
17529f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
17539f007422SMatthias Ringwald             return;
17549f007422SMatthias Ringwald         }
17559f007422SMatthias Ringwald     }
17569f007422SMatthias Ringwald 
17579f007422SMatthias 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
17589f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
17599f007422SMatthias Ringwald     if (command_completed){
17609f007422SMatthias Ringwald         switch (hci_stack->substate){
17619f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
17629f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
17639f007422SMatthias Ringwald                 break;
17649f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
17659f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
17669f007422SMatthias Ringwald                 break;
17679f007422SMatthias Ringwald             default:
17689f007422SMatthias Ringwald                 break;
17699f007422SMatthias Ringwald         }
17709f007422SMatthias Ringwald     }
17710f97eae7SMatthias Ringwald 
177206b9e820SMatthias Ringwald #endif
17730f97eae7SMatthias Ringwald 
1774a2481739S[email protected]     if (!command_completed) return;
1775a2481739S[email protected] 
177607fd2f31SMatthias Ringwald     bool need_baud_change = false;
177707fd2f31SMatthias Ringwald     bool need_addr_change = false;
177806b9e820SMatthias Ringwald 
177906b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
178006b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
17813fb36a29SMatthias Ringwald                         && hci_stack->chipset
17823fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
1783db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
17849796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1785db8bc6ffSMatthias Ringwald 
178606b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
17873fb36a29SMatthias Ringwald                         && hci_stack->chipset
17883fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
178906b9e820SMatthias Ringwald #endif
1790a80162e9SMatthias Ringwald 
17915c363727SMatthias Ringwald     switch(hci_stack->substate){
179206b9e820SMatthias Ringwald 
179306b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
17949f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
1795d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
17969f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
17979f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
17989f007422SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
17999f007422SMatthias Ringwald             break;
180074b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
1801528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
180276fcb19bSMatthias Ringwald             break;
1803e90bae01SMatthias Ringwald         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
180407fd2f31SMatthias Ringwald             log_info("Received local name, need baud change %d", (int) need_baud_change);
18052f48d920SMatthias Ringwald             if (need_baud_change){
18062f48d920SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
18072f48d920SMatthias Ringwald                 return;
18082f48d920SMatthias Ringwald             }
180953860077SMatthias Ringwald             // skip baud change
181074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
181174b323a9SMatthias Ringwald             return;
1812a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
18134696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
1814fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
181561f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
181696b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1817cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate);
1818fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18194696bddbSMatthias Ringwald             }
182074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
182174b323a9SMatthias Ringwald             return;
1822a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1823528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
1824a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1825a80162e9SMatthias Ringwald             return;
182674b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
182774b323a9SMatthias Ringwald             // repeat custom init
182874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
182974b323a9SMatthias Ringwald             return;
183006b9e820SMatthias Ringwald #else
183106b9e820SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
183206b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
183306b9e820SMatthias Ringwald             return ;
183406b9e820SMatthias Ringwald #endif
183506b9e820SMatthias Ringwald 
1836a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
18370e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1838efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1839efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1840eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1841eb3a5314SMatthias Ringwald                 return;
1842eb3a5314SMatthias Ringwald             }
184353860077SMatthias Ringwald             if (need_addr_change){
184453860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
184553860077SMatthias Ringwald                 return;
184653860077SMatthias Ringwald             }
184753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
184853860077SMatthias Ringwald             return;
184906b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
18507224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
18517224be7eSMatthias Ringwald             if (need_baud_change){
185296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1853cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate);
1854fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
18557224be7eSMatthias Ringwald             }
1856eb3a5314SMatthias Ringwald             if (need_addr_change){
1857eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1858eb3a5314SMatthias Ringwald                 return;
1859eb3a5314SMatthias Ringwald             }
1860eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1861eb3a5314SMatthias Ringwald             return;
186253860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
18636ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
18646ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
18656ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
186653860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
186753860077SMatthias Ringwald                 return;
186853860077SMatthias Ringwald             }
186953860077SMatthias Ringwald             // skipping st warm boot
187053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
187153860077SMatthias Ringwald             return;
187253860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
187353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
187453860077SMatthias Ringwald             return;
187506b9e820SMatthias Ringwald #endif
187653860077SMatthias Ringwald         case HCI_INIT_W4_READ_BD_ADDR:
187753860077SMatthias Ringwald             // only read buffer size if supported
18784ea43905SMatthias Ringwald             if (hci_stack->local_supported_commands[0u] & 0x01u) {
187953860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
188053860077SMatthias Ringwald                 return;
188153860077SMatthias Ringwald             }
188253860077SMatthias Ringwald             // skipping read buffer size
188353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1884a828a756SMatthias Ringwald             return;
188574b323a9SMatthias Ringwald         case HCI_INIT_W4_SET_EVENT_MASK:
18866155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
18876155b3d3S[email protected]             if (!hci_classic_supported()){
18882c68f164SMatthias Ringwald #ifdef ENABLE_BLE
18896155b3d3S[email protected]                 if (hci_le_supported()){
189074b323a9SMatthias Ringwald                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
189174b323a9SMatthias Ringwald                     return;
18922c68f164SMatthias Ringwald                 }
18932c68f164SMatthias Ringwald #endif
18946155b3d3S[email protected]                 log_error("Neither BR/EDR nor LE supported");
1895a650ba4dSMatthias Ringwald                 hci_init_done();
189674b323a9SMatthias Ringwald                 return;
18976155b3d3S[email protected]             }
189815a95bd5SMatthias Ringwald             if (!gap_ssp_supported()){
18995c363727SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
190074b323a9SMatthias Ringwald                 return;
19016155b3d3S[email protected]             }
19026155b3d3S[email protected]             break;
1903903ea03aSMatthias Ringwald #ifdef ENABLE_BLE
1904a828a756SMatthias Ringwald         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1905a828a756SMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
19064ea43905SMatthias Ringwald             if (hci_stack->local_supported_commands[0u] & 0x02u) break;
1907daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1908daabb8b8SMatthias Ringwald             return;
1909daabb8b8SMatthias Ringwald 
1910b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1911b435e062SMatthias Ringwald         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
19126fab74dbSMatthias Ringwald             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
19134ea43905SMatthias Ringwald             if ((hci_stack->local_supported_commands[0u] & 0x30u) == 0x30u){
191480d7d618SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1915b435e062SMatthias Ringwald                 return;
1916b435e062SMatthias Ringwald             }
1917b435e062SMatthias Ringwald             // explicit fall through to reduce repetitions
1918b435e062SMatthias Ringwald 
1919b435e062SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1920b435e062SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1921903ea03aSMatthias Ringwald #else
1922903ea03aSMatthias Ringwald             hci_init_done();
1923903ea03aSMatthias Ringwald #endif
1924a828a756SMatthias Ringwald             return;
192506337f4fSMatthias Ringwald #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
192606337f4fSMatthias Ringwald 
192706337f4fSMatthias Ringwald #endif  /* ENABLE_BLE */
1928b435e062SMatthias Ringwald 
19295d23aae8SMatthias Ringwald         case HCI_INIT_W4_WRITE_INQUIRY_MODE:
19305d23aae8SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
19314ea43905SMatthias Ringwald             if (!hci_stack->secure_connections_enable || (hci_stack->local_supported_commands[1u] & 0x02u) == 0u) {
19325d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;
19335d23aae8SMatthias Ringwald                 return;
19345d23aae8SMatthias Ringwald             }
19355d23aae8SMatthias Ringwald             break;
19365d23aae8SMatthias Ringwald 
193747bc3ebbSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
19383b65523cSMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
19393905afbfSMatthias Ringwald             // skip write synchronous flow control if not supported
19403905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x04) break;
19413905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1942cf373d3aSMatthias Ringwald 
1943cf373d3aSMatthias Ringwald             /* fall through */
19443905afbfSMatthias Ringwald 
1945729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
19463905afbfSMatthias Ringwald             // skip write default erroneous data reporting if not supported
19473905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x08) break;
19483905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1949cf373d3aSMatthias Ringwald 
1950cf373d3aSMatthias Ringwald             /* fall through */
19513905afbfSMatthias Ringwald 
1952f064e0bbSMatthias Ringwald         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1953a42798c3SMatthias Ringwald             // skip bcm set sco pcm config on non-Broadcom chipsets
195461f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
19550168d82eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1956cf373d3aSMatthias Ringwald 
1957cf373d3aSMatthias Ringwald             /* fall through */
1958a42798c3SMatthias Ringwald 
1959a42798c3SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1960729ed62eSMatthias Ringwald             if (!hci_le_supported()){
1961729ed62eSMatthias Ringwald                 // SKIP LE init for Classic only configuration
1962a650ba4dSMatthias Ringwald                 hci_init_done();
1963729ed62eSMatthias Ringwald                 return;
1964729ed62eSMatthias Ringwald             }
1965afe9bf34SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM;
1966729ed62eSMatthias Ringwald             break;
1967f3b012f9SMatthias Ringwald 
1968f3b012f9SMatthias Ringwald #else /* !ENABLE_SCO_OVER_HCI */
1969f3b012f9SMatthias Ringwald 
197074b323a9SMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
19718051253fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_PCM
19728051253fSMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) {
19738051253fSMatthias Ringwald                 hci_stack->substate = HCI_INIT_BCM_WRITE_SCO_PCM_INT;
19748051253fSMatthias Ringwald                 return;
19758051253fSMatthias Ringwald             }
19768051253fSMatthias Ringwald #endif
19778051253fSMatthias Ringwald             /* fall through */
19788051253fSMatthias Ringwald 
19794e821764SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM:
1980f3b012f9SMatthias Ringwald #ifdef ENABLE_BLE
1981f3b012f9SMatthias Ringwald             if (hci_le_supported()){
1982f3b012f9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
198374b323a9SMatthias Ringwald                 return;
19846155b3d3S[email protected]             }
1985729ed62eSMatthias Ringwald #endif
1986f3b012f9SMatthias Ringwald             // SKIP LE init for Classic only configuration
1987f3b012f9SMatthias Ringwald             hci_init_done();
1988f3b012f9SMatthias Ringwald             return;
1989f3b012f9SMatthias Ringwald #endif /* ENABLE_SCO_OVER_HCI */
1990f3b012f9SMatthias Ringwald 
1991a4e96e78SMatthias Ringwald // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1992a4e96e78SMatthias Ringwald #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1993a650ba4dSMatthias Ringwald         // Response to command before init done state -> init done
1994a650ba4dSMatthias Ringwald         case (HCI_INIT_DONE-1):
1995a650ba4dSMatthias Ringwald             hci_init_done();
1996a650ba4dSMatthias Ringwald             return;
1997a4e96e78SMatthias Ringwald #endif
1998a650ba4dSMatthias Ringwald 
19996155b3d3S[email protected]         default:
200074b323a9SMatthias Ringwald             break;
20016155b3d3S[email protected]     }
200255975f88SMatthias Ringwald     hci_initializing_next_state();
20036155b3d3S[email protected] }
20046155b3d3S[email protected] 
20050bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
2006229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
20070bbba85bSMatthias Ringwald     bd_addr_t bd_address;
20086535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
20090bbba85bSMatthias Ringwald 
20106bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
20116bc9fa5eSMatthias Ringwald     // cache needed data
20126bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
20136bc9fa5eSMatthias Ringwald #endif
20146bc9fa5eSMatthias Ringwald 
20150bbba85bSMatthias Ringwald     // connection failed, remove entry
20160bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
20170bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
20180bbba85bSMatthias Ringwald 
20196bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
20200bbba85bSMatthias Ringwald     // notify client if dedicated bonding
20210bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
20220bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
20230bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
20240bbba85bSMatthias Ringwald     }
20250bbba85bSMatthias Ringwald 
20260bbba85bSMatthias Ringwald     // if authentication error, also delete link key
20270bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
20280bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
20290bbba85bSMatthias Ringwald     }
20301c79b5e3SMatthias Ringwald #else
20311c79b5e3SMatthias Ringwald     UNUSED(status);
20326bc9fa5eSMatthias Ringwald #endif
20330bbba85bSMatthias Ringwald }
20340bbba85bSMatthias Ringwald 
2035be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
20362f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
20372f5c44baSMatthias Ringwald     // SSP Controller
20382f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
20392f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
20402f5c44baSMatthias Ringwald     }
20412f5c44baSMatthias Ringwald     // eSCO
20422f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
20432f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
20442f5c44baSMatthias Ringwald     }
20452f5c44baSMatthias Ringwald     // Extended features
20462f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
20472f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
20482f5c44baSMatthias Ringwald     }
20492f5c44baSMatthias Ringwald }
20502f5c44baSMatthias Ringwald 
20512f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
20522f5c44baSMatthias Ringwald     // SSP Host
20532f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
20542f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
20552f5c44baSMatthias Ringwald     }
205650c51a77SMatthias Ringwald     // SC Host
205750c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
205850c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
205950c51a77SMatthias Ringwald     }
206050c51a77SMatthias Ringwald }
206150c51a77SMatthias Ringwald 
206250c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
206350c51a77SMatthias Ringwald     // SC Controller
206450c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
206550c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
206650c51a77SMatthias Ringwald     }
20672f5c44baSMatthias Ringwald }
20682f5c44baSMatthias Ringwald 
2069de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
2070de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
207149bafb5eSMatthias Ringwald     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
2072de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
2073de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2074de0df013SMatthias Ringwald     }
2075de0df013SMatthias Ringwald }
2076128825c3SMatthias Ringwald static bool hci_remote_sc_enabled(hci_connection_t * connection){
2077128825c3SMatthias Ringwald     const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
2078128825c3SMatthias Ringwald     return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
2079128825c3SMatthias Ringwald }
2080128825c3SMatthias Ringwald 
2081be500194SMatthias Ringwald #endif
2082de0df013SMatthias Ringwald 
208367c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
208467c6c9dcSMatthias Ringwald     // handle BT initialization
208567c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
208667c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
208767c6c9dcSMatthias Ringwald     }
208867c6c9dcSMatthias Ringwald 
208967c6c9dcSMatthias Ringwald     // help with BT sleep
209067c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
209167c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
209267c6c9dcSMatthias Ringwald         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)) {
209367c6c9dcSMatthias Ringwald         hci_initializing_next_state();
209467c6c9dcSMatthias Ringwald     }
209567c6c9dcSMatthias Ringwald }
209667c6c9dcSMatthias Ringwald 
20979866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
20989866fdc7SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
20998daf94bcSMatthias Ringwald     conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
21009866fdc7SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
2101abdad579SMatthias Ringwald 
21028daf94bcSMatthias Ringwald     if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) {
21031cf0a6c8SMatthias Ringwald         conn->requested_security_level = LEVEL_0;
21049866fdc7SMatthias Ringwald         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
2105abdad579SMatthias Ringwald         return;
2106abdad579SMatthias Ringwald     }
2107abdad579SMatthias Ringwald 
2108abdad579SMatthias Ringwald     // Request Authentication if not already done
2109abdad579SMatthias Ringwald     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
2110abdad579SMatthias Ringwald     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
21119866fdc7SMatthias Ringwald }
21129866fdc7SMatthias Ringwald #endif
21139866fdc7SMatthias Ringwald 
21144f781026SMatthias Ringwald static void handle_command_complete_event(uint8_t * packet, uint16_t size){
2115b08371a9SMilanka Ringwald     UNUSED(size);
2116e76a89eeS[email protected] 
21179cbd2215SMatthias Ringwald     uint16_t manufacturer;
21189cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
2119fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
21201f7b95a1Smatthias.ringwald     hci_connection_t * conn;
2121645b7c25SMatthias Ringwald     uint8_t status;
21229cbd2215SMatthias Ringwald #endif
21236bef4003SMatthias Ringwald     // get num cmd packets - limit to 1 to reduce complexity
21246bef4003SMatthias Ringwald     hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
21257ec5eeaaSmatthias.ringwald 
2126645b7c25SMatthias Ringwald     uint16_t opcode = hci_event_command_complete_get_command_opcode(packet);
2127645b7c25SMatthias Ringwald     switch (opcode){
2128645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_NAME:
2129645b7c25SMatthias Ringwald             if (packet[5]) break;
21309e263bd7SMatthias Ringwald             // terminate, name 248 chars
21319e263bd7SMatthias Ringwald             packet[6+248] = 0;
21329e263bd7SMatthias Ringwald             log_info("local name: %s", &packet[6]);
2133645b7c25SMatthias Ringwald             break;
2134645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BUFFER_SIZE:
21351d279b20Smatthias.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"
2136c3b46f5aSMatthias Ringwald             if (hci_stack->state == HCI_STATE_INITIALIZING) {
2137429122ccSMatthias Ringwald                 uint16_t acl_len = little_endian_read_16(packet, 6);
2138429122ccSMatthias Ringwald                 uint16_t sco_len = packet[8];
2139429122ccSMatthias Ringwald 
2140429122ccSMatthias Ringwald                 // determine usable ACL/SCO payload size
2141429122ccSMatthias Ringwald                 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2142429122ccSMatthias Ringwald                 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2143429122ccSMatthias Ringwald 
2144f8fbdce0SMatthias Ringwald                 hci_stack->acl_packets_total_num = little_endian_read_16(packet, 9);
2145f8fbdce0SMatthias Ringwald                 hci_stack->sco_packets_total_num = little_endian_read_16(packet, 11);
2146a8b12447S[email protected] 
2147429122ccSMatthias Ringwald                 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2148429122ccSMatthias Ringwald                          acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
21491a06f663S[email protected]                          hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2150c3b46f5aSMatthias Ringwald             }
2151645b7c25SMatthias Ringwald             break;
2152645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_RSSI:
2153645b7c25SMatthias Ringwald             if (packet[5] == ERROR_CODE_SUCCESS){
2154891b9fc2SMatthias Ringwald                 uint8_t event[5];
2155891b9fc2SMatthias Ringwald                 event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2156891b9fc2SMatthias Ringwald                 event[1] = 3;
21576535961aSMatthias Ringwald                 (void)memcpy(&event[2], &packet[6], 3);
2158891b9fc2SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2159891b9fc2SMatthias Ringwald             }
2160645b7c25SMatthias Ringwald             break;
2161a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2162645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE:
2163f8fbdce0SMatthias Ringwald             hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2164ee303eddS[email protected]             hci_stack->le_acl_packets_total_num = packet[8];
21656c26b087S[email protected]             // determine usable ACL payload size
21666c26b087S[email protected]             if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
21676c26b087S[email protected]                 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
21686c26b087S[email protected]             }
21699da54300S[email protected]             log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
2170645b7c25SMatthias Ringwald             break;
2171b435e062SMatthias Ringwald #endif
2172b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
2173645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH:
2174dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2175dcd678baSMatthias Ringwald             hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2176dcd678baSMatthias 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);
2177645b7c25SMatthias Ringwald             break;
2178b435e062SMatthias Ringwald #endif
2179d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2180645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE:
2181e691bb38SMatthias Ringwald             hci_stack->le_whitelist_capacity = packet[6];
218215d0a15bSMatthias Ringwald             log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
2183645b7c25SMatthias Ringwald             break;
218465a46ef3S[email protected] #endif
2185645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_BD_ADDR:
2186645b7c25SMatthias Ringwald             reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr);
2187645b7c25SMatthias Ringwald             log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
218833373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
21891624665aSMatthias Ringwald             if (hci_stack->link_key_db){
21901624665aSMatthias Ringwald                 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
21911624665aSMatthias Ringwald             }
219233373e40SMatthias Ringwald #endif
2193645b7c25SMatthias Ringwald             break;
219435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2195645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE:
21963a9fb326S[email protected]             hci_emit_discoverable_enabled(hci_stack->discoverable);
2197645b7c25SMatthias Ringwald             break;
2198645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_INQUIRY_CANCEL:
2199f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2200f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2201f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2202f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2203f5875de5SMatthias Ringwald             }
2204645b7c25SMatthias Ringwald             break;
220535454696SMatthias Ringwald #endif
2206645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES:
22074f781026SMatthias Ringwald             (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8);
220865389bfcS[email protected] 
220935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2210a5a23fc2S[email protected]             // determine usable ACL packet types based on host buffer size and supported features
2211a5a23fc2S[email protected]             hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
22128b96126aSMatthias Ringwald             log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
221335454696SMatthias Ringwald #endif
2214f5d8d141S[email protected]             // Classic/LE
2215f5d8d141S[email protected]             log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2216645b7c25SMatthias Ringwald             break;
2217645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION:
2218645b7c25SMatthias Ringwald             manufacturer = little_endian_read_16(packet, 10);
2219c21d89f3SMatthias Ringwald             // map Cypress to Broadcom
2220c21d89f3SMatthias Ringwald             if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2221c21d89f3SMatthias Ringwald                 log_info("Treat Cypress as Broadcom");
2222c21d89f3SMatthias Ringwald                 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2223c21d89f3SMatthias Ringwald                 little_endian_store_16(packet, 10, manufacturer);
2224c21d89f3SMatthias Ringwald             }
2225c21d89f3SMatthias Ringwald             hci_stack->manufacturer = manufacturer;
22264696bddbSMatthias Ringwald             log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
2227645b7c25SMatthias Ringwald             break;
2228645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
2229a828a756SMatthias Ringwald             hci_stack->local_supported_commands[0] =
22304ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+14u] & 0x80u) >> 7u) |  // bit  0 = Octet 14, bit 7 / Read Buffer Size
22314ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+24u] & 0x40u) >> 5u) |  // bit  1 = Octet 24, bit 6 / Write Le Host Supported
22324ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+10u] & 0x10u) >> 2u) |  // bit  2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
22334ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+18u] & 0x08u)     )  |  // bit  3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
22344ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x01u) << 4u) |  // bit  4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
22354ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x08u) << 2u) |  // bit  5 = Octet 35, bit 3 / LE Read Maximum Data Length
22364ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x20u) << 1u) |  // bit  6 = Octet 35, bit 5 / LE Set Default PHY
22374ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+20u] & 0x10u) << 3u);   // bit  7 = Octet 20, bit 4 / Read Encryption Key Size
22388d2d8af1SMatthias Ringwald             hci_stack->local_supported_commands[1] =
22394ea43905SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+ 2u] & 0x40u) >> 6u) |  // bit  8 = Octet  2, bit 6 / Read Remote Extended Features
224099b14827SMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x08u) >> 2u) |  // bit  9 = Octet 32, bit 3 / Write Secure Connections Host
2241f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+35u] & 0x02u) << 1u) |  // bit 10 = Octet 35, bit 1 / LE Set Address Resolution Enable
2242f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x02u) << 2u) |  // bit 11 = Octet 32, bit 1 / Remote OOB Extended Data Request Reply
2243f21849cbSMatthias Ringwald                 ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+32u] & 0x40u) >> 2u);   // bit 12 = Octet 32, bit 6 / Read Local OOB Extended Data command
22448d2d8af1SMatthias Ringwald             log_info("Local supported commands summary %02x - %02x", hci_stack->local_supported_commands[0],  hci_stack->local_supported_commands[1]);
2245645b7c25SMatthias Ringwald             break;
2246e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
2247645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
22484f781026SMatthias Ringwald             if (packet[5]) return;
22495b9b590fSMatthias Ringwald             hci_stack->synchronous_flow_control_enabled = 1;
2250645b7c25SMatthias Ringwald             break;
2251645b7c25SMatthias Ringwald         case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE:
2252645b7c25SMatthias Ringwald             status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2253573897a0SMatthias Ringwald             handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2254573897a0SMatthias Ringwald             conn   = hci_connection_for_handle(handle);
2255c3b46f5aSMatthias Ringwald             if (conn != NULL) {
22569866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
2257573897a0SMatthias Ringwald                 if (status == 0){
22589866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
22594a659b0eSMatthias Ringwald                     log_info("Handle %04x key Size: %u", handle, key_size);
2260170fafaeSMatthias Ringwald                 } else {
2261e9f98c4aSMatthias Ringwald                     key_size = 1;
22629866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2263573897a0SMatthias Ringwald                 }
22649866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2265c3b46f5aSMatthias Ringwald             }
2266645b7c25SMatthias Ringwald             break;
226775a8e4faSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
226875a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA:
226975a8e4faSMatthias Ringwald         case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{
227075a8e4faSMatthias Ringwald             uint8_t event[67];
227175a8e4faSMatthias Ringwald             event[0] = GAP_EVENT_LOCAL_OOB_DATA;
227275a8e4faSMatthias Ringwald             event[1] = 65;
227375a8e4faSMatthias Ringwald             (void)memset(&event[2], 0, 65);
227475a8e4faSMatthias Ringwald             if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){
227575a8e4faSMatthias Ringwald                 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32);
227675a8e4faSMatthias Ringwald                 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){
227775a8e4faSMatthias Ringwald                     event[2] = 3;
227875a8e4faSMatthias Ringwald                     (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32);
227975a8e4faSMatthias Ringwald                 } else {
228075a8e4faSMatthias Ringwald                     event[2] = 1;
228175a8e4faSMatthias Ringwald                 }
228275a8e4faSMatthias Ringwald             }
228375a8e4faSMatthias Ringwald             hci_emit_event(event, sizeof(event), 0);
228475a8e4faSMatthias Ringwald             break;
228575a8e4faSMatthias Ringwald         }
2286e8c8828eSMatthias Ringwald #endif
228775a8e4faSMatthias Ringwald #endif
22886f35bb46SMatthias Ringwald         default:
22896f35bb46SMatthias Ringwald             break;
22904f781026SMatthias Ringwald     }
2291645b7c25SMatthias Ringwald }
22924f781026SMatthias Ringwald 
22930ce3f217SMatthias Ringwald #ifdef ENABLE_BLE
22940ce3f217SMatthias Ringwald static void event_handle_le_connection_complete(const uint8_t * packet){
22950ce3f217SMatthias Ringwald 	bd_addr_t addr;
22960ce3f217SMatthias Ringwald 	bd_addr_type_t addr_type;
22970ce3f217SMatthias Ringwald 	hci_connection_t * conn;
22980ce3f217SMatthias Ringwald 
22990ce3f217SMatthias Ringwald 	// Connection management
23000ce3f217SMatthias Ringwald 	reverse_bd_addr(&packet[8], addr);
23010ce3f217SMatthias Ringwald 	addr_type = (bd_addr_type_t)packet[7];
23020ce3f217SMatthias Ringwald 	log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
23030ce3f217SMatthias Ringwald 	conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
23040ce3f217SMatthias Ringwald 
23050ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23060ce3f217SMatthias Ringwald 	// handle error: error is reported only to the initiator -> outgoing connection
23070ce3f217SMatthias Ringwald 	if (packet[3]){
23080ce3f217SMatthias Ringwald 
23090ce3f217SMatthias Ringwald 		// handle cancelled outgoing connection
23100ce3f217SMatthias Ringwald 		// "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
23110ce3f217SMatthias Ringwald 		//  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
23120ce3f217SMatthias Ringwald 		//  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
23130ce3f217SMatthias Ringwald 		if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
23141f468175SMatthias Ringwald 		    // reset state
23150ce3f217SMatthias Ringwald             hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
23161f468175SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
23170ce3f217SMatthias Ringwald 			// get outgoing connection conn struct for direct connect
23180ce3f217SMatthias Ringwald 			conn = gap_get_outgoing_connection();
23190ce3f217SMatthias Ringwald 		}
23200ce3f217SMatthias Ringwald 
23210ce3f217SMatthias Ringwald 		// outgoing le connection establishment is done
23220ce3f217SMatthias Ringwald 		if (conn){
23230ce3f217SMatthias Ringwald 			// remove entry
23240ce3f217SMatthias Ringwald 			btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
23250ce3f217SMatthias Ringwald 			btstack_memory_hci_connection_free( conn );
23260ce3f217SMatthias Ringwald 		}
23270ce3f217SMatthias Ringwald 		return;
23280ce3f217SMatthias Ringwald 	}
23290ce3f217SMatthias Ringwald #endif
23300ce3f217SMatthias Ringwald 
23310ce3f217SMatthias Ringwald 	// on success, both hosts receive connection complete event
23320ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_MASTER){
23330ce3f217SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23340ce3f217SMatthias Ringwald 		// if we're master on an le connection, it was an outgoing connection and we're done with it
23350ce3f217SMatthias Ringwald 		// note: no hci_connection_t object exists yet for connect with whitelist
23360ce3f217SMatthias Ringwald 		if (hci_is_le_connection_type(addr_type)){
23370ce3f217SMatthias Ringwald 			hci_stack->le_connecting_state   = LE_CONNECTING_IDLE;
23380ce3f217SMatthias Ringwald 			hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
23390ce3f217SMatthias Ringwald 		}
23400ce3f217SMatthias Ringwald #endif
23410ce3f217SMatthias Ringwald 	} else {
23420ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23430ce3f217SMatthias Ringwald 		// if we're slave, it was an incoming connection, advertisements have stopped
23440ce3f217SMatthias Ringwald 		hci_stack->le_advertisements_active = false;
23450ce3f217SMatthias Ringwald #endif
23460ce3f217SMatthias Ringwald 	}
23470ce3f217SMatthias Ringwald 
23480ce3f217SMatthias Ringwald 	// LE connections are auto-accepted, so just create a connection if there isn't one already
23490ce3f217SMatthias Ringwald 	if (!conn){
23500ce3f217SMatthias Ringwald 		conn = create_connection_for_bd_addr_and_type(addr, addr_type);
23510ce3f217SMatthias Ringwald 	}
23520ce3f217SMatthias Ringwald 
23530ce3f217SMatthias Ringwald 	// no memory, sorry.
23540ce3f217SMatthias Ringwald 	if (!conn){
23550ce3f217SMatthias Ringwald 		return;
23560ce3f217SMatthias Ringwald 	}
23570ce3f217SMatthias Ringwald 
23580ce3f217SMatthias Ringwald 	conn->state = OPEN;
23590ce3f217SMatthias Ringwald 	conn->role  = packet[6];
23600ce3f217SMatthias Ringwald 	conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
23610ce3f217SMatthias Ringwald 	conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
23620ce3f217SMatthias Ringwald 
23630ce3f217SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23640ce3f217SMatthias Ringwald 	if (packet[6] == HCI_ROLE_SLAVE){
23650ce3f217SMatthias Ringwald 		hci_update_advertisements_enabled_for_current_roles();
23660ce3f217SMatthias Ringwald 	}
23670ce3f217SMatthias Ringwald #endif
23680ce3f217SMatthias Ringwald 
2369dde9ff1eSMatthias Ringwald     // init unenhanced att bearer mtu
2370dde9ff1eSMatthias Ringwald     conn->att_connection.mtu = ATT_DEFAULT_MTU;
2371dde9ff1eSMatthias Ringwald     conn->att_connection.mtu_exchanged = false;
2372dde9ff1eSMatthias Ringwald 
23730ce3f217SMatthias Ringwald     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
23740ce3f217SMatthias Ringwald 
23750ce3f217SMatthias Ringwald 	// restart timer
23760ce3f217SMatthias Ringwald 	// btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
23770ce3f217SMatthias Ringwald 	// btstack_run_loop_add_timer(&conn->timeout);
23780ce3f217SMatthias Ringwald 
23790ce3f217SMatthias Ringwald 	log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
23800ce3f217SMatthias Ringwald 
23810ce3f217SMatthias Ringwald 	hci_emit_nr_connections_changed();
23820ce3f217SMatthias Ringwald }
23830ce3f217SMatthias Ringwald #endif
23840ce3f217SMatthias Ringwald 
238517c6fe5cSMatthias Ringwald #ifdef ENABLE_CLASSIC
238617c6fe5cSMatthias 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){
238717c6fe5cSMatthias Ringwald     if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false;
238817c6fe5cSMatthias Ringwald     // LEVEL_4 is tested by l2cap
238917c6fe5cSMatthias Ringwald     // LEVEL 3 requires MITM protection -> check io capabilities
239017c6fe5cSMatthias Ringwald     if (level >= LEVEL_3){
239117c6fe5cSMatthias Ringwald         if (io_cap_remote  >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
239217c6fe5cSMatthias Ringwald         if (io_cap_local   >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false;
239317c6fe5cSMatthias Ringwald         if ((io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY) && (io_cap_local ==  SSP_IO_CAPABILITY_KEYBOARD_ONLY)) return false;
239417c6fe5cSMatthias Ringwald     }
239517c6fe5cSMatthias Ringwald     // LEVEL 2 requires SSP, which is a given
239617c6fe5cSMatthias Ringwald     return true;
239717c6fe5cSMatthias Ringwald }
239817c6fe5cSMatthias Ringwald #endif
239917c6fe5cSMatthias Ringwald 
2400c3b46f5aSMatthias Ringwald static void event_handler(uint8_t *packet, uint16_t size){
24014f781026SMatthias Ringwald 
24024f781026SMatthias Ringwald     uint16_t event_length = packet[1];
24034f781026SMatthias Ringwald 
24044f781026SMatthias Ringwald     // assert packet is complete
24054ea43905SMatthias Ringwald     if (size != (event_length + 2u)){
24064f781026SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
24074f781026SMatthias Ringwald         return;
24084f781026SMatthias Ringwald     }
24094f781026SMatthias Ringwald 
24104f781026SMatthias Ringwald     bd_addr_type_t addr_type;
24114f781026SMatthias Ringwald     hci_con_handle_t handle;
24124f781026SMatthias Ringwald     hci_connection_t * conn;
24134f781026SMatthias Ringwald     int i;
24144f781026SMatthias Ringwald     int create_connection_cmd;
24154f781026SMatthias Ringwald 
24164f781026SMatthias Ringwald #ifdef ENABLE_CLASSIC
24175e91d96cSMatthias Ringwald     hci_link_type_t link_type;
241848f33f37SMatthias Ringwald     bd_addr_t addr;
24194f781026SMatthias Ringwald #endif
24204f781026SMatthias Ringwald 
24214f781026SMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
24224f781026SMatthias Ringwald 
24234f781026SMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
24244f781026SMatthias Ringwald 
24254f781026SMatthias Ringwald         case HCI_EVENT_COMMAND_COMPLETE:
24264f781026SMatthias Ringwald             handle_command_complete_event(packet, size);
242756cf178bSmatthias.ringwald             break;
242856cf178bSmatthias.ringwald 
24297ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
24306bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
24316bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2432229331c6SMatthias Ringwald 
2433229331c6SMatthias Ringwald             // check command status to detected failed outgoing connections
2434c57fa566SMatthias Ringwald             create_connection_cmd = 0;
2435c57fa566SMatthias Ringwald #ifdef ENABLE_CLASSIC
2436c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2437c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2438c57fa566SMatthias Ringwald             }
2439c57fa566SMatthias Ringwald #endif
2440c57fa566SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2441c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2442c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2443c57fa566SMatthias Ringwald             }
2444c57fa566SMatthias Ringwald #endif
2445c57fa566SMatthias Ringwald             if (create_connection_cmd) {
2446229331c6SMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
24478da98cbeSMatthias Ringwald                 addr_type = hci_stack->outgoing_addr_type;
24486ea9315cSMatthias Ringwald                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type);
24496ea9315cSMatthias Ringwald                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), addr_type);
2450229331c6SMatthias Ringwald 
2451229331c6SMatthias Ringwald                 // reset outgoing address info
2452229331c6SMatthias Ringwald                 memset(hci_stack->outgoing_addr, 0, 6);
2453229331c6SMatthias Ringwald                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2454229331c6SMatthias Ringwald 
24556ea9315cSMatthias Ringwald                 // on error
24566ea9315cSMatthias Ringwald                 if (status != ERROR_CODE_SUCCESS){
2457f75e06adSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
24586ea9315cSMatthias Ringwald                     if (hci_is_le_connection_type(addr_type)){
24596ea9315cSMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2460f7e6a692SMatthias Ringwald                         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
24616ea9315cSMatthias Ringwald                     }
2462f75e06adSMatthias Ringwald #endif
2463229331c6SMatthias Ringwald                     // error => outgoing connection failed
24646ea9315cSMatthias Ringwald                     if (conn != NULL){
2465229331c6SMatthias Ringwald                         hci_handle_connection_failed(conn, status);
2466229331c6SMatthias Ringwald                     }
2467229331c6SMatthias Ringwald                 }
24686ea9315cSMatthias Ringwald             }
2469beb3c81dSMatthias Ringwald 
2470beb3c81dSMatthias Ringwald #ifdef ENABLE_CLASSIC
2471beb3c81dSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_inquiry)) {
2472beb3c81dSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2473beb3c81dSMatthias Ringwald                 log_info("command status (inquiry), status %x", status);
2474beb3c81dSMatthias Ringwald                 if (status == ERROR_CODE_SUCCESS) {
2475beb3c81dSMatthias Ringwald                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2476beb3c81dSMatthias Ringwald                 } else {
2477beb3c81dSMatthias Ringwald                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2478beb3c81dSMatthias Ringwald                 }
2479beb3c81dSMatthias Ringwald             }
2480beb3c81dSMatthias Ringwald #endif
24817ec5eeaaSmatthias.ringwald             break;
24827ec5eeaaSmatthias.ringwald 
24832e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
24849784dac1SMatthias Ringwald             if (size < 3) return;
24859784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
24864ea43905SMatthias Ringwald             if (size != (3u + num_handles * 4u)) return;
24879784dac1SMatthias Ringwald             uint16_t offset = 3;
24889784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
24894ea43905SMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fffu;
24904ea43905SMatthias Ringwald                 offset += 2u;
2491f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
24924ea43905SMatthias Ringwald                 offset += 2u;
24932e440c8aS[email protected] 
24945061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
249556cf178bSmatthias.ringwald                 if (!conn){
24969da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
249756cf178bSmatthias.ringwald                     continue;
249856cf178bSmatthias.ringwald                 }
249923bed257S[email protected] 
2500ce41473eSMatthias Ringwald                 if (conn->num_packets_sent >= num_packets){
2501ce41473eSMatthias Ringwald                     conn->num_packets_sent -= num_packets;
2502e35edcc1S[email protected]                 } else {
2503ce41473eSMatthias Ringwald                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2504ce41473eSMatthias Ringwald                     conn->num_packets_sent = 0;
2505e35edcc1S[email protected]                 }
2506ce41473eSMatthias Ringwald                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2507760b20efSMatthias Ringwald 
2508760b20efSMatthias Ringwald #ifdef ENABLE_CLASSIC
2509760b20efSMatthias Ringwald                 // For SCO, we do the can_send_now_check here
2510760b20efSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
2511760b20efSMatthias Ringwald #endif
251256cf178bSmatthias.ringwald             }
25136772a24cSmatthias.ringwald             break;
25142e440c8aS[email protected]         }
251535454696SMatthias Ringwald 
251635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2517f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
2518f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2519f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2520f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2521f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2522f5875de5SMatthias Ringwald             }
2523f5875de5SMatthias Ringwald             break;
2524b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2525b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2526b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2527b7f1ee76SMatthias Ringwald             }
2528b7f1ee76SMatthias Ringwald             break;
25291f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
2530724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
25315e91d96cSMatthias Ringwald             link_type = (hci_link_type_t) packet[11];
253207e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
25335e91d96cSMatthias Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){
25344536712cSMilanka Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
253507e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
253607e010b6SMilanka Ringwald                     break;
253707e010b6SMilanka Ringwald                 }
253807e010b6SMilanka Ringwald             }
253907e010b6SMilanka Ringwald 
254037eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
25415e91d96cSMatthias Ringwald             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type);
25425e91d96cSMatthias Ringwald             addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
25432e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
25441f7b95a1Smatthias.ringwald             if (!conn) {
25455293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
25461f7b95a1Smatthias.ringwald             }
2547ce4c8fabSmatthias.ringwald             if (!conn) {
2548ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
25494536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2550058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
2551ce4c8fabSmatthias.ringwald                 break;
2552ce4c8fabSmatthias.ringwald             }
25535cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
255432ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
2555f3a16b9aSMatthias Ringwald             // store info about eSCO
25565e91d96cSMatthias Ringwald             if (link_type == HCI_LINK_TYPE_ESCO){
255776ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
2558f3a16b9aSMatthias Ringwald             }
255932ab9390Smatthias.ringwald             hci_run();
25601f7b95a1Smatthias.ringwald             break;
25611f7b95a1Smatthias.ringwald 
25626772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2563fe1ed1b8Smatthias.ringwald             // Connection management
2564724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
25659da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2566f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
25672e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2568fe1ed1b8Smatthias.ringwald             if (conn) {
2569b448a0e7Smatthias.ringwald                 if (!packet[2]){
2570c8e4258aSmatthias.ringwald                     conn->state = OPEN;
2571f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
25726909f064SMatthias Ringwald 
25736909f064SMatthias Ringwald                     // queue get remote feature
2574ba018746SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2575ee091cf1Smatthias.ringwald 
2576e6c51921SMatthias Ringwald                     // queue set supervision timeout if we're master
2577d821984bSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){
25788daf94bcSMatthias Ringwald                         connectionSetAuthenticationFlags(conn, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
25796909f064SMatthias Ringwald                     }
25806909f064SMatthias Ringwald 
2581c785ef68Smatthias.ringwald                     // restart timer
2582528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2583528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
2584c785ef68Smatthias.ringwald 
25859da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
258643bfb1bdSmatthias.ringwald 
258743bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
2588b448a0e7Smatthias.ringwald                 } else {
25890bbba85bSMatthias Ringwald                     // connection failed
25900bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
2591fe1ed1b8Smatthias.ringwald                 }
2592fe1ed1b8Smatthias.ringwald             }
25936772a24cSmatthias.ringwald             break;
2594fe1ed1b8Smatthias.ringwald 
259544d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2596724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
259744d0e3d5S[email protected]             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
25981a06f663S[email protected]             if (packet[2]){
259944d0e3d5S[email protected]                 // connection failed
260044d0e3d5S[email protected]                 break;
260144d0e3d5S[email protected]             }
26022e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2603e35edcc1S[email protected]             if (!conn) {
2604e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2605e35edcc1S[email protected]             }
2606e35edcc1S[email protected]             if (!conn) {
2607e35edcc1S[email protected]                 break;
2608e35edcc1S[email protected]             }
26091a06f663S[email protected]             conn->state = OPEN;
2610f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
2611ee752bb8SMatthias Ringwald 
2612ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2613ee752bb8SMatthias Ringwald             // update SCO
2614ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2615ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2616ee752bb8SMatthias Ringwald             }
2617f234b250SMatthias Ringwald             // trigger can send now
2618f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
2619f234b250SMatthias Ringwald                 hci_stack->sco_can_send_now = 1;
2620f234b250SMatthias Ringwald             }
2621ee752bb8SMatthias Ringwald #endif
2622cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
2623cb70c5abSMatthias Ringwald             // configure sco transport
2624cb70c5abSMatthias Ringwald             if (hci_stack->sco_transport != NULL){
2625cb70c5abSMatthias Ringwald                 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT;
2626cb70c5abSMatthias Ringwald                 hci_stack->sco_transport->open(conn->con_handle, sco_format);
2627cb70c5abSMatthias Ringwald             }
2628cb70c5abSMatthias Ringwald #endif
262944d0e3d5S[email protected]             break;
263044d0e3d5S[email protected] 
2631afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2632f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2633afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
2634afd4e962S[email protected]             if (!conn) break;
2635afd4e962S[email protected]             if (!packet[2]){
26362f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
26372f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
26382f5c44baSMatthias Ringwald 
26395ccef624SMatthias Ringwald                 // read extended features if possible
26405ccef624SMatthias Ringwald                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
26415ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
26425ccef624SMatthias Ringwald                     break;
26435ccef624SMatthias Ringwald                 }
26445ccef624SMatthias Ringwald             }
26455ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
26465ccef624SMatthias Ringwald             break;
26475ccef624SMatthias Ringwald 
26485ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
26495ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
26505ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
26515ccef624SMatthias Ringwald             if (!conn) break;
26525ccef624SMatthias Ringwald             // status = ok, page = 1
265350c51a77SMatthias Ringwald             if (!packet[2]) {
265450c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
265550c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
26565ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
265750c51a77SMatthias Ringwald                 bool done = false;
265850c51a77SMatthias Ringwald                 switch (page_number){
265950c51a77SMatthias Ringwald                     case 1:
26602f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
266150c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
266250c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
266350c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
266450c51a77SMatthias Ringwald                         } else {
266550c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
266650c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
266750c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
266850c51a77SMatthias Ringwald                             }
266950c51a77SMatthias Ringwald                             done = true;
267050c51a77SMatthias Ringwald                         }
267150c51a77SMatthias Ringwald                         break;
267250c51a77SMatthias Ringwald                     case 2:
267350c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
267450c51a77SMatthias Ringwald                         done = true;
267550c51a77SMatthias Ringwald                         break;
267650c51a77SMatthias Ringwald                     default:
267750c51a77SMatthias Ringwald                         break;
267850c51a77SMatthias Ringwald                 }
267950c51a77SMatthias Ringwald                 if (!done) break;
2680afd4e962S[email protected]             }
2681de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
2682afd4e962S[email protected]             break;
2683afd4e962S[email protected] 
26847fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
2685608f51bbSMatthias Ringwald             // request handled by hci_run()
26868daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
2687608f51bbSMatthias Ringwald             break;
26887fde4af9Smatthias.ringwald 
26899ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
26901714cbbdSMatthias Ringwald             hci_event_link_key_request_get_bd_addr(packet, addr);
2691f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
26929ab95c90S[email protected]             if (!conn) break;
26931714cbbdSMatthias Ringwald 
26941714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_SUCCESS);
26951714cbbdSMatthias Ringwald 
26967bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
26979ab95c90S[email protected]             // Change Connection Encryption keeps link key type
26989ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
26999ab95c90S[email protected]                 conn->link_key_type = link_key_type;
27009ab95c90S[email protected]             }
2701e9f98c4aSMatthias Ringwald             // cache link key. link keys stored in little-endian format for legacy reasons
2702e9f98c4aSMatthias Ringwald             memcpy(&conn->link_key, &packet[8], 16);
2703e9f98c4aSMatthias Ringwald 
2704bec5f683SMatthias Ringwald             // only store link key:
2705bec5f683SMatthias Ringwald             // - if bondable enabled
2706bec5f683SMatthias Ringwald             if (hci_stack->bondable == false) break;
27076edaed7fSMatthias Ringwald             // - if security level sufficient
27086edaed7fSMatthias Ringwald             if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break;
2709bec5f683SMatthias Ringwald             // - for SSP, also check if remote side requested bonding as well
2710bec5f683SMatthias Ringwald             if (conn->link_key_type != COMBINATION_KEY){
2711532454f9SMatthias Ringwald                 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2712532454f9SMatthias Ringwald                 if (!remote_bonding){
2713bec5f683SMatthias Ringwald                     break;
2714bec5f683SMatthias Ringwald                 }
2715bec5f683SMatthias Ringwald             }
271655597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
27177fde4af9Smatthias.ringwald             break;
27189ab95c90S[email protected]         }
27197fde4af9Smatthias.ringwald 
27207fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
27211714cbbdSMatthias Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
27221714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
27231714cbbdSMatthias Ringwald             if (!conn) break;
27241714cbbdSMatthias Ringwald 
27251714cbbdSMatthias Ringwald             hci_pairing_started(conn, false);
272650dcc63cSMatthias Ringwald             // abort pairing if: non-bondable mode (event is not forwarded to app)
27273a9fb326S[email protected]             if (!hci_stack->bondable ){
27288daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
27291714cbbdSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED);
2730f8fb5f6eS[email protected]                 hci_run();
2731f8fb5f6eS[email protected]                 return;
27324c57c146S[email protected]             }
273350dcc63cSMatthias Ringwald             // abort pairing if: Secure Connections Only mode (event is not forwarded to app)
273450dcc63cSMatthias Ringwald             if (hci_stack->gap_secure_connections_only_mode){
273550dcc63cSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST;
273650dcc63cSMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
273750dcc63cSMatthias Ringwald                 hci_run();
273850dcc63cSMatthias Ringwald                 return;
273950dcc63cSMatthias Ringwald             }
27407fde4af9Smatthias.ringwald             break;
27417fde4af9Smatthias.ringwald 
274250d7398cSMatthias Ringwald         case HCI_EVENT_IO_CAPABILITY_RESPONSE:
274350d7398cSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
274450d7398cSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
274550d7398cSMatthias Ringwald             if (!conn) break;
27461714cbbdSMatthias Ringwald 
27478daf94bcSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE);
27481714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
274950d7398cSMatthias Ringwald             conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet);
2750e276e383SMatthias Ringwald             conn->io_cap_response_io       = hci_event_io_capability_response_get_io_capability(packet);
275150d7398cSMatthias Ringwald             break;
275250d7398cSMatthias Ringwald 
27531d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
27541714cbbdSMatthias Ringwald             hci_event_io_capability_response_get_bd_addr(packet, addr);
27551714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
27561714cbbdSMatthias Ringwald             if (!conn) break;
27571714cbbdSMatthias Ringwald 
27589671e615SMatthias Ringwald             hci_connection_timestamp(conn);
27599671e615SMatthias Ringwald 
27601714cbbdSMatthias Ringwald             hci_pairing_started(conn, true);
27619671e615SMatthias Ringwald 
27629671e615SMatthias Ringwald             // assess security
27639671e615SMatthias Ringwald             if ((hci_stack->gap_secure_connections_only_mode || (conn->requested_security_level == LEVEL_4)) && !hci_remote_sc_enabled(conn)){
27649671e615SMatthias Ringwald                 log_info("Level 4 required, but SC not supported -> abort");
27659671e615SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
27669671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
27679671e615SMatthias Ringwald                 break;
27689671e615SMatthias Ringwald             }
27699671e615SMatthias Ringwald 
277044565b0cSMatthias Ringwald #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
27718dbd6159SMatthias Ringwald             if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
27729671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
277311b03efaSMatthias Ringwald             } else {
27749671e615SMatthias Ringwald                 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
277511b03efaSMatthias Ringwald             }
277644565b0cSMatthias Ringwald #endif
2777dbe1a790S[email protected]             break;
2778dbe1a790S[email protected] 
27791849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
27801849becdSMatthias Ringwald         case HCI_EVENT_REMOTE_OOB_DATA_REQUEST:
27811849becdSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
27821849becdSMatthias Ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_REMOTE_OOB_DATA_REPLY);
27831849becdSMatthias Ringwald             break;
27841849becdSMatthias Ringwald #endif
27851849becdSMatthias Ringwald 
2786dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
278717c6fe5cSMatthias Ringwald             hci_event_user_confirmation_request_get_bd_addr(packet, addr);
2788*367aedc0SMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
2789*367aedc0SMatthias Ringwald             if (!conn) break;
2790*367aedc0SMatthias Ringwald             if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) {
2791*367aedc0SMatthias Ringwald                 if (hci_stack->ssp_auto_accept){
27928daf94bcSMatthias Ringwald                     hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
2793*367aedc0SMatthias Ringwald                 };
2794*367aedc0SMatthias Ringwald             } else {
2795*367aedc0SMatthias Ringwald                 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY);
2796*367aedc0SMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
2797*367aedc0SMatthias Ringwald                 // don't forward event to app
2798*367aedc0SMatthias Ringwald                 hci_run();
2799*367aedc0SMatthias Ringwald                 return;
2800*367aedc0SMatthias Ringwald             }
2801dbe1a790S[email protected]             break;
2802dbe1a790S[email protected] 
2803dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
2804*367aedc0SMatthias Ringwald             // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request
2805*367aedc0SMatthias Ringwald             if (hci_stack->ssp_auto_accept){
28068daf94bcSMatthias Ringwald                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
2807*367aedc0SMatthias Ringwald             };
28081d6b20aeS[email protected]             break;
28091849becdSMatthias Ringwald 
28103dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
28113dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
28123dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
28133dce6128SMatthias Ringwald             if (!conn) break;
28143dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
28153dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
28163dce6128SMatthias Ringwald             break;
281735454696SMatthias Ringwald #endif
28181d6b20aeS[email protected] 
2819f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
2820254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
2821f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
2822f0944df2S[email protected]             if (!conn) break;
28234ea43905SMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == 0u) {
2824254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2825254b78eeSMatthias Ringwald                 if (encryption_enabled){
2826573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
2827573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
28288daf94bcSMatthias Ringwald                         conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED;
2829573897a0SMatthias Ringwald                     }
2830573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
2831573897a0SMatthias Ringwald                     else {
2832fcaf38b9SMatthias Ringwald 
2833fcaf38b9SMatthias Ringwald                         // dedicated bonding: send result and disconnect
2834fcaf38b9SMatthias Ringwald                         if (conn->bonding_flags & BONDING_DEDICATED){
2835fcaf38b9SMatthias Ringwald                             conn->bonding_flags &= ~BONDING_DEDICATED;
2836fcaf38b9SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2837fcaf38b9SMatthias Ringwald                             conn->bonding_status = packet[2];
2838fcaf38b9SMatthias Ringwald                             break;
2839fcaf38b9SMatthias Ringwald                         }
2840fcaf38b9SMatthias Ringwald 
2841254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2842254b78eeSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2843254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2844edc1ac20SMatthias Ringwald                         if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){
2845254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
28469ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2847254b78eeSMatthias Ringwald                             break;
2848254b78eeSMatthias Ringwald                         }
2849254b78eeSMatthias Ringwald 
28506e058d3fSMatthias Ringwald                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
28516e058d3fSMatthias Ringwald                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
2852573897a0SMatthias Ringwald                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
28536e058d3fSMatthias Ringwald                         } else {
28546e058d3fSMatthias Ringwald                             // if not, pretend everything is perfect
28559866fdc7SMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, 16);
28566e058d3fSMatthias Ringwald                         }
2857573897a0SMatthias Ringwald                     }
2858573897a0SMatthias Ringwald #endif
2859f0944df2S[email protected]                 } else {
28608daf94bcSMatthias Ringwald                     conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED;
2861f0944df2S[email protected]                 }
2862ad83dc6aS[email protected]             }
2863573897a0SMatthias Ringwald 
2864f0944df2S[email protected]             break;
2865f0944df2S[email protected] 
286635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
28671eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2868abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
28691eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
28701eb2563eS[email protected]             if (!conn) break;
2871ad83dc6aS[email protected] 
2872dbd5dcc3SMatthias Ringwald             // clear authentication active flag
2873dbd5dcc3SMatthias Ringwald             conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST;
28741714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet));
2875dbd5dcc3SMatthias Ringwald 
2876abdad579SMatthias Ringwald             // authenticated only if auth status == 0
2877abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
2878abdad579SMatthias Ringwald                 // authenticated
28798daf94bcSMatthias Ringwald                 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED;
2880abdad579SMatthias Ringwald 
2881131ef17aSMatthias Ringwald                 // If not already encrypted, start encryption
28828daf94bcSMatthias Ringwald                 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){
28831eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2884ad83dc6aS[email protected]                     break;
2885ad83dc6aS[email protected]                 }
2886abdad579SMatthias Ringwald             }
2887abdad579SMatthias Ringwald 
2888abdad579SMatthias Ringwald             // emit updated security level
28891cf0a6c8SMatthias Ringwald             conn->requested_security_level = LEVEL_0;
28901eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
28911eb2563eS[email protected]             break;
28921714cbbdSMatthias Ringwald 
28931714cbbdSMatthias Ringwald         case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
28941714cbbdSMatthias Ringwald             hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
28951714cbbdSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
28961714cbbdSMatthias Ringwald             if (!conn) break;
28971714cbbdSMatthias Ringwald 
28981714cbbdSMatthias Ringwald             hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet));
28991714cbbdSMatthias Ringwald             break;
290035454696SMatthias Ringwald #endif
290134d2123cS[email protected] 
290286805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
2903ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
2904ccda6e14S[email protected]         // see end of function, too.
2905a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
2906a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
2907f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
290881d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
29094ea43905SMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0u) {
2910c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
29114ea43905SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u;
291281d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2913c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
2914c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
291581d2bdb2SMatthias Ringwald                     if (release_buffer){
291681d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
291781d2bdb2SMatthias Ringwald                     }
2918c6a37cfdSMatthias Ringwald                 }
2919c6a37cfdSMatthias Ringwald             }
292035454696SMatthias Ringwald 
2921c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
2922c6a37cfdSMatthias Ringwald             if (!conn) break;
29231714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
29241714cbbdSMatthias Ringwald             // pairing failed if it was ongoing
29251714cbbdSMatthias Ringwald             hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
29261714cbbdSMatthias Ringwald #endif
2927046ec007SMatthias Ringwald             // mark connection for shutdown
2928a70e17d4SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2929046ec007SMatthias Ringwald 
2930046ec007SMatthias Ringwald             // emit dedicatd bonding event
2931046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2932046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2933046ec007SMatthias Ringwald             }
2934046ec007SMatthias Ringwald 
293535454696SMatthias Ringwald #ifdef ENABLE_BLE
2936d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2937046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
29382b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
2939bbc366e6SMatthias Ringwald                 hci_update_advertisements_enabled_for_current_roles();
29409a2e4658SMatthias Ringwald             }
294135454696SMatthias Ringwald #endif
2942d70217a2SMatthias Ringwald #endif
2943ccda6e14S[email protected]             break;
29446772a24cSmatthias.ringwald 
2945c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
2946313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
2947d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
2948c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
29497586ee35S[email protected]             } else {
29507586ee35S[email protected]                 // if no special requests, just reboot stack
29517586ee35S[email protected]                 hci_power_control_off();
29527586ee35S[email protected]                 hci_power_control_on();
2953c68bdf90Smatthias.ringwald             }
2954c68bdf90Smatthias.ringwald             break;
2955c68bdf90Smatthias.ringwald 
29560e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
29575cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
29585cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
2959c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
2960f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
2961c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2962c4c88f1bSJakob Krantz             if (!conn) break;
29635cf766e8SMatthias Ringwald             conn->role = packet[9];
29645cf766e8SMatthias Ringwald             break;
29650e6f3837SMatthias Ringwald #endif
29665cf766e8SMatthias Ringwald 
296763fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2968d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
29694fa24b5fS[email protected]             if (hci_transport_synchronous()) {
297063fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
29714fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
29724fa24b5fS[email protected]             }
297381d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
2974d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
2975d051460cS[email protected]             hci_release_packet_buffer();
2976701e3307SMatthias Ringwald 
297763fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
297863fa3374SMatthias Ringwald 
297935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
298063fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
2981701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
298235454696SMatthias Ringwald #endif
29836b4af23dS[email protected]             break;
29846b4af23dS[email protected] 
298535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
298663fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
298763fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
2988f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 1;
298963fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
299063fa3374SMatthias Ringwald             return;
29911cfb383eSMatthias Ringwald 
29921cfb383eSMatthias Ringwald         // explode inquriy results for easier consumption
29931cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
29941cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
29951cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
29969784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
29971cfb383eSMatthias Ringwald             break;
299835454696SMatthias Ringwald #endif
299963fa3374SMatthias Ringwald 
3000a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
30015909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
30025909f7f2Smatthias.ringwald             switch (packet[2]){
3003d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
300457c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
30054f4e0224SMatthias Ringwald                     // log_info("advertising report received");
30066fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
300757c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
30087bdc6798S[email protected]                     break;
3009d70217a2SMatthias Ringwald #endif
30105909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
30110ce3f217SMatthias Ringwald 					event_handle_le_connection_complete(packet);
30125909f7f2Smatthias.ringwald                     break;
30135909f7f2Smatthias.ringwald 
3014f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
3015c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
3016c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
3017c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
3018c9db5c21SMilanka Ringwald                     if (!conn) break;
3019c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
3020c9db5c21SMilanka Ringwald                     break;
302165a46ef3S[email protected] 
302273cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
302373cd8a2aSMatthias Ringwald                     // connection
302473cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
302573cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
302673cd8a2aSMatthias Ringwald                     if (conn) {
302773cd8a2aSMatthias Ringwald                         // read arguments
302873cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
302973cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
303073cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
303173cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
303273cd8a2aSMatthias Ringwald 
303373cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
303473cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
303573cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
303673cd8a2aSMatthias 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);
303773cd8a2aSMatthias Ringwald                         if (update_parameter){
303873cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
303973cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
304073cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
304173cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
304273cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
304373cd8a2aSMatthias Ringwald                         } else {
3044c3898ca4SMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY;
304573cd8a2aSMatthias Ringwald                         }
304673cd8a2aSMatthias Ringwald                     }
304773cd8a2aSMatthias Ringwald                     break;
30480f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
30490f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
30500f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
30510f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
30520f3b27c5SMatthias Ringwald                     if (conn) {
30530f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
30540f3b27c5SMatthias Ringwald                     }
30550f3b27c5SMatthias Ringwald                     break;
30560f3b27c5SMatthias Ringwald #endif
30575909f7f2Smatthias.ringwald                 default:
30585909f7f2Smatthias.ringwald                     break;
30595909f7f2Smatthias.ringwald             }
30605909f7f2Smatthias.ringwald             break;
30615909f7f2Smatthias.ringwald #endif
30620b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
30630b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
30640b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
30650b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
30660b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
30670b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
30680b36101dSMatthias Ringwald                     break;
30690b36101dSMatthias Ringwald                 default:
30700b36101dSMatthias Ringwald                     break;
30710b36101dSMatthias Ringwald             }
30720b36101dSMatthias Ringwald             break;
30736772a24cSmatthias.ringwald         default:
30746772a24cSmatthias.ringwald             break;
3075fe1ed1b8Smatthias.ringwald     }
3076fe1ed1b8Smatthias.ringwald 
307767c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
307889db417bSmatthias.ringwald 
307986805605S[email protected]     // notify upper stack
3080d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
308194ab26f8Smatthias.ringwald 
308286805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
3083797b2a3fSMatthias Ringwald     if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){
3084f8fbdce0SMatthias Ringwald 		handle = little_endian_read_16(packet, 3);
308505ae8de3SMatthias Ringwald 		hci_connection_t * aConn = hci_connection_for_handle(handle);
3086046ec007SMatthias Ringwald 		// discard connection if app did not trigger a reconnect in the event handler
3087797b2a3fSMatthias Ringwald 		if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
308805ae8de3SMatthias Ringwald 			hci_shutdown_connection(aConn);
3089b0136355SMatthias Ringwald 		}
309086805605S[email protected]     }
309186805605S[email protected] 
309294ab26f8Smatthias.ringwald 	// execute main loop
309394ab26f8Smatthias.ringwald 	hci_run();
309416833f0aSmatthias.ringwald }
309516833f0aSmatthias.ringwald 
309635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
30976f28d2eeSMatthias Ringwald 
30986be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
30996f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
31006f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn);
31016f28d2eeSMatthias Ringwald 
31026f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
310359c33575SMatthias Ringwald     log_debug("SCO TX Timeout");
31045a6b2dbdSMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
31056f28d2eeSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
31066f28d2eeSMatthias Ringwald     if (!conn) return;
31076f28d2eeSMatthias Ringwald 
3108afaddd67SMatthias Ringwald     // trigger send
3109afaddd67SMatthias Ringwald     conn->sco_tx_ready = 1;
3110e4157653SMatthias Ringwald     // extra packet if CVSD but SCO buffer is too short
3111a1df452eSMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
3112e4157653SMatthias Ringwald         conn->sco_tx_ready++;
3113e4157653SMatthias Ringwald     }
3114afaddd67SMatthias Ringwald     hci_notify_if_sco_can_send_now();
31156f28d2eeSMatthias Ringwald }
31166f28d2eeSMatthias Ringwald 
311759c33575SMatthias Ringwald 
311859c33575SMatthias Ringwald #define SCO_TX_AFTER_RX_MS (6)
311959c33575SMatthias Ringwald 
31206f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn){
312159c33575SMatthias Ringwald 
31226f28d2eeSMatthias Ringwald     uint32_t now = btstack_run_loop_get_time_ms();
312359c33575SMatthias Ringwald     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
312459c33575SMatthias Ringwald     int time_delta_ms = sco_tx_ms - now;
312559c33575SMatthias Ringwald 
312659c33575SMatthias Ringwald     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
312759c33575SMatthias Ringwald 
312859c33575SMatthias Ringwald     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
312959c33575SMatthias Ringwald     btstack_run_loop_set_timer(timer, time_delta_ms);
313059c33575SMatthias Ringwald     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
313159c33575SMatthias Ringwald     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
313259c33575SMatthias Ringwald     btstack_run_loop_add_timer(timer);
31336f28d2eeSMatthias Ringwald }
31346be3cf7fSMatthias Ringwald #endif
31356f28d2eeSMatthias Ringwald 
3136c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
31370b3f95dfSMatthias Ringwald     // lookup connection struct
31382b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
31392b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
31400b3f95dfSMatthias Ringwald     if (!conn) return;
31410b3f95dfSMatthias Ringwald 
31426be3cf7fSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3143760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
3144760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
3145a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
3146760b20efSMatthias Ringwald             packet[2] = 0x3c;
3147760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
3148760b20efSMatthias Ringwald             size = 63;
31490b3f95dfSMatthias Ringwald         }
31500b3f95dfSMatthias Ringwald     }
3151760b20efSMatthias Ringwald 
3152f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
3153f234b250SMatthias Ringwald         // Nothing to do
3154f234b250SMatthias Ringwald     } else {
315549205f5dSMatthias 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);
3156760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
31576f28d2eeSMatthias Ringwald             uint32_t now = btstack_run_loop_get_time_ms();
315859c33575SMatthias Ringwald 
315959c33575SMatthias Ringwald             if (!conn->sco_rx_valid){
316059c33575SMatthias Ringwald                 // ignore first 10 packets
31616f28d2eeSMatthias Ringwald                 conn->sco_rx_count++;
316259c33575SMatthias Ringwald                 // log_debug("sco rx count %u", conn->sco_rx_count);
316359c33575SMatthias Ringwald                 if (conn->sco_rx_count == 10) {
316459c33575SMatthias Ringwald                     // use first timestamp as is and pretent it just started
31656f28d2eeSMatthias Ringwald                     conn->sco_rx_ms = now;
31666f28d2eeSMatthias Ringwald                     conn->sco_rx_valid = 1;
316759c33575SMatthias Ringwald                     conn->sco_rx_count = 0;
316859c33575SMatthias Ringwald                     sco_schedule_tx(conn);
316959c33575SMatthias Ringwald                 }
317059c33575SMatthias Ringwald             } else {
317159c33575SMatthias Ringwald                 // track expected arrival timme
317259c33575SMatthias Ringwald                 conn->sco_rx_count++;
317359c33575SMatthias Ringwald                 conn->sco_rx_ms += 7;
317459c33575SMatthias Ringwald                 int delta = (int32_t) (now - conn->sco_rx_ms);
317559c33575SMatthias Ringwald                 if (delta > 0){
317659c33575SMatthias Ringwald                     conn->sco_rx_ms++;
317759c33575SMatthias Ringwald                 }
317859c33575SMatthias Ringwald                 // log_debug("sco rx %u", conn->sco_rx_ms);
31796f28d2eeSMatthias Ringwald                 sco_schedule_tx(conn);
31806f28d2eeSMatthias Ringwald             }
3181760b20efSMatthias Ringwald         }
3182f234b250SMatthias Ringwald     }
31836be3cf7fSMatthias Ringwald #endif
31846be3cf7fSMatthias Ringwald 
31850b3f95dfSMatthias Ringwald     // deliver to app
31860b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
31870b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
31880b3f95dfSMatthias Ringwald     }
31890b3f95dfSMatthias Ringwald 
3190ed325439SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3191ed325439SMatthias Ringwald     // We can send one packet for each received packet
3192ed325439SMatthias Ringwald     conn->sco_tx_ready++;
3193ed325439SMatthias Ringwald     hci_notify_if_sco_can_send_now();
3194ed325439SMatthias Ringwald #endif
3195ed325439SMatthias Ringwald 
31960b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
31972b838201SMatthias Ringwald     conn->num_packets_completed++;
31982b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
31992b838201SMatthias Ringwald     hci_run();
32002b838201SMatthias Ringwald #endif
3201c91d150bS[email protected] }
320235454696SMatthias Ringwald #endif
3203c91d150bS[email protected] 
32040a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
32055bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
320610e830c9Smatthias.ringwald     switch (packet_type) {
320710e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
320810e830c9Smatthias.ringwald             event_handler(packet, size);
320910e830c9Smatthias.ringwald             break;
321010e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
321110e830c9Smatthias.ringwald             acl_handler(packet, size);
321210e830c9Smatthias.ringwald             break;
321335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3214c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
3215c91d150bS[email protected]             sco_handler(packet, size);
3216202c8a4cSMatthias Ringwald             break;
321735454696SMatthias Ringwald #endif
321810e830c9Smatthias.ringwald         default:
321910e830c9Smatthias.ringwald             break;
322010e830c9Smatthias.ringwald     }
322110e830c9Smatthias.ringwald }
322210e830c9Smatthias.ringwald 
3223d6b06661SMatthias Ringwald /**
3224d6b06661SMatthias Ringwald  * @brief Add event packet handler.
3225d6b06661SMatthias Ringwald  */
3226d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3227d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
3228d6b06661SMatthias Ringwald }
3229d6b06661SMatthias Ringwald 
3230d6b06661SMatthias Ringwald 
3231fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
32323d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
3233fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
323416833f0aSmatthias.ringwald }
323516833f0aSmatthias.ringwald 
323635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
32378abbe8b5SMatthias Ringwald /**
32388abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
32398abbe8b5SMatthias Ringwald  */
32403d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
32418abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
32428abbe8b5SMatthias Ringwald }
324335454696SMatthias Ringwald #endif
32448abbe8b5SMatthias Ringwald 
324571de195eSMatthias Ringwald static void hci_state_reset(void){
3246595bdbfbS[email protected]     // no connections yet
3247595bdbfbS[email protected]     hci_stack->connections = NULL;
324874308b23Smatthias.ringwald 
324974308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
325074308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
325174308b23Smatthias.ringwald     // hci_stack->connectable = 0;
325274308b23Smatthias.ringwald     // hci_stack->bondable = 1;
3253b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
3254595bdbfbS[email protected] 
325544935e40S[email protected]     // buffer is free
325644935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
325744935e40S[email protected] 
3258595bdbfbS[email protected]     // no pending cmds
3259595bdbfbS[email protected]     hci_stack->decline_reason = 0;
3260595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
3261595bdbfbS[email protected] 
3262c214d65bSMatthias Ringwald     hci_stack->secure_connections_active = false;
3263c214d65bSMatthias Ringwald 
3264bea424a5SMatthias Ringwald #ifdef ENABLE_CLASSIC
3265bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = 0xffff;
3266bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = 0xffff;
3267bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = 0xff;
3268496bb884SMatthias Ringwald     hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY;
3269bea424a5SMatthias Ringwald #endif
3270bea424a5SMatthias Ringwald 
3271cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
3272cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
3273cf01e888SMatthias Ringwald #endif
3274cf01e888SMatthias Ringwald 
3275595bdbfbS[email protected]     // LE
3276b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
3277b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
3278b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
3279d70217a2SMatthias Ringwald #endif
3280d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3281a61834b6SMatthias Ringwald     hci_stack->le_scanning_active  = false;
3282b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3283d5b1a89eSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
3284e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
3285d70217a2SMatthias Ringwald #endif
3286a61834b6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3287a61834b6SMatthias Ringwald     hci_stack->le_advertisements_active = false;
3288a61834b6SMatthias Ringwald     if ((hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_PARAMS_SET) != 0){
3289a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3290a61834b6SMatthias Ringwald     }
3291a61834b6SMatthias Ringwald     if (hci_stack->le_advertisements_data != NULL){
3292a61834b6SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3293a61834b6SMatthias Ringwald     }
3294a61834b6SMatthias Ringwald #endif
3295595bdbfbS[email protected] }
3296595bdbfbS[email protected] 
329735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
32982d5e09d6SMatthias Ringwald /**
32992d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
33002d5e09d6SMatthias Ringwald  */
33012d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
33022d5e09d6SMatthias Ringwald     // store and open remote device db
33032d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
33042d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
33052d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
33062d5e09d6SMatthias Ringwald     }
33072d5e09d6SMatthias Ringwald }
330835454696SMatthias Ringwald #endif
33092d5e09d6SMatthias Ringwald 
33102d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
3311475c8125Smatthias.ringwald 
33123a9fb326S[email protected] #ifdef HAVE_MALLOC
33133a9fb326S[email protected]     if (!hci_stack) {
33143a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
33153a9fb326S[email protected]     }
33163a9fb326S[email protected] #else
33173a9fb326S[email protected]     hci_stack = &hci_stack_static;
33183a9fb326S[email protected] #endif
331966fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
33203a9fb326S[email protected] 
3321475c8125Smatthias.ringwald     // reference to use transport layer implementation
33223a9fb326S[email protected]     hci_stack->hci_transport = transport;
3323475c8125Smatthias.ringwald 
332411e23e5fSmatthias.ringwald     // reference to used config
33253a9fb326S[email protected]     hci_stack->config = config;
332611e23e5fSmatthias.ringwald 
332726a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
332826a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
332926a9b6daSMatthias Ringwald 
33308fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
33313a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
33328fcba05dSmatthias.ringwald 
333316833f0aSmatthias.ringwald     // register packet handlers with transport
333410e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
3335f5454fc6Smatthias.ringwald 
33363a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
3337e2386ba1S[email protected] 
3338e2386ba1S[email protected]     // class of device
33393a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
3340a45d6b9fS[email protected] 
3341f20168b8Smatthias.ringwald     // bondable by default
3342f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
3343f20168b8Smatthias.ringwald 
3344e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
334563168530SMatthias Ringwald     // classic name
334663168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
3347c4c88f1bSJakob Krantz 
3348c4c88f1bSJakob Krantz     // Master slave policy
3349c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
3350170fafaeSMatthias Ringwald 
3351b4eb4420SMatthias Ringwald     // Allow Role Switch
3352b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
3353b4eb4420SMatthias Ringwald 
335478315a58SMatthias Ringwald     // Default / minimum security level = 2
335578315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
335678315a58SMatthias Ringwald 
33575dbec6b3SMatthias Ringwald     // Default Security Mode 4
33585dbec6b3SMatthias Ringwald     hci_stack->gap_security_mode = GAP_SECURITY_MODE_4;
33595dbec6b3SMatthias Ringwald 
3360cd345294SMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3
3361cd345294SMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 7;
3362d821984bSMatthias Ringwald 
3363d821984bSMatthias Ringwald     // Link Supervision Timeout
3364d821984bSMatthias Ringwald     hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT;
3365d821984bSMatthias Ringwald 
3366e9f343c8SMatthias Ringwald #endif
336763168530SMatthias Ringwald 
336863048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
33693a9fb326S[email protected]     hci_stack->ssp_enable = 1;
33703a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
33713a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
33723a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
337369a97523S[email protected] 
33745d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
33755d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
33765d23aae8SMatthias Ringwald 
3377fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
3378fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
3379d950d659SMatthias Ringwald 
3380831711daSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3381831711daSMatthias Ringwald     // connection parameter to use for outgoing connections
3382cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3383cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3384831711daSMatthias Ringwald     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3385831711daSMatthias Ringwald     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3386831711daSMatthias Ringwald     hci_stack->le_connection_latency      = 4;         // 4
3387831711daSMatthias Ringwald     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3388831711daSMatthias Ringwald     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3389831711daSMatthias Ringwald     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
33907261e5d8SMatthias Ringwald 
33917261e5d8SMatthias Ringwald     // default LE Scanning
33928b69e4c7SMatthias Ringwald     hci_stack->le_scan_type     =   0x1; // active
33938b69e4c7SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0; // 300 ms
33948b69e4c7SMatthias Ringwald     hci_stack->le_scan_window   =  0x30; //  30 ms
3395831711daSMatthias Ringwald #endif
3396831711daSMatthias Ringwald 
33972b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
33982b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
33992b6ab3e6SMatthias Ringwald #endif
34002b6ab3e6SMatthias Ringwald 
3401831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
3402831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3403831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3404831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3405831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3406831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3407831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3408831711daSMatthias Ringwald 
3409595bdbfbS[email protected]     hci_state_reset();
3410475c8125Smatthias.ringwald }
3411475c8125Smatthias.ringwald 
34124688f216SMatthias Ringwald void hci_deinit(void){
34134688f216SMatthias Ringwald #ifdef HAVE_MALLOC
34144688f216SMatthias Ringwald     if (hci_stack) {
34154688f216SMatthias Ringwald         free(hci_stack);
34164688f216SMatthias Ringwald     }
34174688f216SMatthias Ringwald #endif
34184688f216SMatthias Ringwald     hci_stack = NULL;
3419b5bbcbf4SMatthias Ringwald 
3420b5bbcbf4SMatthias Ringwald #ifdef ENABLE_CLASSIC
34214688f216SMatthias Ringwald     disable_l2cap_timeouts = 0;
3422b5bbcbf4SMatthias Ringwald #endif
34234688f216SMatthias Ringwald }
34244688f216SMatthias Ringwald 
34253fb36a29SMatthias Ringwald /**
34263fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
34273fb36a29SMatthias Ringwald  */
34283fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
34293fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
34303fb36a29SMatthias Ringwald 
34313fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
34323fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
34333fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
34343fb36a29SMatthias Ringwald     }
34353fb36a29SMatthias Ringwald }
34363fb36a29SMatthias Ringwald 
3437fb55bd0aSMatthias Ringwald /**
3438d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3439fb55bd0aSMatthias Ringwald  */
3440fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
3441fb55bd0aSMatthias Ringwald     // references to used control implementation
3442fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
3443d0b87befSMatthias Ringwald     // init with transport config
3444d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
3445fb55bd0aSMatthias Ringwald }
3446fb55bd0aSMatthias Ringwald 
344771de195eSMatthias Ringwald void hci_close(void){
3448e6d6524dSMatthias Ringwald 
3449e6d6524dSMatthias Ringwald #ifdef ENABLE_CLASSIC
3450404843c1Smatthias.ringwald     // close remote device db
3451a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
3452a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
3453404843c1Smatthias.ringwald     }
3454e6d6524dSMatthias Ringwald #endif
34557224be7eSMatthias Ringwald 
34567224be7eSMatthias Ringwald     btstack_linked_list_iterator_t lit;
34577224be7eSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
34587224be7eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
34597224be7eSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
34607224be7eSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
34617224be7eSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
34627224be7eSMatthias Ringwald         hci_shutdown_connection(connection);
3463f5454fc6Smatthias.ringwald     }
34647224be7eSMatthias Ringwald 
3465f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
34663a9fb326S[email protected] 
34673a9fb326S[email protected] #ifdef HAVE_MALLOC
34683a9fb326S[email protected]     free(hci_stack);
34693a9fb326S[email protected] #endif
34703a9fb326S[email protected]     hci_stack = NULL;
3471404843c1Smatthias.ringwald }
3472404843c1Smatthias.ringwald 
3473cb70c5abSMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
3474cb70c5abSMatthias Ringwald void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){
3475cb70c5abSMatthias Ringwald     hci_stack->sco_transport = sco_transport;
3476cb70c5abSMatthias Ringwald     sco_transport->register_packet_handler(&packet_handler);
3477cb70c5abSMatthias Ringwald }
3478cb70c5abSMatthias Ringwald #endif
3479cb70c5abSMatthias Ringwald 
348035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3481170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3482170fafaeSMatthias Ringwald     // validate ranage and set
3483170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
3484170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
3485170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3486170fafaeSMatthias Ringwald }
348778315a58SMatthias Ringwald 
3488137715ebSMatthias Ringwald uint8_t gap_set_security_mode(gap_security_mode_t security_mode){
3489137715ebSMatthias Ringwald     if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){
34905dbec6b3SMatthias Ringwald         hci_stack->gap_security_mode = security_mode;
3491137715ebSMatthias Ringwald         return ERROR_CODE_SUCCESS;
3492137715ebSMatthias Ringwald     } else {
3493137715ebSMatthias Ringwald         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3494137715ebSMatthias Ringwald     }
34955dbec6b3SMatthias Ringwald }
34965dbec6b3SMatthias Ringwald 
34975dbec6b3SMatthias Ringwald gap_security_mode_t gap_get_security_mode(void){
34985dbec6b3SMatthias Ringwald     return hci_stack->gap_security_mode;
34995dbec6b3SMatthias Ringwald }
35005dbec6b3SMatthias Ringwald 
350178315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
350278315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
350378315a58SMatthias Ringwald }
350478315a58SMatthias Ringwald 
350578315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
350678315a58SMatthias Ringwald     return hci_stack->gap_security_level;
350778315a58SMatthias Ringwald }
350830cdf3c6SMatthias Ringwald 
350930cdf3c6SMatthias Ringwald void gap_set_secure_connections_only_mode(bool enable){
351030cdf3c6SMatthias Ringwald     hci_stack->gap_secure_connections_only_mode = enable;
351130cdf3c6SMatthias Ringwald }
351230cdf3c6SMatthias Ringwald 
351330cdf3c6SMatthias Ringwald bool gap_get_secure_connections_only_mode(void){
351430cdf3c6SMatthias Ringwald     return hci_stack->gap_secure_connections_only_mode;
351530cdf3c6SMatthias Ringwald }
3516170fafaeSMatthias Ringwald #endif
3517170fafaeSMatthias Ringwald 
3518170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
351960b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
35209e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
35219e61646fS[email protected] }
352276f27cffSMatthias Ringwald 
3523c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3524c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
3525c33e56d3SMatthias Ringwald }
3526c33e56d3SMatthias Ringwald 
3527b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
3528b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3529b4eb4420SMatthias Ringwald }
3530b4eb4420SMatthias Ringwald 
3531b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
3532b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
3533b4eb4420SMatthias Ringwald }
3534b4eb4420SMatthias Ringwald 
35350c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
35360c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
35370c3eb48dSMatthias Ringwald }
35380c3eb48dSMatthias Ringwald 
353976f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
354076f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
354176f27cffSMatthias Ringwald }
354235454696SMatthias Ringwald #endif
35439e61646fS[email protected] 
354476f27cffSMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3545f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3546f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
35476535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3548f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
3549f456b2d0S[email protected] }
355076f27cffSMatthias Ringwald #endif
3551f456b2d0S[email protected] 
35528d213e1aSmatthias.ringwald // State-Module-Driver overview
35538d213e1aSmatthias.ringwald // state                    module  low-level
35548d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
35558d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
35568d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
35578d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
3558d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
3559d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
3560c7e0c5f6Smatthias.ringwald 
356140d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
35627301ad89Smatthias.ringwald 
3563038bc64cSmatthias.ringwald     // power on
3564f9a30166Smatthias.ringwald     int err = 0;
35653a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
3566d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
3567f9a30166Smatthias.ringwald     }
3568038bc64cSmatthias.ringwald     if (err){
35699da54300S[email protected]         log_error( "POWER_ON failed");
3570038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3571038bc64cSmatthias.ringwald         return err;
3572038bc64cSmatthias.ringwald     }
3573038bc64cSmatthias.ringwald 
357424b3c629SMatthias Ringwald     // int chipset driver
35753fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
35763fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
35773fb36a29SMatthias Ringwald     }
35783fb36a29SMatthias Ringwald 
357924b3c629SMatthias Ringwald     // init transport
358024b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
358124b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
358224b3c629SMatthias Ringwald     }
358324b3c629SMatthias Ringwald 
358424b3c629SMatthias Ringwald     // open transport
358524b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
3586038bc64cSmatthias.ringwald     if (err){
35879da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
35883a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3589d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3590f9a30166Smatthias.ringwald         }
3591038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3592038bc64cSmatthias.ringwald         return err;
3593038bc64cSmatthias.ringwald     }
35948d213e1aSmatthias.ringwald     return 0;
35958d213e1aSmatthias.ringwald }
3596038bc64cSmatthias.ringwald 
359740d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
35988d213e1aSmatthias.ringwald 
35999da54300S[email protected]     log_info("hci_power_control_off");
36009418f9c9Smatthias.ringwald 
36018d213e1aSmatthias.ringwald     // close low-level device
360224b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
36038d213e1aSmatthias.ringwald 
36049da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
36059418f9c9Smatthias.ringwald 
36068d213e1aSmatthias.ringwald     // power off
36073a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
3608d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
36098d213e1aSmatthias.ringwald     }
36109418f9c9Smatthias.ringwald 
36119da54300S[email protected]     log_info("hci_power_control_off - control closed");
36129418f9c9Smatthias.ringwald 
36133a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
361472ea5239Smatthias.ringwald }
361572ea5239Smatthias.ringwald 
361640d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
361772ea5239Smatthias.ringwald 
36189da54300S[email protected]     log_info("hci_power_control_sleep");
36193144bce4Smatthias.ringwald 
3620b429b9b7Smatthias.ringwald #if 0
3621b429b9b7Smatthias.ringwald     // don't close serial port during sleep
3622b429b9b7Smatthias.ringwald 
362372ea5239Smatthias.ringwald     // close low-level device
36243a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
3625b429b9b7Smatthias.ringwald #endif
362672ea5239Smatthias.ringwald 
362772ea5239Smatthias.ringwald     // sleep mode
36283a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
3629d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
363072ea5239Smatthias.ringwald     }
3631b429b9b7Smatthias.ringwald 
36323a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
36338d213e1aSmatthias.ringwald }
36348d213e1aSmatthias.ringwald 
363540d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
3636b429b9b7Smatthias.ringwald 
36379da54300S[email protected]     log_info("hci_power_control_wake");
3638b429b9b7Smatthias.ringwald 
3639b429b9b7Smatthias.ringwald     // wake on
36403a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
3641d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
3642b429b9b7Smatthias.ringwald     }
3643b429b9b7Smatthias.ringwald 
3644b429b9b7Smatthias.ringwald #if 0
3645b429b9b7Smatthias.ringwald     // open low-level device
36463a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
3647b429b9b7Smatthias.ringwald     if (err){
36489da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
36493a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3650d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3651b429b9b7Smatthias.ringwald         }
3652b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
3653b429b9b7Smatthias.ringwald         return err;
3654b429b9b7Smatthias.ringwald     }
3655b429b9b7Smatthias.ringwald #endif
3656b429b9b7Smatthias.ringwald 
3657b429b9b7Smatthias.ringwald     return 0;
3658b429b9b7Smatthias.ringwald }
3659b429b9b7Smatthias.ringwald 
366044935e40S[email protected] static void hci_power_transition_to_initializing(void){
366144935e40S[email protected]     // set up state machine
366244935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
366344935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
366444935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
36655c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
366644935e40S[email protected] }
3667b429b9b7Smatthias.ringwald 
366842bd3d77SMatthias Ringwald // returns error
366942bd3d77SMatthias Ringwald static int hci_power_control_state_off(HCI_POWER_MODE power_mode){
367042bd3d77SMatthias Ringwald     int err;
36718d213e1aSmatthias.ringwald     switch (power_mode){
36728d213e1aSmatthias.ringwald         case HCI_POWER_ON:
36738d213e1aSmatthias.ringwald             err = hci_power_control_on();
367442bd3d77SMatthias Ringwald             if (err != 0) {
3675f04a0c31SMatthias Ringwald                 log_error("hci_power_control_on() error %d", err);
367697b61c7bS[email protected]                 return err;
367797b61c7bS[email protected]             }
367844935e40S[email protected]             hci_power_transition_to_initializing();
36798d213e1aSmatthias.ringwald             break;
36808d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
36818d213e1aSmatthias.ringwald             // do nothing
36828d213e1aSmatthias.ringwald             break;
36838d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3684b546ac54Smatthias.ringwald             // do nothing (with SLEEP == OFF)
36858d213e1aSmatthias.ringwald             break;
36867bbeb3adSMilanka Ringwald         default:
36877bbeb3adSMilanka Ringwald             btstack_assert(false);
36887bbeb3adSMilanka Ringwald             break;
36898d213e1aSmatthias.ringwald     }
369042bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
369142bd3d77SMatthias Ringwald }
36927301ad89Smatthias.ringwald 
369342bd3d77SMatthias Ringwald static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){
36948d213e1aSmatthias.ringwald     switch (power_mode){
36958d213e1aSmatthias.ringwald         case HCI_POWER_ON:
36968d213e1aSmatthias.ringwald             // do nothing
36978d213e1aSmatthias.ringwald             break;
36988d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
36998d213e1aSmatthias.ringwald             // no connections yet, just turn it off
37008d213e1aSmatthias.ringwald             hci_power_control_off();
37018d213e1aSmatthias.ringwald             break;
37028d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3703b546ac54Smatthias.ringwald             // no connections yet, just turn it off
370472ea5239Smatthias.ringwald             hci_power_control_sleep();
37058d213e1aSmatthias.ringwald             break;
37067bbeb3adSMilanka Ringwald         default:
37077bbeb3adSMilanka Ringwald             btstack_assert(false);
37087bbeb3adSMilanka Ringwald             break;
37098d213e1aSmatthias.ringwald     }
371042bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
371142bd3d77SMatthias Ringwald }
37127301ad89Smatthias.ringwald 
371342bd3d77SMatthias Ringwald static int hci_power_control_state_working(HCI_POWER_MODE power_mode) {
37148d213e1aSmatthias.ringwald     switch (power_mode){
37158d213e1aSmatthias.ringwald         case HCI_POWER_ON:
37168d213e1aSmatthias.ringwald             // do nothing
37178d213e1aSmatthias.ringwald             break;
37188d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
3719c7e0c5f6Smatthias.ringwald             // see hci_run
37203a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3721beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
37228d213e1aSmatthias.ringwald             break;
37238d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3724b546ac54Smatthias.ringwald             // see hci_run
37253a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
372674b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
37278d213e1aSmatthias.ringwald             break;
37287bbeb3adSMilanka Ringwald         default:
37297bbeb3adSMilanka Ringwald             btstack_assert(false);
37307bbeb3adSMilanka Ringwald             break;
37318d213e1aSmatthias.ringwald     }
373242bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
373342bd3d77SMatthias Ringwald }
37347301ad89Smatthias.ringwald 
373542bd3d77SMatthias Ringwald static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) {
37368d213e1aSmatthias.ringwald     switch (power_mode){
37378d213e1aSmatthias.ringwald         case HCI_POWER_ON:
373844935e40S[email protected]             hci_power_transition_to_initializing();
37398d213e1aSmatthias.ringwald             break;
37408d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
37418d213e1aSmatthias.ringwald             // do nothing
37428d213e1aSmatthias.ringwald             break;
37438d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3744b546ac54Smatthias.ringwald             // see hci_run
37453a9fb326S[email protected]             hci_stack->state = HCI_STATE_FALLING_ASLEEP;
374674b323a9SMatthias Ringwald             hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
37478d213e1aSmatthias.ringwald             break;
37487bbeb3adSMilanka Ringwald         default:
37497bbeb3adSMilanka Ringwald             btstack_assert(false);
37507bbeb3adSMilanka Ringwald             break;
37518d213e1aSmatthias.ringwald     }
375200278272SMatthias Ringwald     return ERROR_CODE_SUCCESS;
375342bd3d77SMatthias Ringwald }
37548d213e1aSmatthias.ringwald 
375542bd3d77SMatthias Ringwald static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) {
37568d213e1aSmatthias.ringwald     switch (power_mode){
37578d213e1aSmatthias.ringwald         case HCI_POWER_ON:
375828171530Smatthias.ringwald 
3759423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
376028171530Smatthias.ringwald             // nothing to do, if H4 supports power management
3761d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
37623a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
376374b323a9SMatthias Ringwald                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
376428171530Smatthias.ringwald                         break;
376528171530Smatthias.ringwald                     }
376628171530Smatthias.ringwald #endif
376744935e40S[email protected]             hci_power_transition_to_initializing();
37688d213e1aSmatthias.ringwald             break;
37698d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
3770b546ac54Smatthias.ringwald             // see hci_run
37713a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3772beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
37738d213e1aSmatthias.ringwald             break;
37748d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3775b546ac54Smatthias.ringwald             // do nothing
37768d213e1aSmatthias.ringwald             break;
37777bbeb3adSMilanka Ringwald         default:
37787bbeb3adSMilanka Ringwald             btstack_assert(false);
37797bbeb3adSMilanka Ringwald             break;
37808d213e1aSmatthias.ringwald     }
378142bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
378242bd3d77SMatthias Ringwald }
37838d213e1aSmatthias.ringwald 
378442bd3d77SMatthias Ringwald static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) {
378542bd3d77SMatthias Ringwald     int err;
37868d213e1aSmatthias.ringwald     switch (power_mode){
37878d213e1aSmatthias.ringwald         case HCI_POWER_ON:
3788423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
378928171530Smatthias.ringwald             // nothing to do, if H4 supports power management
3790d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
37913a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
37925c363727SMatthias Ringwald                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3793758b46ceSmatthias.ringwald                         hci_update_scan_enable();
379428171530Smatthias.ringwald                         break;
379528171530Smatthias.ringwald                     }
379628171530Smatthias.ringwald #endif
37973144bce4Smatthias.ringwald             err = hci_power_control_wake();
37983144bce4Smatthias.ringwald             if (err) return err;
379944935e40S[email protected]             hci_power_transition_to_initializing();
38008d213e1aSmatthias.ringwald             break;
38018d213e1aSmatthias.ringwald         case HCI_POWER_OFF:
38023a9fb326S[email protected]             hci_stack->state = HCI_STATE_HALTING;
3803beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
38048d213e1aSmatthias.ringwald             break;
38058d213e1aSmatthias.ringwald         case HCI_POWER_SLEEP:
3806b546ac54Smatthias.ringwald             // do nothing
38078d213e1aSmatthias.ringwald             break;
38087bbeb3adSMilanka Ringwald         default:
38097bbeb3adSMilanka Ringwald             btstack_assert(false);
38107bbeb3adSMilanka Ringwald             break;
38118d213e1aSmatthias.ringwald     }
381242bd3d77SMatthias Ringwald     return ERROR_CODE_SUCCESS;
381342bd3d77SMatthias Ringwald }
38147bbeb3adSMilanka Ringwald 
381542bd3d77SMatthias Ringwald int hci_power_control(HCI_POWER_MODE power_mode){
381642bd3d77SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
381724f87726SMatthias Ringwald     int err = 0;
381842bd3d77SMatthias Ringwald     switch (hci_stack->state){
381942bd3d77SMatthias Ringwald         case HCI_STATE_OFF:
382042bd3d77SMatthias Ringwald             err = hci_power_control_state_off(power_mode);
382142bd3d77SMatthias Ringwald             break;
382242bd3d77SMatthias Ringwald         case HCI_STATE_INITIALIZING:
382342bd3d77SMatthias Ringwald             err = hci_power_control_state_initializing(power_mode);
382442bd3d77SMatthias Ringwald             break;
382542bd3d77SMatthias Ringwald         case HCI_STATE_WORKING:
382642bd3d77SMatthias Ringwald             err = hci_power_control_state_working(power_mode);
382742bd3d77SMatthias Ringwald             break;
382842bd3d77SMatthias Ringwald         case HCI_STATE_HALTING:
382942bd3d77SMatthias Ringwald             err = hci_power_control_state_halting(power_mode);
383042bd3d77SMatthias Ringwald             break;
383142bd3d77SMatthias Ringwald         case HCI_STATE_FALLING_ASLEEP:
383242bd3d77SMatthias Ringwald             err = hci_power_control_state_falling_asleep(power_mode);
383342bd3d77SMatthias Ringwald             break;
383442bd3d77SMatthias Ringwald         case HCI_STATE_SLEEPING:
383542bd3d77SMatthias Ringwald             err = hci_power_control_state_sleeping(power_mode);
383642bd3d77SMatthias Ringwald             break;
38377bbeb3adSMilanka Ringwald         default:
38387bbeb3adSMilanka Ringwald             btstack_assert(false);
38397bbeb3adSMilanka Ringwald             break;
384011e23e5fSmatthias.ringwald     }
384124f87726SMatthias Ringwald     if (err != 0){
384242bd3d77SMatthias Ringwald         return err;
384342bd3d77SMatthias Ringwald     }
384468d92d03Smatthias.ringwald 
3845038bc64cSmatthias.ringwald     // create internal event
3846ee8bf225Smatthias.ringwald 	hci_emit_state();
3847ee8bf225Smatthias.ringwald 
384868d92d03Smatthias.ringwald 	// trigger next/first action
384968d92d03Smatthias.ringwald 	hci_run();
385068d92d03Smatthias.ringwald 
3851475c8125Smatthias.ringwald     return 0;
3852475c8125Smatthias.ringwald }
3853475c8125Smatthias.ringwald 
385435454696SMatthias Ringwald 
385535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
385635454696SMatthias Ringwald 
3857758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
3858758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
3859a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3860758b46ceSmatthias.ringwald     hci_run();
3861758b46ceSmatthias.ringwald }
3862758b46ceSmatthias.ringwald 
386315a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
3864381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
3865381fbed8Smatthias.ringwald 
38663a9fb326S[email protected]     if (hci_stack->discoverable == enable){
38673a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
3868381fbed8Smatthias.ringwald         return;
3869381fbed8Smatthias.ringwald     }
3870381fbed8Smatthias.ringwald 
38713a9fb326S[email protected]     hci_stack->discoverable = enable;
3872758b46ceSmatthias.ringwald     hci_update_scan_enable();
3873758b46ceSmatthias.ringwald }
3874b031bebbSmatthias.ringwald 
387515a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
3876758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
3877758b46ceSmatthias.ringwald 
3878758b46ceSmatthias.ringwald     // don't emit event
38793a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
3880758b46ceSmatthias.ringwald 
38813a9fb326S[email protected]     hci_stack->connectable = enable;
3882758b46ceSmatthias.ringwald     hci_update_scan_enable();
3883381fbed8Smatthias.ringwald }
388435454696SMatthias Ringwald #endif
3885381fbed8Smatthias.ringwald 
388615a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
38876535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
38885061f3afS[email protected] }
38895061f3afS[email protected] 
38902b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
38912b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
38922b838201SMatthias Ringwald 
38932b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
38942b838201SMatthias Ringwald     hci_reserve_packet_buffer();
38952b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
38962b838201SMatthias Ringwald 
38972b838201SMatthias Ringwald     uint16_t size = 0;
38982b838201SMatthias Ringwald     uint16_t num_handles = 0;
38992b838201SMatthias Ringwald     packet[size++] = 0x35;
39002b838201SMatthias Ringwald     packet[size++] = 0x0c;
39012b838201SMatthias Ringwald     size++;  // skip param len
39022b838201SMatthias Ringwald     size++;  // skip num handles
39032b838201SMatthias Ringwald 
39042b838201SMatthias Ringwald     // add { handle, packets } entries
39052b838201SMatthias Ringwald     btstack_linked_item_t * it;
39062b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
39072b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
39082b838201SMatthias Ringwald         if (connection->num_packets_completed){
39092b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
39102b838201SMatthias Ringwald             size += 2;
39112b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
39122b838201SMatthias Ringwald             size += 2;
39132b838201SMatthias Ringwald             //
39142b838201SMatthias Ringwald             num_handles++;
39152b838201SMatthias Ringwald             connection->num_packets_completed = 0;
39162b838201SMatthias Ringwald         }
39172b838201SMatthias Ringwald     }
39182b838201SMatthias Ringwald 
39192b838201SMatthias Ringwald     packet[2] = size - 3;
39202b838201SMatthias Ringwald     packet[3] = num_handles;
39212b838201SMatthias Ringwald 
39222b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
39232b838201SMatthias Ringwald 
39242b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
39252b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
39262b838201SMatthias Ringwald 
39272b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
39282b838201SMatthias Ringwald     if (hci_transport_synchronous()){
3929e2d22487SMatthias Ringwald         hci_release_packet_buffer();
3930068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
39312b838201SMatthias Ringwald     }
39322b838201SMatthias Ringwald }
39332b838201SMatthias Ringwald #endif
39342b838201SMatthias Ringwald 
393526fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
393626fe9592SMatthias Ringwald     UNUSED(ds);
393726fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
3938beceeddeSMatthias Ringwald     // allow packet handlers to defer final shutdown
3939beceeddeSMatthias Ringwald     hci_emit_state();
394026fe9592SMatthias Ringwald     hci_run();
394126fe9592SMatthias Ringwald }
394226fe9592SMatthias Ringwald 
3943f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
39444ea43905SMatthias Ringwald     if (hci_stack->acl_fragmentation_total_size > 0u) {
3945b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3946b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3947b5d8b22bS[email protected]         if (connection) {
394828a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3949b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
3950f30077b7SMatthias Ringwald                 return true;
3951b5d8b22bS[email protected]             }
395228a0332dSMatthias Ringwald         } else {
3953b5d8b22bS[email protected]             // connection gone -> discard further fragments
395428a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3955b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
3956b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
3957b5d8b22bS[email protected]         }
3958b5d8b22bS[email protected]     }
3959f30077b7SMatthias Ringwald     return false;
39602b838201SMatthias Ringwald }
3961b031bebbSmatthias.ringwald 
396235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3963f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
3964f30077b7SMatthias Ringwald 
3965b031bebbSmatthias.ringwald     // decline incoming connections
39663a9fb326S[email protected]     if (hci_stack->decline_reason){
39673a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
39683a9fb326S[email protected]         hci_stack->decline_reason = 0;
39693a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3970f30077b7SMatthias Ringwald         return true;
3971ce4c8fabSmatthias.ringwald     }
3972bea424a5SMatthias Ringwald     // write page scan activity
3973bea424a5SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_interval != 0xffff) && hci_classic_supported()){
3974bea424a5SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window);
3975bea424a5SMatthias Ringwald         hci_stack->new_page_scan_interval = 0xffff;
3976bea424a5SMatthias Ringwald         hci_stack->new_page_scan_window = 0xffff;
3977bea424a5SMatthias Ringwald         return true;
3978bea424a5SMatthias Ringwald     }
3979bea424a5SMatthias Ringwald     // write page scan type
3980bea424a5SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_type != 0xff) && hci_classic_supported()){
3981bea424a5SMatthias Ringwald         hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type);
3982bea424a5SMatthias Ringwald         hci_stack->new_page_scan_type = 0xff;
3983bea424a5SMatthias Ringwald         return true;
3984bea424a5SMatthias Ringwald     }
3985b031bebbSmatthias.ringwald     // send scan enable
39860e588213SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
39873a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
39883a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
3989f30077b7SMatthias Ringwald         return true;
3990b031bebbSmatthias.ringwald     }
3991f5875de5SMatthias Ringwald     // start/stop inquiry
3992a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
3993f5875de5SMatthias Ringwald         uint8_t duration = hci_stack->inquiry_state;
3994beb3c81dSMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE;
3995496bb884SMatthias Ringwald         hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0);
3996f30077b7SMatthias Ringwald         return true;
3997f5875de5SMatthias Ringwald     }
3998f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3999f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
4000f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
4001f30077b7SMatthias Ringwald         return true;
4002f5875de5SMatthias Ringwald     }
4003b7f1ee76SMatthias Ringwald     // remote name request
4004b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
4005b7f1ee76SMatthias Ringwald         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
4006b7f1ee76SMatthias Ringwald         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
4007ee8a36c8SMatthias Ringwald                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
4008f30077b7SMatthias Ringwald         return true;
4009b7f1ee76SMatthias Ringwald     }
4010cf01e888SMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
4011cf01e888SMatthias Ringwald     // Local OOB data
4012cf01e888SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){
4013cf01e888SMatthias Ringwald         hci_stack->classic_read_local_oob_data = false;
4014cf01e888SMatthias Ringwald         if (hci_stack->local_supported_commands[1] & 0x10u){
4015cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_extended_oob_data);
4016cf01e888SMatthias Ringwald         } else {
4017cf01e888SMatthias Ringwald             hci_send_cmd(&hci_read_local_oob_data);
4018cf01e888SMatthias Ringwald         }
4019cf01e888SMatthias Ringwald     }
4020cf01e888SMatthias Ringwald #endif
40210a51f88bSMatthias Ringwald     // pairing
40220a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
40230a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
40240a51f88bSMatthias Ringwald         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
40253f659ee4SMilanka Ringwald         uint8_t pin_code[16];
40260a51f88bSMatthias Ringwald         switch (state){
40270a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
40283f659ee4SMilanka Ringwald                 memset(pin_code, 0, 16);
40293f659ee4SMilanka Ringwald                 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len);
40303f659ee4SMilanka Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code);
40310a51f88bSMatthias Ringwald                 break;
40320a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
40330a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
40340a51f88bSMatthias Ringwald                 break;
40350a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
4036d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
40370a51f88bSMatthias Ringwald                 break;
40380a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
40390a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
40400a51f88bSMatthias Ringwald                 break;
40410a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
40420a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
40430a51f88bSMatthias Ringwald                 break;
40440a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
40450a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
40460a51f88bSMatthias Ringwald                 break;
40470a51f88bSMatthias Ringwald             default:
40480a51f88bSMatthias Ringwald                 break;
40490a51f88bSMatthias Ringwald         }
4050f30077b7SMatthias Ringwald         return true;
4051f30077b7SMatthias Ringwald     }
4052f30077b7SMatthias Ringwald     return false;
40530a51f88bSMatthias Ringwald }
405435454696SMatthias Ringwald #endif
4055b031bebbSmatthias.ringwald 
4056a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4057f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
4058f30077b7SMatthias Ringwald 
4059f30077b7SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
4060f30077b7SMatthias Ringwald 
4061f30077b7SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
40624ea43905SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false;
4063d70217a2SMatthias Ringwald 
4064a41310b7SMatthias Ringwald 
4065a41310b7SMatthias Ringwald     // Phase 1: collect what to stop
4066a41310b7SMatthias Ringwald 
4067a41310b7SMatthias Ringwald     bool scanning_stop = false;
4068a41310b7SMatthias Ringwald     bool connecting_stop = false;
4069a41310b7SMatthias Ringwald     bool advertising_stop = false;
4070a41310b7SMatthias Ringwald 
4071a41310b7SMatthias Ringwald #ifndef ENABLE_LE_CENTRAL
4072a41310b7SMatthias Ringwald     UNUSED(scanning_stop);
40730abd9f64SMatthias Ringwald     UNUSED(connecting_stop);
4074a41310b7SMatthias Ringwald #endif
4075a41310b7SMatthias Ringwald #ifndef ENABLE_LE_PERIPHERAL
4076a41310b7SMatthias Ringwald     UNUSED(advertising_stop);
4077a41310b7SMatthias Ringwald #endif
4078a41310b7SMatthias Ringwald 
407929c24bebSMatthias Ringwald     // check if whitelist needs modification
408029c24bebSMatthias Ringwald     bool whitelist_modification_pending = false;
408129c24bebSMatthias Ringwald     btstack_linked_list_iterator_t lit;
408229c24bebSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
408329c24bebSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
408429c24bebSMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
408529c24bebSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
408629c24bebSMatthias Ringwald             whitelist_modification_pending = true;
408729c24bebSMatthias Ringwald             break;
408829c24bebSMatthias Ringwald         }
408929c24bebSMatthias Ringwald     }
409021debf25SMatthias Ringwald     // check if resolving list needs modification
409121debf25SMatthias Ringwald     bool resolving_list_modification_pending = false;
409221debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
4093ea151974SMatthias Ringwald     bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0;
4094ea151974SMatthias Ringwald 	if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){
409521debf25SMatthias Ringwald         resolving_list_modification_pending = true;
409621debf25SMatthias Ringwald     }
409721debf25SMatthias Ringwald #endif
409829c24bebSMatthias Ringwald 
4099d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4100fde725feSMatthias Ringwald     // scanning control
41013251a108SMatthias Ringwald     if (hci_stack->le_scanning_active) {
410229c24bebSMatthias Ringwald         // stop if:
410329c24bebSMatthias Ringwald         // - parameter change required
410429c24bebSMatthias Ringwald         // - it's disabled
410529c24bebSMatthias Ringwald         // - whitelist change required but used for scanning
410621debf25SMatthias Ringwald         // - resolving list modified
410729c24bebSMatthias Ringwald         bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1;
410821debf25SMatthias Ringwald         if ((hci_stack->le_scanning_param_update) ||
410921debf25SMatthias Ringwald             !hci_stack->le_scanning_enabled ||
411021debf25SMatthias Ringwald             scanning_uses_whitelist ||
411121debf25SMatthias Ringwald             resolving_list_modification_pending){
411221debf25SMatthias Ringwald 
41132d5c2a27SMatthias Ringwald             scanning_stop = true;
4114fde725feSMatthias Ringwald         }
4115fde725feSMatthias Ringwald     }
411629c24bebSMatthias Ringwald #endif
4117fde725feSMatthias Ringwald 
411829c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
411929c24bebSMatthias Ringwald     // connecting control
4120f496d06eSMatthias Ringwald     bool connecting_with_whitelist;
4121f496d06eSMatthias Ringwald     switch (hci_stack->le_connecting_state){
4122f496d06eSMatthias Ringwald         case LE_CONNECTING_DIRECT:
4123f496d06eSMatthias Ringwald         case LE_CONNECTING_WHITELIST:
4124af64f147SMatthias Ringwald             // stop connecting if:
4125af64f147SMatthias Ringwald             // - connecting uses white and whitelist modification pending
4126af64f147SMatthias Ringwald             // - if it got disabled
412721debf25SMatthias Ringwald             // - resolving list modified
4128f496d06eSMatthias Ringwald             connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST;
4129f496d06eSMatthias Ringwald             if ((connecting_with_whitelist && whitelist_modification_pending) ||
413021debf25SMatthias Ringwald                 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) ||
413121debf25SMatthias Ringwald                 resolving_list_modification_pending) {
413221debf25SMatthias Ringwald 
413329c24bebSMatthias Ringwald                 connecting_stop = true;
413429c24bebSMatthias Ringwald             }
4135f496d06eSMatthias Ringwald             break;
4136f496d06eSMatthias Ringwald         default:
4137f496d06eSMatthias Ringwald             break;
413829c24bebSMatthias Ringwald     }
4139d70217a2SMatthias Ringwald #endif
414029c24bebSMatthias Ringwald 
4141d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
414245c102fdSMatthias Ringwald     // le advertisement control
4143bbc366e6SMatthias Ringwald     if (hci_stack->le_advertisements_active){
414429c24bebSMatthias Ringwald         // stop if:
414529c24bebSMatthias Ringwald         // - parameter change required
414629c24bebSMatthias Ringwald         // - it's disabled
4147ba44ad41SMatthias Ringwald         // - whitelist change required but used for advertisement filter policy
414821debf25SMatthias Ringwald         // - resolving list modified
4149a61834b6SMatthias Ringwald         bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0;
41504e5d21eaSMatthias Ringwald         bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0;
4151a61834b6SMatthias Ringwald         if (advertising_change ||
4152a61834b6SMatthias Ringwald             (hci_stack->le_advertisements_enabled_for_current_roles == 0) ||
415321debf25SMatthias Ringwald             (advertising_uses_whitelist & whitelist_modification_pending) ||
415421debf25SMatthias Ringwald             resolving_list_modification_pending) {
415521debf25SMatthias Ringwald 
4156fde725feSMatthias Ringwald             advertising_stop = true;
4157fde725feSMatthias Ringwald         }
4158fde725feSMatthias Ringwald     }
4159a41310b7SMatthias Ringwald #endif
4160fde725feSMatthias Ringwald 
4161a41310b7SMatthias Ringwald 
4162a41310b7SMatthias Ringwald     // Phase 2: stop everything that should be off during modifications
4163a41310b7SMatthias Ringwald 
4164a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4165a41310b7SMatthias Ringwald     if (scanning_stop){
41665226d7f2SMatthias Ringwald         hci_stack->le_scanning_active = false;
4167a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
4168a41310b7SMatthias Ringwald         return true;
4169a41310b7SMatthias Ringwald     }
4170a41310b7SMatthias Ringwald #endif
4171a41310b7SMatthias Ringwald 
4172a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4173a41310b7SMatthias Ringwald     if (connecting_stop){
4174a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_create_connection_cancel);
4175a41310b7SMatthias Ringwald         return true;
4176a41310b7SMatthias Ringwald     }
4177a41310b7SMatthias Ringwald #endif
4178a41310b7SMatthias Ringwald 
4179a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4180fde725feSMatthias Ringwald     if (advertising_stop){
41815226d7f2SMatthias Ringwald         hci_stack->le_advertisements_active = false;
418245c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 0);
4183f30077b7SMatthias Ringwald         return true;
418445c102fdSMatthias Ringwald     }
4185a41310b7SMatthias Ringwald #endif
4186fde725feSMatthias Ringwald 
4187a41310b7SMatthias Ringwald     // Phase 3: modify
4188a41310b7SMatthias Ringwald 
4189a41310b7SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4190a41310b7SMatthias Ringwald     if (hci_stack->le_scanning_param_update){
4191a41310b7SMatthias Ringwald         hci_stack->le_scanning_param_update = false;
4192a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window,
4193a41310b7SMatthias Ringwald                      hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy);
4194a41310b7SMatthias Ringwald         return true;
4195a41310b7SMatthias Ringwald     }
4196a41310b7SMatthias Ringwald #endif
4197a41310b7SMatthias Ringwald 
4198a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
419945c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
420045c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
42016bcfa632SMatthias Ringwald         hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type;
420245c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_parameters,
420345c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_min,
420445c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_max,
420545c102fdSMatthias Ringwald                      hci_stack->le_advertisements_type,
42066bcfa632SMatthias Ringwald                      hci_stack->le_advertisements_own_addr_type,
420745c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address_type,
420845c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address,
420945c102fdSMatthias Ringwald                      hci_stack->le_advertisements_channel_map,
421045c102fdSMatthias Ringwald                      hci_stack->le_advertisements_filter_policy);
4211f30077b7SMatthias Ringwald         return true;
421245c102fdSMatthias Ringwald     }
4213501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
4214501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
42157a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
42167a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
42176535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
42186535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
42193c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
42207a85e4f5SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
4221f30077b7SMatthias Ringwald         return true;
422245c102fdSMatthias Ringwald     }
4223501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
4224501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4225f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
4226f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
42276535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
42286535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
42293c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
4230214bfd60SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
4231f30077b7SMatthias Ringwald         return true;
4232501f56b3SMatthias Ringwald     }
4233d70217a2SMatthias Ringwald #endif
42349956955bSMatthias Ringwald 
423513eb2a2eSMatthias Ringwald 
4236057ab60cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4237a41310b7SMatthias Ringwald     // if connect with whitelist was active and is not cancelled yet, wait until next time
4238a41310b7SMatthias Ringwald     if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false;
4239057ab60cSMatthias Ringwald #endif
4240057ab60cSMatthias Ringwald 
4241a41310b7SMatthias Ringwald     // LE Whitelist Management
4242a41310b7SMatthias Ringwald     if (whitelist_modification_pending){
42439956955bSMatthias Ringwald         // add/remove entries
4244665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4245665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
4246665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4247453459ddSMatthias Ringwald 			if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
4248453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4249453459ddSMatthias Ringwald 				hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address);
4250453459ddSMatthias Ringwald 				return true;
4251453459ddSMatthias Ringwald 			}
42529956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
4253453459ddSMatthias Ringwald 				entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER;
4254453459ddSMatthias Ringwald                 entry->state |= LE_WHITELIST_ON_CONTROLLER;
42559956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
4256f30077b7SMatthias Ringwald                 return true;
42579956955bSMatthias Ringwald             }
4258453459ddSMatthias Ringwald             if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){
4259665d90f2SMatthias Ringwald 				btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
42609956955bSMatthias Ringwald 				btstack_memory_whitelist_entry_free(entry);
42619956955bSMatthias Ringwald             }
42629956955bSMatthias Ringwald         }
426391915b0bSMatthias Ringwald     }
42649956955bSMatthias Ringwald 
426521debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
426621debf25SMatthias Ringwald     // LE Resolving List Management
4267ea151974SMatthias Ringwald     if (resolving_list_supported) {
426821debf25SMatthias Ringwald 		uint16_t i;
426921debf25SMatthias Ringwald 		switch (hci_stack->le_resolving_list_state) {
427021debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION:
427121debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
427221debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_set_address_resolution_enabled, 1);
427321debf25SMatthias Ringwald 				return true;
427421debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_READ_SIZE:
427521debf25SMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR;
427621debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_read_resolving_list_size);
427721debf25SMatthias Ringwald 				return true;
427821debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_SEND_CLEAR:
427902b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
4280ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_add_entries, 0xff,
4281ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_add_entries));
4282ea151974SMatthias Ringwald 				(void) memset(hci_stack->le_resolving_list_remove_entries, 0,
4283ea151974SMatthias Ringwald 							  sizeof(hci_stack->le_resolving_list_remove_entries));
428421debf25SMatthias Ringwald 				hci_send_cmd(&hci_le_clear_resolving_list);
428521debf25SMatthias Ringwald 				return true;
428602b02cffSMatthias Ringwald 			case LE_RESOLVING_LIST_REMOVE_ENTRIES:
428702b02cffSMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
428802b02cffSMatthias Ringwald 					uint8_t offset = i >> 3;
428902b02cffSMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
429002b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue;
429102b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_remove_entries[offset] &= ~mask;
429202b02cffSMatthias Ringwald 					bd_addr_t peer_identity_addreses;
429302b02cffSMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
429402b02cffSMatthias Ringwald 					sm_key_t peer_irk;
429502b02cffSMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
429602b02cffSMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
4297f5228c62SMatthias Ringwald 
4298f5228c62SMatthias Ringwald #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE
4299f5228c62SMatthias Ringwald 					// trigger whitelist entry 'update' (work around for controller bug)
4300f5228c62SMatthias Ringwald 					btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4301f5228c62SMatthias Ringwald 					while (btstack_linked_list_iterator_has_next(&lit)) {
4302f5228c62SMatthias Ringwald 						whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit);
4303f5228c62SMatthias Ringwald 						if (entry->address_type != peer_identity_addr_type) continue;
4304f5228c62SMatthias Ringwald 						if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue;
4305f5228c62SMatthias Ringwald 						log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses));
4306f5228c62SMatthias Ringwald 						entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER;
4307f5228c62SMatthias Ringwald 					}
4308f5228c62SMatthias Ringwald #endif
4309f5228c62SMatthias Ringwald 
4310ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type,
4311ea151974SMatthias Ringwald 								 peer_identity_addreses);
431202b02cffSMatthias Ringwald 					return true;
431302b02cffSMatthias Ringwald 				}
431402b02cffSMatthias Ringwald 
431502b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES;
431602b02cffSMatthias Ringwald 
431702b02cffSMatthias Ringwald 				/* fall through */
431802b02cffSMatthias Ringwald 
431921debf25SMatthias Ringwald 			case LE_RESOLVING_LIST_ADD_ENTRIES:
432021debf25SMatthias Ringwald 				for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) {
432121debf25SMatthias Ringwald 					uint8_t offset = i >> 3;
432221debf25SMatthias Ringwald 					uint8_t mask = 1 << (i & 7);
432302b02cffSMatthias Ringwald 					if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue;
432402b02cffSMatthias Ringwald 					hci_stack->le_resolving_list_add_entries[offset] &= ~mask;
432521debf25SMatthias Ringwald 					bd_addr_t peer_identity_addreses;
432621debf25SMatthias Ringwald 					int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN;
432721debf25SMatthias Ringwald 					sm_key_t peer_irk;
432821debf25SMatthias Ringwald 					le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk);
432921debf25SMatthias Ringwald 					if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue;
433021debf25SMatthias Ringwald 					const uint8_t *local_irk = gap_get_persistent_irk();
433121debf25SMatthias Ringwald 					// command uses format specifier 'P' that stores 16-byte value without flip
433221debf25SMatthias Ringwald 					uint8_t local_irk_flipped[16];
433321debf25SMatthias Ringwald 					uint8_t peer_irk_flipped[16];
433421debf25SMatthias Ringwald 					reverse_128(local_irk, local_irk_flipped);
433521debf25SMatthias Ringwald 					reverse_128(peer_irk, peer_irk_flipped);
4336ea151974SMatthias Ringwald 					hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses,
4337ea151974SMatthias Ringwald 								 peer_irk_flipped, local_irk_flipped);
433821debf25SMatthias Ringwald 					return true;
433921debf25SMatthias Ringwald 				}
434002b02cffSMatthias Ringwald 				hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
434121debf25SMatthias Ringwald 				break;
434202b02cffSMatthias Ringwald 
434321debf25SMatthias Ringwald 			default:
434421debf25SMatthias Ringwald 				break;
434521debf25SMatthias Ringwald 		}
4346ea151974SMatthias Ringwald 	}
434721debf25SMatthias Ringwald     hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE;
434821debf25SMatthias Ringwald #endif
4349a41310b7SMatthias Ringwald 
4350a41310b7SMatthias Ringwald     // Phase 4: restore state
435129c24bebSMatthias Ringwald 
435229c24bebSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4353af64f147SMatthias Ringwald     // re-start scanning
435429c24bebSMatthias Ringwald     if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){
435529c24bebSMatthias Ringwald         hci_stack->le_scanning_active = true;
435629c24bebSMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
435729c24bebSMatthias Ringwald         return true;
435829c24bebSMatthias Ringwald     }
435929c24bebSMatthias Ringwald #endif
436029c24bebSMatthias Ringwald 
436113eb2a2eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4362af64f147SMatthias Ringwald     // re-start connecting
4363af64f147SMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){
43649956955bSMatthias Ringwald         bd_addr_t null_addr;
43659956955bSMatthias Ringwald         memset(null_addr, 0, 6);
43666bcfa632SMatthias Ringwald         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
43676bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
43689956955bSMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
4369cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
4370cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
43719956955bSMatthias Ringwald                      1,         // use whitelist
43729956955bSMatthias Ringwald                      0,         // peer address type
43739956955bSMatthias Ringwald                      null_addr, // peer bd addr
43746bcfa632SMatthias Ringwald                      hci_stack->le_connection_own_addr_type,   // our addr type:
437573044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_min,    // conn interval min
437673044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_max,    // conn interval max
437773044eb2SMatthias Ringwald                      hci_stack->le_connection_latency,         // conn latency
437873044eb2SMatthias Ringwald                      hci_stack->le_supervision_timeout,        // conn latency
437973044eb2SMatthias Ringwald                      hci_stack->le_minimum_ce_length,          // min ce length
438073044eb2SMatthias Ringwald                      hci_stack->le_maximum_ce_length           // max ce length
43819956955bSMatthias Ringwald         );
4382f30077b7SMatthias Ringwald         return true;
43839956955bSMatthias Ringwald     }
4384d70217a2SMatthias Ringwald #endif
4385a41310b7SMatthias Ringwald 
4386a41310b7SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
4387a41310b7SMatthias Ringwald     // re-start advertising
43888978dcf1SMatthias Ringwald     if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){
4389a41310b7SMatthias Ringwald         // check if advertisements should be enabled given
43905226d7f2SMatthias Ringwald         hci_stack->le_advertisements_active = true;
43916bcfa632SMatthias Ringwald         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_advertisements_own_address);
4392a41310b7SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 1);
4393a41310b7SMatthias Ringwald         return true;
4394a41310b7SMatthias Ringwald     }
4395a41310b7SMatthias Ringwald #endif
4396a41310b7SMatthias Ringwald 
4397f30077b7SMatthias Ringwald     return false;
43987bdc6798S[email protected] }
4399b2f949feS[email protected] #endif
44007bdc6798S[email protected] 
440188a03c8dSMatthias Ringwald static bool hci_run_general_pending_commands(void){
4402f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
4403a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
440405ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
440532ab9390Smatthias.ringwald 
44060bf6344aS[email protected]         switch(connection->state){
44070bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
44084f3229d8S[email protected]                 switch(connection->address_type){
440935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4410f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
44119da54300S[email protected]                         log_info("sending hci_create_connection");
4412b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
44134f3229d8S[email protected]                         break;
441435454696SMatthias Ringwald #endif
44154f3229d8S[email protected]                     default:
4416a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4417d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
44189da54300S[email protected]                         log_info("sending hci_le_create_connection");
44196bcfa632SMatthias Ringwald                         hci_stack->le_connection_own_addr_type =  hci_stack->le_own_addr_type;
44206bcfa632SMatthias Ringwald                         hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address);
44214f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
4422cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_interval,    // conn scan interval
4423cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_window,      // conn scan windows
44244f3229d8S[email protected]                                      0,         // don't use whitelist
44254f3229d8S[email protected]                                      connection->address_type, // peer address type
44264f3229d8S[email protected]                                      connection->address,      // peer bd addr
44276bcfa632SMatthias Ringwald                                      hci_stack->le_connection_own_addr_type,   // our addr type:
442873044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_min,    // conn interval min
442973044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_max,    // conn interval max
443073044eb2SMatthias Ringwald                                      hci_stack->le_connection_latency,         // conn latency
443173044eb2SMatthias Ringwald                                      hci_stack->le_supervision_timeout,        // conn latency
443273044eb2SMatthias Ringwald                                      hci_stack->le_minimum_ce_length,          // min ce length
443373044eb2SMatthias Ringwald                                      hci_stack->le_maximum_ce_length          // max ce length
44344f3229d8S[email protected]                         );
44354f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
4436b2f949feS[email protected] #endif
4437d70217a2SMatthias Ringwald #endif
44384f3229d8S[email protected]                         break;
44394f3229d8S[email protected]                 }
4440f30077b7SMatthias Ringwald                 return true;
4441ad83dc6aS[email protected] 
444235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
44430bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
44445cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
4445f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
444676ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
4447895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
4448c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
4449e35edcc1S[email protected]                 }
4450f30077b7SMatthias Ringwald                 return true;
445135454696SMatthias Ringwald #endif
44520bf6344aS[email protected] 
4453a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4454d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
44550bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
44560bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
44570bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
4458f30077b7SMatthias Ringwald                 return true;
4459a6725849S[email protected] #endif
4460d70217a2SMatthias Ringwald #endif
44610bf6344aS[email protected]             case SEND_DISCONNECT:
44620bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
44636ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4464f30077b7SMatthias Ringwald                 return true;
44650bf6344aS[email protected] 
44660bf6344aS[email protected]             default:
44670bf6344aS[email protected]                 break;
4468c7e0c5f6Smatthias.ringwald         }
4469c7e0c5f6Smatthias.ringwald 
4470cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
4471cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
4472cabf004eSMatthias Ringwald 
44738daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_READ_RSSI){
44748daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_READ_RSSI);
4475891b9fc2SMatthias Ringwald             hci_send_cmd(&hci_read_rssi, connection->con_handle);
4476f30077b7SMatthias Ringwald             return true;
4477891b9fc2SMatthias Ringwald         }
4478891b9fc2SMatthias Ringwald 
447994418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
448094418890SMatthias Ringwald 
44818daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT){
44828daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_WRITE_SUPERVISION_TIMEOUT);
44836909f064SMatthias Ringwald             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
4484f30077b7SMatthias Ringwald             return true;
44856909f064SMatthias Ringwald         }
44866909f064SMatthias Ringwald 
4487ad20f0c8SMatthias Ringwald         // Handling link key request requires remote supported features
44888daf94bcSMatthias Ringwald         if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){
4489608f51bbSMatthias Ringwald             log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL);
44908daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST);
449130e72d78SMatthias Ringwald 
4492e9f98c4aSMatthias Ringwald             // lookup link key using cached key first
4493e9f98c4aSMatthias Ringwald             bool have_link_key = connection->link_key_type != INVALID_LINK_KEY;
4494e9f98c4aSMatthias Ringwald             if (!have_link_key && (hci_stack->link_key_db != NULL)){
4495e9f98c4aSMatthias Ringwald                 have_link_key = hci_stack->link_key_db->get_link_key(connection->address, connection->link_key, &connection->link_key_type);
4496e9f98c4aSMatthias Ringwald             }
449730e72d78SMatthias Ringwald 
4498128825c3SMatthias Ringwald             bool sc_enabled_remote = hci_remote_sc_enabled(connection);
4499e9f98c4aSMatthias Ringwald             bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(connection->link_key_type) == 1) && !sc_enabled_remote;
450030e72d78SMatthias Ringwald             if (sc_downgrade){
450130e72d78SMatthias Ringwald                 log_info("Link key based on SC, but remote does not support SC -> disconnect");
450230e72d78SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
450330e72d78SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
450430e72d78SMatthias Ringwald                 return true;
450530e72d78SMatthias Ringwald             }
450630e72d78SMatthias Ringwald 
4507e9f98c4aSMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level);
450830e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
4509e9f98c4aSMatthias Ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key);
451032ab9390Smatthias.ringwald             } else {
451132ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
451232ab9390Smatthias.ringwald             }
4513f30077b7SMatthias Ringwald             return true;
451432ab9390Smatthias.ringwald         }
45151d6b20aeS[email protected] 
45168daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){
45179da54300S[email protected]             log_info("denying to pin request");
45188daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST);
451934d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
4520f30077b7SMatthias Ringwald             return true;
45214c57c146S[email protected]         }
45224c57c146S[email protected] 
45238daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){
45248daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY);
4525a8d20135SMatthias Ringwald             // set authentication requirements:
4526a8d20135SMatthias Ringwald             // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic)
4527532454f9SMatthias Ringwald             // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote
4528a8d20135SMatthias Ringwald             uint8_t authreq = hci_stack->ssp_authentication_requirement & 1;
45299faad3abS[email protected]             if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
45309faad3abS[email protected]                 authreq |= 1;
4531106d6d11S[email protected]             }
4532532454f9SMatthias Ringwald             bool bonding = hci_stack->bondable;
45338daf94bcSMatthias Ringwald             if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){
4534532454f9SMatthias Ringwald                 // if we have received IO Cap Response, we're in responder role
4535532454f9SMatthias Ringwald                 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4536532454f9SMatthias Ringwald                 if (bonding && !remote_bonding){
4537532454f9SMatthias Ringwald                     log_info("Remote not bonding, dropping local flag");
4538532454f9SMatthias Ringwald                     bonding = false;
4539532454f9SMatthias Ringwald                 }
4540532454f9SMatthias Ringwald             }
4541532454f9SMatthias Ringwald             if (bonding){
4542a8d20135SMatthias Ringwald                 if (connection->bonding_flags & BONDING_DEDICATED){
4543a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
4544532454f9SMatthias Ringwald                 } else {
4545a8d20135SMatthias Ringwald                     authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
4546a8d20135SMatthias Ringwald                 }
4547532454f9SMatthias Ringwald             }
45481849becdSMatthias Ringwald             uint8_t have_oob_data = 0;
45491849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
45501849becdSMatthias Ringwald             if (connection->classic_oob_c_192 != NULL){
45511849becdSMatthias Ringwald                     have_oob_data |= 1;
45521849becdSMatthias Ringwald             }
45531849becdSMatthias Ringwald             if (connection->classic_oob_c_256 != NULL){
45541849becdSMatthias Ringwald                 have_oob_data |= 2;
45551849becdSMatthias Ringwald             }
45561849becdSMatthias Ringwald #endif
45571849becdSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq);
455811b03efaSMatthias Ringwald             return true;
4559f8fb5f6eS[email protected]         }
456011b03efaSMatthias Ringwald 
45618daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) {
45628daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
456311b03efaSMatthias Ringwald             hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
4564f30077b7SMatthias Ringwald             return true;
456532ab9390Smatthias.ringwald         }
456632ab9390Smatthias.ringwald 
45671849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
45681849becdSMatthias Ringwald         if (connection->authentication_flags & SEND_REMOTE_OOB_DATA_REPLY){
45691849becdSMatthias Ringwald             connectionClearAuthenticationFlags(connection, SEND_REMOTE_OOB_DATA_REPLY);
45701849becdSMatthias Ringwald             const uint8_t zero[16] = { 0 };
45711849becdSMatthias Ringwald             const uint8_t * r_192 = zero;
45721849becdSMatthias Ringwald             const uint8_t * c_192 = zero;
45731849becdSMatthias Ringwald             const uint8_t * r_256 = zero;
45741849becdSMatthias Ringwald             const uint8_t * c_256 = zero;
45751849becdSMatthias Ringwald             // verify P-256 OOB
45761849becdSMatthias Ringwald             if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) {
45771849becdSMatthias Ringwald                 c_256 = connection->classic_oob_c_256;
45781849becdSMatthias Ringwald                 if (connection->classic_oob_r_256 != NULL) {
45791849becdSMatthias Ringwald                     r_256 = connection->classic_oob_r_256;
45801849becdSMatthias Ringwald                 }
45811849becdSMatthias Ringwald             }
45821849becdSMatthias Ringwald             // verify P-192 OOB
45831849becdSMatthias Ringwald             if ((connection->classic_oob_c_192 != NULL)) {
45841849becdSMatthias Ringwald                 c_192 = connection->classic_oob_c_192;
45851849becdSMatthias Ringwald                 if (connection->classic_oob_r_192 != NULL) {
45861849becdSMatthias Ringwald                     r_192 = connection->classic_oob_r_192;
45871849becdSMatthias Ringwald                 }
45881849becdSMatthias Ringwald             }
45891849becdSMatthias Ringwald             // Reply
45901849becdSMatthias Ringwald             if (c_256 != zero) {
45911849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256);
45921849becdSMatthias Ringwald             } else if (c_192 != zero){
45931849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192);
45941849becdSMatthias Ringwald             } else {
45951849becdSMatthias Ringwald                 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address);
45961849becdSMatthias Ringwald             }
45971849becdSMatthias Ringwald             return true;
45981849becdSMatthias Ringwald         }
45991849becdSMatthias Ringwald #endif
46001849becdSMatthias Ringwald 
46018daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){
46028daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY);
460334d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
4604f30077b7SMatthias Ringwald             return true;
4605dbe1a790S[email protected]         }
4606dbe1a790S[email protected] 
4607*367aedc0SMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){
4608*367aedc0SMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY);
4609*367aedc0SMatthias Ringwald             hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address);
4610*367aedc0SMatthias Ringwald             return true;
4611*367aedc0SMatthias Ringwald         }
4612*367aedc0SMatthias Ringwald 
46138daf94bcSMatthias Ringwald         if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){
46148daf94bcSMatthias Ringwald             connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY);
461534d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
4616f30077b7SMatthias Ringwald             return true;
4617dbe1a790S[email protected]         }
4618afd4e962S[email protected] 
4619ba018746SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
4620ba018746SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
462134d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
4622f30077b7SMatthias Ringwald             return true;
46232bd8b7e7S[email protected]         }
46242bd8b7e7S[email protected] 
46255ccef624SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
46265ccef624SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
46275ccef624SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
46285ccef624SMatthias Ringwald             return true;
46295ccef624SMatthias Ringwald         }
46305ccef624SMatthias Ringwald 
463182721f83SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
463282721f83SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
463382721f83SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
463482721f83SMatthias Ringwald             return true;
463582721f83SMatthias Ringwald         }
463682721f83SMatthias Ringwald 
4637ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
4638ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
46391bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
46406ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
46416ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4642f30077b7SMatthias Ringwald             return true;
4643ad83dc6aS[email protected]         }
464476f27cffSMatthias Ringwald 
464534d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
464634d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
4647abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
464834d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
4649f30077b7SMatthias Ringwald             return true;
4650afd4e962S[email protected]         }
465176f27cffSMatthias Ringwald 
4652dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
4653dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
4654dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
4655f30077b7SMatthias Ringwald             return true;
4656dce78009S[email protected]         }
4657573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
4658573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
4659573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
4660f30077b7SMatthias Ringwald             return true;
4661573897a0SMatthias Ringwald         }
466276f27cffSMatthias Ringwald #endif
466376f27cffSMatthias Ringwald 
466476f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
466576f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
46661714cbbdSMatthias Ringwald #ifdef ENABLE_CLASSIC
46671714cbbdSMatthias Ringwald             hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS);
46681714cbbdSMatthias Ringwald #endif
46696ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
46706ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
46716ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
4672f30077b7SMatthias Ringwald                 return true;
467376f27cffSMatthias Ringwald             }
46746ef3696aSMatthias Ringwald         }
4675da886c03S[email protected] 
46766cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
4677f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
4678f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
4679f8ee3071SMatthias Ringwald             case 0:
4680f8ee3071SMatthias Ringwald                 break;
4681f8ee3071SMatthias Ringwald             case 0xffff:
4682f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
4683f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
4684f30077b7SMatthias Ringwald                 return true;
4685f8ee3071SMatthias Ringwald             default:
4686f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
4687f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
4688f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
4689f30077b7SMatthias Ringwald                 return true;
4690f8ee3071SMatthias Ringwald         }
469188a03c8dSMatthias Ringwald 
4692140c0557SMatthias Ringwald         if (connection->sniff_subrating_max_latency != 0xffff){
4693140c0557SMatthias Ringwald             uint16_t max_latency = connection->sniff_subrating_max_latency;
4694140c0557SMatthias Ringwald             connection->sniff_subrating_max_latency = 0;
4695140c0557SMatthias Ringwald             hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout);
4696140c0557SMatthias Ringwald             return true;
4697140c0557SMatthias Ringwald         }
4698140c0557SMatthias Ringwald 
4699965a4ccfSMatthias Ringwald         if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){
4700278ff8a9SMatthias Ringwald             uint8_t service_type = (uint8_t) connection->qos_service_type;
4701965a4ccfSMatthias Ringwald             connection->qos_service_type = HCI_SERVICE_TYPE_INVALID;
4702278ff8a9SMatthias 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);
4703278ff8a9SMatthias Ringwald             return true;
4704278ff8a9SMatthias Ringwald         }
4705278ff8a9SMatthias Ringwald 
470688a03c8dSMatthias Ringwald         if (connection->request_role != HCI_ROLE_INVALID){
470788a03c8dSMatthias Ringwald             hci_role_t role = connection->request_role;
470888a03c8dSMatthias Ringwald             connection->request_role = HCI_ROLE_INVALID;
470988a03c8dSMatthias Ringwald             hci_send_cmd(&hci_switch_role_command, connection->address, role);
471088a03c8dSMatthias Ringwald             return true;
471188a03c8dSMatthias Ringwald         }
47126cdc2862SMatthias Ringwald #endif
4713f8ee3071SMatthias Ringwald 
4714a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
471573cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
471673cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
471773cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
4718da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
471973cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
4720c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
4721c37a3166S[email protected]                              0x0000, 0xffff);
4722f30077b7SMatthias Ringwald                 return true;
472373cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
472473cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
472573cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
472673cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
472773cd8a2aSMatthias Ringwald                              0x0000, 0xffff);
4728f30077b7SMatthias Ringwald                 return true;
472973cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
473073cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
473173cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
4732f30077b7SMatthias Ringwald                 return true;
473373cd8a2aSMatthias Ringwald             default:
473473cd8a2aSMatthias Ringwald                 break;
4735c37a3166S[email protected]         }
47364ea43905SMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xffu){
4737b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
4738b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
4739b90f6e0aSMatthias 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);
4740f30077b7SMatthias Ringwald             return true;
4741b90f6e0aSMatthias Ringwald         }
4742c37a3166S[email protected] #endif
4743dbe1a790S[email protected]     }
4744f30077b7SMatthias Ringwald     return false;
4745f30077b7SMatthias Ringwald }
4746c7e0c5f6Smatthias.ringwald 
4747f30077b7SMatthias Ringwald static void hci_run(void){
4748f30077b7SMatthias Ringwald 
4749f30077b7SMatthias Ringwald     bool done;
4750f30077b7SMatthias Ringwald 
4751f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
4752f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
4753f30077b7SMatthias Ringwald     if (done) return;
4754f30077b7SMatthias Ringwald 
4755f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4756f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
4757f30077b7SMatthias Ringwald     if (!hci_can_send_comand_packet_transport()) return;
4758f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
4759f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
4760f30077b7SMatthias Ringwald         return;
4761f30077b7SMatthias Ringwald     }
4762f30077b7SMatthias Ringwald #endif
4763f30077b7SMatthias Ringwald 
4764f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
4765f30077b7SMatthias Ringwald 
4766f30077b7SMatthias Ringwald     // global/non-connection oriented commands
4767f30077b7SMatthias Ringwald 
4768f30077b7SMatthias Ringwald 
4769f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
4770f30077b7SMatthias Ringwald     // general gap classic
4771f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
4772f30077b7SMatthias Ringwald     if (done) return;
4773f30077b7SMatthias Ringwald #endif
4774f30077b7SMatthias Ringwald 
4775f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
4776f30077b7SMatthias Ringwald     // general gap le
4777f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
4778f30077b7SMatthias Ringwald     if (done) return;
4779f30077b7SMatthias Ringwald #endif
4780f30077b7SMatthias Ringwald 
4781f30077b7SMatthias Ringwald     // send pending HCI commands
478288a03c8dSMatthias Ringwald     done = hci_run_general_pending_commands();
4783f30077b7SMatthias Ringwald     if (done) return;
4784f30077b7SMatthias Ringwald 
4785f30077b7SMatthias Ringwald     // stack state sub statemachines
478605ae8de3SMatthias Ringwald     hci_connection_t * connection;
47873a9fb326S[email protected]     switch (hci_stack->state){
47883429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
478974b323a9SMatthias Ringwald             hci_initializing_run();
47903429f56bSmatthias.ringwald             break;
4791c7e0c5f6Smatthias.ringwald 
4792c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
4793c7e0c5f6Smatthias.ringwald 
479426fe9592SMatthias Ringwald             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
479526fe9592SMatthias Ringwald             switch (hci_stack->substate){
4796beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4797beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4798beceeddeSMatthias Ringwald 
4799a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4800d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4801beceeddeSMatthias Ringwald                     // free whitelist entries
48029956955bSMatthias Ringwald                     {
4803665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_t lit;
4804665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4805665d90f2SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&lit)){
4806665d90f2SMatthias Ringwald                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4807665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
48089956955bSMatthias Ringwald                             btstack_memory_whitelist_entry_free(entry);
48099956955bSMatthias Ringwald                         }
48109956955bSMatthias Ringwald                     }
48119956955bSMatthias Ringwald #endif
4812d70217a2SMatthias Ringwald #endif
4813c7e0c5f6Smatthias.ringwald                     // close all open connections
48143a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
4815c7e0c5f6Smatthias.ringwald                     if (connection){
4816711e6c80SMatthias Ringwald                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4817d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
481832ab9390Smatthias.ringwald 
48198fca890eSMatthias Ringwald                         // check state
48208fca890eSMatthias Ringwald                         if (connection->state == SENT_DISCONNECT) return;
48218fca890eSMatthias Ringwald                         connection->state = SENT_DISCONNECT;
48228fca890eSMatthias Ringwald 
48238837e9efSMatthias Ringwald                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4824c7e0c5f6Smatthias.ringwald 
48258837e9efSMatthias Ringwald                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
48268837e9efSMatthias Ringwald                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
48278837e9efSMatthias Ringwald 
48288837e9efSMatthias Ringwald                         // ... which would be ignored anyway as we shutdown (free) the connection now
4829c7e0c5f6Smatthias.ringwald                         hci_shutdown_connection(connection);
48308837e9efSMatthias Ringwald 
48318837e9efSMatthias Ringwald                         // finally, send the disconnect command
48326ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4833c7e0c5f6Smatthias.ringwald                         return;
4834c7e0c5f6Smatthias.ringwald                     }
483526fe9592SMatthias Ringwald 
4836beceeddeSMatthias Ringwald                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4837beceeddeSMatthias Ringwald                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4838beceeddeSMatthias Ringwald                         log_info("HCI_STATE_HALTING: wait 50 ms");
483926fe9592SMatthias Ringwald                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4840beceeddeSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
484126fe9592SMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
484226fe9592SMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
484326fe9592SMatthias Ringwald                         break;
4844beceeddeSMatthias Ringwald                     }
484526fe9592SMatthias Ringwald 
4846cf373d3aSMatthias Ringwald                     /* fall through */
484726fe9592SMatthias Ringwald 
484826fe9592SMatthias Ringwald                 case HCI_HALTING_CLOSE:
48499da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling off");
4850c7e0c5f6Smatthias.ringwald 
485172ea5239Smatthias.ringwald                     // switch mode
4852c7e0c5f6Smatthias.ringwald                     hci_power_control_off();
48539418f9c9Smatthias.ringwald 
48549da54300S[email protected]                     log_info("HCI_STATE_HALTING, emitting state");
485572ea5239Smatthias.ringwald                     hci_emit_state();
48569da54300S[email protected]                     log_info("HCI_STATE_HALTING, done");
485772ea5239Smatthias.ringwald                     break;
4858beceeddeSMatthias Ringwald 
4859beceeddeSMatthias Ringwald                 case HCI_HALTING_W4_TIMER:
4860beceeddeSMatthias Ringwald                     // keep waiting
4861beceeddeSMatthias Ringwald 
4862beceeddeSMatthias Ringwald                     break;
486326fe9592SMatthias Ringwald                 default:
486426fe9592SMatthias Ringwald                     break;
486526fe9592SMatthias Ringwald             }
486626fe9592SMatthias Ringwald 
486726fe9592SMatthias Ringwald             break;
4868c7e0c5f6Smatthias.ringwald 
486972ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
48703a9fb326S[email protected]             switch(hci_stack->substate) {
487174b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_DISCONNECT:
48729da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
487372ea5239Smatthias.ringwald                     // close all open connections
48743a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
487566da7044Smatthias.ringwald 
4876423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
487766da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
4878d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
487966da7044Smatthias.ringwald                         connection = NULL;
488066da7044Smatthias.ringwald                     }
488166da7044Smatthias.ringwald #endif
488272ea5239Smatthias.ringwald                     if (connection){
488332ab9390Smatthias.ringwald 
488472ea5239Smatthias.ringwald                         // send disconnect
4885d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
488632ab9390Smatthias.ringwald 
48879da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
48886ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
488972ea5239Smatthias.ringwald 
489072ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
489172ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
489272ea5239Smatthias.ringwald                         return;
489372ea5239Smatthias.ringwald                     }
489472ea5239Smatthias.ringwald 
489592368cd3S[email protected]                     if (hci_classic_supported()){
489689db417bSmatthias.ringwald                         // disable page and inquiry scan
4897d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
489832ab9390Smatthias.ringwald 
48999da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
49003a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
490189db417bSmatthias.ringwald 
490289db417bSmatthias.ringwald                         // continue in next sub state
490374b323a9SMatthias Ringwald                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
490489db417bSmatthias.ringwald                         break;
490592368cd3S[email protected]                     }
4906cf373d3aSMatthias Ringwald 
4907cf373d3aSMatthias Ringwald                     /* fall through */
490892368cd3S[email protected] 
490974b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_COMPLETE:
49109da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
4911423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
491228171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
4913d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
491428171530Smatthias.ringwald                         // SLEEP MODE reached
49153a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
491628171530Smatthias.ringwald                         hci_emit_state();
491728171530Smatthias.ringwald                         break;
491828171530Smatthias.ringwald                     }
491928171530Smatthias.ringwald #endif
492072ea5239Smatthias.ringwald                     // switch mode
49213a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4922c7e0c5f6Smatthias.ringwald                     hci_emit_state();
492328171530Smatthias.ringwald                     break;
492428171530Smatthias.ringwald 
492589db417bSmatthias.ringwald                 default:
492689db417bSmatthias.ringwald                     break;
492789db417bSmatthias.ringwald             }
4928c7e0c5f6Smatthias.ringwald             break;
4929c7e0c5f6Smatthias.ringwald 
49303429f56bSmatthias.ringwald         default:
49313429f56bSmatthias.ringwald             break;
49321f504dbdSmatthias.ringwald     }
49333429f56bSmatthias.ringwald }
493416833f0aSmatthias.ringwald 
493531452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
493635454696SMatthias Ringwald     // house-keeping
493735454696SMatthias Ringwald 
493835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4939c8e4258aSmatthias.ringwald     bd_addr_t addr;
4940c8e4258aSmatthias.ringwald     hci_connection_t * conn;
4941c123d999SMatthias Ringwald #endif
4942c123d999SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
49436f35bb46SMatthias Ringwald     uint8_t initiator_filter_policy;
49449cbd2215SMatthias Ringwald #endif
4945c8e4258aSmatthias.ringwald 
49466f35bb46SMatthias Ringwald     uint16_t opcode = little_endian_read_16(packet, 0);
49476f35bb46SMatthias Ringwald     switch (opcode) {
49489cbd2215SMatthias Ringwald         case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE:
49499cbd2215SMatthias Ringwald             hci_stack->loopback_mode = packet[3];
49509cbd2215SMatthias Ringwald             break;
49519cbd2215SMatthias Ringwald 
49529cbd2215SMatthias Ringwald #ifdef ENABLE_CLASSIC
49536f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_CREATE_CONNECTION:
4954724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
49559da54300S[email protected]             log_info("Create_connection to %s", bd_addr_to_str(addr));
4956c8e4258aSmatthias.ringwald 
4957f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4958ad83dc6aS[email protected]             if (!conn) {
4959f16129ceSMatthias Ringwald                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
496017f1ba2aSmatthias.ringwald                 if (!conn) {
496117f1ba2aSmatthias.ringwald                     // notify client that alloc failed
49622deddeceSMatthias Ringwald                     hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4963f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
496417f1ba2aSmatthias.ringwald                 }
4965ad83dc6aS[email protected]                 conn->state = SEND_CREATE_CONNECTION;
4966f3e2cd2aSMatthias Ringwald                 conn->role  = HCI_ROLE_MASTER;
4967ad83dc6aS[email protected]             }
4968ad83dc6aS[email protected]             log_info("conn state %u", conn->state);
4969ad83dc6aS[email protected]             switch (conn->state) {
4970ad83dc6aS[email protected]                 // if connection active exists
4971ad83dc6aS[email protected]                 case OPEN:
4972f5e5741dSMatthias Ringwald                     // and OPEN, emit connection complete command
4973274dad91SMatthias Ringwald                     hci_emit_connection_complete(addr, conn->con_handle, 0);
4974f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
4975672e36abSMatthias Ringwald                 case RECEIVED_DISCONNECTION_COMPLETE:
4976672e36abSMatthias Ringwald                     // create connection triggered in disconnect complete event, let's do it now
4977672e36abSMatthias Ringwald                     break;
4978ad83dc6aS[email protected]                 case SEND_CREATE_CONNECTION:
4979532f91a5SMatthias Ringwald                     // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
4980532f91a5SMatthias Ringwald                     break;
4981ad83dc6aS[email protected]                 default:
4982ad83dc6aS[email protected]                     // otherwise, just ignore as it is already in the open process
4983f5e5741dSMatthias Ringwald                     return -1; // packet not sent to controller
4984ad83dc6aS[email protected]             }
4985c8e4258aSmatthias.ringwald             conn->state = SENT_CREATE_CONNECTION;
4986229331c6SMatthias Ringwald 
4987229331c6SMatthias Ringwald             // track outgoing connection
4988f16129ceSMatthias Ringwald             hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
49896535961aSMatthias Ringwald             (void) memcpy(hci_stack->outgoing_addr, addr, 6);
49906f35bb46SMatthias Ringwald             break;
49916f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY:
4992a98592bcSMatthias Ringwald             if (hci_stack->link_key_db) {
4993724d70a2SMatthias Ringwald                 reverse_bd_addr(&packet[3], addr);
4994a98592bcSMatthias Ringwald                 hci_stack->link_key_db->delete_link_key(addr);
49958ef73945Smatthias.ringwald             }
49966f35bb46SMatthias Ringwald             break;
4997ee752bb8SMatthias Ringwald 
49985b7087c7SMatthias Ringwald #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT)
49996f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION:
5000ee752bb8SMatthias Ringwald             // setup_synchronous_connection? Voice setting at offset 22
5001ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
5002ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
50036f35bb46SMatthias Ringwald             break;
50046f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION:
5005ee752bb8SMatthias Ringwald             // accept_synchronus_connection? Voice setting at offset 18
5006ee752bb8SMatthias Ringwald             // TODO: compare to current setting if sco connection already active
5007ee752bb8SMatthias Ringwald             hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
50086f35bb46SMatthias Ringwald             break;
5009ee752bb8SMatthias Ringwald #endif
501035454696SMatthias Ringwald #endif
50114b3e1e19SMatthias Ringwald 
5012a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
50136f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS:
5014b95a5a35SMatthias Ringwald             hci_stack->le_random_address_set = 1;
5015b95a5a35SMatthias Ringwald             reverse_bd_addr(&packet[3], hci_stack->le_random_address);
50166f35bb46SMatthias Ringwald             break;
50177e8d8b1dSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
50186f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE:
50195226d7f2SMatthias Ringwald             hci_stack->le_advertisements_active = packet[3] != 0;
50206f35bb46SMatthias Ringwald             break;
5021d70217a2SMatthias Ringwald #endif
5022d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
50236f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION:
5024b04dfa37SMatthias Ringwald             // white list used?
50256f35bb46SMatthias Ringwald             initiator_filter_policy = packet[7];
5026b04dfa37SMatthias Ringwald             switch (initiator_filter_policy) {
5027b04dfa37SMatthias Ringwald                 case 0:
5028b04dfa37SMatthias Ringwald                     // whitelist not used
5029b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
5030b04dfa37SMatthias Ringwald                     break;
5031b04dfa37SMatthias Ringwald                 case 1:
5032b04dfa37SMatthias Ringwald                     hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
5033b04dfa37SMatthias Ringwald                     break;
5034b04dfa37SMatthias Ringwald                 default:
5035b04dfa37SMatthias Ringwald                     log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
5036b04dfa37SMatthias Ringwald                     break;
5037b04dfa37SMatthias Ringwald             }
5038c163146eSMatthias Ringwald             // track outgoing connection
503905002aecSMatthias Ringwald             hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type
5040c163146eSMatthias Ringwald             reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address
50416f35bb46SMatthias Ringwald             break;
50426f35bb46SMatthias Ringwald         case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL:
50436ea9315cSMatthias Ringwald             hci_stack->le_connecting_state = LE_CONNECTING_CANCEL;
50446f35bb46SMatthias Ringwald             break;
50459cbd2215SMatthias Ringwald #endif
50469cbd2215SMatthias Ringwald #endif
50476f35bb46SMatthias Ringwald         default:
50486f35bb46SMatthias Ringwald             break;
5049b04dfa37SMatthias Ringwald     }
505069a97523S[email protected] 
50513a9fb326S[email protected]     hci_stack->num_cmd_packets--;
50525bb5bc3eS[email protected] 
50535bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
5054bfea0222SMatthias Ringwald     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
505531452debSmatthias.ringwald }
50568adf0ddaSmatthias.ringwald 
50572bd8b7e7S[email protected] // disconnect because of security block
50582bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
50592bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
50602bd8b7e7S[email protected]     if (!connection) return;
50612bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
50622bd8b7e7S[email protected] }
50632bd8b7e7S[email protected] 
50642bd8b7e7S[email protected] 
5065dbe1a790S[email protected] // Configure Secure Simple Pairing
5066dbe1a790S[email protected] 
506735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
506835454696SMatthias Ringwald 
5069dbe1a790S[email protected] // enable will enable SSP during init
507015a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
50713a9fb326S[email protected]     hci_stack->ssp_enable = enable;
5072dbe1a790S[email protected] }
5073dbe1a790S[email protected] 
507495d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
507515a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
50762bd8b7e7S[email protected] }
50772bd8b7e7S[email protected] 
5078dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
507915a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
50803a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
5081dbe1a790S[email protected] }
508215a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
50833a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
5084dbe1a790S[email protected] }
5085dbe1a790S[email protected] 
5086dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
508715a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
50883a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
5089dbe1a790S[email protected] }
50905d23aae8SMatthias Ringwald 
50915d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
50925d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
50935d23aae8SMatthias Ringwald }
50945d23aae8SMatthias Ringwald 
509535454696SMatthias Ringwald #endif
5096dbe1a790S[email protected] 
509794be1a66SMatthias Ringwald // va_list part of hci_send_cmd
509894be1a66SMatthias Ringwald int hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){
5099d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
51009d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
51019d14b626S[email protected]         return 0;
51029d14b626S[email protected]     }
51039d14b626S[email protected] 
51045127cc62S[email protected]     // for HCI INITIALIZATION
51059da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
51065127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
51075127cc62S[email protected] 
51089d14b626S[email protected]     hci_reserve_packet_buffer();
51099d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
511094be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
5111bfea0222SMatthias Ringwald     int err = hci_send_cmd_packet(packet, size);
5112bfea0222SMatthias Ringwald 
5113593702caSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
5114593702caSMatthias Ringwald     if ((err < 0) || hci_transport_synchronous()){
5115e2d22487SMatthias Ringwald         hci_release_packet_buffer();
5116068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
5117bfea0222SMatthias Ringwald     }
5118bfea0222SMatthias Ringwald 
5119bfea0222SMatthias Ringwald     return err;
512094be1a66SMatthias Ringwald }
51219d14b626S[email protected] 
512294be1a66SMatthias Ringwald /**
512394be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
512494be1a66SMatthias Ringwald  */
512594be1a66SMatthias Ringwald int hci_send_cmd(const hci_cmd_t * cmd, ...){
51261cd208adSmatthias.ringwald     va_list argptr;
51271cd208adSmatthias.ringwald     va_start(argptr, cmd);
512894be1a66SMatthias Ringwald     int res = hci_send_cmd_va_arg(cmd, argptr);
51291cd208adSmatthias.ringwald     va_end(argptr);
513094be1a66SMatthias Ringwald     return res;
513193b8dc03Smatthias.ringwald }
5132c8e4258aSmatthias.ringwald 
5133ee091cf1Smatthias.ringwald // Create various non-HCI events.
5134ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
5135ee091cf1Smatthias.ringwald 
5136d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
5137fb37a842SMatthias Ringwald     // dump packet
5138d6b06661SMatthias Ringwald     if (dump) {
5139300c1ba4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
5140d6b06661SMatthias Ringwald     }
51411ef6bb52SMatthias Ringwald 
5142fb37a842SMatthias Ringwald     // dispatch to all event handlers
51431ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
51441ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
51451ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
51461ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
5147d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
51481ef6bb52SMatthias Ringwald     }
5149d6b06661SMatthias Ringwald }
5150d6b06661SMatthias Ringwald 
5151d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
5152fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
51533d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
5154d6b06661SMatthias Ringwald }
5155d6b06661SMatthias Ringwald 
515635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5157701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
51583bc639ceSMatthias Ringwald     // notify SCO sender if waiting
5159701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
5160701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
51613bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
5162701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
5163701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
51643d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
51653bc639ceSMatthias Ringwald     }
51663bc639ceSMatthias Ringwald }
51671cfb383eSMatthias Ringwald 
51681cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
51699784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
5170ac9136ccSMatthias Ringwald     uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN];
51711cfb383eSMatthias Ringwald 
51721cfb383eSMatthias Ringwald     uint8_t * eir_data;
51731cfb383eSMatthias Ringwald     ad_context_t context;
51741cfb383eSMatthias Ringwald     const uint8_t * name;
51751cfb383eSMatthias Ringwald     uint8_t         name_len;
51761cfb383eSMatthias Ringwald 
51779784dac1SMatthias Ringwald     if (size < 3) return;
51789784dac1SMatthias Ringwald 
51791cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
5180a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
51811cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
51821cfb383eSMatthias Ringwald 
51839784dac1SMatthias Ringwald     switch (event_type){
51849784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
51859784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
51869784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
51879784dac1SMatthias Ringwald             break;
51889784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
51899784dac1SMatthias Ringwald             if (size != 257) return;
51909784dac1SMatthias Ringwald             if (num_responses != 1) return;
51919784dac1SMatthias Ringwald             break;
51929784dac1SMatthias Ringwald         default:
51939784dac1SMatthias Ringwald             return;
51949784dac1SMatthias Ringwald     }
51959784dac1SMatthias Ringwald 
51961cfb383eSMatthias Ringwald     // event[1] is set at the end
51971cfb383eSMatthias Ringwald     int i;
51981cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
51991cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
52001cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
52011cfb383eSMatthias Ringwald         uint8_t event_size = 18;    // if name is not set by EIR
52021cfb383eSMatthias Ringwald 
52036535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
52040e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
52056535961aSMatthias Ringwald         (void)memcpy(&event[9],
52066535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
52076535961aSMatthias Ringwald                      3); // class of device
52086535961aSMatthias Ringwald         (void)memcpy(&event[12],
52096535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
52106535961aSMatthias Ringwald                      2); // clock offset
52111cfb383eSMatthias Ringwald 
52121cfb383eSMatthias Ringwald         switch (event_type){
52131cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
52141cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
52151cfb383eSMatthias Ringwald                 break;
52161cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
52171cfb383eSMatthias Ringwald                 event[14] = 1;
5218a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
52191cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
52201cfb383eSMatthias Ringwald                 break;
52211cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
52221cfb383eSMatthias Ringwald                 event[14] = 1;
5223a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
522479186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
52251cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
52261cfb383eSMatthias Ringwald                 name = NULL;
5227a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
5228a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
52291cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
52301cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
52311cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
5232ac9136ccSMatthias Ringwald                     // Prefer Complete Local Name over Shortened Local Name
52331cfb383eSMatthias Ringwald                     switch (data_type){
52341cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
52351cfb383eSMatthias Ringwald                             if (name) continue;
5236cf373d3aSMatthias Ringwald                             /* fall through */
52371cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
52381cfb383eSMatthias Ringwald                             name = data;
52391cfb383eSMatthias Ringwald                             name_len = data_size;
52401cfb383eSMatthias Ringwald                             break;
5241ac9136ccSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_DEVICE_ID:
5242ac9136ccSMatthias Ringwald                             if (data_size != 8) break;
5243ac9136ccSMatthias Ringwald                             event[16] = 1;
52443c0c7fefSMatthias Ringwald                             memcpy(&event[17], data, 8);
5245ac9136ccSMatthias Ringwald                             break;
52461cfb383eSMatthias Ringwald                         default:
52471cfb383eSMatthias Ringwald                             break;
52481cfb383eSMatthias Ringwald                     }
52491cfb383eSMatthias Ringwald                 }
52501cfb383eSMatthias Ringwald                 if (name){
5251ac9136ccSMatthias Ringwald                     event[25] = 1;
52521cfb383eSMatthias Ringwald                     // truncate name if needed
52531cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
5254ac9136ccSMatthias Ringwald                     event[26] = len;
5255ac9136ccSMatthias Ringwald                     (void)memcpy(&event[27], name, len);
52561cfb383eSMatthias Ringwald                     event_size += len;
52571cfb383eSMatthias Ringwald                 }
52581cfb383eSMatthias Ringwald                 break;
52597bbeb3adSMilanka Ringwald             default:
52607bbeb3adSMilanka Ringwald                 return;
52611cfb383eSMatthias Ringwald         }
52621cfb383eSMatthias Ringwald         event[1] = event_size - 2;
52631cfb383eSMatthias Ringwald         hci_emit_event(event, event_size, 1);
52641cfb383eSMatthias Ringwald     }
52651cfb383eSMatthias Ringwald }
526635454696SMatthias Ringwald #endif
52673bc639ceSMatthias Ringwald 
526871de195eSMatthias Ringwald void hci_emit_state(void){
52693a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
5270425d1371Smatthias.ringwald     uint8_t event[3];
527180d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
52724ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
52733a9fb326S[email protected]     event[2] = hci_stack->state;
5274d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5275c8e4258aSmatthias.ringwald }
5276c8e4258aSmatthias.ringwald 
527735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
52782deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
5279425d1371Smatthias.ringwald     uint8_t event[13];
5280c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
5281425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
528217f1ba2aSmatthias.ringwald     event[2] = status;
52832deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
52842deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
5285c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
5286c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
5287d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5288c8e4258aSmatthias.ringwald }
528952db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
529052db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
529152db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
529252db98b2SMatthias Ringwald     uint8_t event[4];
529352db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
529452db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
529552db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
529652db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
529752db98b2SMatthias Ringwald }
529835454696SMatthias Ringwald #endif
5299c8e4258aSmatthias.ringwald 
530035454696SMatthias Ringwald #ifdef ENABLE_BLE
5301d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5302667ba9d1SMatthias 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){
53034f3229d8S[email protected]     uint8_t event[21];
53044f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
53054ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
53064f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
53074f3229d8S[email protected]     event[3] = status;
5308fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
53094f3229d8S[email protected]     event[6] = 0; // TODO: role
53106e2e9a6bS[email protected]     event[7] = address_type;
5311724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
5312f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
5313f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
5314f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
53154f3229d8S[email protected]     event[20] = 0; // master clock accuracy
5316d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
53174f3229d8S[email protected] }
531835454696SMatthias Ringwald #endif
5319d70217a2SMatthias Ringwald #endif
53204f3229d8S[email protected] 
5321fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
5322fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
5323fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
5324fd43c0e0SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
5325fd43c0e0SMatthias Ringwald }
5326fd43c0e0SMatthias Ringwald 
5327fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
5328425d1371Smatthias.ringwald     uint8_t event[6];
53293c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
53304ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
53313c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
5332fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
53333c4d4b90Smatthias.ringwald     event[5] = reason;
5334d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
53353c4d4b90Smatthias.ringwald }
53363c4d4b90Smatthias.ringwald 
5337b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
5338e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
5339425d1371Smatthias.ringwald     uint8_t event[3];
534080d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
53414ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
534243bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
5343d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
534443bfb1bdSmatthias.ringwald }
5345038bc64cSmatthias.ringwald 
5346b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
5347e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
5348425d1371Smatthias.ringwald     uint8_t event[2];
534980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
53504ea43905SMatthias Ringwald     event[1] = sizeof(event) - 2u;
5351d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5352038bc64cSmatthias.ringwald }
53531b0e3922Smatthias.ringwald 
535435454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
535535454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
535635454696SMatthias Ringwald     uint8_t event[9];
535735454696SMatthias Ringwald     int pos = 0;
535835454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
53594ea43905SMatthias Ringwald     event[pos++] = sizeof(event) - 2u;
536035454696SMatthias Ringwald     event[pos++] = status;
536135454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
5362d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5363381fbed8Smatthias.ringwald }
5364458bf4e8S[email protected] 
536535454696SMatthias Ringwald 
536635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
536735454696SMatthias Ringwald 
5368b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
5369df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
5370a00031e2S[email protected]     uint8_t event[5];
5371e00caf9cS[email protected]     int pos = 0;
53725611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
5373e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
5374f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
5375e00caf9cS[email protected]     pos += 2;
5376e00caf9cS[email protected]     event[pos++] = level;
5377d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5378e00caf9cS[email protected] }
5379e00caf9cS[email protected] 
538035454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
538135454696SMatthias Ringwald     if (!connection) return LEVEL_0;
53828daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
5383fcaf38b9SMatthias Ringwald     // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key
53848daf94bcSMatthias Ringwald     if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
5385170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
53864051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
5387170fafaeSMatthias Ringwald     // LEVEL 4 always requires 128 bit encrytion key size
53880e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
5389170fafaeSMatthias Ringwald         security_level = LEVEL_3;
5390170fafaeSMatthias Ringwald     }
5391170fafaeSMatthias Ringwald     return security_level;
539235454696SMatthias Ringwald }
539335454696SMatthias Ringwald 
539435454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled){
539535454696SMatthias Ringwald     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
539635454696SMatthias Ringwald     uint8_t event[3];
539735454696SMatthias Ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
539835454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
539935454696SMatthias Ringwald     event[2] = enabled;
5400d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
5401ad83dc6aS[email protected] }
5402ad83dc6aS[email protected] 
540398a2fd1cSMatthias Ringwald // query if remote side supports eSCO
5404073bd0faSMatthias Ringwald int hci_remote_esco_supported(hci_con_handle_t con_handle){
540598a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
540698a2fd1cSMatthias Ringwald     if (!connection) return 0;
540776ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
540898a2fd1cSMatthias Ringwald }
540998a2fd1cSMatthias Ringwald 
541067aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
541167aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
541267aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
541367aae551SMatthias Ringwald }
541467aae551SMatthias Ringwald 
54152bd8b7e7S[email protected] // query if remote side supports SSP
54162bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
54172bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
54182bd8b7e7S[email protected]     if (!connection) return 0;
541967aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
54202bd8b7e7S[email protected] }
54212bd8b7e7S[email protected] 
542215a95bd5SMatthias Ringwald int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
5423df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
5424df3354fcS[email protected] }
5425df3354fcS[email protected] 
5426458bf4e8S[email protected] // GAP API
5427458bf4e8S[email protected] /**
5428458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
5429458bf4e8S[email protected]  * @praram enabled
5430458bf4e8S[email protected]  */
54314c57c146S[email protected] void gap_set_bondable_mode(int enable){
54323a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
5433458bf4e8S[email protected] }
54344ef6443cSMatthias Ringwald /**
54354ef6443cSMatthias Ringwald  * @brief Get bondable mode.
54364ef6443cSMatthias Ringwald  * @return 1 if bondable
54374ef6443cSMatthias Ringwald  */
54384ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
54394ef6443cSMatthias Ringwald     return hci_stack->bondable;
54404ef6443cSMatthias Ringwald }
5441cb230b9dS[email protected] 
5442cb230b9dS[email protected] /**
544334d2123cS[email protected]  * @brief map link keys to security levels
5444cb230b9dS[email protected]  */
544534d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
544634d2123cS[email protected]     switch (link_key_type){
54473c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
54483c68dfa9S[email protected]             return LEVEL_4;
54493c68dfa9S[email protected]         case COMBINATION_KEY:
54503c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
54513c68dfa9S[email protected]             return LEVEL_3;
54523c68dfa9S[email protected]         default:
54533c68dfa9S[email protected]             return LEVEL_2;
54543c68dfa9S[email protected]     }
5455cb230b9dS[email protected] }
5456cb230b9dS[email protected] 
54578b35e16aSMatthias Ringwald /**
54588b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
54598b35e16aSMatthias Ringwald  */
54608b35e16aSMatthias Ringwald int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
54618b35e16aSMatthias Ringwald     switch (link_key_type){
54628b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
54638b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
54648b35e16aSMatthias Ringwald             return 1;
54658b35e16aSMatthias Ringwald         default:
54668b35e16aSMatthias Ringwald             return 0;
54678b35e16aSMatthias Ringwald     }
54688b35e16aSMatthias Ringwald }
54698b35e16aSMatthias Ringwald 
54708b35e16aSMatthias Ringwald /**
54718b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
54728b35e16aSMatthias Ringwald  */
54738b35e16aSMatthias Ringwald int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
54748b35e16aSMatthias Ringwald     switch (link_key_type){
54758b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
54768b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
54778b35e16aSMatthias Ringwald             return 1;
54788b35e16aSMatthias Ringwald         default:
54798b35e16aSMatthias Ringwald             return 0;
54808b35e16aSMatthias Ringwald     }
54818b35e16aSMatthias Ringwald }
54828b35e16aSMatthias Ringwald 
5483106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
54845127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
5485106d6d11S[email protected]     return level > LEVEL_2;
5486106d6d11S[email protected] }
5487106d6d11S[email protected] 
548834d2123cS[email protected] /**
548934d2123cS[email protected]  * @brief get current security level
549034d2123cS[email protected]  */
549134d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
549234d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
549334d2123cS[email protected]     if (!connection) return LEVEL_0;
549434d2123cS[email protected]     return gap_security_level_for_connection(connection);
549534d2123cS[email protected] }
549634d2123cS[email protected] 
5497cb230b9dS[email protected] /**
5498cb230b9dS[email protected]  * @brief request connection to device to
5499cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
5500cb230b9dS[email protected]  */
550134d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
550234d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
550334d2123cS[email protected]     if (!connection){
5504a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
550534d2123cS[email protected]         return;
550634d2123cS[email protected]     }
5507defbf200SMatthias Ringwald 
5508defbf200SMatthias Ringwald     btstack_assert(hci_is_le_connection(connection) == false);
5509defbf200SMatthias Ringwald 
551034d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
551183d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
551283d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
551383d08d7cSMatthias Ringwald 
5514dbd5dcc3SMatthias Ringwald     // authentication active if authentication request was sent or planned level > 0
5515dbd5dcc3SMatthias Ringwald     bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0);
5516dbd5dcc3SMatthias Ringwald     if (authentication_active){
55171cf0a6c8SMatthias Ringwald         // authentication already active
551883d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
551983d08d7cSMatthias Ringwald             // increase requested level as new level is higher
552083d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
552183d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
552283d08d7cSMatthias Ringwald         }
55231cf0a6c8SMatthias Ringwald     } else {
552483d08d7cSMatthias Ringwald         // no request active, notify if security sufficient
552583d08d7cSMatthias Ringwald         if (requested_level <= current_level){
5526a00031e2S[email protected]             hci_emit_security_level(con_handle, current_level);
552734d2123cS[email protected]             return;
552834d2123cS[email protected]         }
5529a00031e2S[email protected] 
5530e060c07dSMatthias Ringwald         // store request
553134d2123cS[email protected]         connection->requested_security_level = requested_level;
5532a00031e2S[email protected] 
55331cf0a6c8SMatthias Ringwald         // start to authenticate connection
55341eb2563eS[email protected]         connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
5535e80b2cf9S[email protected]         hci_run();
5536e00caf9cS[email protected]     }
55371cf0a6c8SMatthias Ringwald }
5538ad83dc6aS[email protected] 
5539ad83dc6aS[email protected] /**
5540ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
5541ad83dc6aS[email protected]  * @param device
5542ad83dc6aS[email protected]  * @param request MITM protection
5543ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
5544ad83dc6aS[email protected]  */
5545ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
5546ad83dc6aS[email protected] 
5547ad83dc6aS[email protected]     // create connection state machine
5548f16129ceSMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
5549ad83dc6aS[email protected] 
5550ad83dc6aS[email protected]     if (!connection){
5551ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
5552ad83dc6aS[email protected]     }
5553ad83dc6aS[email protected] 
5554ad83dc6aS[email protected]     // delete linkn key
555515a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
5556ad83dc6aS[email protected] 
5557ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
5558ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
5559ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
5560f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
5561ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
5562ad83dc6aS[email protected] 
5563ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
5564ad83dc6aS[email protected] 
5565ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
5566ad83dc6aS[email protected]     // handle: authentication failure
5567ad83dc6aS[email protected]     // handle: disconnect on done
5568ad83dc6aS[email protected] 
5569ad83dc6aS[email protected]     hci_run();
5570ad83dc6aS[email protected] 
5571ad83dc6aS[email protected]     return 0;
5572ad83dc6aS[email protected] }
557335454696SMatthias Ringwald #endif
55748e618f72S[email protected] 
55758e618f72S[email protected] void gap_set_local_name(const char * local_name){
55768e618f72S[email protected]     hci_stack->local_name = local_name;
55778e618f72S[email protected] }
55788e618f72S[email protected] 
557935454696SMatthias Ringwald 
558035454696SMatthias Ringwald #ifdef ENABLE_BLE
558135454696SMatthias Ringwald 
5582d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5583d8e8f12aSMatthias Ringwald void gap_start_scan(void){
5584fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = true;
55857bdc6798S[email protected]     hci_run();
55867bdc6798S[email protected] }
55878e618f72S[email protected] 
5588d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
5589fde725feSMatthias Ringwald     hci_stack->le_scanning_enabled = false;
55907bdc6798S[email protected]     hci_run();
55917bdc6798S[email protected] }
55924f3229d8S[email protected] 
5593a7a719e9SMatthias Ringwald void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){
5594ef11999fSmatthias.ringwald     hci_stack->le_scan_type          = scan_type;
5595a7a719e9SMatthias Ringwald     hci_stack->le_scan_filter_policy = scanning_filter_policy;
5596ef11999fSmatthias.ringwald     hci_stack->le_scan_interval      = scan_interval;
5597ef11999fSmatthias.ringwald     hci_stack->le_scan_window        = scan_window;
55988b69e4c7SMatthias Ringwald     hci_stack->le_scanning_param_update = true;
5599ef11999fSmatthias.ringwald     hci_run();
5600ef11999fSmatthias.ringwald }
56014f3229d8S[email protected] 
5602a7a719e9SMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
5603a7a719e9SMatthias Ringwald     gap_set_scan_params(scan_type, scan_interval, scan_window, 0);
5604a7a719e9SMatthias Ringwald }
5605a7a719e9SMatthias Ringwald 
5606667ba9d1SMatthias Ringwald uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){
56074f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
56084f3229d8S[email protected]     if (!conn){
5609d32b3f05SMatthias Ringwald         // disallow if le connection is already outgoing
5610d32b3f05SMatthias Ringwald         if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
5611d32b3f05SMatthias Ringwald             log_error("le connection already active");
5612d32b3f05SMatthias Ringwald             return ERROR_CODE_COMMAND_DISALLOWED;
5613d32b3f05SMatthias Ringwald         }
5614d32b3f05SMatthias Ringwald 
5615d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
56162e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
56174f3229d8S[email protected]         if (!conn){
56184f3229d8S[email protected]             // notify client that alloc failed
56196e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
5620d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
5621472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
56224f3229d8S[email protected]         }
5623d5b1a89eSMatthias Ringwald 
5624d5b1a89eSMatthias Ringwald         // set le connecting state
5625d5b1a89eSMatthias Ringwald         if (hci_is_le_connection_type(addr_type)){
5626d5b1a89eSMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_DIRECT;
5627d5b1a89eSMatthias Ringwald         }
5628d5b1a89eSMatthias Ringwald 
56294f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
5630d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
5631564fca32S[email protected]         hci_run();
5632b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
56334f3229d8S[email protected]     }
56340bf6344aS[email protected] 
56350bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
5636a1df452eSMatthias Ringwald         (conn->state == SEND_CREATE_CONNECTION) ||
56370e588213SMatthias Ringwald         (conn->state == SENT_CREATE_CONNECTION)) {
56382e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
5639d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
5640616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
56410bf6344aS[email protected]     }
56420bf6344aS[email protected] 
5643b0136355SMatthias Ringwald     // check if connection was just disconnected
5644b0136355SMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
5645b0136355SMatthias Ringwald         log_info("gap_connect: send create connection (again)");
5646b0136355SMatthias Ringwald         conn->state = SEND_CREATE_CONNECTION;
5647b0136355SMatthias Ringwald         hci_run();
5648b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
5649b0136355SMatthias Ringwald     }
5650b0136355SMatthias Ringwald 
5651d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
5652d5b1a89eSMatthias Ringwald     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS);
56534f3229d8S[email protected]     hci_run();
5654b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
56554f3229d8S[email protected] }
56564f3229d8S[email protected] 
56577851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
5658d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
5659665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
5660a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
56610bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
56620bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
56630bf6344aS[email protected]         switch (conn->state){
5664a6725849S[email protected]             case SEND_CREATE_CONNECTION:
56657851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
56669c77c9dbSMatthias Ringwald             case SENT_CANCEL_CONNECTION:
56677851196eSmatthias.ringwald                 return conn;
56687851196eSmatthias.ringwald             default:
56697851196eSmatthias.ringwald                 break;
56707851196eSmatthias.ringwald         };
56717851196eSmatthias.ringwald     }
56727851196eSmatthias.ringwald     return NULL;
56737851196eSmatthias.ringwald }
56747851196eSmatthias.ringwald 
5675d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
5676d8e8f12aSMatthias Ringwald     hci_connection_t * conn = gap_get_outgoing_connection();
5677616edd56SMatthias Ringwald     if (!conn) return 0;
56787851196eSmatthias.ringwald     switch (conn->state){
56797851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
56807851196eSmatthias.ringwald             // skip sending create connection and emit event instead
568110f8f469SMatthias Ringwald             hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
56822e77e513S[email protected]             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
5683665d90f2SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
56847851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
56850bf6344aS[email protected]             break;
5686a6725849S[email protected]         case SENT_CREATE_CONNECTION:
56877851196eSmatthias.ringwald             // request to send cancel connection
56880bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
56890bf6344aS[email protected]             hci_run();
56900bf6344aS[email protected]             break;
56910bf6344aS[email protected]         default:
56920bf6344aS[email protected]             break;
56930bf6344aS[email protected]     }
5694616edd56SMatthias Ringwald     return 0;
5695e31f89a7S[email protected] }
5696d70217a2SMatthias Ringwald #endif
56974f3229d8S[email protected] 
569813e645d2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5699c37a3166S[email protected] /**
57006012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
5701cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
5702cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
57036012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
57046012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
57056012052bSMatthias Ringwald  * @param conn_latency, default: 4
57066012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
57076012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
57086012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
57096012052bSMatthias Ringwald  */
57106012052bSMatthias Ringwald 
5711cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
5712cbe54ab2SJakob Krantz     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
5713cbe54ab2SJakob Krantz     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
5714cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
5715cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
57166012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
57176012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
57186012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
57196012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
57206012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
57216012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
57226012052bSMatthias Ringwald }
572313e645d2SMatthias Ringwald #endif
57246012052bSMatthias Ringwald 
57256012052bSMatthias Ringwald /**
5726c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
5727c37a3166S[email protected]  * @param handle
5728c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
5729c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
5730c37a3166S[email protected]  * @param conn_latency
5731c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
5732c37a3166S[email protected]  * @returns 0 if ok
5733c37a3166S[email protected]  */
5734c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5735c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5736c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5737c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5738c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
5739c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
5740c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
5741c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
574284cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
5743cfc59f1bSMatthias Ringwald     hci_run();
5744c37a3166S[email protected]     return 0;
5745c37a3166S[email protected] }
5746c37a3166S[email protected] 
574745c102fdSMatthias Ringwald /**
5748b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
5749b68d7bc3SMatthias Ringwald  * @param handle
5750b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
5751b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
5752b68d7bc3SMatthias Ringwald  * @param conn_latency
5753b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
5754b68d7bc3SMatthias Ringwald  * @returns 0 if ok
5755b68d7bc3SMatthias Ringwald  */
5756b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5757b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5758b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5759b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5760b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
5761b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
5762b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
5763b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
5764b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
576509c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
576609c9c963SMatthias Ringwald     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5767b68d7bc3SMatthias Ringwald     return 0;
5768b68d7bc3SMatthias Ringwald }
5769b68d7bc3SMatthias Ringwald 
5770d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5771d70217a2SMatthias Ringwald 
5772b68d7bc3SMatthias Ringwald /**
577345c102fdSMatthias Ringwald  * @brief Set Advertisement Data
577445c102fdSMatthias Ringwald  * @param advertising_data_length
577545c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
577645c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
577745c102fdSMatthias Ringwald  */
577845c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
577945c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
578045c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
5781501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5782bbc366e6SMatthias Ringwald     hci_run();
578345c102fdSMatthias Ringwald }
5784501f56b3SMatthias Ringwald 
5785501f56b3SMatthias Ringwald /**
5786501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
5787501f56b3SMatthias Ringwald  * @param advertising_data_length
5788501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
5789501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
5790501f56b3SMatthias Ringwald  */
5791501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5792501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
5793501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
5794501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5795bbc366e6SMatthias Ringwald     hci_run();
579645c102fdSMatthias Ringwald }
579745c102fdSMatthias Ringwald 
579845c102fdSMatthias Ringwald /**
579945c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
580045c102fdSMatthias Ringwald  * @param adv_int_min
580145c102fdSMatthias Ringwald  * @param adv_int_max
580245c102fdSMatthias Ringwald  * @param adv_type
580345c102fdSMatthias Ringwald  * @param direct_address_type
580445c102fdSMatthias Ringwald  * @param direct_address
580545c102fdSMatthias Ringwald  * @param channel_map
580645c102fdSMatthias Ringwald  * @param filter_policy
580745c102fdSMatthias Ringwald  *
580845c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
580945c102fdSMatthias Ringwald  */
581045c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5811b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
581245c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
581345c102fdSMatthias Ringwald 
581445c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
581545c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
581645c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
581745c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
581845c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
581945c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
58206535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
58216535961aSMatthias Ringwald                  6);
582245c102fdSMatthias Ringwald 
5823a61834b6SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET;
5824bbc366e6SMatthias Ringwald     hci_run();
582545c102fdSMatthias Ringwald  }
582645c102fdSMatthias Ringwald 
582745c102fdSMatthias Ringwald /**
582845c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
582945c102fdSMatthias Ringwald  * @param enabled
583045c102fdSMatthias Ringwald  */
583145c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
58325226d7f2SMatthias Ringwald     hci_stack->le_advertisements_enabled = enabled != 0;
5833bbc366e6SMatthias Ringwald     hci_update_advertisements_enabled_for_current_roles();
5834cfc59f1bSMatthias Ringwald     hci_run();
583545c102fdSMatthias Ringwald }
583645c102fdSMatthias Ringwald 
583735454696SMatthias Ringwald #endif
583806e5cf96SMatthias Ringwald 
583906e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
584006e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
584106e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
584206e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
584306e5cf96SMatthias Ringwald 
584464068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
584506e5cf96SMatthias Ringwald     // update advertisement parameters, too
584606e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5847bbc366e6SMatthias Ringwald     hci_run();
584864068776SMatthias Ringwald #endif
584964068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
585006e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
585164068776SMatthias Ringwald #endif
585206e5cf96SMatthias Ringwald }
585306e5cf96SMatthias Ringwald 
5854d70217a2SMatthias Ringwald #endif
585545c102fdSMatthias Ringwald 
5856616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
58575917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
58585917a5c5S[email protected]     if (!conn){
58597851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
5860616edd56SMatthias Ringwald         return 0;
58615917a5c5S[email protected]     }
58627fd7aa6fSMatthias Ringwald     // ignore if already disconnected
58637fd7aa6fSMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
58647fd7aa6fSMatthias Ringwald         return 0;
58657fd7aa6fSMatthias Ringwald     }
58665917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
58675917a5c5S[email protected]     hci_run();
5868616edd56SMatthias Ringwald     return 0;
58694f3229d8S[email protected] }
587004a6ef8cSmatthias.ringwald 
5871228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
5872228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5873228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
58748daf94bcSMatthias Ringwald     connectionSetAuthenticationFlags(hci_connection, AUTH_FLAG_READ_RSSI);
5875228e430cSMatthias Ringwald     hci_run();
5876228e430cSMatthias Ringwald     return 1;
5877228e430cSMatthias Ringwald }
5878228e430cSMatthias Ringwald 
5879a1bf5ae7SMatthias Ringwald /**
5880a1bf5ae7SMatthias Ringwald  * @brief Get connection type
5881a1bf5ae7SMatthias Ringwald  * @param con_handle
5882a1bf5ae7SMatthias Ringwald  * @result connection_type
5883a1bf5ae7SMatthias Ringwald  */
5884a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
5885a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5886a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
5887a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
5888a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
5889a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
5890a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
5891a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
5892a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
5893f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
5894a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
5895a1bf5ae7SMatthias Ringwald         default:
5896a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
5897a1bf5ae7SMatthias Ringwald     }
5898a1bf5ae7SMatthias Ringwald }
5899a1bf5ae7SMatthias Ringwald 
59002dceb1d6SMatthias Ringwald hci_role_t gap_get_role(hci_con_handle_t connection_handle){
59012dceb1d6SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
59022dceb1d6SMatthias Ringwald     if (!conn) return HCI_ROLE_INVALID;
59032dceb1d6SMatthias Ringwald     return (hci_role_t) conn->role;
59042dceb1d6SMatthias Ringwald }
59052dceb1d6SMatthias Ringwald 
59062dceb1d6SMatthias Ringwald 
590744f858f3SMatthias Ringwald #ifdef ENABLE_CLASSIC
5908667ba9d1SMatthias Ringwald uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){
590988a03c8dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
591088a03c8dSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
591188a03c8dSMatthias Ringwald     conn->request_role = role;
591288a03c8dSMatthias Ringwald     hci_run();
5913d04a455eSMatthias Ringwald     return ERROR_CODE_SUCCESS;
591488a03c8dSMatthias Ringwald }
591544f858f3SMatthias Ringwald #endif
591688a03c8dSMatthias Ringwald 
5917a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
59184f551432SMatthias Ringwald 
5919b45b7749SMilanka Ringwald uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
5920b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5921b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5922b90f6e0aSMatthias Ringwald 
5923b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
5924b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
5925b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
5926b90f6e0aSMatthias Ringwald     conn->le_phy_update_phy_options = phy_options;
5927b90f6e0aSMatthias Ringwald 
5928b90f6e0aSMatthias Ringwald     hci_run();
5929b90f6e0aSMatthias Ringwald 
5930b90f6e0aSMatthias Ringwald     return 0;
5931b90f6e0aSMatthias Ringwald }
5932b90f6e0aSMatthias Ringwald 
5933667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
59347a92a9dbSMatthias Ringwald     // check if already in list
59357a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_t it;
59367a92a9dbSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
59377a92a9dbSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)) {
59387a92a9dbSMatthias Ringwald         whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it);
59397a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
59407a92a9dbSMatthias Ringwald             continue;
59417a92a9dbSMatthias Ringwald         }
59427a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
59437a92a9dbSMatthias Ringwald             continue;
59447a92a9dbSMatthias Ringwald         }
5945287379ccSMatthias Ringwald 		// disallow if already scheduled to add
5946287379ccSMatthias Ringwald 		if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){
59477a92a9dbSMatthias Ringwald 			return ERROR_CODE_COMMAND_DISALLOWED;
59487a92a9dbSMatthias Ringwald 		}
5949287379ccSMatthias Ringwald 		// still on controller, but scheduled to remove -> re-add
5950287379ccSMatthias Ringwald 		entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER;
5951287379ccSMatthias Ringwald 		return ERROR_CODE_SUCCESS;
5952287379ccSMatthias Ringwald     }
59537a92a9dbSMatthias Ringwald     // alloc and add to list
5954e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
5955e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
5956e83201bcSMatthias Ringwald     entry->address_type = address_type;
59576535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
5958e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5959665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
5960226db5efSMatthias Ringwald     return ERROR_CODE_SUCCESS;
5961ac9c45e0SMatthias Ringwald }
5962ac9c45e0SMatthias Ringwald 
5963667ba9d1SMatthias Ringwald static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
5964665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
5965665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5966665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5967665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
59687a92a9dbSMatthias Ringwald         if (entry->address_type != address_type) {
59697a92a9dbSMatthias Ringwald             continue;
59707a92a9dbSMatthias Ringwald         }
59717a92a9dbSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) {
59727a92a9dbSMatthias Ringwald             continue;
59737a92a9dbSMatthias Ringwald         }
5974e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5975e83201bcSMatthias Ringwald             // remove from controller if already present
5976e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5977a3b69fdeSMatthias Ringwald         }  else {
5978226db5efSMatthias Ringwald             // directly remove entry from whitelist
5979665d90f2SMatthias Ringwald             btstack_linked_list_iterator_remove(&it);
5980e83201bcSMatthias Ringwald             btstack_memory_whitelist_entry_free(entry);
5981e83201bcSMatthias Ringwald         }
5982a3b69fdeSMatthias Ringwald         return ERROR_CODE_SUCCESS;
5983a3b69fdeSMatthias Ringwald     }
5984a3b69fdeSMatthias Ringwald     return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
598542ff5ba1SMatthias Ringwald }
598642ff5ba1SMatthias Ringwald 
5987226db5efSMatthias Ringwald static void hci_whitelist_clear(void){
5988665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
5989665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5990665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5991665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5992e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5993e83201bcSMatthias Ringwald             // remove from controller if already present
5994e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5995e83201bcSMatthias Ringwald             continue;
5996e83201bcSMatthias Ringwald         }
599791915b0bSMatthias Ringwald         // directly remove entry from whitelist
5998665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
5999e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
6000e83201bcSMatthias Ringwald     }
6001226db5efSMatthias Ringwald }
6002226db5efSMatthias Ringwald 
6003a3b69fdeSMatthias Ringwald /**
6004a3b69fdeSMatthias Ringwald  * @brief Clear Whitelist
6005a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6006a3b69fdeSMatthias Ringwald  */
6007a3b69fdeSMatthias Ringwald uint8_t gap_whitelist_clear(void){
6008a3b69fdeSMatthias Ringwald     hci_whitelist_clear();
6009a3b69fdeSMatthias Ringwald     hci_run();
6010a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6011a3b69fdeSMatthias Ringwald }
6012a3b69fdeSMatthias Ringwald 
6013a3b69fdeSMatthias Ringwald /**
6014a3b69fdeSMatthias Ringwald  * @brief Add Device to Whitelist
6015a3b69fdeSMatthias Ringwald  * @param address_typ
6016a3b69fdeSMatthias Ringwald  * @param address
6017a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6018a3b69fdeSMatthias Ringwald  */
6019667ba9d1SMatthias Ringwald uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){
6020a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
6021a3b69fdeSMatthias Ringwald     if (status){
6022a3b69fdeSMatthias Ringwald         return status;
6023a3b69fdeSMatthias Ringwald     }
6024a3b69fdeSMatthias Ringwald     hci_run();
6025a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6026a3b69fdeSMatthias Ringwald }
6027a3b69fdeSMatthias Ringwald 
6028a3b69fdeSMatthias Ringwald /**
6029a3b69fdeSMatthias Ringwald  * @brief Remove Device from Whitelist
6030a3b69fdeSMatthias Ringwald  * @param address_typ
6031a3b69fdeSMatthias Ringwald  * @param address
6032a3b69fdeSMatthias Ringwald  * @returns 0 if ok
6033a3b69fdeSMatthias Ringwald  */
6034667ba9d1SMatthias Ringwald uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){
6035a3b69fdeSMatthias Ringwald     uint8_t status = hci_whitelist_remove(address_type, address);
6036a3b69fdeSMatthias Ringwald     if (status){
6037a3b69fdeSMatthias Ringwald         return status;
6038a3b69fdeSMatthias Ringwald     }
6039a3b69fdeSMatthias Ringwald     hci_run();
6040a3b69fdeSMatthias Ringwald     return ERROR_CODE_SUCCESS;
6041a3b69fdeSMatthias Ringwald }
6042a3b69fdeSMatthias Ringwald 
6043226db5efSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
6044226db5efSMatthias Ringwald /**
604595e257d9SMatthias Ringwald  *  @brief Connect with Whitelist
604695e257d9SMatthias Ringwald  *  @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions
604795e257d9SMatthias Ringwald  *  @returns - if ok
604895e257d9SMatthias Ringwald  */
604995e257d9SMatthias Ringwald uint8_t gap_connect_with_whitelist(void){
605095e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){
605195e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
605295e257d9SMatthias Ringwald     }
605395e257d9SMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
605495e257d9SMatthias Ringwald     hci_run();
605595e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
605695e257d9SMatthias Ringwald }
605795e257d9SMatthias Ringwald 
605895e257d9SMatthias Ringwald /**
6059226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
6060226db5efSMatthias Ringwald  * @param address_typ
6061226db5efSMatthias Ringwald  * @param address
6062226db5efSMatthias Ringwald  * @returns 0 if ok
6063226db5efSMatthias Ringwald  */
6064667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){
606595e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
6066226db5efSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
6067226db5efSMatthias Ringwald     }
6068226db5efSMatthias Ringwald 
6069226db5efSMatthias Ringwald     uint8_t status = hci_whitelist_add(address_type, address);
607063f2efc9SMatthias Ringwald     if (status == BTSTACK_MEMORY_ALLOC_FAILED) {
6071226db5efSMatthias Ringwald         return status;
6072226db5efSMatthias Ringwald     }
6073226db5efSMatthias Ringwald 
6074226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST;
6075226db5efSMatthias Ringwald 
6076226db5efSMatthias Ringwald     hci_run();
607795e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6078226db5efSMatthias Ringwald }
6079226db5efSMatthias Ringwald 
6080226db5efSMatthias Ringwald /**
6081226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
6082226db5efSMatthias Ringwald  * @param address_typ
6083226db5efSMatthias Ringwald  * @param address
6084226db5efSMatthias Ringwald  * @returns 0 if ok
6085226db5efSMatthias Ringwald  */
6086667ba9d1SMatthias Ringwald uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){
608795e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){
608895e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
608995e257d9SMatthias Ringwald     }
609095e257d9SMatthias Ringwald 
6091226db5efSMatthias Ringwald     hci_whitelist_remove(address_type, address);
609295e257d9SMatthias Ringwald     if (btstack_linked_list_empty(&hci_stack->le_whitelist)){
609395e257d9SMatthias Ringwald         hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
609495e257d9SMatthias Ringwald     }
6095226db5efSMatthias Ringwald     hci_run();
6096226db5efSMatthias Ringwald     return 0;
6097226db5efSMatthias Ringwald }
6098226db5efSMatthias Ringwald 
6099226db5efSMatthias Ringwald /**
6100226db5efSMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
6101226db5efSMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
6102226db5efSMatthias Ringwald  */
610395e257d9SMatthias Ringwald uint8_t gap_auto_connection_stop_all(void){
610495e257d9SMatthias Ringwald     if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) {
610595e257d9SMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
610695e257d9SMatthias Ringwald     }
6107226db5efSMatthias Ringwald     hci_whitelist_clear();
6108226db5efSMatthias Ringwald     hci_stack->le_connecting_request = LE_CONNECTING_IDLE;
6109e83201bcSMatthias Ringwald     hci_run();
611095e257d9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6111ac9c45e0SMatthias Ringwald }
6112c9db5c21SMilanka Ringwald 
6113b45b7749SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){
6114b45b7749SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6115c9db5c21SMilanka Ringwald     if (!conn) return 0;
6116c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
6117c9db5c21SMilanka Ringwald }
6118d70217a2SMatthias Ringwald #endif
61194f551432SMatthias Ringwald #endif
61204f551432SMatthias Ringwald 
612135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
6122ac9c45e0SMatthias Ringwald /**
6123ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
6124a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
6125ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
6126ff00ed1cSMatthias Ringwald  */
6127ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
6128ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
6129ff00ed1cSMatthias Ringwald }
6130ff00ed1cSMatthias Ringwald 
6131ff00ed1cSMatthias Ringwald /**
6132f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
6133f5875de5SMatthias Ringwald  * @param duration in 1.28s units
6134f5875de5SMatthias Ringwald  * @return 0 if ok
6135f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
6136f5875de5SMatthias Ringwald  */
6137f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
613899449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
6139f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6140a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
6141f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
6142f5875de5SMatthias Ringwald     }
6143f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
6144f5875de5SMatthias Ringwald     hci_run();
6145f5875de5SMatthias Ringwald     return 0;
6146f5875de5SMatthias Ringwald }
6147f5875de5SMatthias Ringwald 
6148f5875de5SMatthias Ringwald /**
6149f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
6150f5875de5SMatthias Ringwald  * @returns 0 if ok
6151f5875de5SMatthias Ringwald  */
6152f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
6153a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
6154f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
6155f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
6156f5875de5SMatthias Ringwald         hci_emit_event(event, sizeof(event), 1);
6157f5875de5SMatthias Ringwald         return 0;
6158f5875de5SMatthias Ringwald     }
6159f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
6160f5875de5SMatthias Ringwald     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
6161f5875de5SMatthias Ringwald     hci_run();
6162f5875de5SMatthias Ringwald     return 0;
6163f5875de5SMatthias Ringwald }
6164f5875de5SMatthias Ringwald 
6165496bb884SMatthias Ringwald void gap_inquiry_set_lap(uint32_t lap){
6166496bb884SMatthias Ringwald     hci_stack->inquiry_lap = lap;
6167496bb884SMatthias Ringwald }
6168496bb884SMatthias Ringwald 
6169b7f1ee76SMatthias Ringwald 
6170b7f1ee76SMatthias Ringwald /**
6171b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
6172b7f1ee76SMatthias Ringwald  * @param addr
6173b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
6174b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
6175b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
6176b7f1ee76SMatthias Ringwald  */
6177667ba9d1SMatthias Ringwald int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
6178b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
61796535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
6180b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
6181b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
6182b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
6183b7f1ee76SMatthias Ringwald     hci_run();
6184b7f1ee76SMatthias Ringwald     return 0;
6185b7f1ee76SMatthias Ringwald }
6186b7f1ee76SMatthias Ringwald 
6187667ba9d1SMatthias Ringwald static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){
61880a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
61896535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
61900a51f88bSMatthias Ringwald     hci_run();
61910a51f88bSMatthias Ringwald     return 0;
61920a51f88bSMatthias Ringwald }
61930a51f88bSMatthias Ringwald 
61940a51f88bSMatthias Ringwald /**
6195aad97216SMatthias Ringwald  * @brief Legacy Pairing Pin Code Response for binary data / non-strings
6196aad97216SMatthias Ringwald  * @param addr
6197aad97216SMatthias Ringwald  * @param pin_data
6198aad97216SMatthias Ringwald  * @param pin_len
6199aad97216SMatthias Ringwald  * @return 0 if ok
6200aad97216SMatthias Ringwald  */
6201667ba9d1SMatthias Ringwald int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){
6202aad97216SMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6203aad97216SMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin_data;
6204aad97216SMatthias Ringwald     hci_stack->gap_pairing_pin_len = pin_len;
6205aad97216SMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
6206aad97216SMatthias Ringwald }
6207aad97216SMatthias Ringwald 
6208aad97216SMatthias Ringwald /**
62090a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
62100a51f88bSMatthias Ringwald  * @param addr
62110a51f88bSMatthias Ringwald  * @param pin
62120a51f88bSMatthias Ringwald  * @return 0 if ok
62130a51f88bSMatthias Ringwald  */
6214667ba9d1SMatthias Ringwald int gap_pin_code_response(const bd_addr_t addr, const char * pin){
6215aad97216SMatthias Ringwald     return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin));
62160a51f88bSMatthias Ringwald }
62170a51f88bSMatthias Ringwald 
62180a51f88bSMatthias Ringwald /**
62190a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
62200a51f88bSMatthias Ringwald  * @param addr
62210a51f88bSMatthias Ringwald  * @param pin
62220a51f88bSMatthias Ringwald  * @return 0 if ok
62230a51f88bSMatthias Ringwald  */
62240a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
6225cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
62260a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
62270a51f88bSMatthias Ringwald }
62280a51f88bSMatthias Ringwald 
62290a51f88bSMatthias Ringwald /**
62300a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
62310a51f88bSMatthias Ringwald  * @param addr
62320a51f88bSMatthias Ringwald  * @param passkey
62330a51f88bSMatthias Ringwald  * @return 0 if ok
62340a51f88bSMatthias Ringwald  */
6235667ba9d1SMatthias Ringwald int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){
6236cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
6237d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
62380a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
62390a51f88bSMatthias Ringwald }
62400a51f88bSMatthias Ringwald 
62410a51f88bSMatthias Ringwald /**
62420a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
62430a51f88bSMatthias Ringwald  * @param addr
62440a51f88bSMatthias Ringwald  * @param pin
62450a51f88bSMatthias Ringwald  * @return 0 if ok
62460a51f88bSMatthias Ringwald  */
6247667ba9d1SMatthias Ringwald int gap_ssp_passkey_negative(const bd_addr_t addr){
6248cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
62490a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
62500a51f88bSMatthias Ringwald }
62510a51f88bSMatthias Ringwald 
62520a51f88bSMatthias Ringwald /**
62530a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
62540a51f88bSMatthias Ringwald  * @param addr
62550a51f88bSMatthias Ringwald  * @param passkey
62560a51f88bSMatthias Ringwald  * @return 0 if ok
62570a51f88bSMatthias Ringwald  */
6258667ba9d1SMatthias Ringwald int gap_ssp_confirmation_response(const bd_addr_t addr){
6259cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
62600a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
62610a51f88bSMatthias Ringwald }
62620a51f88bSMatthias Ringwald 
62630a51f88bSMatthias Ringwald /**
62640a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
62650a51f88bSMatthias Ringwald  * @param addr
62660a51f88bSMatthias Ringwald  * @param pin
62670a51f88bSMatthias Ringwald  * @return 0 if ok
62680a51f88bSMatthias Ringwald  */
6269667ba9d1SMatthias Ringwald int gap_ssp_confirmation_negative(const bd_addr_t addr){
6270cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
62710a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
62720a51f88bSMatthias Ringwald }
62730a51f88bSMatthias Ringwald 
627444565b0cSMatthias Ringwald #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY
627544565b0cSMatthias Ringwald 
627644565b0cSMatthias Ringwald static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){
627744565b0cSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
627844565b0cSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
627944565b0cSMatthias Ringwald     connectionSetAuthenticationFlags(conn, flag);
628044565b0cSMatthias Ringwald     hci_run();
628144565b0cSMatthias Ringwald     return ERROR_CODE_SUCCESS;
628244565b0cSMatthias Ringwald }
628344565b0cSMatthias Ringwald 
628444565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){
628544565b0cSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_REPLY);
628644565b0cSMatthias Ringwald }
628744565b0cSMatthias Ringwald 
628844565b0cSMatthias Ringwald uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){
628944565b0cSMatthias Ringwald     return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_NEGATIVE_REPLY);
629044565b0cSMatthias Ringwald }
629144565b0cSMatthias Ringwald #endif
629244565b0cSMatthias Ringwald 
62931849becdSMatthias Ringwald #ifdef ENABLE_CLASSIC_PAIRING_OOB
62941849becdSMatthias Ringwald /**
62951849becdSMatthias Ringwald  * @brief Report Remote OOB Data
62961849becdSMatthias Ringwald  * @param bd_addr
62971849becdSMatthias Ringwald  * @param c_192 Simple Pairing Hash C derived from P-192 public key
62981849becdSMatthias Ringwald  * @param r_192 Simple Pairing Randomizer derived from P-192 public key
62991849becdSMatthias Ringwald  * @param c_256 Simple Pairing Hash C derived from P-256 public key
63001849becdSMatthias Ringwald  * @param r_256 Simple Pairing Randomizer derived from P-256 public key
63011849becdSMatthias Ringwald  */
63021849becdSMatthias 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){
63031849becdSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
63041849becdSMatthias Ringwald     if (connection == NULL) {
63051849becdSMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
63061849becdSMatthias Ringwald     }
63071849becdSMatthias Ringwald     connection->classic_oob_c_192 = c_192;
63081849becdSMatthias Ringwald     connection->classic_oob_r_192 = r_192;
63091849becdSMatthias Ringwald     connection->classic_oob_c_256 = c_256;
63101849becdSMatthias Ringwald     connection->classic_oob_r_256 = r_256;
63111849becdSMatthias Ringwald     return ERROR_CODE_SUCCESS;
63121849becdSMatthias Ringwald }
6313cf01e888SMatthias Ringwald /**
6314cf01e888SMatthias Ringwald  * @brief Generate new OOB data
6315cf01e888SMatthias Ringwald  * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures
6316cf01e888SMatthias Ringwald  */
6317cf01e888SMatthias Ringwald void gap_ssp_generate_oob_data(void){
6318cf01e888SMatthias Ringwald     hci_stack->classic_read_local_oob_data = true;
6319cf01e888SMatthias Ringwald     hci_run();
6320cf01e888SMatthias Ringwald }
6321cf01e888SMatthias Ringwald 
63221849becdSMatthias Ringwald #endif
63231849becdSMatthias Ringwald 
6324f5875de5SMatthias Ringwald /**
6325f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
6326f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
6327f6858d14SMatthias Ringwald  */
6328b45b7749SMilanka Ringwald void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){
6329b45b7749SMilanka Ringwald     hci_stack->inquiry_mode = inquiry_mode;
6330f6858d14SMatthias Ringwald }
6331f6858d14SMatthias Ringwald 
6332f6858d14SMatthias Ringwald /**
6333d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
6334d950d659SMatthias Ringwald  */
6335d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
6336d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
6337d950d659SMatthias Ringwald }
6338d950d659SMatthias Ringwald 
6339d950d659SMatthias Ringwald /**
6340d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
6341d950d659SMatthias Ringwald  * @return current voice setting
6342d950d659SMatthias Ringwald  */
63430cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
6344d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
6345d950d659SMatthias Ringwald }
6346d950d659SMatthias Ringwald 
6347400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
6348400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
6349400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
6350400ff5abSMatthias Ringwald     if (!transport_name) return 0;
6351400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
6352400ff5abSMatthias Ringwald }
6353400ff5abSMatthias Ringwald 
6354b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
6355b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
6356b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
6357b3aad8daSMatthias Ringwald  */
6358b3aad8daSMatthias Ringwald int hci_get_sco_packet_length(void){
6359a3069afeSMatthias Ringwald     int sco_packet_length = 0;
6360cf119f3bSMatthias Ringwald 
63611e20a53eSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
63626f28d2eeSMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
63631431ce27SMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
6364cf119f3bSMatthias Ringwald 
6365400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
6366400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
6367cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
636852e46257SMatthias Ringwald         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
636952e46257SMatthias Ringwald         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
6370400ff5abSMatthias Ringwald     } else {
6371400ff5abSMatthias Ringwald         // 3 byte SCO header + SCO packet size over the air (60 bytes)
6372400ff5abSMatthias Ringwald         sco_packet_length = 3 + 60 * multiplier;
6373d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
6374d966a453SMatthias Ringwald         if (sco_packet_length > hci_stack->sco_data_packet_length){
6375d966a453SMatthias Ringwald             sco_packet_length = 3 + 60;
6376d966a453SMatthias Ringwald         }
6377400ff5abSMatthias Ringwald     }
6378a3069afeSMatthias Ringwald #endif
63795b7087c7SMatthias Ringwald 
63805b7087c7SMatthias Ringwald #ifdef HAVE_SCO_TRANSPORT
63815b7087c7SMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
63821e20a53eSMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
63835b7087c7SMatthias Ringwald     sco_packet_length = 3 + 60 * multiplier;
63845b7087c7SMatthias Ringwald #endif
6385a3069afeSMatthias Ringwald     return sco_packet_length;
6386b3aad8daSMatthias Ringwald }
6387b3aad8daSMatthias Ringwald 
6388c4c88f1bSJakob Krantz /**
6389c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
6390c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
6391c4c88f1bSJakob Krantz */
6392c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
6393c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
6394c4c88f1bSJakob Krantz }
6395c4c88f1bSJakob Krantz 
6396c4c88f1bSJakob Krantz #endif
6397ec111c8bSMatthias Ringwald 
6398ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
6399ec111c8bSMatthias Ringwald     return hci_stack->state;
6400ec111c8bSMatthias Ringwald }
6401ec111c8bSMatthias Ringwald 
640207e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
64035e91d96cSMatthias Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){
640407e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
640507e010b6SMilanka Ringwald }
640607e010b6SMilanka Ringwald #endif
6407ec111c8bSMatthias Ringwald 
6408d950d659SMatthias Ringwald /**
6409d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
6410d23838ecSMatthias Ringwald  */
6411c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
6412d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
6413d23838ecSMatthias Ringwald }
6414d23838ecSMatthias Ringwald 
641571de195eSMatthias Ringwald void hci_disconnect_all(void){
6416665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
6417665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6418665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6419665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
642004a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
642104a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
642204a6ef8cSmatthias.ringwald     }
6423d31fba26S[email protected]     hci_run();
642404a6ef8cSmatthias.ringwald }
642533373e40SMatthias Ringwald 
642633373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
642733373e40SMatthias Ringwald     return hci_stack->manufacturer;
642833373e40SMatthias Ringwald }
64299c6e867eSMatthias Ringwald 
64303e329ddfSandryblack #ifdef ENABLE_BLE
64319c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
64329c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
64339c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
64349c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
64359c6e867eSMatthias Ringwald }
64369c6e867eSMatthias Ringwald 
64379c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
64389c6e867eSMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
64396a79f6baSMatthias Ringwald #endif
64409c6e867eSMatthias Ringwald 
64419c6e867eSMatthias Ringwald int gap_encryption_key_size(hci_con_handle_t con_handle){
6442c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6443c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
6444c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
64456a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
6446c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
6447c5fb5ca4SMatthias Ringwald         if (sm_conn->sm_connection_encrypted) {
64489c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
64499c6e867eSMatthias Ringwald         }
64506a79f6baSMatthias Ringwald #endif
64516a79f6baSMatthias Ringwald     } else {
6452c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
64538daf94bcSMatthias Ringwald         if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){
6454c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
6455c5fb5ca4SMatthias Ringwald         }
6456c5fb5ca4SMatthias Ringwald #endif
64576a79f6baSMatthias Ringwald     }
6458c5fb5ca4SMatthias Ringwald     return 0;
6459c5fb5ca4SMatthias Ringwald }
64609c6e867eSMatthias Ringwald 
64619c6e867eSMatthias Ringwald int gap_authenticated(hci_con_handle_t con_handle){
6462c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6463c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
64645f3981bfSMatthias Ringwald 
6465c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
64666a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
64675f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
64685f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6469c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6470c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated;
64716a79f6baSMatthias Ringwald #endif
647259a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
64735f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
6474f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6475c5fb5ca4SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
647659a1a47aSMatthias Ringwald #endif
64775f3981bfSMatthias Ringwald         default:
64785f3981bfSMatthias Ringwald             return 0;
64795f3981bfSMatthias Ringwald     }
64809c6e867eSMatthias Ringwald }
64819c6e867eSMatthias Ringwald 
6482f1dfbe18SMatthias Ringwald int gap_secure_connection(hci_con_handle_t con_handle){
6483c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
6484c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
64858b35e16aSMatthias Ringwald 
6486c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
64876a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
64888b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
64898b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
6490c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
6491c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc;
64926a79f6baSMatthias Ringwald #endif
649359a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
64948b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
6495f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
6496c5fb5ca4SMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
649759a1a47aSMatthias Ringwald #endif
64988b35e16aSMatthias Ringwald         default:
64998b35e16aSMatthias Ringwald             return 0;
65008b35e16aSMatthias Ringwald     }
6501f1dfbe18SMatthias Ringwald }
6502f1dfbe18SMatthias Ringwald 
65031e122704SMatthias Ringwald bool gap_bonded(hci_con_handle_t con_handle){
65041e122704SMatthias Ringwald 	hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
65051e122704SMatthias Ringwald 	if (hci_connection == NULL) return 0;
65061e122704SMatthias Ringwald 
650748f33f37SMatthias Ringwald #ifdef ENABLE_CLASSIC
65081e122704SMatthias Ringwald 	link_key_t link_key;
65091e122704SMatthias Ringwald 	link_key_type_t link_key_type;
651048f33f37SMatthias Ringwald #endif
65111e122704SMatthias Ringwald 	switch (hci_connection->address_type){
65126a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
65131e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_PUBLIC:
65141e122704SMatthias Ringwald 		case BD_ADDR_TYPE_LE_RANDOM:
65151e122704SMatthias Ringwald 			return hci_connection->sm_connection.sm_le_db_index >= 0;
65166a79f6baSMatthias Ringwald #endif
65171e122704SMatthias Ringwald #ifdef ENABLE_CLASSIC
65181e122704SMatthias Ringwald 		case BD_ADDR_TYPE_SCO:
65191e122704SMatthias Ringwald 		case BD_ADDR_TYPE_ACL:
65201e122704SMatthias Ringwald 			return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type);
65211e122704SMatthias Ringwald #endif
65221e122704SMatthias Ringwald 		default:
65231e122704SMatthias Ringwald 			return false;
65241e122704SMatthias Ringwald 	}
65251e122704SMatthias Ringwald }
65261e122704SMatthias Ringwald 
65276a79f6baSMatthias Ringwald #ifdef ENABLE_BLE
65289c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
65299c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
65309c6e867eSMatthias Ringwald     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
65319c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
65329c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
65339c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
65349c6e867eSMatthias Ringwald }
65359c6e867eSMatthias Ringwald #endif
6536f8ee3071SMatthias Ringwald 
6537f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
6538f8ee3071SMatthias 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){
6539f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6540f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6541f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
6542f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
6543f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
6544f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
6545f8ee3071SMatthias Ringwald     hci_run();
6546f8ee3071SMatthias Ringwald     return 0;
6547f8ee3071SMatthias Ringwald }
6548f8ee3071SMatthias Ringwald 
6549f8ee3071SMatthias Ringwald /**
6550f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
6551f8ee3071SMatthias Ringwald  * @param con_handle
6552f8ee3071SMatthias Ringwald  @ @return 0 if ok
6553f8ee3071SMatthias Ringwald  */
6554f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
6555f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6556f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6557f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
6558f8ee3071SMatthias Ringwald     hci_run();
6559f8ee3071SMatthias Ringwald     return 0;
6560f8ee3071SMatthias Ringwald }
6561bea424a5SMatthias Ringwald 
6562140c0557SMatthias 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){
6563140c0557SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6564140c0557SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6565140c0557SMatthias Ringwald     conn->sniff_subrating_max_latency = max_latency;
6566140c0557SMatthias Ringwald     conn->sniff_subrating_min_remote_timeout = min_remote_timeout;
6567140c0557SMatthias Ringwald     conn->sniff_subrating_min_local_timeout = min_local_timeout;
6568140c0557SMatthias Ringwald     hci_run();
6569dc8d5bd3SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6570140c0557SMatthias Ringwald }
6571140c0557SMatthias Ringwald 
6572278ff8a9SMatthias 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){
6573278ff8a9SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
6574278ff8a9SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
6575278ff8a9SMatthias Ringwald     conn->qos_service_type = service_type;
6576278ff8a9SMatthias Ringwald     conn->qos_token_rate = token_rate;
6577278ff8a9SMatthias Ringwald     conn->qos_peak_bandwidth = peak_bandwidth;
6578278ff8a9SMatthias Ringwald     conn->qos_latency = latency;
6579278ff8a9SMatthias Ringwald     conn->qos_delay_variation = delay_variation;
6580278ff8a9SMatthias Ringwald     hci_run();
6581278ff8a9SMatthias Ringwald     return ERROR_CODE_SUCCESS;
6582278ff8a9SMatthias Ringwald }
6583278ff8a9SMatthias Ringwald 
6584bea424a5SMatthias Ringwald void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){
6585bea424a5SMatthias Ringwald     hci_stack->new_page_scan_interval = page_scan_interval;
6586bea424a5SMatthias Ringwald     hci_stack->new_page_scan_window = page_scan_window;
6587bea424a5SMatthias Ringwald     hci_run();
6588bea424a5SMatthias Ringwald }
6589bea424a5SMatthias Ringwald 
6590bea424a5SMatthias Ringwald void gap_set_page_scan_type(page_scan_type_t page_scan_type){
6591bea424a5SMatthias Ringwald     hci_stack->new_page_scan_type = (uint8_t) page_scan_type;
6592bea424a5SMatthias Ringwald     hci_run();
6593bea424a5SMatthias Ringwald }
6594bea424a5SMatthias Ringwald 
6595f8ee3071SMatthias Ringwald #endif
6596beceeddeSMatthias Ringwald 
6597beceeddeSMatthias Ringwald void hci_halting_defer(void){
6598beceeddeSMatthias Ringwald     if (hci_stack->state != HCI_STATE_HALTING) return;
6599beceeddeSMatthias Ringwald     switch (hci_stack->substate){
6600beceeddeSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
6601beceeddeSMatthias Ringwald         case HCI_HALTING_CLOSE:
6602beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
6603beceeddeSMatthias Ringwald             break;
6604beceeddeSMatthias Ringwald         default:
6605beceeddeSMatthias Ringwald             break;
6606beceeddeSMatthias Ringwald     }
6607beceeddeSMatthias Ringwald }
6608eddac615SMatthias Ringwald 
660921debf25SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
661021debf25SMatthias Ringwald void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){
661121debf25SMatthias Ringwald     if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
661221debf25SMatthias Ringwald     if (le_device_db_index >= le_device_db_max_count()) return;
661321debf25SMatthias Ringwald     uint8_t offset = le_device_db_index >> 3;
661421debf25SMatthias Ringwald     uint8_t mask = 1 << (le_device_db_index & 7);
661502b02cffSMatthias Ringwald     hci_stack->le_resolving_list_add_entries[offset] |= mask;
661621debf25SMatthias Ringwald     if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
661702b02cffSMatthias Ringwald     	// note: go back to remove entries, otherwise, a remove + add will skip the add
661802b02cffSMatthias Ringwald         hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
661902b02cffSMatthias Ringwald     }
662002b02cffSMatthias Ringwald }
662102b02cffSMatthias Ringwald 
662202b02cffSMatthias Ringwald void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){
662302b02cffSMatthias Ringwald 	if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return;
662402b02cffSMatthias Ringwald 	if (le_device_db_index >= le_device_db_max_count()) return;
662502b02cffSMatthias Ringwald 	uint8_t offset = le_device_db_index >> 3;
662602b02cffSMatthias Ringwald 	uint8_t mask = 1 << (le_device_db_index & 7);
662702b02cffSMatthias Ringwald 	hci_stack->le_resolving_list_remove_entries[offset] |= mask;
662802b02cffSMatthias Ringwald 	if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){
662902b02cffSMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES;
663021debf25SMatthias Ringwald 	}
663121debf25SMatthias Ringwald }
6632cf38a091SMatthias Ringwald 
6633cf38a091SMatthias Ringwald uint8_t gap_load_resolving_list_from_le_device_db(void){
6634cf38a091SMatthias Ringwald 	if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) {
6635cf38a091SMatthias Ringwald 		return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
6636cf38a091SMatthias Ringwald 	}
6637cf38a091SMatthias Ringwald 	if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){
6638cf38a091SMatthias Ringwald 		// restart le resolving list update
6639cf38a091SMatthias Ringwald 		hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE;
6640cf38a091SMatthias Ringwald 	}
6641cf38a091SMatthias Ringwald 	return ERROR_CODE_SUCCESS;
6642cf38a091SMatthias Ringwald }
664321debf25SMatthias Ringwald #endif
664421debf25SMatthias Ringwald 
6645eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
664618976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
664718976c74SMatthias Ringwald     hci_connection_t * conn;
664818976c74SMatthias Ringwald 
664918976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
665018976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
665118976c74SMatthias Ringwald 
66527d33cb26SMilanka Ringwald     // setup Controller info
66537d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
66547d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
66557d33cb26SMilanka Ringwald 
665618976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
665718976c74SMatthias Ringwald     addr[5] = 0x01;
665818976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
665918976c74SMatthias Ringwald     conn->con_handle = addr[5];
666018976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
666118976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
66627d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
666318976c74SMatthias Ringwald 
666418976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
666518976c74SMatthias Ringwald     addr[5] = 0x02;
666618976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
666718976c74SMatthias Ringwald     conn->con_handle = addr[5];
666818976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
666918976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
66707d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
667118976c74SMatthias Ringwald 
667218976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
667318976c74SMatthias Ringwald     addr[5] = 0x03;
667418976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
667518976c74SMatthias Ringwald     conn->con_handle = addr[5];
667618976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
667718976c74SMatthias Ringwald     conn->state = OPEN;
66787d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
667918976c74SMatthias Ringwald 
668018976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
668118976c74SMatthias Ringwald     addr[5] = 0x04;
668218976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
668318976c74SMatthias Ringwald     conn->con_handle = addr[5];
668418976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
668518976c74SMatthias Ringwald     conn->state = OPEN;
66867d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
668718976c74SMatthias Ringwald 
668818976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
668918976c74SMatthias Ringwald     addr[5] = 0x05;
669018976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
669118976c74SMatthias Ringwald     conn->con_handle = addr[5];
669218976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
669318976c74SMatthias Ringwald     conn->state = OPEN;
66947d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
66958046a24aSMatthias Ringwald     conn->sm_connection.sm_connection_encrypted = 1;
669618976c74SMatthias Ringwald }
669718976c74SMatthias Ringwald 
6698eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
6699eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
6700eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
6701eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
6702eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
6703eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
6704eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
6705eddac615SMatthias Ringwald     }
6706eddac615SMatthias Ringwald }
67071470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
67081470db0cSMatthias Ringwald     hci_init_done();
67091470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
67101470db0cSMatthias Ringwald }
6711eddac615SMatthias Ringwald #endif
6712