xref: /btstack/src/hci.c (revision be5001946fb6e2cbdacb5fdf1273814b6c01ff55)
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"
6245c102fdSMatthias Ringwald #endif
6345c102fdSMatthias Ringwald 
6493b8dc03Smatthias.ringwald #include <stdarg.h>
6593b8dc03Smatthias.ringwald #include <string.h>
6656fe0872Smatthias.ringwald #include <stdio.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 
96169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
9762473419SMatthias Ringwald 
9862473419SMatthias Ringwald #ifndef HCI_RESET_RESEND_TIMEOUT_MS
99659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
10062473419SMatthias Ringwald #endif
101ee091cf1Smatthias.ringwald 
1021cfb383eSMatthias Ringwald // Names are arbitrarily shortened to 32 bytes if not requested otherwise
1031cfb383eSMatthias Ringwald #ifndef GAP_INQUIRY_MAX_NAME_LEN
1041cfb383eSMatthias Ringwald #define GAP_INQUIRY_MAX_NAME_LEN 32
1051cfb383eSMatthias Ringwald #endif
1061cfb383eSMatthias Ringwald 
107f5875de5SMatthias Ringwald // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
108f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MIN 0x01
109f5875de5SMatthias Ringwald #define GAP_INQUIRY_DURATION_MAX 0x30
110f5875de5SMatthias Ringwald #define GAP_INQUIRY_STATE_ACTIVE 0x80
111f5875de5SMatthias Ringwald #define GAP_INQUIRY_STATE_IDLE 0
112f5875de5SMatthias Ringwald #define GAP_INQUIRY_STATE_W2_CANCEL 0x81
113f5875de5SMatthias Ringwald #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
114f5875de5SMatthias Ringwald 
115b7f1ee76SMatthias Ringwald // GAP Remote Name Request
116b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_IDLE 0
117b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W2_SEND 1
118b7f1ee76SMatthias Ringwald #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
119b7f1ee76SMatthias Ringwald 
1200a51f88bSMatthias Ringwald // GAP Pairing
1210a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_IDLE                       0
1220a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN                   1
1230a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
1240a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY               3
1250a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
1260a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
1270a51f88bSMatthias Ringwald #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
1280a51f88bSMatthias Ringwald 
1290a51f88bSMatthias Ringwald 
130b83d5eabSMatthias Ringwald // prototypes
13135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
132758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
13335454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled);
13435454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
13535454696SMatthias Ringwald static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
13667aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection);
13735454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
13835454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
139a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
14035454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
141ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
14296a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
14352db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
1449784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size);
14552db98b2SMatthias Ringwald #endif
1461cfb383eSMatthias Ringwald 
1477586ee35S[email protected] static int  hci_power_control_on(void);
1487586ee35S[email protected] static void hci_power_control_off(void);
1496da48142SSean Wilson static void hci_state_reset(void);
150fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void);
151fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
152b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
153b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
154b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
155b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
156b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
15795d71764SMatthias Ringwald static void hci_run(void);
15895d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
15995d71764SMatthias Ringwald static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
1606a5ffed8SMatthias Ringwald 
1616a5ffed8SMatthias Ringwald #ifdef ENABLE_CLASSIC
162f234b250SMatthias Ringwald static int hci_have_usb_transport(void);
1636a5ffed8SMatthias Ringwald #endif
1645d509858SMatthias Ringwald 
165a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
166e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
16739677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
168384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
16942ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
1709c77c9dbSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void);
1715d509858SMatthias Ringwald #endif
172d70217a2SMatthias Ringwald #endif
173758b46ceSmatthias.ringwald 
17406b35ec0Smatthias.ringwald // the STACK is here
1753a9fb326S[email protected] #ifndef HAVE_MALLOC
1763a9fb326S[email protected] static hci_stack_t   hci_stack_static;
1773a9fb326S[email protected] #endif
1783a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
17916833f0aSmatthias.ringwald 
1801c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
18163168530SMatthias Ringwald // default name
18263168530SMatthias Ringwald static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
18363168530SMatthias Ringwald 
18466fb9560S[email protected] // test helper
18566fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
1861c9e5e9dSMatthias Ringwald #endif
18766fb9560S[email protected] 
18896a45072S[email protected] /**
18996a45072S[email protected]  * create connection for given address
19096a45072S[email protected]  *
19196a45072S[email protected]  * @return connection OR NULL, if no memory left
19296a45072S[email protected]  */
19396a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
1941a06f663S[email protected]     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
195bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
19696a45072S[email protected]     if (!conn) return NULL;
197058e3d6bSMatthias Ringwald     bd_addr_copy(conn->address, addr);
19896a45072S[email protected]     conn->address_type = addr_type;
19996a45072S[email protected]     conn->con_handle = 0xffff;
20096a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
20196a45072S[email protected]     conn->bonding_flags = 0;
20296a45072S[email protected]     conn->requested_security_level = LEVEL_0;
20352db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
20491a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
20591a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
20696a45072S[email protected]     hci_connection_timestamp(conn);
20752db98b2SMatthias Ringwald #endif
20896a45072S[email protected]     conn->acl_recombination_length = 0;
20996a45072S[email protected]     conn->acl_recombination_pos = 0;
210ce41473eSMatthias Ringwald     conn->num_packets_sent = 0;
211760b20efSMatthias Ringwald 
212da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
213b90f6e0aSMatthias Ringwald #ifdef ENABLE_BLE
214b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys = 0xff;
215b90f6e0aSMatthias Ringwald #endif
2160f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
2170f3b27c5SMatthias Ringwald     conn->le_max_tx_octets = 27;
2180f3b27c5SMatthias Ringwald #endif
219665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
22096a45072S[email protected]     return conn;
22196a45072S[email protected] }
22266fb9560S[email protected] 
223da886c03S[email protected] 
224da886c03S[email protected] /**
225da886c03S[email protected]  * get le connection parameter range
226da886c03S[email protected] *
227da886c03S[email protected]  * @return le connection parameter range struct
228da886c03S[email protected]  */
2294ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
2304ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
231da886c03S[email protected] }
232da886c03S[email protected] 
233da886c03S[email protected] /**
234da886c03S[email protected]  * set le connection parameter range
235da886c03S[email protected]  *
236da886c03S[email protected]  */
237da886c03S[email protected] 
2384ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
2394ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
240da886c03S[email protected] }
241da886c03S[email protected] 
242da886c03S[email protected] /**
24373cd8a2aSMatthias Ringwald  * @brief Test if connection parameters are inside in existing rage
24473cd8a2aSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
24573cd8a2aSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
24673cd8a2aSMatthias Ringwald  * @param conn_latency
24773cd8a2aSMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
24873cd8a2aSMatthias Ringwald  * @returns 1 if included
24973cd8a2aSMatthias Ringwald  */
25073cd8a2aSMatthias 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){
25173cd8a2aSMatthias Ringwald     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
25273cd8a2aSMatthias Ringwald     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
25373cd8a2aSMatthias Ringwald 
25473cd8a2aSMatthias Ringwald     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
25573cd8a2aSMatthias Ringwald     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
25673cd8a2aSMatthias Ringwald 
25773cd8a2aSMatthias Ringwald     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
25873cd8a2aSMatthias Ringwald     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
25973cd8a2aSMatthias Ringwald 
26073cd8a2aSMatthias Ringwald     return 1;
26173cd8a2aSMatthias Ringwald }
26273cd8a2aSMatthias Ringwald 
26373cd8a2aSMatthias Ringwald /**
2642b6ab3e6SMatthias Ringwald  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
2652b6ab3e6SMatthias Ringwald  * @note: default: 1
2662b6ab3e6SMatthias Ringwald  * @param max_peripheral_connections
2672b6ab3e6SMatthias Ringwald  */
268d4e4907bSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2692b6ab3e6SMatthias Ringwald void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
2702b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
2712b6ab3e6SMatthias Ringwald }
272d4e4907bSMatthias Ringwald #endif
2732b6ab3e6SMatthias Ringwald 
2742b6ab3e6SMatthias Ringwald /**
275da886c03S[email protected]  * get hci connections iterator
276da886c03S[email protected]  *
277da886c03S[email protected]  * @return hci connections iterator
278da886c03S[email protected]  */
279da886c03S[email protected] 
280665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
281665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
282da886c03S[email protected] }
283da886c03S[email protected] 
28497addcc5Smatthias.ringwald /**
285ee091cf1Smatthias.ringwald  * get connection for a given handle
286ee091cf1Smatthias.ringwald  *
287ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
288ee091cf1Smatthias.ringwald  */
2895061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
290665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
291665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
292665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
293665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2943ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
295da886c03S[email protected]             return item;
296ee091cf1Smatthias.ringwald         }
297ee091cf1Smatthias.ringwald     }
298ee091cf1Smatthias.ringwald     return NULL;
299ee091cf1Smatthias.ringwald }
300ee091cf1Smatthias.ringwald 
30196a45072S[email protected] /**
30296a45072S[email protected]  * get connection for given address
30396a45072S[email protected]  *
30496a45072S[email protected]  * @return connection OR NULL, if not found
30596a45072S[email protected]  */
3062e77e513S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
307665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
308665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
309665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
310665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
31196a45072S[email protected]         if (connection->address_type != addr_type)  continue;
31296a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
31362bda3fbS[email protected]         return connection;
31462bda3fbS[email protected]     }
31562bda3fbS[email protected]     return NULL;
31662bda3fbS[email protected] }
31762bda3fbS[email protected] 
3183e5e0926SMatthias Ringwald inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
3193e5e0926SMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
3203e5e0926SMatthias Ringwald }
32152db98b2SMatthias Ringwald 
322228e430cSMatthias Ringwald inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
323228e430cSMatthias Ringwald     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
324228e430cSMatthias Ringwald }
325228e430cSMatthias Ringwald 
32652db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
32752db98b2SMatthias Ringwald 
328ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
329ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
330ee752bb8SMatthias Ringwald     int connections = 0;
331ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
332ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
333ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
334ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
335ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
336ee752bb8SMatthias Ringwald         connections++;
337ee752bb8SMatthias Ringwald     }
338ee752bb8SMatthias Ringwald     return connections;
339ee752bb8SMatthias Ringwald }
340ee752bb8SMatthias Ringwald #endif
341ee752bb8SMatthias Ringwald 
342ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
34391a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
344aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
345528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
346c785ef68Smatthias.ringwald         // connections might be timed out
347c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
348c785ef68Smatthias.ringwald     }
349f316a845SMatthias Ringwald #else
350c1ab6cc1SMatthias Ringwald     if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){
3515f26aadcSMatthias Ringwald         // connections might be timed out
3525f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
3535f26aadcSMatthias Ringwald     }
3545f26aadcSMatthias Ringwald #endif
355c785ef68Smatthias.ringwald }
356ee091cf1Smatthias.ringwald 
357ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
358aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
359528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
360f316a845SMatthias Ringwald #else
361528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
3625f26aadcSMatthias Ringwald #endif
363ee091cf1Smatthias.ringwald }
364ee091cf1Smatthias.ringwald 
36543bfb1bdSmatthias.ringwald /**
36680ca58a0Smatthias.ringwald  * add authentication flags and reset timer
36796a45072S[email protected]  * @note: assumes classic connection
3682e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
3697fde4af9Smatthias.ringwald  */
3707fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
3717fde4af9Smatthias.ringwald     bd_addr_t addr;
372724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
373f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3747fde4af9Smatthias.ringwald     if (conn) {
37528ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
37680ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
3777fde4af9Smatthias.ringwald     }
3787fde4af9Smatthias.ringwald }
3797fde4af9Smatthias.ringwald 
38080ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
3815061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
38280ca58a0Smatthias.ringwald     if (!conn) return 0;
3836724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
3846724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
3856724cd9eS[email protected]     return 0;
38680ca58a0Smatthias.ringwald }
38780ca58a0Smatthias.ringwald 
38815a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
38955597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
3902bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
391a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
392c12e46e7Smatthias.ringwald }
39355597469SMatthias Ringwald 
39455597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
39555597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
3962bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
39755597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
398c12e46e7Smatthias.ringwald }
3991b6fb31bSMatthias Ringwald 
400ceecb9d9SMatthias Ringwald void gap_delete_all_link_keys(void){
401ceecb9d9SMatthias Ringwald     bd_addr_t  addr;
402ceecb9d9SMatthias Ringwald     link_key_t link_key;
403ceecb9d9SMatthias Ringwald     link_key_type_t type;
404ceecb9d9SMatthias Ringwald     btstack_link_key_iterator_t it;
405ceecb9d9SMatthias Ringwald     int ok = gap_link_key_iterator_init(&it);
406ceecb9d9SMatthias Ringwald     if (!ok) {
407ceecb9d9SMatthias Ringwald         log_error("could not initialize iterator");
408ceecb9d9SMatthias Ringwald         return;
409ceecb9d9SMatthias Ringwald     }
410ceecb9d9SMatthias Ringwald     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
411ceecb9d9SMatthias Ringwald         gap_drop_link_key_for_bd_addr(addr);
412ceecb9d9SMatthias Ringwald     }
413ceecb9d9SMatthias Ringwald     gap_link_key_iterator_done(&it);
414ceecb9d9SMatthias Ringwald }
415ceecb9d9SMatthias Ringwald 
4161b6fb31bSMatthias Ringwald int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
4171b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4181b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db->iterator_init) return 0;
4191b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_init(it);
4201b6fb31bSMatthias Ringwald }
4211b6fb31bSMatthias 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){
4221b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return 0;
4231b6fb31bSMatthias Ringwald     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
4241b6fb31bSMatthias Ringwald }
4251b6fb31bSMatthias Ringwald void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
4261b6fb31bSMatthias Ringwald     if (!hci_stack->link_key_db) return;
4271b6fb31bSMatthias Ringwald     hci_stack->link_key_db->iterator_done(it);
4281b6fb31bSMatthias Ringwald }
42935454696SMatthias Ringwald #endif
430c12e46e7Smatthias.ringwald 
43195d71764SMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
432ce41473eSMatthias Ringwald     switch (connection->address_type){
433ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
434ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
435ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
436ce41473eSMatthias Ringwald         case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
437ce41473eSMatthias Ringwald             return 1;
438ce41473eSMatthias Ringwald         default:
439ce41473eSMatthias Ringwald             return 0;
440ce41473eSMatthias Ringwald     }
4410bf6344aS[email protected] }
4420bf6344aS[email protected] 
4437fde4af9Smatthias.ringwald /**
44443bfb1bdSmatthias.ringwald  * count connections
44543bfb1bdSmatthias.ringwald  */
44640d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
44756c253c9Smatthias.ringwald     int count = 0;
448665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
449a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){
45015a27967SMatthias Ringwald         count++;
45115a27967SMatthias Ringwald     }
45243bfb1bdSmatthias.ringwald     return count;
45343bfb1bdSmatthias.ringwald }
454c8e4258aSmatthias.ringwald 
45595d71764SMatthias Ringwald static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
456ee303eddS[email protected] 
457f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
458f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
459ee303eddS[email protected] 
460665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
461a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
462998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
463ce41473eSMatthias Ringwald         if (hci_is_le_connection(connection)){
464ce41473eSMatthias Ringwald             num_packets_sent_le += connection->num_packets_sent;
465ce41473eSMatthias Ringwald         }
466f16129ceSMatthias Ringwald         if (connection->address_type == BD_ADDR_TYPE_ACL){
467ce41473eSMatthias Ringwald             num_packets_sent_classic += connection->num_packets_sent;
468ee303eddS[email protected]         }
469ee303eddS[email protected]     }
470d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
471ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
472ee303eddS[email protected]     int free_slots_le = 0;
473ee303eddS[email protected] 
474ee303eddS[email protected]     if (free_slots_classic < 0){
4759da54300S[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);
476998906cdSmatthias.ringwald         return 0;
477998906cdSmatthias.ringwald     }
478ee303eddS[email protected] 
479ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
480ee303eddS[email protected]         // if we have LE slots, they are used
481ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
482ee303eddS[email protected]         if (free_slots_le < 0){
4839da54300S[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);
484ee303eddS[email protected]             return 0;
485998906cdSmatthias.ringwald         }
486ee303eddS[email protected]     } else {
487ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
488ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
489ee303eddS[email protected]         if (free_slots_classic < 0){
4909da54300S[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);
491ee303eddS[email protected]             return 0;
492ee303eddS[email protected]         }
493ee303eddS[email protected]     }
494ee303eddS[email protected] 
495ee303eddS[email protected]     switch (address_type){
496ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
4972125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
498ee303eddS[email protected]             return 0;
499ee303eddS[email protected] 
500f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
501ee303eddS[email protected]             return free_slots_classic;
502ee303eddS[email protected] 
503ee303eddS[email protected]         default:
504cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
505ee303eddS[email protected]                return free_slots_le;
506ee303eddS[email protected]            }
507cb00d3aaS[email protected]            return free_slots_classic;
508cb00d3aaS[email protected]     }
509998906cdSmatthias.ringwald }
510998906cdSmatthias.ringwald 
5112125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
5122125de09SMatthias Ringwald     // get connection type
5132125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5142125de09SMatthias Ringwald     if (!connection){
5152125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
5162125de09SMatthias Ringwald         return 0;
5172125de09SMatthias Ringwald     }
5182125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
5192125de09SMatthias Ringwald }
5202125de09SMatthias Ringwald 
52135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
522701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
523f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
524665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
525760b20efSMatthias Ringwald     if (hci_stack->synchronous_flow_control_enabled){
526760b20efSMatthias Ringwald         // explicit flow control
527665d90f2SMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
528e35edcc1S[email protected]             hci_connection_t * connection = (hci_connection_t *) it;
529ce41473eSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
530ce41473eSMatthias Ringwald             num_sco_packets_sent += connection->num_packets_sent;
531e35edcc1S[email protected]         }
532e35edcc1S[email protected]         if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
533701e3307SMatthias Ringwald             log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
53444d0e3d5S[email protected]             return 0;
53544d0e3d5S[email protected]         }
536e35edcc1S[email protected]         return hci_stack->sco_packets_total_num - num_sco_packets_sent;
53749205f5dSMatthias Ringwald     } else {
53849205f5dSMatthias Ringwald         // implicit flow control -- TODO
5396f28d2eeSMatthias Ringwald         int num_ready = 0;
5406f28d2eeSMatthias Ringwald         for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
5416f28d2eeSMatthias Ringwald             hci_connection_t * connection = (hci_connection_t *) it;
5426f28d2eeSMatthias Ringwald             if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
5436f28d2eeSMatthias Ringwald             if (connection->sco_tx_ready == 0) continue;
5446f28d2eeSMatthias Ringwald             num_ready++;
54549205f5dSMatthias Ringwald         }
5466f28d2eeSMatthias Ringwald         return num_ready;
5476f28d2eeSMatthias Ringwald     }
548e35edcc1S[email protected] }
54935454696SMatthias Ringwald #endif
55044d0e3d5S[email protected] 
5512b838201SMatthias Ringwald // only used to send HCI Host Number Completed Packets
5522b838201SMatthias Ringwald static int hci_can_send_comand_packet_transport(void){
553ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
554ac928cc2S[email protected] 
555ac928cc2S[email protected]     // check for async hci transport implementations
556ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
557ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
558ac928cc2S[email protected]             return 0;
559ac928cc2S[email protected]         }
560ac928cc2S[email protected]     }
5612b838201SMatthias Ringwald     return 1;
5622b838201SMatthias Ringwald }
563ac928cc2S[email protected] 
5642b838201SMatthias Ringwald // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
5652b838201SMatthias Ringwald int hci_can_send_command_packet_now(void){
5662b838201SMatthias Ringwald     if (hci_can_send_comand_packet_transport() == 0) return 0;
567ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
568ac928cc2S[email protected] }
569ac928cc2S[email protected] 
5709d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
571ac928cc2S[email protected]     // check for async hci transport implementations
5729d04d3a7SMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
5739d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
574ac928cc2S[email protected] }
5759d04d3a7SMatthias Ringwald 
5769d04d3a7SMatthias Ringwald static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
5779d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
5789d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
579ac928cc2S[email protected] }
5809d04d3a7SMatthias Ringwald 
5819d04d3a7SMatthias Ringwald int hci_can_send_acl_le_packet_now(void){
5829d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
5839d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
5849d04d3a7SMatthias Ringwald }
5859d04d3a7SMatthias Ringwald 
5869d04d3a7SMatthias Ringwald int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
5879d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
588e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
589ac928cc2S[email protected] }
590ac928cc2S[email protected] 
591ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
592ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
593ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
5946b4af23dS[email protected] }
5956b4af23dS[email protected] 
59635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
59735454696SMatthias Ringwald int hci_can_send_acl_classic_packet_now(void){
59835454696SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
599f16129ceSMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL);
60035454696SMatthias Ringwald }
60135454696SMatthias Ringwald 
602701e3307SMatthias Ringwald int hci_can_send_prepared_sco_packet_now(void){
603d057580eSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
604f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
605f234b250SMatthias Ringwald         return hci_stack->sco_can_send_now;
606f234b250SMatthias Ringwald     } else {
607701e3307SMatthias Ringwald         return hci_number_free_sco_slots() > 0;
60844d0e3d5S[email protected]     }
609f234b250SMatthias Ringwald }
61044d0e3d5S[email protected] 
611701e3307SMatthias Ringwald int hci_can_send_sco_packet_now(void){
612d057580eSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
613701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
61444d0e3d5S[email protected] }
61544d0e3d5S[email protected] 
616d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
617d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
618d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
619d057580eSMatthias Ringwald }
62035454696SMatthias Ringwald #endif
621d057580eSMatthias Ringwald 
62295d71764SMatthias Ringwald // used for internal checks in l2cap.c
623c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
624c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
625c8b9416aS[email protected] }
626c8b9416aS[email protected] 
6276b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
6286b4af23dS[email protected] int hci_reserve_packet_buffer(void){
6299d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
6309d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
6319d14b626S[email protected]         return 0;
6329d14b626S[email protected]     }
6336b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
6346b4af23dS[email protected]     return 1;
6356b4af23dS[email protected] }
6366b4af23dS[email protected] 
63768a0fcf7S[email protected] void hci_release_packet_buffer(void){
63868a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
63968a0fcf7S[email protected] }
64068a0fcf7S[email protected] 
6416b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
6427f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
6436b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
6446b4af23dS[email protected] }
6456b4af23dS[email protected] 
646452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
647452cf3bbS[email protected] 
648452cf3bbS[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);
649452cf3bbS[email protected] 
650452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
651452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
652a1df452eSMatthias Ringwald     if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0)){
653452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
654452cf3bbS[email protected]     }
655452cf3bbS[email protected] 
6560f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
6570f3b27c5SMatthias Ringwald     if (hci_is_le_connection(connection)){
6580f3b27c5SMatthias Ringwald         max_acl_data_packet_length = connection->le_max_tx_octets;
6590f3b27c5SMatthias Ringwald     }
6600f3b27c5SMatthias Ringwald #endif
661452cf3bbS[email protected] 
662d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
663d999b54eSMatthias Ringwald 
664452cf3bbS[email protected]     int err;
665452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
666ff3cc4a5SMatthias Ringwald     while (true){
667452cf3bbS[email protected] 
668d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
669d999b54eSMatthias Ringwald 
670452cf3bbS[email protected]         // get current data
671452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
672452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
673452cf3bbS[email protected]         int more_fragments = 0;
674452cf3bbS[email protected] 
675452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
676452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
677452cf3bbS[email protected]             more_fragments = 1;
678452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
679452cf3bbS[email protected]         }
680452cf3bbS[email protected] 
681452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
682452cf3bbS[email protected]         if (acl_header_pos > 0){
683f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
684452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
685f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
686452cf3bbS[email protected]         }
687452cf3bbS[email protected] 
688452cf3bbS[email protected]         // update header len
689f8fbdce0SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
690452cf3bbS[email protected] 
691452cf3bbS[email protected]         // count packet
692ce41473eSMatthias Ringwald         connection->num_packets_sent++;
693f04a0c31SMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
694d999b54eSMatthias Ringwald 
695d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
696d999b54eSMatthias Ringwald         if (more_fragments){
697d999b54eSMatthias Ringwald             // update start of next fragment to send
698d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
699d999b54eSMatthias Ringwald         } else {
700d999b54eSMatthias Ringwald             // done
701d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
702d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
703d999b54eSMatthias Ringwald         }
704452cf3bbS[email protected] 
705452cf3bbS[email protected]         // send packet
706452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
707452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
7085bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
70981d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 1;
710452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
711452cf3bbS[email protected] 
712f04a0c31SMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
713d999b54eSMatthias Ringwald 
714452cf3bbS[email protected]         // done yet?
715452cf3bbS[email protected]         if (!more_fragments) break;
716452cf3bbS[email protected] 
717452cf3bbS[email protected]         // can send more?
718452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
719452cf3bbS[email protected]     }
720452cf3bbS[email protected] 
721d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
722452cf3bbS[email protected] 
723d051460cS[email protected]     // release buffer now for synchronous transport
724203bace6S[email protected]     if (hci_transport_synchronous()){
72581d2bdb2SMatthias Ringwald         hci_stack->acl_fragmentation_tx_active = 0;
726452cf3bbS[email protected]         hci_release_packet_buffer();
727fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
728452cf3bbS[email protected]     }
729452cf3bbS[email protected] 
730452cf3bbS[email protected]     return err;
731452cf3bbS[email protected] }
732452cf3bbS[email protected] 
733826f7347S[email protected] // pre: caller has reserved the packet buffer
734826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
7357856c818Smatthias.ringwald 
736452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
737452cf3bbS[email protected] 
738826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
739826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
740826f7347S[email protected]         return 0;
741826f7347S[email protected]     }
742826f7347S[email protected] 
743d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
744d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
745d713a683S[email protected] 
746826f7347S[email protected]     // check for free places on Bluetooth module
747d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
748826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
74997b61c7bS[email protected]         hci_release_packet_buffer();
750068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
75197b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
75297b61c7bS[email protected]     }
7536218e6f1Smatthias.ringwald 
7545061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
75597b61c7bS[email protected]     if (!connection) {
7565fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
75797b61c7bS[email protected]         hci_release_packet_buffer();
758068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
75997b61c7bS[email protected]         return 0;
76097b61c7bS[email protected]     }
76152db98b2SMatthias Ringwald 
76252db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
76356cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
76452db98b2SMatthias Ringwald #endif
76556cf178bSmatthias.ringwald 
766452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
7677856c818Smatthias.ringwald 
768452cf3bbS[email protected]     // setup data
769452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
770452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
7716218e6f1Smatthias.ringwald 
772452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
773ee091cf1Smatthias.ringwald }
774ee091cf1Smatthias.ringwald 
77535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
77644d0e3d5S[email protected] // pre: caller has reserved the packet buffer
77744d0e3d5S[email protected] int hci_send_sco_packet_buffer(int size){
77844d0e3d5S[email protected] 
77944d0e3d5S[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
78044d0e3d5S[email protected] 
78144d0e3d5S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
78244d0e3d5S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
78344d0e3d5S[email protected]         return 0;
78444d0e3d5S[email protected]     }
78544d0e3d5S[email protected] 
78644d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
7874b3e1e19SMatthias Ringwald 
7884b3e1e19SMatthias Ringwald     // skip checks in loopback mode
7894b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
79044d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
79144d0e3d5S[email protected] 
79244d0e3d5S[email protected]         // check for free places on Bluetooth module
793701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
794cbf638a9SMatthias Ringwald             log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
79544d0e3d5S[email protected]             hci_release_packet_buffer();
796068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
79744d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
79844d0e3d5S[email protected]         }
79944d0e3d5S[email protected] 
800e35edcc1S[email protected]         // track send packet in connection struct
801e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
802e35edcc1S[email protected]         if (!connection) {
803e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
804e35edcc1S[email protected]             hci_release_packet_buffer();
805068b8592SMatthias Ringwald             hci_emit_transport_packet_sent();
806e35edcc1S[email protected]             return 0;
807e35edcc1S[email protected]         }
808f234b250SMatthias Ringwald 
809f234b250SMatthias Ringwald         if (hci_have_usb_transport()){
810f234b250SMatthias Ringwald             // token used
811f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 0;
812f234b250SMatthias Ringwald         } else {
813760b20efSMatthias Ringwald             if (hci_stack->synchronous_flow_control_enabled){
814ce41473eSMatthias Ringwald                 connection->num_packets_sent++;
8156f28d2eeSMatthias Ringwald             } else {
816e4157653SMatthias Ringwald                 connection->sco_tx_ready--;
817760b20efSMatthias Ringwald             }
8184b3e1e19SMatthias Ringwald         }
819f234b250SMatthias Ringwald     }
82044d0e3d5S[email protected] 
82144d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
822543e835cSMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
823543e835cSMatthias Ringwald 
824543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
825543e835cSMatthias Ringwald         hci_release_packet_buffer();
826fd43c0e0SMatthias Ringwald         hci_emit_transport_packet_sent();
827543e835cSMatthias Ringwald     }
828543e835cSMatthias Ringwald 
829543e835cSMatthias Ringwald     return err;
83044d0e3d5S[email protected] }
83135454696SMatthias Ringwald #endif
83244d0e3d5S[email protected] 
83316833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
8347856c818Smatthias.ringwald 
835e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
836e76a89eeS[email protected] 
8377856c818Smatthias.ringwald     // get info
8387856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
8395061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
8407856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
8417856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
8427856c818Smatthias.ringwald 
8437856c818Smatthias.ringwald     // ignore non-registered handle
8447856c818Smatthias.ringwald     if (!conn){
8459da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
8467856c818Smatthias.ringwald         return;
8477856c818Smatthias.ringwald     }
8487856c818Smatthias.ringwald 
849e76a89eeS[email protected]     // assert packet is complete
850a1df452eSMatthias Ringwald     if ((acl_length + 4) != size){
851f04a0c31SMatthias Ringwald         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
852e76a89eeS[email protected]         return;
853e76a89eeS[email protected]     }
854e76a89eeS[email protected] 
85552db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
8567856c818Smatthias.ringwald     // update idle timestamp
8577856c818Smatthias.ringwald     hci_connection_timestamp(conn);
85852db98b2SMatthias Ringwald #endif
8597856c818Smatthias.ringwald 
8602b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
8612b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
8622b838201SMatthias Ringwald     conn->num_packets_completed++;
8632b838201SMatthias Ringwald #endif
8642b838201SMatthias Ringwald 
8657856c818Smatthias.ringwald     // handle different packet types
8667856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
8677856c818Smatthias.ringwald 
8687856c818Smatthias.ringwald         case 0x01: // continuation fragment
8697856c818Smatthias.ringwald 
8700ca847afS[email protected]             // sanity checks
8717856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
8729da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
8737856c818Smatthias.ringwald                 return;
8747856c818Smatthias.ringwald             }
8750e588213SMatthias Ringwald             if ((conn->acl_recombination_pos + acl_length) > (4 + HCI_ACL_BUFFER_SIZE)){
8760ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
8770ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
8780ca847afS[email protected]                 conn->acl_recombination_pos = 0;
8790ca847afS[email protected]                 return;
8800ca847afS[email protected]             }
8817856c818Smatthias.ringwald 
8827856c818Smatthias.ringwald             // append fragment payload (header already stored)
8836535961aSMatthias Ringwald             (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos],
8846535961aSMatthias Ringwald                          &packet[4], acl_length);
8857856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
8867856c818Smatthias.ringwald 
8879da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
888decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
8897856c818Smatthias.ringwald 
8907856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
891a1df452eSMatthias Ringwald             if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4 + 4)){ // pos already incl. ACL header
892d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
8937856c818Smatthias.ringwald                 // reset recombination buffer
8947856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
8957856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
8967856c818Smatthias.ringwald             }
8977856c818Smatthias.ringwald             break;
8987856c818Smatthias.ringwald 
8997856c818Smatthias.ringwald         case 0x02: { // first fragment
9007856c818Smatthias.ringwald 
90123a77e1aS[email protected]             // sanity check
90223a77e1aS[email protected]             if (conn->acl_recombination_pos) {
90323a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
90423a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
90523a77e1aS[email protected]             }
90623a77e1aS[email protected] 
9077856c818Smatthias.ringwald             // peek into L2CAP packet!
9087856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
9097856c818Smatthias.ringwald 
9109da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
911decc01a8Smatthias.ringwald 
9127856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
913a1df452eSMatthias Ringwald             if (acl_length >= (l2cap_length + 4)){
9147856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
915d6b06661SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4);
9167856c818Smatthias.ringwald             } else {
9170ca847afS[email protected] 
9180ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
9190ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
9200ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
9210ca847afS[email protected]                     return;
9220ca847afS[email protected]                 }
9230ca847afS[email protected] 
9247856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
9256535961aSMatthias Ringwald                 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE],
9266535961aSMatthias Ringwald                              packet, acl_length + 4);
9277856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
9287856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
929f8fbdce0SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
9307856c818Smatthias.ringwald             }
9317856c818Smatthias.ringwald             break;
9327856c818Smatthias.ringwald 
9337856c818Smatthias.ringwald         }
9347856c818Smatthias.ringwald         default:
9359da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
9367856c818Smatthias.ringwald             return;
9377856c818Smatthias.ringwald     }
93894ab26f8Smatthias.ringwald 
93994ab26f8Smatthias.ringwald     // execute main loop
94094ab26f8Smatthias.ringwald     hci_run();
94116833f0aSmatthias.ringwald }
94222909952Smatthias.ringwald 
94367a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
9449da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
9453c4d4b90Smatthias.ringwald 
946b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
947ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
948ee752bb8SMatthias Ringwald     int addr_type = conn->address_type;
949ee752bb8SMatthias Ringwald #endif
950b3264428SMatthias Ringwald #endif
951ee752bb8SMatthias Ringwald 
952528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
953c785ef68Smatthias.ringwald 
954665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
955a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
9563c4d4b90Smatthias.ringwald 
9573c4d4b90Smatthias.ringwald     // now it's gone
958c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
959ee752bb8SMatthias Ringwald 
960b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
961034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
962ee752bb8SMatthias Ringwald     // update SCO
963ee752bb8SMatthias Ringwald     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
964ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
965ee752bb8SMatthias Ringwald     }
966034e9b53SMatthias Ringwald #endif
967b3264428SMatthias Ringwald #endif
968c7e0c5f6Smatthias.ringwald }
969c7e0c5f6Smatthias.ringwald 
97035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
97135454696SMatthias Ringwald 
9720c042179S[email protected] static const uint16_t packet_type_sizes[] = {
9738f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
9748f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
9758f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
9768f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
9778f8108aaSmatthias.ringwald };
97865389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
97965389bfcS[email protected]      0, // 3 slot packets
98065389bfcS[email protected]      1, // 5 slot packets
98165389bfcS[email protected]     25, // EDR 2 mpbs
98265389bfcS[email protected]     26, // EDR 3 mbps
98365389bfcS[email protected]     39, // 3 slot EDR packts
98465389bfcS[email protected]     40, // 5 slot EDR packet
98565389bfcS[email protected] };
98665389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
98765389bfcS[email protected]     0x0f00, // 3 slot packets
98865389bfcS[email protected]     0xf000, // 5 slot packets
98965389bfcS[email protected]     0x1102, // EDR 2 mpbs
99065389bfcS[email protected]     0x2204, // EDR 3 mbps
99165389bfcS[email protected]     0x0300, // 3 slot EDR packts
99265389bfcS[email protected]     0x3000, // 5 slot EDR packet
99365389bfcS[email protected] };
9948f8108aaSmatthias.ringwald 
99565389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
99665389bfcS[email protected]     // enable packet types based on size
9978f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
998f16a69bbS[email protected]     unsigned int i;
9998f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
10008f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
10018f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
10028f8108aaSmatthias.ringwald             packet_types |= 1 << i;
10038f8108aaSmatthias.ringwald         }
10048f8108aaSmatthias.ringwald     }
100565389bfcS[email protected]     // disable packet types due to missing local supported features
100665389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
1007f04a0c31SMatthias Ringwald         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
100865389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
100965389bfcS[email protected]         if (feature_set) continue;
101065389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
101165389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
101265389bfcS[email protected]     }
10138f8108aaSmatthias.ringwald     // flip bits for "may not be used"
10148f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
10158f8108aaSmatthias.ringwald     return packet_types;
10168f8108aaSmatthias.ringwald }
10178f8108aaSmatthias.ringwald 
10188f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
10193a9fb326S[email protected]     return hci_stack->packet_types;
10208f8108aaSmatthias.ringwald }
102135454696SMatthias Ringwald #endif
10228f8108aaSmatthias.ringwald 
1023facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
10247dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
10253a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
10267dc17943Smatthias.ringwald }
10277dc17943Smatthias.ringwald 
1028f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
10293a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
10307dc17943Smatthias.ringwald }
10317dc17943Smatthias.ringwald 
103206b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
10333e68d23dSMatthias Ringwald int hci_extended_sco_link_supported(void){
10343e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
10353e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
10363e68d23dSMatthias Ringwald }
103706b9e820SMatthias Ringwald #endif
10383e68d23dSMatthias Ringwald 
10396ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
10406ac9a97eS[email protected]     // No. 54, byte 6, bit 6
10416ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
10426ac9a97eS[email protected] }
10436ac9a97eS[email protected] 
104415a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
10456ac9a97eS[email protected]     // No. 51, byte 6, bit 3
10463a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
1047f5d8d141S[email protected] }
1048f5d8d141S[email protected] 
10497f02f414SMatthias Ringwald static int hci_classic_supported(void){
105035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
10516ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
10523a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
105335454696SMatthias Ringwald #else
105435454696SMatthias Ringwald     return 0;
105535454696SMatthias Ringwald #endif
1056f5d8d141S[email protected] }
1057f5d8d141S[email protected] 
10587f02f414SMatthias Ringwald static int hci_le_supported(void){
1059a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
10606ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
10613a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
1062f5d8d141S[email protected] #else
1063f5d8d141S[email protected]     return 0;
1064f5d8d141S[email protected] #endif
1065f5d8d141S[email protected] }
1066f5d8d141S[email protected] 
1067b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
1068b95a5a35SMatthias Ringwald 
1069b95a5a35SMatthias Ringwald /**
1070b95a5a35SMatthias Ringwald  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
1071b95a5a35SMatthias Ringwald  */
1072b95a5a35SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1073b95a5a35SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
1074b95a5a35SMatthias Ringwald     if (hci_stack->le_own_addr_type){
10756535961aSMatthias Ringwald         (void)memcpy(addr, hci_stack->le_random_address, 6);
107669a97523S[email protected]     } else {
10776535961aSMatthias Ringwald         (void)memcpy(addr, hci_stack->local_bd_addr, 6);
107869a97523S[email protected]     }
107969a97523S[email protected] }
108069a97523S[email protected] 
1081e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1082384b59deSMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
10839ec2630cSMatthias Ringwald 
1084d1dc057bS[email protected]     int offset = 3;
1085d1dc057bS[email protected]     int num_reports = packet[offset];
1086d1dc057bS[email protected]     offset += 1;
1087d1dc057bS[email protected] 
108857c9da5bS[email protected]     int i;
10894f4e0224SMatthias Ringwald     // log_info("HCI: handle adv report with num reports: %d", num_reports);
109003fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1091a1df452eSMatthias Ringwald     for (i=0; (i<num_reports) && (offset < size);i++){
109233e6948bSMatthias Ringwald         // sanity checks on data_length:
109333e6948bSMatthias Ringwald         uint8_t data_length = packet[offset + 8];
109433e6948bSMatthias Ringwald         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1095a1df452eSMatthias Ringwald         if ((offset + 9 + data_length + 1) > size)    return;
109633e6948bSMatthias Ringwald         // setup event
1097a0aac9c4S[email protected]         uint8_t event_size = 10 + data_length;
1098d1dc057bS[email protected]         int pos = 0;
1099045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
110057c9da5bS[email protected]         event[pos++] = event_size;
11016535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address
1102d1dc057bS[email protected]         offset += 8;
1103d1dc057bS[email protected]         pos += 8;
1104d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
110533e6948bSMatthias Ringwald         event[pos++] = data_length;
110633e6948bSMatthias Ringwald         offset++;
11076535961aSMatthias Ringwald         (void)memcpy(&event[pos], &packet[offset], data_length);
110857c9da5bS[email protected]         pos +=    data_length;
1109d1dc057bS[email protected]         offset += data_length + 1; // rssi
1110d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
111157c9da5bS[email protected]     }
111257c9da5bS[email protected] }
1113b2f949feS[email protected] #endif
1114e8c8828eSMatthias Ringwald #endif
111557c9da5bS[email protected] 
11162b6ab3e6SMatthias Ringwald #ifdef ENABLE_BLE
11172b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
11182b6ab3e6SMatthias Ringwald static void hci_reenable_advertisements_if_needed(void){
11192b6ab3e6SMatthias Ringwald     if (!hci_stack->le_advertisements_active && hci_stack->le_advertisements_enabled){
11202b6ab3e6SMatthias Ringwald         // get number of active le slave connections
11212b6ab3e6SMatthias Ringwald         int num_slave_connections = 0;
11222b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_t it;
11232b6ab3e6SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
11242b6ab3e6SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
11252b6ab3e6SMatthias Ringwald             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
11262b6ab3e6SMatthias Ringwald             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
11272b6ab3e6SMatthias Ringwald             if (con->state != OPEN) continue;
11282b6ab3e6SMatthias Ringwald             if (con->role  != HCI_ROLE_SLAVE) continue;
11292b6ab3e6SMatthias Ringwald             if (!hci_is_le_connection(con)) continue;
11302b6ab3e6SMatthias Ringwald             num_slave_connections++;
11312b6ab3e6SMatthias Ringwald         }
11322b6ab3e6SMatthias Ringwald         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
11332b6ab3e6SMatthias Ringwald         if (num_slave_connections < hci_stack->le_max_number_peripheral_connections){
11342b6ab3e6SMatthias Ringwald             hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
11352b6ab3e6SMatthias Ringwald         }
11362b6ab3e6SMatthias Ringwald     }
11372b6ab3e6SMatthias Ringwald }
11382b6ab3e6SMatthias Ringwald #endif
11392b6ab3e6SMatthias Ringwald #endif
11402b6ab3e6SMatthias Ringwald 
1141cd77dd38SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
114206b9e820SMatthias Ringwald 
114396b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
114496b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
11459796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
114696b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
1147a1df452eSMatthias Ringwald     if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){
114896b53536SMatthias Ringwald         baud_rate = 3000000;
114996b53536SMatthias Ringwald     }
115096b53536SMatthias Ringwald     return baud_rate;
115196b53536SMatthias Ringwald }
115296b53536SMatthias Ringwald 
1153ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
11549ec2630cSMatthias Ringwald     UNUSED(ds);
11559ec2630cSMatthias Ringwald 
11560305bdeaSMatthias Ringwald     switch (hci_stack->substate){
11570305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
11587b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
11590305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
11607b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
11610305bdeaSMatthias Ringwald             hci_run();
11620305bdeaSMatthias Ringwald             break;
11639f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
11649f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
11659f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
11669f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
11679f007422SMatthias Ringwald             }
1168cf373d3aSMatthias Ringwald 
1169cf373d3aSMatthias Ringwald             /* fall through */
1170cf373d3aSMatthias Ringwald 
1171e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1172e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
1173e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1174e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
1175e47e68c7SMatthias Ringwald             hci_run();
1176688c2635SMatthias Ringwald             break;
11777224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
11787224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
117996b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1180cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
11817dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
11827224be7eSMatthias Ringwald             }
1183834bce8cSMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
118461f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1185834bce8cSMatthias Ringwald                 if (hci_stack->hci_transport->reset_link){
1186834bce8cSMatthias Ringwald                     log_info("Link Reset");
1187834bce8cSMatthias Ringwald                     hci_stack->hci_transport->reset_link();
1188834bce8cSMatthias Ringwald                 }
1189772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1190772a36d3SMatthias Ringwald                 hci_run();
1191772a36d3SMatthias Ringwald             }
11924696bddbSMatthias Ringwald             break;
1193559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1194559961d0SMatthias Ringwald             // otherwise continue
1195559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1196559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1197559961d0SMatthias Ringwald             break;
11980305bdeaSMatthias Ringwald         default:
11990305bdeaSMatthias Ringwald             break;
12000305bdeaSMatthias Ringwald     }
12010305bdeaSMatthias Ringwald }
120206b9e820SMatthias Ringwald #endif
12030305bdeaSMatthias Ringwald 
120471de195eSMatthias Ringwald static void hci_initializing_next_state(void){
120574b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
120674b323a9SMatthias Ringwald }
120774b323a9SMatthias Ringwald 
120874b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
120971de195eSMatthias Ringwald static void hci_initializing_run(void){
1210148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
121174b323a9SMatthias Ringwald     switch (hci_stack->substate){
121274b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
121374b323a9SMatthias Ringwald             hci_state_reset();
1214a0cf2f3fSMatthias Ringwald 
121506b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
12160305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
1217659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1218528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1219528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1220a0cf2f3fSMatthias Ringwald #endif
12210305bdeaSMatthias Ringwald             // send command
122274b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
12230305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
122474b323a9SMatthias Ringwald             break;
122576fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
122676fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
122776fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
122876fcb19bSMatthias Ringwald             break;
1229e90bae01SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
1230e90bae01SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
1231e90bae01SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1232e90bae01SMatthias Ringwald             break;
123306b9e820SMatthias Ringwald 
123406b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1235e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1236e47e68c7SMatthias Ringwald             hci_state_reset();
1237e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1238659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1239528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1240528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1241e47e68c7SMatthias Ringwald             // send command
1242e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1243e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1244e47e68c7SMatthias Ringwald             break;
12458d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
12468d29070eSMatthias Ringwald             hci_state_reset();
12478d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
12488d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
12498d29070eSMatthias Ringwald             break;
1250fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE: {
125196b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
12523fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1253f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
125474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
12550305bdeaSMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
12564696bddbSMatthias Ringwald             // STLC25000D: baudrate change happens within 0.5 s after command was send,
12574696bddbSMatthias Ringwald             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
125861f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1259659d758cSMatthias Ringwald                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1260528a4a3bSMatthias Ringwald                 btstack_run_loop_add_timer(&hci_stack->timeout);
12614696bddbSMatthias Ringwald             }
126274b323a9SMatthias Ringwald             break;
1263fab26ab3SMatthias Ringwald         }
1264fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
126596b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
12663fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1267f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1268eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1269eb3a5314SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1270eb3a5314SMatthias Ringwald             break;
1271fab26ab3SMatthias Ringwald         }
127274b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
127374b323a9SMatthias Ringwald             // Custom initialization
12743fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
1275ae334e9eSMatthias Ringwald                 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1276ee720f3aSMatthias Ringwald                 int send_cmd = 0;
1277ae334e9eSMatthias Ringwald                 switch (hci_stack->chipset_result){
1278f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_VALID_COMMAND:
1279ee720f3aSMatthias Ringwald                         send_cmd = 1;
1280e47e68c7SMatthias Ringwald                         hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1281e47e68c7SMatthias Ringwald                         break;
1282f41911edSMatthias Ringwald                     case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1283ee720f3aSMatthias Ringwald                         send_cmd = 1;
1284f41911edSMatthias Ringwald                         // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1285e47e68c7SMatthias Ringwald                         log_info("CSR Warm Boot");
1286659d758cSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1287528a4a3bSMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1288528a4a3bSMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
1289a1df452eSMatthias Ringwald                         if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO)
1290772a36d3SMatthias Ringwald                             && hci_stack->config
12913fb36a29SMatthias Ringwald                             && hci_stack->chipset
12923fb36a29SMatthias Ringwald                             // && hci_stack->chipset->set_baudrate_command -- there's no such command
1293772a36d3SMatthias Ringwald                             && hci_stack->hci_transport->set_baudrate
12942caefae9SMatthias Ringwald                             && hci_transport_uart_get_main_baud_rate()){
1295772a36d3SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1296772a36d3SMatthias Ringwald                         } else {
12979f007422SMatthias Ringwald                            hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1298772a36d3SMatthias Ringwald                         }
1299e47e68c7SMatthias Ringwald                         break;
1300f41911edSMatthias Ringwald                     default:
1301f41911edSMatthias Ringwald                         break;
1302e47e68c7SMatthias Ringwald                 }
1303ee720f3aSMatthias Ringwald 
1304ee720f3aSMatthias Ringwald                 if (send_cmd){
1305ee720f3aSMatthias Ringwald                     int size = 3 + hci_stack->hci_packet_buffer[2];
1306ee720f3aSMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1307ee720f3aSMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
13080305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
130974b323a9SMatthias Ringwald                     break;
131074b323a9SMatthias Ringwald                 }
1311148ca237SMatthias Ringwald                 log_info("Init script done");
131292a0d36dSMatthias Ringwald 
1313559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1314ae334e9eSMatthias Ringwald                 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1315a1df452eSMatthias Ringwald                    (  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)
1316a1df452eSMatthias Ringwald                 ||    (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){
1317e021ff1eSMatthias Ringwald 
1318559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
131992a0d36dSMatthias Ringwald                     int need_baud_change = hci_stack->config
13203fb36a29SMatthias Ringwald                         && hci_stack->chipset
13213fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
132292a0d36dSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
13239796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
132492a0d36dSMatthias Ringwald                     if (need_baud_change) {
13259796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1326cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
132792a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
132892a0d36dSMatthias Ringwald                     }
1329559961d0SMatthias Ringwald 
1330f19b3c9eSMatthias Ringwald                     uint16_t bcm_delay_ms = 300;
1331f19b3c9eSMatthias Ringwald                     // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time
1332f19b3c9eSMatthias Ringwald                     //   -> Work around: wait here.
1333f19b3c9eSMatthias Ringwald                     log_info("BCM delay (%u ms) after init script", bcm_delay_ms);
1334559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1335f19b3c9eSMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms);
1336559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1337559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
1338559961d0SMatthias Ringwald                     break;
133992a0d36dSMatthias Ringwald                 }
134074b323a9SMatthias Ringwald             }
134174b323a9SMatthias Ringwald             // otherwise continue
1342a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1343a828a756SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1344a828a756SMatthias Ringwald             break;
134553860077SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
134653860077SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
13473fb36a29SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1348f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
134953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
135053860077SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
135153860077SMatthias Ringwald             break;
135206b9e820SMatthias Ringwald #endif
135306b9e820SMatthias Ringwald 
135406b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
135506b9e820SMatthias Ringwald             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
135606b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
135706b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
135806b9e820SMatthias Ringwald             break;
135953860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
136053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
136153860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
136253860077SMatthias Ringwald             break;
136374b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
136474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
13650305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_buffer_size);
136674b323a9SMatthias Ringwald             break;
136753860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
136853860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
13690305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
137074b323a9SMatthias Ringwald             break;
13712b838201SMatthias Ringwald 
13722b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
13732b838201SMatthias Ringwald         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
13742b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
13752b838201SMatthias Ringwald             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
13762b838201SMatthias Ringwald             break;
13772b838201SMatthias Ringwald         case HCI_INIT_HOST_BUFFER_SIZE:
13782b838201SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
13792b838201SMatthias Ringwald             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
13802b838201SMatthias Ringwald                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
13812b838201SMatthias Ringwald             break;
13822b838201SMatthias Ringwald #endif
13832b838201SMatthias Ringwald 
138474b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
13850305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
138674b323a9SMatthias Ringwald             if (hci_le_supported()){
138774b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
138874b323a9SMatthias Ringwald             } else {
138974b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
139074b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
139174b323a9SMatthias Ringwald             }
139274b323a9SMatthias Ringwald             break;
13932b838201SMatthias Ringwald 
139435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
139574b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
139674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
13970305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
139874b323a9SMatthias Ringwald             break;
139974b323a9SMatthias Ringwald         case HCI_INIT_WRITE_PAGE_TIMEOUT:
140074b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
14010305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
140274b323a9SMatthias Ringwald             break;
1403c33e56d3SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1404c33e56d3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1405c33e56d3SMatthias Ringwald             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1406c33e56d3SMatthias Ringwald             break;
140774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
140874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
14090305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
141074b323a9SMatthias Ringwald             break;
14111c2a62f5SMatthias Ringwald         case HCI_INIT_WRITE_LOCAL_NAME: {
14120305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
14131c2a62f5SMatthias Ringwald             hci_reserve_packet_buffer();
14141c2a62f5SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
14151c2a62f5SMatthias Ringwald             // construct HCI Command and send
14161c2a62f5SMatthias Ringwald             uint16_t opcode = hci_write_local_name.opcode;
14171c2a62f5SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
14181c2a62f5SMatthias Ringwald             packet[0] = opcode & 0xff;
14191c2a62f5SMatthias Ringwald             packet[1] = opcode >> 8;
14201c2a62f5SMatthias Ringwald             packet[2] = DEVICE_NAME_LEN;
14211c2a62f5SMatthias Ringwald             memset(&packet[3], 0, DEVICE_NAME_LEN);
142279186815SMatthias Ringwald             uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
142379186815SMatthias Ringwald             uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN);
142479186815SMatthias Ringwald             // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call
142579186815SMatthias Ringwald             (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy);
14261c2a62f5SMatthias Ringwald             // expand '00:00:00:00:00:00' in name with bd_addr
14273c9da642SMatthias Ringwald             btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr);
14281c2a62f5SMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
142974b323a9SMatthias Ringwald             break;
14301c2a62f5SMatthias Ringwald         }
143129af07f3SMatthias Ringwald         case HCI_INIT_WRITE_EIR_DATA: {
14328a114470SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
143329af07f3SMatthias Ringwald             hci_reserve_packet_buffer();
143429af07f3SMatthias Ringwald             uint8_t * packet = hci_stack->hci_packet_buffer;
143563873210SMatthias Ringwald             // construct HCI Command in-place and send
143629af07f3SMatthias Ringwald             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
143729af07f3SMatthias Ringwald             hci_stack->last_cmd_opcode = opcode;
143863873210SMatthias Ringwald             uint16_t offset = 0;
143963873210SMatthias Ringwald             packet[offset++] = opcode & 0xff;
144063873210SMatthias Ringwald             packet[offset++] = opcode >> 8;
144163873210SMatthias Ringwald             packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN;
144263873210SMatthias Ringwald             packet[offset++] = 0;  // FEC not required
144363873210SMatthias Ringwald             memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1444ad0d1108SMatthias Ringwald             if (hci_stack->eir_data){
144563873210SMatthias Ringwald                 // copy items and expand '00:00:00:00:00:00' in name with bd_addr
144663873210SMatthias Ringwald                 ad_context_t context;
144763873210SMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) {
144863873210SMatthias Ringwald                     uint8_t data_type   = ad_iterator_get_data_type(&context);
144963873210SMatthias Ringwald                     uint8_t size        = ad_iterator_get_data_len(&context);
145063873210SMatthias Ringwald                     const uint8_t *data = ad_iterator_get_data(&context);
145163873210SMatthias Ringwald                     // copy item
145263873210SMatthias Ringwald                     packet[offset++] = size + 1;
145363873210SMatthias Ringwald                     packet[offset++] = data_type;
145463873210SMatthias Ringwald                     memcpy(&packet[offset], data, size);
145563873210SMatthias Ringwald                     // update name item
145663873210SMatthias Ringwald                     if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){
14573c9da642SMatthias Ringwald                         btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr);
145863873210SMatthias Ringwald                     }
145963873210SMatthias Ringwald                     offset += size;
146063873210SMatthias Ringwald                 }
1461ad0d1108SMatthias Ringwald             } else {
146279186815SMatthias Ringwald                 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name);
146379186815SMatthias Ringwald                 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2);
146463873210SMatthias Ringwald                 packet[offset++] = bytes_to_copy + 1;
146563873210SMatthias Ringwald                 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
146679186815SMatthias Ringwald                 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy);
146729af07f3SMatthias Ringwald                 // expand '00:00:00:00:00:00' in name with bd_addr
14683c9da642SMatthias Ringwald                 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr);
146963873210SMatthias Ringwald             }
1470a8c4e5adSMatthias Ringwald             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN);
1471ff00ed1cSMatthias Ringwald             break;
147229af07f3SMatthias Ringwald         }
1473f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
1474f6858d14SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
14758a114470SMatthias Ringwald             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1476f6858d14SMatthias Ringwald             break;
14775d23aae8SMatthias Ringwald         case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE:
14785d23aae8SMatthias Ringwald             hci_send_cmd(&hci_write_secure_connections_host_support, 1);
14795d23aae8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE;
14805d23aae8SMatthias Ringwald             break;
148174b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SCAN_ENABLE:
148274b323a9SMatthias Ringwald             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
148374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
148474b323a9SMatthias Ringwald             break;
1485483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
1486729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1487729ed62eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1488729ed62eSMatthias Ringwald             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1489729ed62eSMatthias Ringwald             break;
1490483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1491483c5078SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1492483c5078SMatthias Ringwald             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1493483c5078SMatthias Ringwald             break;
1494a42798c3SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1495a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1496a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1497a42798c3SMatthias Ringwald             log_info("BCM: Route SCO data via HCI transport");
1498a42798c3SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1499a42798c3SMatthias Ringwald             break;
1500a42798c3SMatthias Ringwald 
150135454696SMatthias Ringwald #endif
1502a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
150374b323a9SMatthias Ringwald         // LE INIT
150474b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
150574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
15060305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_read_buffer_size);
150774b323a9SMatthias Ringwald             break;
1508daabb8b8SMatthias Ringwald         case HCI_INIT_LE_SET_EVENT_MASK:
1509daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1510729710c0SMatthias Ringwald             hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1511daabb8b8SMatthias Ringwald             break;
151274b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
151374b323a9SMatthias Ringwald             // LE Supported Host = 1, Simultaneous Host = 0
151474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
15150305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
151674b323a9SMatthias Ringwald             break;
1517b435e062SMatthias Ringwald #endif
1518b435e062SMatthias Ringwald 
1519b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1520dcd678baSMatthias Ringwald         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1521dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1522dcd678baSMatthias Ringwald             hci_send_cmd(&hci_le_read_maximum_data_length);
1523dcd678baSMatthias Ringwald             break;
1524dcd678baSMatthias Ringwald         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1525dcd678baSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1526b435e062SMatthias 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);
1527dcd678baSMatthias Ringwald             break;
1528b435e062SMatthias Ringwald #endif
1529b435e062SMatthias Ringwald 
1530b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
15313b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
15323b6d4121SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
15333b6d4121SMatthias Ringwald             hci_send_cmd(&hci_le_read_white_list_size);
15343b6d4121SMatthias Ringwald             break;
153574b323a9SMatthias Ringwald         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1536b95a5a35SMatthias Ringwald             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
153774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
153863270faaSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, 1, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0);
153974b323a9SMatthias Ringwald             break;
154074b323a9SMatthias Ringwald #endif
154174b323a9SMatthias Ringwald         default:
154274b323a9SMatthias Ringwald             return;
154374b323a9SMatthias Ringwald     }
154455975f88SMatthias Ringwald }
154555975f88SMatthias Ringwald 
1546a650ba4dSMatthias Ringwald static void hci_init_done(void){
1547a650ba4dSMatthias Ringwald     // done. tell the app
1548a650ba4dSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1549a650ba4dSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1550a650ba4dSMatthias Ringwald     hci_emit_state();
1551a650ba4dSMatthias Ringwald     hci_run();
1552a650ba4dSMatthias Ringwald }
1553a650ba4dSMatthias Ringwald 
155407fd2f31SMatthias Ringwald static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){
155507fd2f31SMatthias Ringwald     bool command_completed = false;
15560e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1557f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
15586155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
155907fd2f31SMatthias Ringwald             command_completed = true;
1560148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
15616155b3d3S[email protected]         } else {
1562d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
15636155b3d3S[email protected]         }
15646155b3d3S[email protected]     }
15650f97eae7SMatthias Ringwald 
15660e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
15676155b3d3S[email protected]         uint8_t  status = packet[2];
1568f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
15696155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
15706155b3d3S[email protected]             if (status){
157107fd2f31SMatthias Ringwald                 command_completed = true;
1572148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
15736155b3d3S[email protected]             } else {
15746155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
15756155b3d3S[email protected]             }
15766155b3d3S[email protected]         } else {
1577148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
15786155b3d3S[email protected]         }
15796155b3d3S[email protected]     }
158006b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1581e47e68c7SMatthias Ringwald     // Vendor == CSR
15820e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
1583e47e68c7SMatthias Ringwald         // TODO: track actual command
158407fd2f31SMatthias Ringwald         command_completed = true;
1585e47e68c7SMatthias Ringwald     }
1586a2481739S[email protected] 
15874e9daa6fSMatthias Ringwald     // Vendor == Toshiba
15880e588213SMatthias Ringwald     if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){
15894e9daa6fSMatthias Ringwald         // TODO: track actual command
159007fd2f31SMatthias Ringwald         command_completed = true;
1591004902f1SMatthias Ringwald         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1592004902f1SMatthias Ringwald         hci_stack->num_cmd_packets = 1;
15934e9daa6fSMatthias Ringwald     }
159407fd2f31SMatthias Ringwald #endif
159507fd2f31SMatthias Ringwald 
159607fd2f31SMatthias Ringwald     return command_completed;
159707fd2f31SMatthias Ringwald }
159807fd2f31SMatthias Ringwald 
159907fd2f31SMatthias Ringwald static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){
160007fd2f31SMatthias Ringwald 
160107fd2f31SMatthias Ringwald     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
160207fd2f31SMatthias Ringwald 
160307fd2f31SMatthias Ringwald     bool command_completed =  hci_initializing_event_handler_command_completed(packet);
160407fd2f31SMatthias Ringwald 
160507fd2f31SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
16064e9daa6fSMatthias Ringwald 
16070f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
16080f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
16090f97eae7SMatthias Ringwald     //
16100f97eae7SMatthias Ringwald     // HCI Reset
16110f97eae7SMatthias Ringwald     // Timeout 100 ms
16120f97eae7SMatthias Ringwald     // HCI Reset
16130f97eae7SMatthias Ringwald     // Command Complete Reset
16140f97eae7SMatthias Ringwald     // HCI Read Local Version Information
16150f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
16160f97eae7SMatthias Ringwald     // hang...
16170f97eae7SMatthias Ringwald     //
16180f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
16190f97eae7SMatthias Ringwald     if (!command_completed
1620a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
16210e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){
16220f97eae7SMatthias Ringwald 
1623f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
16240f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
16250f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
16260f97eae7SMatthias Ringwald             return;
16270f97eae7SMatthias Ringwald         }
16280f97eae7SMatthias Ringwald     }
16290f97eae7SMatthias Ringwald 
16309f007422SMatthias Ringwald     // CSR & H5
16319f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
16329f007422SMatthias Ringwald     if (!command_completed
1633a1df452eSMatthias Ringwald             && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE)
16340e588213SMatthias Ringwald             && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){
16359f007422SMatthias Ringwald 
16369f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
16379f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
16389f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
16399f007422SMatthias Ringwald             return;
16409f007422SMatthias Ringwald         }
16419f007422SMatthias Ringwald     }
16429f007422SMatthias Ringwald 
16439f007422SMatthias 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
16449f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
16459f007422SMatthias Ringwald     if (command_completed){
16469f007422SMatthias Ringwald         switch (hci_stack->substate){
16479f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
16489f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
16499f007422SMatthias Ringwald                 break;
16509f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
16519f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
16529f007422SMatthias Ringwald                 break;
16539f007422SMatthias Ringwald             default:
16549f007422SMatthias Ringwald                 break;
16559f007422SMatthias Ringwald         }
16569f007422SMatthias Ringwald     }
16570f97eae7SMatthias Ringwald 
165806b9e820SMatthias Ringwald #endif
16590f97eae7SMatthias Ringwald 
1660a2481739S[email protected]     if (!command_completed) return;
1661a2481739S[email protected] 
166207fd2f31SMatthias Ringwald     bool need_baud_change = false;
166307fd2f31SMatthias Ringwald     bool need_addr_change = false;
166406b9e820SMatthias Ringwald 
166506b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
166606b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
16673fb36a29SMatthias Ringwald                         && hci_stack->chipset
16683fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
1669db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
16709796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1671db8bc6ffSMatthias Ringwald 
167206b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
16733fb36a29SMatthias Ringwald                         && hci_stack->chipset
16743fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
167506b9e820SMatthias Ringwald #endif
1676a80162e9SMatthias Ringwald 
16775c363727SMatthias Ringwald     switch(hci_stack->substate){
167806b9e820SMatthias Ringwald 
167906b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
16809f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
1681d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
16829f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
16839f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
16849f007422SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
16859f007422SMatthias Ringwald             break;
168674b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
1687528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
168876fcb19bSMatthias Ringwald             break;
1689e90bae01SMatthias Ringwald         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
169007fd2f31SMatthias Ringwald             log_info("Received local name, need baud change %d", (int) need_baud_change);
16912f48d920SMatthias Ringwald             if (need_baud_change){
16922f48d920SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
16932f48d920SMatthias Ringwald                 return;
16942f48d920SMatthias Ringwald             }
169553860077SMatthias Ringwald             // skip baud change
169674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
169774b323a9SMatthias Ringwald             return;
1698a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
16994696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
1700fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
170161f37892SMatthias Ringwald             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
170296b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1703cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1704fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
17054696bddbSMatthias Ringwald             }
170674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
170774b323a9SMatthias Ringwald             return;
1708a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1709528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
1710a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1711a80162e9SMatthias Ringwald             return;
171274b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
171374b323a9SMatthias Ringwald             // repeat custom init
171474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
171574b323a9SMatthias Ringwald             return;
171606b9e820SMatthias Ringwald #else
171706b9e820SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
171806b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
171906b9e820SMatthias Ringwald             return ;
172006b9e820SMatthias Ringwald #endif
172106b9e820SMatthias Ringwald 
1722a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
17230e588213SMatthias Ringwald             if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) &&
1724efd3b327SMatthias Ringwald               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1725efd3b327SMatthias Ringwald                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1726eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1727eb3a5314SMatthias Ringwald                 return;
1728eb3a5314SMatthias Ringwald             }
172953860077SMatthias Ringwald             if (need_addr_change){
173053860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
173153860077SMatthias Ringwald                 return;
173253860077SMatthias Ringwald             }
173353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
173453860077SMatthias Ringwald             return;
173506b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
17367224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
17377224be7eSMatthias Ringwald             if (need_baud_change){
173896b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1739cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1740fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
17417224be7eSMatthias Ringwald             }
1742eb3a5314SMatthias Ringwald             if (need_addr_change){
1743eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1744eb3a5314SMatthias Ringwald                 return;
1745eb3a5314SMatthias Ringwald             }
1746eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1747eb3a5314SMatthias Ringwald             return;
174853860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
17496ca9a99aSMatthias Ringwald             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
17506ca9a99aSMatthias Ringwald             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
17516ca9a99aSMatthias Ringwald             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
175253860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
175353860077SMatthias Ringwald                 return;
175453860077SMatthias Ringwald             }
175553860077SMatthias Ringwald             // skipping st warm boot
175653860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
175753860077SMatthias Ringwald             return;
175853860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
175953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
176053860077SMatthias Ringwald             return;
176106b9e820SMatthias Ringwald #endif
176253860077SMatthias Ringwald         case HCI_INIT_W4_READ_BD_ADDR:
176353860077SMatthias Ringwald             // only read buffer size if supported
176453860077SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x01) {
176553860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
176653860077SMatthias Ringwald                 return;
176753860077SMatthias Ringwald             }
176853860077SMatthias Ringwald             // skipping read buffer size
176953860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1770a828a756SMatthias Ringwald             return;
177174b323a9SMatthias Ringwald         case HCI_INIT_W4_SET_EVENT_MASK:
17726155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
17736155b3d3S[email protected]             if (!hci_classic_supported()){
17742c68f164SMatthias Ringwald #ifdef ENABLE_BLE
17756155b3d3S[email protected]                 if (hci_le_supported()){
177674b323a9SMatthias Ringwald                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
177774b323a9SMatthias Ringwald                     return;
17782c68f164SMatthias Ringwald                 }
17792c68f164SMatthias Ringwald #endif
17806155b3d3S[email protected]                 log_error("Neither BR/EDR nor LE supported");
1781a650ba4dSMatthias Ringwald                 hci_init_done();
178274b323a9SMatthias Ringwald                 return;
17836155b3d3S[email protected]             }
178415a95bd5SMatthias Ringwald             if (!gap_ssp_supported()){
17855c363727SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
178674b323a9SMatthias Ringwald                 return;
17876155b3d3S[email protected]             }
17886155b3d3S[email protected]             break;
1789903ea03aSMatthias Ringwald #ifdef ENABLE_BLE
1790a828a756SMatthias Ringwald         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1791a828a756SMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
1792a828a756SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x02) break;
1793daabb8b8SMatthias Ringwald             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1794daabb8b8SMatthias Ringwald             return;
1795daabb8b8SMatthias Ringwald 
1796b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1797b435e062SMatthias Ringwald         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
17986fab74dbSMatthias Ringwald             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1799b435e062SMatthias Ringwald             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
180080d7d618SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1801b435e062SMatthias Ringwald                 return;
1802b435e062SMatthias Ringwald             }
1803b435e062SMatthias Ringwald             // explicit fall through to reduce repetitions
1804b435e062SMatthias Ringwald 
1805b435e062SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1806b435e062SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1807903ea03aSMatthias Ringwald #else
1808903ea03aSMatthias Ringwald             hci_init_done();
1809903ea03aSMatthias Ringwald #endif
1810a828a756SMatthias Ringwald             return;
181106337f4fSMatthias Ringwald #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
181206337f4fSMatthias Ringwald 
181306337f4fSMatthias Ringwald #endif  /* ENABLE_BLE */
1814b435e062SMatthias Ringwald 
18155d23aae8SMatthias Ringwald         case HCI_INIT_W4_WRITE_INQUIRY_MODE:
18165d23aae8SMatthias Ringwald             // skip write secure connections host support if not supported or disabled
18170d589c37SMatthias Ringwald             if (!hci_stack->secure_connections_enable || (hci_stack->local_supported_commands[1] & 0x02) == 0) {
18185d23aae8SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;
18195d23aae8SMatthias Ringwald                 return;
18205d23aae8SMatthias Ringwald             }
18215d23aae8SMatthias Ringwald             break;
18225d23aae8SMatthias Ringwald 
182347bc3ebbSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
18243b65523cSMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
18253905afbfSMatthias Ringwald             // skip write synchronous flow control if not supported
18263905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x04) break;
18273905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1828cf373d3aSMatthias Ringwald 
1829cf373d3aSMatthias Ringwald             /* fall through */
18303905afbfSMatthias Ringwald 
1831729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
18323905afbfSMatthias Ringwald             // skip write default erroneous data reporting if not supported
18333905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x08) break;
18343905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1835cf373d3aSMatthias Ringwald 
1836cf373d3aSMatthias Ringwald             /* fall through */
18373905afbfSMatthias Ringwald 
1838f064e0bbSMatthias Ringwald         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1839a42798c3SMatthias Ringwald             // skip bcm set sco pcm config on non-Broadcom chipsets
184061f37892SMatthias Ringwald             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1841a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1842cf373d3aSMatthias Ringwald 
1843cf373d3aSMatthias Ringwald             /* fall through */
1844a42798c3SMatthias Ringwald 
1845a42798c3SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1846729ed62eSMatthias Ringwald             if (!hci_le_supported()){
1847729ed62eSMatthias Ringwald                 // SKIP LE init for Classic only configuration
1848a650ba4dSMatthias Ringwald                 hci_init_done();
1849729ed62eSMatthias Ringwald                 return;
1850729ed62eSMatthias Ringwald             }
1851729ed62eSMatthias Ringwald             break;
1852f3b012f9SMatthias Ringwald 
1853f3b012f9SMatthias Ringwald #else /* !ENABLE_SCO_OVER_HCI */
1854f3b012f9SMatthias Ringwald 
185574b323a9SMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1856f3b012f9SMatthias Ringwald #ifdef ENABLE_BLE
1857f3b012f9SMatthias Ringwald             if (hci_le_supported()){
1858f3b012f9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
185974b323a9SMatthias Ringwald                 return;
18606155b3d3S[email protected]             }
1861729ed62eSMatthias Ringwald #endif
1862f3b012f9SMatthias Ringwald             // SKIP LE init for Classic only configuration
1863f3b012f9SMatthias Ringwald             hci_init_done();
1864f3b012f9SMatthias Ringwald             return;
1865f3b012f9SMatthias Ringwald #endif /* ENABLE_SCO_OVER_HCI */
1866f3b012f9SMatthias Ringwald 
1867a4e96e78SMatthias Ringwald // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1868a4e96e78SMatthias Ringwald #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1869a650ba4dSMatthias Ringwald         // Response to command before init done state -> init done
1870a650ba4dSMatthias Ringwald         case (HCI_INIT_DONE-1):
1871a650ba4dSMatthias Ringwald             hci_init_done();
1872a650ba4dSMatthias Ringwald             return;
1873a4e96e78SMatthias Ringwald #endif
1874a650ba4dSMatthias Ringwald 
18756155b3d3S[email protected]         default:
187674b323a9SMatthias Ringwald             break;
18776155b3d3S[email protected]     }
187855975f88SMatthias Ringwald     hci_initializing_next_state();
18796155b3d3S[email protected] }
18806155b3d3S[email protected] 
18810bbba85bSMatthias Ringwald static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
1882229331c6SMatthias Ringwald     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
18830bbba85bSMatthias Ringwald     bd_addr_t bd_address;
18846535961aSMatthias Ringwald     (void)memcpy(&bd_address, conn->address, 6);
18850bbba85bSMatthias Ringwald 
18866bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
18876bc9fa5eSMatthias Ringwald     // cache needed data
18886bc9fa5eSMatthias Ringwald     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
18896bc9fa5eSMatthias Ringwald #endif
18906bc9fa5eSMatthias Ringwald 
18910bbba85bSMatthias Ringwald     // connection failed, remove entry
18920bbba85bSMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
18930bbba85bSMatthias Ringwald     btstack_memory_hci_connection_free( conn );
18940bbba85bSMatthias Ringwald 
18956bc9fa5eSMatthias Ringwald #ifdef ENABLE_CLASSIC
18960bbba85bSMatthias Ringwald     // notify client if dedicated bonding
18970bbba85bSMatthias Ringwald     if (notify_dedicated_bonding_failed){
18980bbba85bSMatthias Ringwald         log_info("hci notify_dedicated_bonding_failed");
18990bbba85bSMatthias Ringwald         hci_emit_dedicated_bonding_result(bd_address, status);
19000bbba85bSMatthias Ringwald     }
19010bbba85bSMatthias Ringwald 
19020bbba85bSMatthias Ringwald     // if authentication error, also delete link key
19030bbba85bSMatthias Ringwald     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
19040bbba85bSMatthias Ringwald         gap_drop_link_key_for_bd_addr(bd_address);
19050bbba85bSMatthias Ringwald     }
19066bc9fa5eSMatthias Ringwald #endif
19070bbba85bSMatthias Ringwald }
19080bbba85bSMatthias Ringwald 
1909*be500194SMatthias Ringwald #ifdef ENABLE_CLASSIC
19102f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){
19112f5c44baSMatthias Ringwald     // SSP Controller
19122f5c44baSMatthias Ringwald     if (features[6] & (1 << 3)){
19132f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER;
19142f5c44baSMatthias Ringwald     }
19152f5c44baSMatthias Ringwald     // eSCO
19162f5c44baSMatthias Ringwald     if (features[3] & (1<<7)){
19172f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 1;
19182f5c44baSMatthias Ringwald     }
19192f5c44baSMatthias Ringwald     // Extended features
19202f5c44baSMatthias Ringwald     if (features[7] & (1<<7)){
19212f5c44baSMatthias Ringwald         conn->remote_supported_features[0] |= 2;
19222f5c44baSMatthias Ringwald     }
19232f5c44baSMatthias Ringwald }
19242f5c44baSMatthias Ringwald 
19252f5c44baSMatthias Ringwald static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){
19262f5c44baSMatthias Ringwald     // SSP Host
19272f5c44baSMatthias Ringwald     if (features[0] & (1 << 0)){
19282f5c44baSMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST;
19292f5c44baSMatthias Ringwald     }
193050c51a77SMatthias Ringwald     // SC Host
193150c51a77SMatthias Ringwald     if (features[0] & (1 << 3)){
193250c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST;
193350c51a77SMatthias Ringwald     }
193450c51a77SMatthias Ringwald }
193550c51a77SMatthias Ringwald 
193650c51a77SMatthias Ringwald static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){
193750c51a77SMatthias Ringwald     // SC Controller
193850c51a77SMatthias Ringwald     if (features[1] & (1 << 0)){
193950c51a77SMatthias Ringwald         conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
194050c51a77SMatthias Ringwald     }
19412f5c44baSMatthias Ringwald }
19422f5c44baSMatthias Ringwald 
1943de0df013SMatthias Ringwald static void hci_handle_remote_features_received(hci_connection_t * conn){
1944de0df013SMatthias Ringwald     conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
194549bafb5eSMatthias Ringwald     log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags);
1946de0df013SMatthias Ringwald     if (conn->bonding_flags & BONDING_DEDICATED){
1947de0df013SMatthias Ringwald         conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1948de0df013SMatthias Ringwald     }
1949de0df013SMatthias Ringwald }
1950*be500194SMatthias Ringwald #endif
1951de0df013SMatthias Ringwald 
195267c6c9dcSMatthias Ringwald static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) {
195367c6c9dcSMatthias Ringwald     // handle BT initialization
195467c6c9dcSMatthias Ringwald     if (hci_stack->state == HCI_STATE_INITIALIZING) {
195567c6c9dcSMatthias Ringwald         hci_initializing_event_handler(packet, size);
195667c6c9dcSMatthias Ringwald     }
195767c6c9dcSMatthias Ringwald 
195867c6c9dcSMatthias Ringwald     // help with BT sleep
195967c6c9dcSMatthias Ringwald     if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP)
196067c6c9dcSMatthias Ringwald         && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE)
196167c6c9dcSMatthias Ringwald         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)) {
196267c6c9dcSMatthias Ringwald         hci_initializing_next_state();
196367c6c9dcSMatthias Ringwald     }
196467c6c9dcSMatthias Ringwald }
196567c6c9dcSMatthias Ringwald 
19669866fdc7SMatthias Ringwald #ifdef ENABLE_CLASSIC
19679866fdc7SMatthias Ringwald static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) {
19689866fdc7SMatthias Ringwald     conn->authentication_flags |= CONNECTION_ENCRYPTED;
19699866fdc7SMatthias Ringwald     conn->encryption_key_size = encryption_key_size;
1970abdad579SMatthias Ringwald 
1971abdad579SMatthias Ringwald     if ((conn->authentication_flags & CONNECTION_AUTHENTICATED) != 0) {
19729866fdc7SMatthias Ringwald         hci_emit_security_level(conn->con_handle, gap_security_level_for_connection(conn));
1973abdad579SMatthias Ringwald         return;
1974abdad579SMatthias Ringwald     }
1975abdad579SMatthias Ringwald 
1976abdad579SMatthias Ringwald     // Request Authentication if not already done
1977abdad579SMatthias Ringwald     if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
1978abdad579SMatthias Ringwald     conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
19799866fdc7SMatthias Ringwald }
19809866fdc7SMatthias Ringwald #endif
19819866fdc7SMatthias Ringwald 
198216833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
1983e76a89eeS[email protected] 
1984e76a89eeS[email protected]     uint16_t event_length = packet[1];
1985e76a89eeS[email protected] 
1986e76a89eeS[email protected]     // assert packet is complete
1987a1df452eSMatthias Ringwald     if (size != (event_length + 2)){
19883dce6128SMatthias Ringwald         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1989e76a89eeS[email protected]         return;
1990e76a89eeS[email protected]     }
1991e76a89eeS[email protected] 
19921281a47eSmatthias.ringwald     bd_addr_t addr;
199396a45072S[email protected]     bd_addr_type_t addr_type;
1994fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
19951f7b95a1Smatthias.ringwald     hci_connection_t * conn;
199656cf178bSmatthias.ringwald     int i;
1997c57fa566SMatthias Ringwald     int create_connection_cmd;
1998c57fa566SMatthias Ringwald 
19990014e02cSMatthias Ringwald #ifdef ENABLE_CLASSIC
20000014e02cSMatthias Ringwald     uint8_t link_type;
20010014e02cSMatthias Ringwald #endif
200235454696SMatthias Ringwald 
20030e2df43fSMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
20045909f7f2Smatthias.ringwald 
20050e2df43fSMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
200622909952Smatthias.ringwald 
20076772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
20086bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
20096bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
20107ec5eeaaSmatthias.ringwald 
20119e263bd7SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
201206b9e820SMatthias Ringwald                 if (packet[5]) break;
20139e263bd7SMatthias Ringwald                 // terminate, name 248 chars
20149e263bd7SMatthias Ringwald                 packet[6+248] = 0;
20159e263bd7SMatthias Ringwald                 log_info("local name: %s", &packet[6]);
20169e263bd7SMatthias Ringwald             }
201767c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
20181d279b20Smatthias.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"
2019429122ccSMatthias Ringwald                 if (hci_stack->state == HCI_STATE_INITIALIZING){
2020429122ccSMatthias Ringwald                     uint16_t acl_len = little_endian_read_16(packet, 6);
2021429122ccSMatthias Ringwald                     uint16_t sco_len = packet[8];
2022429122ccSMatthias Ringwald 
2023429122ccSMatthias Ringwald                     // determine usable ACL/SCO payload size
2024429122ccSMatthias Ringwald                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
2025429122ccSMatthias Ringwald                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
2026429122ccSMatthias Ringwald 
2027f8fbdce0SMatthias Ringwald                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
2028f8fbdce0SMatthias Ringwald                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
2029a8b12447S[email protected] 
2030429122ccSMatthias Ringwald                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
2031429122ccSMatthias Ringwald                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
20321a06f663S[email protected]                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
2033e2edc0c3Smatthias.ringwald                 }
203456cf178bSmatthias.ringwald             }
203567c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_rssi)){
2036891b9fc2SMatthias Ringwald                 if (packet[5] == 0){
2037891b9fc2SMatthias Ringwald                     uint8_t event[5];
2038891b9fc2SMatthias Ringwald                     event[0] = GAP_EVENT_RSSI_MEASUREMENT;
2039891b9fc2SMatthias Ringwald                     event[1] = 3;
20406535961aSMatthias Ringwald                     (void)memcpy(&event[2], &packet[6], 3);
2041891b9fc2SMatthias Ringwald                     hci_emit_event(event, sizeof(event), 1);
2042891b9fc2SMatthias Ringwald                 }
2043891b9fc2SMatthias Ringwald             }
2044a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
204567c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
2046f8fbdce0SMatthias Ringwald                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
2047ee303eddS[email protected]                 hci_stack->le_acl_packets_total_num  = packet[8];
20486c26b087S[email protected]                 // determine usable ACL payload size
20496c26b087S[email protected]                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
20506c26b087S[email protected]                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
20516c26b087S[email protected]                 }
20529da54300S[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);
205365a46ef3S[email protected]             }
2054b435e062SMatthias Ringwald #endif
2055b435e062SMatthias Ringwald #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
205667c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
2057dcd678baSMatthias Ringwald                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
2058dcd678baSMatthias Ringwald                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
2059dcd678baSMatthias 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);
2060dcd678baSMatthias Ringwald             }
2061b435e062SMatthias Ringwald #endif
2062d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
206367c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
2064e691bb38SMatthias Ringwald                 hci_stack->le_whitelist_capacity = packet[6];
206515d0a15bSMatthias Ringwald                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
20663b6d4121SMatthias Ringwald             }
206765a46ef3S[email protected] #endif
206867c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
2069724d70a2SMatthias Ringwald                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
2070724d70a2SMatthias Ringwald 				hci_stack->local_bd_addr);
20719da54300S[email protected]                 log_info("Local Address, Status: 0x%02x: Addr: %s",
20723a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
207333373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
20741624665aSMatthias Ringwald                 if (hci_stack->link_key_db){
20751624665aSMatthias Ringwald                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
20761624665aSMatthias Ringwald                 }
207733373e40SMatthias Ringwald #endif
2078188981d2Smatthias.ringwald             }
207935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
208067c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
20813a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
2082381fbed8Smatthias.ringwald             }
208367c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
2084f5875de5SMatthias Ringwald                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
2085f5875de5SMatthias Ringwald                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2086f5875de5SMatthias Ringwald                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2087f5875de5SMatthias Ringwald                     hci_emit_event(event, sizeof(event), 1);
2088f5875de5SMatthias Ringwald                 }
2089f5875de5SMatthias Ringwald             }
209035454696SMatthias Ringwald #endif
209135454696SMatthias Ringwald 
209265389bfcS[email protected]             // Note: HCI init checks
209367c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
20946535961aSMatthias Ringwald                 (void)memcpy(hci_stack->local_supported_features,
20956535961aSMatthias Ringwald 			     &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
20966535961aSMatthias Ringwald 			     8);
209765389bfcS[email protected] 
209835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2099a5a23fc2S[email protected]                 // determine usable ACL packet types based on host buffer size and supported features
2100a5a23fc2S[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]);
21018b96126aSMatthias Ringwald                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
210235454696SMatthias Ringwald #endif
2103f5d8d141S[email protected]                 // Classic/LE
2104f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
2105559e517eS[email protected]             }
210667c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
2107f8fbdce0SMatthias Ringwald                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
2108f8fbdce0SMatthias Ringwald                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
2109c21d89f3SMatthias Ringwald                 uint16_t manufacturer = little_endian_read_16(packet, 10);
2110c21d89f3SMatthias Ringwald                 // map Cypress to Broadcom
2111c21d89f3SMatthias Ringwald                 if (manufacturer  == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){
2112c21d89f3SMatthias Ringwald                     log_info("Treat Cypress as Broadcom");
2113c21d89f3SMatthias Ringwald                     manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION;
2114c21d89f3SMatthias Ringwald                     little_endian_store_16(packet, 10, manufacturer);
2115c21d89f3SMatthias Ringwald                 }
2116c21d89f3SMatthias Ringwald                 hci_stack->manufacturer = manufacturer;
2117f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
2118f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
21194696bddbSMatthias Ringwald                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
21204696bddbSMatthias Ringwald             }
212167c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
2122a828a756SMatthias Ringwald                 hci_stack->local_supported_commands[0] =
2123a1df452eSMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7) |  // bit 0 = Octet 14, bit 7 / Read Buffer Size
2124a1df452eSMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5) |  // bit 1 = Octet 24, bit 6 / Write Le Host Supported
2125a1df452eSMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2) |  // bit 2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
21268d2d8af1SMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)     ) |  // bit 3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
21270e588213SMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4) |  // bit 4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
21280e588213SMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2) |  // bit 5 = Octet 35, bit 3 / LE Read Maximum Data Length
21296e058d3fSMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x20) << 1) |  // bit 6 = Octet 35, bit 5 / LE Set Default PHY
21306e058d3fSMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+20] & 0x10) << 3);   // bit 7 = Octet 20, bit 4 / Read Encryption Key Size
21318d2d8af1SMatthias Ringwald                 hci_stack->local_supported_commands[1] =
21325d23aae8SMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+ 2] & 0x40) >> 6) |  // bit 8 = Octet  2, bit 6 / Read Remote Extended Features
21335d23aae8SMatthias Ringwald                     ((packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+32] & 0x08) >> 2);   // bit 9 = Octet 32, bit 3 / Write Secure Connections Host
21348d2d8af1SMatthias Ringwald                 log_info("Local supported commands summary %02x - %02x", hci_stack->local_supported_commands[0],  hci_stack->local_supported_commands[1]);
2135a828a756SMatthias Ringwald             }
2136e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
213767c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
21385b9b590fSMatthias Ringwald                 if (packet[5] == 0){
21395b9b590fSMatthias Ringwald                     hci_stack->synchronous_flow_control_enabled = 1;
21405b9b590fSMatthias Ringwald                 }
21415b9b590fSMatthias Ringwald             }
214267c6c9dcSMatthias Ringwald             else if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_encryption_key_size)){
2143573897a0SMatthias Ringwald                 uint8_t status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE];
2144573897a0SMatthias Ringwald                 handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1);
2145573897a0SMatthias Ringwald                 conn   = hci_connection_for_handle(handle);
2146573897a0SMatthias Ringwald                 if (!conn) break;
21479866fdc7SMatthias Ringwald                 uint8_t key_size = 0;
2148573897a0SMatthias Ringwald                 if (status == 0){
21499866fdc7SMatthias Ringwald                     key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3];
2150573897a0SMatthias Ringwald                     log_info("Handle %x04x key Size: %u", handle, key_size);
2151170fafaeSMatthias Ringwald                 } else {
21529866fdc7SMatthias Ringwald                     log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status);
2153573897a0SMatthias Ringwald                 }
21549866fdc7SMatthias Ringwald                 hci_handle_read_encryption_key_size_complete(conn, key_size);
2155573897a0SMatthias Ringwald             }
2156e8c8828eSMatthias Ringwald #endif
215756cf178bSmatthias.ringwald             break;
215856cf178bSmatthias.ringwald 
21597ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
21606bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
21616bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
2162229331c6SMatthias Ringwald 
2163229331c6SMatthias Ringwald             // check command status to detected failed outgoing connections
2164c57fa566SMatthias Ringwald             create_connection_cmd = 0;
2165c57fa566SMatthias Ringwald #ifdef ENABLE_CLASSIC
2166c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2167c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2168c57fa566SMatthias Ringwald             }
2169c57fa566SMatthias Ringwald #endif
2170c57fa566SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2171c57fa566SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
2172c57fa566SMatthias Ringwald                 create_connection_cmd = 1;
2173c57fa566SMatthias Ringwald             }
2174c57fa566SMatthias Ringwald #endif
2175c57fa566SMatthias Ringwald             if (create_connection_cmd) {
2176229331c6SMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2177229331c6SMatthias Ringwald                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, hci_stack->outgoing_addr_type);
2178229331c6SMatthias 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), hci_stack->outgoing_addr_type);
2179229331c6SMatthias Ringwald 
2180229331c6SMatthias Ringwald                 // reset outgoing address info
2181229331c6SMatthias Ringwald                 memset(hci_stack->outgoing_addr, 0, 6);
2182229331c6SMatthias Ringwald                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
2183229331c6SMatthias Ringwald 
2184229331c6SMatthias Ringwald                 // error => outgoing connection failed
2185229331c6SMatthias Ringwald                 if ((conn != NULL) && (status != 0)){
2186229331c6SMatthias Ringwald                     hci_handle_connection_failed(conn, status);
2187229331c6SMatthias Ringwald                 }
2188229331c6SMatthias Ringwald             }
21897ec5eeaaSmatthias.ringwald             break;
21907ec5eeaaSmatthias.ringwald 
21912e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
21929784dac1SMatthias Ringwald             if (size < 3) return;
21939784dac1SMatthias Ringwald             uint16_t num_handles = packet[2];
219477b3fe1aSMatthias Ringwald             if (size != (3 + num_handles * 4)) return;
21959784dac1SMatthias Ringwald             uint16_t offset = 3;
21969784dac1SMatthias Ringwald             for (i=0; i<num_handles;i++){
219780117cebSMatthias Ringwald                 handle = little_endian_read_16(packet, offset) & 0x0fff;
21982e440c8aS[email protected]                 offset += 2;
2199f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
22002e440c8aS[email protected]                 offset += 2;
22012e440c8aS[email protected] 
22025061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
220356cf178bSmatthias.ringwald                 if (!conn){
22049da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
220556cf178bSmatthias.ringwald                     continue;
220656cf178bSmatthias.ringwald                 }
220723bed257S[email protected] 
2208ce41473eSMatthias Ringwald                 if (conn->num_packets_sent >= num_packets){
2209ce41473eSMatthias Ringwald                     conn->num_packets_sent -= num_packets;
2210e35edcc1S[email protected]                 } else {
2211ce41473eSMatthias Ringwald                     log_error("hci_number_completed_packets, more packet slots freed then sent.");
2212ce41473eSMatthias Ringwald                     conn->num_packets_sent = 0;
2213e35edcc1S[email protected]                 }
2214ce41473eSMatthias Ringwald                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent);
2215760b20efSMatthias Ringwald 
2216760b20efSMatthias Ringwald #ifdef ENABLE_CLASSIC
2217760b20efSMatthias Ringwald                 // For SCO, we do the can_send_now_check here
2218760b20efSMatthias Ringwald                 hci_notify_if_sco_can_send_now();
2219760b20efSMatthias Ringwald #endif
222056cf178bSmatthias.ringwald             }
22216772a24cSmatthias.ringwald             break;
22222e440c8aS[email protected]         }
222335454696SMatthias Ringwald 
222435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2225f5875de5SMatthias Ringwald         case HCI_EVENT_INQUIRY_COMPLETE:
2226f5875de5SMatthias Ringwald             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2227f5875de5SMatthias Ringwald                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2228f5875de5SMatthias Ringwald                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2229f5875de5SMatthias Ringwald                 hci_emit_event(event, sizeof(event), 1);
2230f5875de5SMatthias Ringwald             }
2231f5875de5SMatthias Ringwald             break;
2232b7f1ee76SMatthias Ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2233b7f1ee76SMatthias Ringwald             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2234b7f1ee76SMatthias Ringwald                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2235b7f1ee76SMatthias Ringwald             }
2236b7f1ee76SMatthias Ringwald             break;
22371f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
2238724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
223907e010b6SMilanka Ringwald             if (hci_stack->gap_classic_accept_callback != NULL){
224007e010b6SMilanka Ringwald                 if ((*hci_stack->gap_classic_accept_callback)(addr) == 0){
22414536712cSMilanka Ringwald                     hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR;
224207e010b6SMilanka Ringwald                     bd_addr_copy(hci_stack->decline_addr, addr);
224307e010b6SMilanka Ringwald                     break;
224407e010b6SMilanka Ringwald                 }
224507e010b6SMilanka Ringwald             }
224607e010b6SMilanka Ringwald 
224737eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
22482d00edd4Smatthias.ringwald             link_type = packet[11];
22499da54300S[email protected]             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
2250a1df452eSMatthias Ringwald             addr_type = (link_type == 1) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO;
22512e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
22521f7b95a1Smatthias.ringwald             if (!conn) {
22535293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
22541f7b95a1Smatthias.ringwald             }
2255ce4c8fabSmatthias.ringwald             if (!conn) {
2256ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
22574536712cSMilanka Ringwald                 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
2258058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
2259ce4c8fabSmatthias.ringwald                 break;
2260ce4c8fabSmatthias.ringwald             }
22615cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
226232ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
2263f3a16b9aSMatthias Ringwald             // store info about eSCO
2264f3a16b9aSMatthias Ringwald             if (link_type == 0x02){
226576ccfb2aSMatthias Ringwald                 conn->remote_supported_features[0] |= 1;
2266f3a16b9aSMatthias Ringwald             }
226732ab9390Smatthias.ringwald             hci_run();
22681f7b95a1Smatthias.ringwald             break;
22691f7b95a1Smatthias.ringwald 
22706772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2271fe1ed1b8Smatthias.ringwald             // Connection management
2272724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
22739da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2274f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
22752e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2276fe1ed1b8Smatthias.ringwald             if (conn) {
2277b448a0e7Smatthias.ringwald                 if (!packet[2]){
2278c8e4258aSmatthias.ringwald                     conn->state = OPEN;
2279f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
22806909f064SMatthias Ringwald 
22816909f064SMatthias Ringwald                     // queue get remote feature
2282ba018746SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
2283ee091cf1Smatthias.ringwald 
2284e6c51921SMatthias Ringwald                     // queue set supervision timeout if we're master
2285a1df452eSMatthias Ringwald                     if ((hci_stack->link_supervision_timeout != 0) && (conn->role == HCI_ROLE_MASTER)){
22866909f064SMatthias Ringwald                         connectionSetAuthenticationFlags(conn, WRITE_SUPERVISION_TIMEOUT);
22876909f064SMatthias Ringwald                     }
22886909f064SMatthias Ringwald 
2289c785ef68Smatthias.ringwald                     // restart timer
2290528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2291528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
2292c785ef68Smatthias.ringwald 
22939da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
229443bfb1bdSmatthias.ringwald 
229543bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
2296b448a0e7Smatthias.ringwald                 } else {
22970bbba85bSMatthias Ringwald                     // connection failed
22980bbba85bSMatthias Ringwald                     hci_handle_connection_failed(conn, packet[2]);
2299fe1ed1b8Smatthias.ringwald                 }
2300fe1ed1b8Smatthias.ringwald             }
23016772a24cSmatthias.ringwald             break;
2302fe1ed1b8Smatthias.ringwald 
230344d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2304724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
230544d0e3d5S[email protected]             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
23061a06f663S[email protected]             if (packet[2]){
230744d0e3d5S[email protected]                 // connection failed
230844d0e3d5S[email protected]                 break;
230944d0e3d5S[email protected]             }
23102e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2311e35edcc1S[email protected]             if (!conn) {
2312e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2313e35edcc1S[email protected]             }
2314e35edcc1S[email protected]             if (!conn) {
2315e35edcc1S[email protected]                 break;
2316e35edcc1S[email protected]             }
23171a06f663S[email protected]             conn->state = OPEN;
2318f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
2319ee752bb8SMatthias Ringwald 
2320ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
2321ee752bb8SMatthias Ringwald             // update SCO
2322ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2323ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2324ee752bb8SMatthias Ringwald             }
2325f234b250SMatthias Ringwald             // trigger can send now
2326f234b250SMatthias Ringwald             if (hci_have_usb_transport()){
2327f234b250SMatthias Ringwald                 hci_stack->sco_can_send_now = 1;
2328f234b250SMatthias Ringwald             }
2329ee752bb8SMatthias Ringwald #endif
233044d0e3d5S[email protected]             break;
233144d0e3d5S[email protected] 
2332afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2333f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2334afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
2335afd4e962S[email protected]             if (!conn) break;
2336afd4e962S[email protected]             if (!packet[2]){
23372f5c44baSMatthias Ringwald                 const uint8_t * features = &packet[5];
23382f5c44baSMatthias Ringwald                 hci_handle_remote_features_page_0(conn, features);
23392f5c44baSMatthias Ringwald 
23405ccef624SMatthias Ringwald                 // read extended features if possible
23415ccef624SMatthias Ringwald                 if (((hci_stack->local_supported_commands[1] & 1) != 0) && ((conn->remote_supported_features[0] & 2) != 0)) {
23425ccef624SMatthias Ringwald                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
23435ccef624SMatthias Ringwald                     break;
23445ccef624SMatthias Ringwald                 }
23455ccef624SMatthias Ringwald             }
23465ccef624SMatthias Ringwald             hci_handle_remote_features_received(conn);
23475ccef624SMatthias Ringwald             break;
23485ccef624SMatthias Ringwald 
23495ccef624SMatthias Ringwald         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
23505ccef624SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
23515ccef624SMatthias Ringwald             conn = hci_connection_for_handle(handle);
23525ccef624SMatthias Ringwald             if (!conn) break;
23535ccef624SMatthias Ringwald             // status = ok, page = 1
235450c51a77SMatthias Ringwald             if (!packet[2]) {
235550c51a77SMatthias Ringwald                 uint8_t page_number = packet[5];
235650c51a77SMatthias Ringwald                 uint8_t maximum_page_number = packet[6];
23575ccef624SMatthias Ringwald                 const uint8_t * features = &packet[7];
235850c51a77SMatthias Ringwald                 bool done = false;
235950c51a77SMatthias Ringwald                 switch (page_number){
236050c51a77SMatthias Ringwald                     case 1:
23612f5c44baSMatthias Ringwald                         hci_handle_remote_features_page_1(conn, features);
236250c51a77SMatthias Ringwald                         if (maximum_page_number >= 2){
236350c51a77SMatthias Ringwald                             // get Secure Connections (Controller) from Page 2 if available
236450c51a77SMatthias Ringwald                             conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
236550c51a77SMatthias Ringwald                         } else {
236650c51a77SMatthias Ringwald                             // otherwise, assume SC (Controller) == SC (Host)
236750c51a77SMatthias Ringwald                             if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){
236850c51a77SMatthias Ringwald                                 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
236950c51a77SMatthias Ringwald                             }
237050c51a77SMatthias Ringwald                             done = true;
237150c51a77SMatthias Ringwald                         }
237250c51a77SMatthias Ringwald                         break;
237350c51a77SMatthias Ringwald                     case 2:
237450c51a77SMatthias Ringwald                         hci_handle_remote_features_page_2(conn, features);
237550c51a77SMatthias Ringwald                         done = true;
237650c51a77SMatthias Ringwald                         break;
237750c51a77SMatthias Ringwald                     default:
237850c51a77SMatthias Ringwald                         break;
237950c51a77SMatthias Ringwald                 }
238050c51a77SMatthias Ringwald                 if (!done) break;
2381afd4e962S[email protected]             }
2382de0df013SMatthias Ringwald             hci_handle_remote_features_received(conn);
2383afd4e962S[email protected]             break;
2384afd4e962S[email protected] 
23857fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
23869da54300S[email protected]             log_info("HCI_EVENT_LINK_KEY_REQUEST");
23877fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
238874d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2389a98592bcSMatthias Ringwald             if (hci_stack->bondable && !hci_stack->link_key_db) break;
239032ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
239164472d52Smatthias.ringwald             hci_run();
2392d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
239329d53098Smatthias.ringwald             return;
23947fde4af9Smatthias.ringwald 
23959ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2396724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
2397f16129ceSMatthias Ringwald             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
23989ab95c90S[email protected]             if (!conn) break;
23999ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
24007bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
24019ab95c90S[email protected]             // Change Connection Encryption keeps link key type
24029ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
24039ab95c90S[email protected]                 conn->link_key_type = link_key_type;
24049ab95c90S[email protected]             }
240555597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
240629d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
24077fde4af9Smatthias.ringwald             break;
24089ab95c90S[email protected]         }
24097fde4af9Smatthias.ringwald 
24107fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
24116724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
24124c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
24133a9fb326S[email protected]             if (!hci_stack->bondable){
2414899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2415f8fb5f6eS[email protected]                 hci_run();
2416f8fb5f6eS[email protected]                 return;
24174c57c146S[email protected]             }
2418d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2419a98592bcSMatthias Ringwald             if (!hci_stack->link_key_db) break;
2420a6ef64baSMilanka Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
2421a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
24227fde4af9Smatthias.ringwald             break;
24237fde4af9Smatthias.ringwald 
24241d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
24251d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2426dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2427dbe1a790S[email protected]             break;
2428dbe1a790S[email protected] 
2429dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
24306724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
24313a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
2432dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2433dbe1a790S[email protected]             break;
2434dbe1a790S[email protected] 
2435dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
24366724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
24373a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
2438dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
24391d6b20aeS[email protected]             break;
24403dce6128SMatthias Ringwald         case HCI_EVENT_MODE_CHANGE:
24413dce6128SMatthias Ringwald             handle = hci_event_mode_change_get_handle(packet);
24423dce6128SMatthias Ringwald             conn = hci_connection_for_handle(handle);
24433dce6128SMatthias Ringwald             if (!conn) break;
24443dce6128SMatthias Ringwald             conn->connection_mode = hci_event_mode_change_get_mode(packet);
24453dce6128SMatthias Ringwald             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
24463dce6128SMatthias Ringwald             break;
244735454696SMatthias Ringwald #endif
24481d6b20aeS[email protected] 
2449f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
2450254b78eeSMatthias Ringwald             handle = hci_event_encryption_change_get_connection_handle(packet);
2451f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
2452f0944df2S[email protected]             if (!conn) break;
2453254b78eeSMatthias Ringwald             if (hci_event_encryption_change_get_status(packet) == 0) {
2454254b78eeSMatthias Ringwald                 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet);
2455254b78eeSMatthias Ringwald                 if (encryption_enabled){
2456573897a0SMatthias Ringwald                     if (hci_is_le_connection(conn)){
2457573897a0SMatthias Ringwald                         // For LE, we accept connection as encrypted
2458f0944df2S[email protected]                         conn->authentication_flags |= CONNECTION_ENCRYPTED;
2459573897a0SMatthias Ringwald                     }
2460573897a0SMatthias Ringwald #ifdef ENABLE_CLASSIC
2461573897a0SMatthias Ringwald                     else {
2462254b78eeSMatthias Ringwald                         // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS)
2463254b78eeSMatthias Ringwald                         bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type) != 0;
2464254b78eeSMatthias Ringwald                         bool connected_uses_aes_ccm = encryption_enabled == 2;
2465254b78eeSMatthias Ringwald                         if (sc_used_during_pairing && !connected_uses_aes_ccm){
2466254b78eeSMatthias Ringwald                             log_info("SC during pairing, but only E0 now -> abort");
24679ece71c2SMatthias Ringwald                             conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2468254b78eeSMatthias Ringwald                             break;
2469254b78eeSMatthias Ringwald                         }
2470254b78eeSMatthias Ringwald 
24716e058d3fSMatthias Ringwald                         if ((hci_stack->local_supported_commands[0] & 0x80) != 0){
24726e058d3fSMatthias Ringwald                             // For Classic, we need to validate encryption key size first, if possible (== supported by Controller)
2473573897a0SMatthias Ringwald                             conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
24746e058d3fSMatthias Ringwald                         } else {
24756e058d3fSMatthias Ringwald                             // if not, pretend everything is perfect
24769866fdc7SMatthias Ringwald                             hci_handle_read_encryption_key_size_complete(conn, 16);
24776e058d3fSMatthias Ringwald                         }
2478573897a0SMatthias Ringwald                     }
2479573897a0SMatthias Ringwald #endif
2480f0944df2S[email protected]                 } else {
2481536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2482f0944df2S[email protected]                 }
2483ad83dc6aS[email protected]             }
2484573897a0SMatthias Ringwald 
2485f0944df2S[email protected]             break;
2486f0944df2S[email protected] 
248735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
24881eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2489abdad579SMatthias Ringwald             handle = hci_event_authentication_complete_get_connection_handle(packet);
24901eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
24911eb2563eS[email protected]             if (!conn) break;
2492ad83dc6aS[email protected] 
249363fc2b30SMatthias Ringwald             // ignore authentication event if we didn't request it
249463fc2b30SMatthias Ringwald             if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) == 0) break;
249563fc2b30SMatthias Ringwald 
2496ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
2497ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
2498ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
2499ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
25001bd5283dS[email protected]                 conn->bonding_status = packet[2];
2501ad83dc6aS[email protected]                 break;
2502ad83dc6aS[email protected]             }
2503ad83dc6aS[email protected] 
2504abdad579SMatthias Ringwald             // authenticated only if auth status == 0
2505abdad579SMatthias Ringwald             if (hci_event_authentication_complete_get_status(packet) == 0){
2506abdad579SMatthias Ringwald                 // authenticated
2507abdad579SMatthias Ringwald                 conn->authentication_flags |= CONNECTION_AUTHENTICATED;
2508abdad579SMatthias Ringwald 
2509abdad579SMatthias Ringwald                 // If link key sufficient for requested security and not already encrypted, start encryption
2510abdad579SMatthias Ringwald                 if (((gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level)) &&
2511abdad579SMatthias Ringwald                     ((conn->authentication_flags & CONNECTION_ENCRYPTED) == 0)){
25121eb2563eS[email protected]                     conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2513ad83dc6aS[email protected]                     break;
2514ad83dc6aS[email protected]                 }
2515abdad579SMatthias Ringwald             }
2516abdad579SMatthias Ringwald 
2517abdad579SMatthias Ringwald             // emit updated security level
25181eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
25191eb2563eS[email protected]             break;
252035454696SMatthias Ringwald #endif
252134d2123cS[email protected] 
252286805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
2523ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
2524ccda6e14S[email protected]         // see end of function, too.
2525a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
2526a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
2527f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
252881d2bdb2SMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
2529c6a37cfdSMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0) {
2530c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
253181d2bdb2SMatthias Ringwald                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0;
253281d2bdb2SMatthias Ringwald                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2533c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_total_size = 0;
2534c6a37cfdSMatthias Ringwald                     hci_stack->acl_fragmentation_pos = 0;
253581d2bdb2SMatthias Ringwald                     if (release_buffer){
253681d2bdb2SMatthias Ringwald                         hci_release_packet_buffer();
253781d2bdb2SMatthias Ringwald                     }
2538c6a37cfdSMatthias Ringwald                 }
2539c6a37cfdSMatthias Ringwald             }
254035454696SMatthias Ringwald 
2541c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
2542c6a37cfdSMatthias Ringwald             if (!conn) break;
2543046ec007SMatthias Ringwald             // mark connection for shutdown
2544a70e17d4SMatthias Ringwald             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2545046ec007SMatthias Ringwald 
2546046ec007SMatthias Ringwald             // emit dedicatd bonding event
2547046ec007SMatthias Ringwald             if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2548046ec007SMatthias Ringwald                 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status);
2549046ec007SMatthias Ringwald             }
2550046ec007SMatthias Ringwald 
255135454696SMatthias Ringwald #ifdef ENABLE_BLE
2552d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2553046ec007SMatthias Ringwald             // re-enable advertisements for le connections if active
25542b6ab3e6SMatthias Ringwald             if (hci_is_le_connection(conn)){
25552b6ab3e6SMatthias Ringwald                 hci_reenable_advertisements_if_needed();
25569a2e4658SMatthias Ringwald             }
255735454696SMatthias Ringwald #endif
2558d70217a2SMatthias Ringwald #endif
2559ccda6e14S[email protected]             break;
25606772a24cSmatthias.ringwald 
2561c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
2562313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
2563d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
2564c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
25657586ee35S[email protected]             } else {
25667586ee35S[email protected]                 // if no special requests, just reboot stack
25677586ee35S[email protected]                 hci_power_control_off();
25687586ee35S[email protected]                 hci_power_control_on();
2569c68bdf90Smatthias.ringwald             }
2570c68bdf90Smatthias.ringwald             break;
2571c68bdf90Smatthias.ringwald 
25720e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
25735cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
25745cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
2575c4c88f1bSJakob Krantz             reverse_bd_addr(&packet[3], addr);
2576f16129ceSMatthias Ringwald             addr_type = BD_ADDR_TYPE_ACL;
2577c4c88f1bSJakob Krantz             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2578c4c88f1bSJakob Krantz             if (!conn) break;
25795cf766e8SMatthias Ringwald             conn->role = packet[9];
25805cf766e8SMatthias Ringwald             break;
25810e6f3837SMatthias Ringwald #endif
25825cf766e8SMatthias Ringwald 
258363fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2584d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
25854fa24b5fS[email protected]             if (hci_transport_synchronous()) {
258663fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
25874fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
25884fa24b5fS[email protected]             }
258981d2bdb2SMatthias Ringwald             hci_stack->acl_fragmentation_tx_active = 0;
2590d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
2591d051460cS[email protected]             hci_release_packet_buffer();
2592701e3307SMatthias Ringwald 
259363fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
259463fa3374SMatthias Ringwald 
259535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
259663fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
2597701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
259835454696SMatthias Ringwald #endif
25996b4af23dS[email protected]             break;
26006b4af23dS[email protected] 
260135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
260263fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
260363fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
2604f234b250SMatthias Ringwald             hci_stack->sco_can_send_now = 1;
260563fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
260663fa3374SMatthias Ringwald             return;
26071cfb383eSMatthias Ringwald 
26081cfb383eSMatthias Ringwald         // explode inquriy results for easier consumption
26091cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
26101cfb383eSMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
26111cfb383eSMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
26129784dac1SMatthias Ringwald             gap_inquiry_explode(packet, size);
26131cfb383eSMatthias Ringwald             break;
261435454696SMatthias Ringwald #endif
261563fa3374SMatthias Ringwald 
2616a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
26175909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
26185909f7f2Smatthias.ringwald             switch (packet[2]){
2619d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
262057c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
26214f4e0224SMatthias Ringwald                     // log_info("advertising report received");
26226fab74dbSMatthias Ringwald                     if (!hci_stack->le_scanning_enabled) break;
262357c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
26247bdc6798S[email protected]                     break;
2625d70217a2SMatthias Ringwald #endif
26265909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
26275909f7f2Smatthias.ringwald                     // Connection management
2628724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[8], addr);
26297bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
26309da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
26312e77e513S[email protected]                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
26329c77c9dbSMatthias Ringwald 
2633d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
263442ff5ba1SMatthias Ringwald                     // if auto-connect, remove from whitelist in both roles
263542ff5ba1SMatthias Ringwald                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
263642ff5ba1SMatthias Ringwald                         hci_remove_from_whitelist(addr_type, addr);
263742ff5ba1SMatthias Ringwald                     }
263842ff5ba1SMatthias Ringwald                     // handle error: error is reported only to the initiator -> outgoing connection
26395909f7f2Smatthias.ringwald                     if (packet[3]){
26409c77c9dbSMatthias Ringwald 
26419c77c9dbSMatthias Ringwald                         // handle cancelled outgoing connection
26429c77c9dbSMatthias Ringwald                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
26439c77c9dbSMatthias Ringwald                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
26449c77c9dbSMatthias Ringwald                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
26459c77c9dbSMatthias Ringwald                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
26469c77c9dbSMatthias Ringwald                             conn = gap_get_outgoing_connection();
26479c77c9dbSMatthias Ringwald                         }
26489c77c9dbSMatthias Ringwald 
264942ff5ba1SMatthias Ringwald                         // outgoing connection establishment is done
265042ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
265142ff5ba1SMatthias Ringwald                         // remove entry
26525909f7f2Smatthias.ringwald                         if (conn){
2653665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
26545909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
26555909f7f2Smatthias.ringwald                         }
26565909f7f2Smatthias.ringwald                         break;
26575909f7f2Smatthias.ringwald                     }
2658d70217a2SMatthias Ringwald #endif
265942ff5ba1SMatthias Ringwald                     // on success, both hosts receive connection complete event
26605cf766e8SMatthias Ringwald                     if (packet[6] == HCI_ROLE_MASTER){
2661d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
266242ff5ba1SMatthias Ringwald                         // if we're master, it was an outgoing connection and we're done with it
266342ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2664d70217a2SMatthias Ringwald #endif
266542ff5ba1SMatthias Ringwald                     } else {
2666d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
266742ff5ba1SMatthias Ringwald                         // if we're slave, it was an incoming connection, advertisements have stopped
2668171293d3SMatthias Ringwald                         hci_stack->le_advertisements_active = 0;
2669d70217a2SMatthias Ringwald #endif
267042ff5ba1SMatthias Ringwald                     }
2671171293d3SMatthias Ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
267242ff5ba1SMatthias Ringwald                     if (!conn){
267396a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
26745909f7f2Smatthias.ringwald                     }
267542ff5ba1SMatthias Ringwald                     // no memory, sorry.
26765909f7f2Smatthias.ringwald                     if (!conn){
26775909f7f2Smatthias.ringwald                         break;
26785909f7f2Smatthias.ringwald                     }
26795909f7f2Smatthias.ringwald 
26805909f7f2Smatthias.ringwald                     conn->state = OPEN;
26815cf766e8SMatthias Ringwald                     conn->role  = packet[6];
2682c9db5c21SMilanka Ringwald                     conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2683c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
26845909f7f2Smatthias.ringwald 
26852b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
26862b6ab3e6SMatthias Ringwald                     if (packet[6] == HCI_ROLE_SLAVE){
26872b6ab3e6SMatthias Ringwald                         hci_reenable_advertisements_if_needed();
26882b6ab3e6SMatthias Ringwald                     }
26892b6ab3e6SMatthias Ringwald #endif
26902b6ab3e6SMatthias Ringwald 
26915909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
26925909f7f2Smatthias.ringwald 
26935909f7f2Smatthias.ringwald                     // restart timer
2694528a4a3bSMatthias Ringwald                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2695528a4a3bSMatthias Ringwald                     // btstack_run_loop_add_timer(&conn->timeout);
26965909f7f2Smatthias.ringwald 
26979da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
26985909f7f2Smatthias.ringwald 
26995909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
27005909f7f2Smatthias.ringwald                     break;
27015909f7f2Smatthias.ringwald 
2702f8fbdce0SMatthias Ringwald                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2703c9db5c21SMilanka Ringwald                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2704c9db5c21SMilanka Ringwald                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2705c9db5c21SMilanka Ringwald                     conn = hci_connection_for_handle(handle);
2706c9db5c21SMilanka Ringwald                     if (!conn) break;
2707c9db5c21SMilanka Ringwald                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2708c9db5c21SMilanka Ringwald                     break;
270965a46ef3S[email protected] 
271073cd8a2aSMatthias Ringwald                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
271173cd8a2aSMatthias Ringwald                     // connection
271273cd8a2aSMatthias Ringwald                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
271373cd8a2aSMatthias Ringwald                     conn = hci_connection_for_handle(handle);
271473cd8a2aSMatthias Ringwald                     if (conn) {
271573cd8a2aSMatthias Ringwald                         // read arguments
271673cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
271773cd8a2aSMatthias Ringwald                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
271873cd8a2aSMatthias Ringwald                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
271973cd8a2aSMatthias Ringwald                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
272073cd8a2aSMatthias Ringwald 
272173cd8a2aSMatthias Ringwald                         // validate against current connection parameter range
272273cd8a2aSMatthias Ringwald                         le_connection_parameter_range_t existing_range;
272373cd8a2aSMatthias Ringwald                         gap_get_connection_parameter_range(&existing_range);
272473cd8a2aSMatthias 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);
272573cd8a2aSMatthias Ringwald                         if (update_parameter){
272673cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
272773cd8a2aSMatthias Ringwald                             conn->le_conn_interval_min = le_conn_interval_min;
272873cd8a2aSMatthias Ringwald                             conn->le_conn_interval_max = le_conn_interval_max;
272973cd8a2aSMatthias Ringwald                             conn->le_conn_latency = le_conn_latency;
273073cd8a2aSMatthias Ringwald                             conn->le_supervision_timeout = le_supervision_timeout;
273173cd8a2aSMatthias Ringwald                         } else {
273273cd8a2aSMatthias Ringwald                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
273373cd8a2aSMatthias Ringwald                         }
273473cd8a2aSMatthias Ringwald                     }
273573cd8a2aSMatthias Ringwald                     break;
27360f3b27c5SMatthias Ringwald #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS
27370f3b27c5SMatthias Ringwald                 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE:
27380f3b27c5SMatthias Ringwald                     handle = hci_subevent_le_data_length_change_get_connection_handle(packet);
27390f3b27c5SMatthias Ringwald                     conn = hci_connection_for_handle(handle);
27400f3b27c5SMatthias Ringwald                     if (conn) {
27410f3b27c5SMatthias Ringwald                         conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet);
27420f3b27c5SMatthias Ringwald                     }
27430f3b27c5SMatthias Ringwald                     break;
27440f3b27c5SMatthias Ringwald #endif
27455909f7f2Smatthias.ringwald                 default:
27465909f7f2Smatthias.ringwald                     break;
27475909f7f2Smatthias.ringwald             }
27485909f7f2Smatthias.ringwald             break;
27495909f7f2Smatthias.ringwald #endif
27500b36101dSMatthias Ringwald         case HCI_EVENT_VENDOR_SPECIFIC:
27510b36101dSMatthias Ringwald             // Vendor specific commands often create vendor specific event instead of num completed packets
27520b36101dSMatthias Ringwald             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
27530b36101dSMatthias Ringwald             switch (hci_stack->manufacturer){
27540b36101dSMatthias Ringwald                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
27550b36101dSMatthias Ringwald                     hci_stack->num_cmd_packets = 1;
27560b36101dSMatthias Ringwald                     break;
27570b36101dSMatthias Ringwald                 default:
27580b36101dSMatthias Ringwald                     break;
27590b36101dSMatthias Ringwald             }
27600b36101dSMatthias Ringwald             break;
27616772a24cSmatthias.ringwald         default:
27626772a24cSmatthias.ringwald             break;
2763fe1ed1b8Smatthias.ringwald     }
2764fe1ed1b8Smatthias.ringwald 
276567c6c9dcSMatthias Ringwald     handle_event_for_current_stack_state(packet, size);
276689db417bSmatthias.ringwald 
276786805605S[email protected]     // notify upper stack
2768d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
276994ab26f8Smatthias.ringwald 
277086805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
27710e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
277286805605S[email protected]         if (!packet[2]){
2773f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
277405ae8de3SMatthias Ringwald             hci_connection_t * aConn = hci_connection_for_handle(handle);
277505ae8de3SMatthias Ringwald             if (aConn) {
2776046ec007SMatthias Ringwald                 // discard connection if app did not trigger a reconnect in the event handler
2777b0136355SMatthias Ringwald                 if (aConn->state == RECEIVED_DISCONNECTION_COMPLETE){
277805ae8de3SMatthias Ringwald                     hci_shutdown_connection(aConn);
2779b0136355SMatthias Ringwald                 }
278086805605S[email protected]             }
278186805605S[email protected]         }
278286805605S[email protected]     }
278386805605S[email protected] 
278494ab26f8Smatthias.ringwald 	// execute main loop
278594ab26f8Smatthias.ringwald 	hci_run();
278616833f0aSmatthias.ringwald }
278716833f0aSmatthias.ringwald 
278835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
27896f28d2eeSMatthias Ringwald 
27906f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
27916f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn);
27926f28d2eeSMatthias Ringwald 
27936f28d2eeSMatthias Ringwald static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
279459c33575SMatthias Ringwald     log_debug("SCO TX Timeout");
27955a6b2dbdSMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
27966f28d2eeSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
27976f28d2eeSMatthias Ringwald     if (!conn) return;
27986f28d2eeSMatthias Ringwald 
2799afaddd67SMatthias Ringwald     // trigger send
2800afaddd67SMatthias Ringwald     conn->sco_tx_ready = 1;
2801e4157653SMatthias Ringwald     // extra packet if CVSD but SCO buffer is too short
2802a1df452eSMatthias Ringwald     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){
2803e4157653SMatthias Ringwald         conn->sco_tx_ready++;
2804e4157653SMatthias Ringwald     }
2805afaddd67SMatthias Ringwald     hci_notify_if_sco_can_send_now();
28066f28d2eeSMatthias Ringwald }
28076f28d2eeSMatthias Ringwald 
280859c33575SMatthias Ringwald 
280959c33575SMatthias Ringwald #define SCO_TX_AFTER_RX_MS (6)
281059c33575SMatthias Ringwald 
28116f28d2eeSMatthias Ringwald static void sco_schedule_tx(hci_connection_t * conn){
281259c33575SMatthias Ringwald 
28136f28d2eeSMatthias Ringwald     uint32_t now = btstack_run_loop_get_time_ms();
281459c33575SMatthias Ringwald     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
281559c33575SMatthias Ringwald     int time_delta_ms = sco_tx_ms - now;
281659c33575SMatthias Ringwald 
281759c33575SMatthias Ringwald     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
281859c33575SMatthias Ringwald 
281959c33575SMatthias Ringwald     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
282059c33575SMatthias Ringwald     btstack_run_loop_set_timer(timer, time_delta_ms);
282159c33575SMatthias Ringwald     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
282259c33575SMatthias Ringwald     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
282359c33575SMatthias Ringwald     btstack_run_loop_add_timer(timer);
28246f28d2eeSMatthias Ringwald }
28256f28d2eeSMatthias Ringwald 
2826c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
28270b3f95dfSMatthias Ringwald     // lookup connection struct
28282b838201SMatthias Ringwald     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
28292b838201SMatthias Ringwald     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
28300b3f95dfSMatthias Ringwald     if (!conn) return;
28310b3f95dfSMatthias Ringwald 
2832760b20efSMatthias Ringwald     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
2833760b20efSMatthias Ringwald     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
2834a1df452eSMatthias Ringwald         if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
2835760b20efSMatthias Ringwald             packet[2] = 0x3c;
2836760b20efSMatthias Ringwald             memmove(&packet[3], &packet[23], 63);
2837760b20efSMatthias Ringwald             size = 63;
28380b3f95dfSMatthias Ringwald         }
28390b3f95dfSMatthias Ringwald     }
2840760b20efSMatthias Ringwald 
2841f234b250SMatthias Ringwald     if (hci_have_usb_transport()){
2842f234b250SMatthias Ringwald         // Nothing to do
2843f234b250SMatthias Ringwald     } else {
284449205f5dSMatthias 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);
2845760b20efSMatthias Ringwald         if (hci_stack->synchronous_flow_control_enabled == 0){
28466f28d2eeSMatthias Ringwald             uint32_t now = btstack_run_loop_get_time_ms();
284759c33575SMatthias Ringwald 
284859c33575SMatthias Ringwald             if (!conn->sco_rx_valid){
284959c33575SMatthias Ringwald                 // ignore first 10 packets
28506f28d2eeSMatthias Ringwald                 conn->sco_rx_count++;
285159c33575SMatthias Ringwald                 // log_debug("sco rx count %u", conn->sco_rx_count);
285259c33575SMatthias Ringwald                 if (conn->sco_rx_count == 10) {
285359c33575SMatthias Ringwald                     // use first timestamp as is and pretent it just started
28546f28d2eeSMatthias Ringwald                     conn->sco_rx_ms = now;
28556f28d2eeSMatthias Ringwald                     conn->sco_rx_valid = 1;
285659c33575SMatthias Ringwald                     conn->sco_rx_count = 0;
285759c33575SMatthias Ringwald                     sco_schedule_tx(conn);
285859c33575SMatthias Ringwald                 }
285959c33575SMatthias Ringwald             } else {
286059c33575SMatthias Ringwald                 // track expected arrival timme
286159c33575SMatthias Ringwald                 conn->sco_rx_count++;
286259c33575SMatthias Ringwald                 conn->sco_rx_ms += 7;
286359c33575SMatthias Ringwald                 int delta = (int32_t) (now - conn->sco_rx_ms);
286459c33575SMatthias Ringwald                 if (delta > 0){
286559c33575SMatthias Ringwald                     conn->sco_rx_ms++;
286659c33575SMatthias Ringwald                 }
286759c33575SMatthias Ringwald                 // log_debug("sco rx %u", conn->sco_rx_ms);
28686f28d2eeSMatthias Ringwald                 sco_schedule_tx(conn);
28696f28d2eeSMatthias Ringwald             }
2870760b20efSMatthias Ringwald         }
2871f234b250SMatthias Ringwald     }
28720b3f95dfSMatthias Ringwald     // deliver to app
28730b3f95dfSMatthias Ringwald     if (hci_stack->sco_packet_handler) {
28740b3f95dfSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
28750b3f95dfSMatthias Ringwald     }
28760b3f95dfSMatthias Ringwald 
28770b3f95dfSMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
28782b838201SMatthias Ringwald     conn->num_packets_completed++;
28792b838201SMatthias Ringwald     hci_stack->host_completed_packets = 1;
28802b838201SMatthias Ringwald     hci_run();
28812b838201SMatthias Ringwald #endif
2882c91d150bS[email protected] }
288335454696SMatthias Ringwald #endif
2884c91d150bS[email protected] 
28850a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
28865bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
288710e830c9Smatthias.ringwald     switch (packet_type) {
288810e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
288910e830c9Smatthias.ringwald             event_handler(packet, size);
289010e830c9Smatthias.ringwald             break;
289110e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
289210e830c9Smatthias.ringwald             acl_handler(packet, size);
289310e830c9Smatthias.ringwald             break;
289435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2895c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
2896c91d150bS[email protected]             sco_handler(packet, size);
2897202c8a4cSMatthias Ringwald             break;
289835454696SMatthias Ringwald #endif
289910e830c9Smatthias.ringwald         default:
290010e830c9Smatthias.ringwald             break;
290110e830c9Smatthias.ringwald     }
290210e830c9Smatthias.ringwald }
290310e830c9Smatthias.ringwald 
2904d6b06661SMatthias Ringwald /**
2905d6b06661SMatthias Ringwald  * @brief Add event packet handler.
2906d6b06661SMatthias Ringwald  */
2907d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2908d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2909d6b06661SMatthias Ringwald }
2910d6b06661SMatthias Ringwald 
2911d6b06661SMatthias Ringwald 
2912fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
29133d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2914fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
291516833f0aSmatthias.ringwald }
291616833f0aSmatthias.ringwald 
291735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
29188abbe8b5SMatthias Ringwald /**
29198abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
29208abbe8b5SMatthias Ringwald  */
29213d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
29228abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
29238abbe8b5SMatthias Ringwald }
292435454696SMatthias Ringwald #endif
29258abbe8b5SMatthias Ringwald 
292671de195eSMatthias Ringwald static void hci_state_reset(void){
2927595bdbfbS[email protected]     // no connections yet
2928595bdbfbS[email protected]     hci_stack->connections = NULL;
292974308b23Smatthias.ringwald 
293074308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
293174308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
293274308b23Smatthias.ringwald     // hci_stack->connectable = 0;
293374308b23Smatthias.ringwald     // hci_stack->bondable = 1;
2934b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
2935595bdbfbS[email protected] 
293644935e40S[email protected]     // buffer is free
293744935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
293844935e40S[email protected] 
2939595bdbfbS[email protected]     // no pending cmds
2940595bdbfbS[email protected]     hci_stack->decline_reason = 0;
2941595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
2942595bdbfbS[email protected] 
2943595bdbfbS[email protected]     // LE
2944b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
2945b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
2946b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
2947d70217a2SMatthias Ringwald #endif
2948d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
29496fab74dbSMatthias Ringwald     hci_stack->le_scanning_active  = 0;
2950e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
2951b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2952e83201bcSMatthias Ringwald     hci_stack->le_whitelist = 0;
2953e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
2954d70217a2SMatthias Ringwald #endif
2955595bdbfbS[email protected] }
2956595bdbfbS[email protected] 
295735454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
29582d5e09d6SMatthias Ringwald /**
29592d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
29602d5e09d6SMatthias Ringwald  */
29612d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
29622d5e09d6SMatthias Ringwald     // store and open remote device db
29632d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
29642d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
29652d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
29662d5e09d6SMatthias Ringwald     }
29672d5e09d6SMatthias Ringwald }
296835454696SMatthias Ringwald #endif
29692d5e09d6SMatthias Ringwald 
29702d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
2971475c8125Smatthias.ringwald 
29723a9fb326S[email protected] #ifdef HAVE_MALLOC
29733a9fb326S[email protected]     if (!hci_stack) {
29743a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
29753a9fb326S[email protected]     }
29763a9fb326S[email protected] #else
29773a9fb326S[email protected]     hci_stack = &hci_stack_static;
29783a9fb326S[email protected] #endif
297966fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
29803a9fb326S[email protected] 
2981475c8125Smatthias.ringwald     // reference to use transport layer implementation
29823a9fb326S[email protected]     hci_stack->hci_transport = transport;
2983475c8125Smatthias.ringwald 
298411e23e5fSmatthias.ringwald     // reference to used config
29853a9fb326S[email protected]     hci_stack->config = config;
298611e23e5fSmatthias.ringwald 
298726a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
298826a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
298926a9b6daSMatthias Ringwald 
29908fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
29913a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
29928fcba05dSmatthias.ringwald 
299316833f0aSmatthias.ringwald     // register packet handlers with transport
299410e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
2995f5454fc6Smatthias.ringwald 
29963a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
2997e2386ba1S[email protected] 
2998e2386ba1S[email protected]     // class of device
29993a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
3000a45d6b9fS[email protected] 
3001f20168b8Smatthias.ringwald     // bondable by default
3002f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
3003f20168b8Smatthias.ringwald 
3004e9f343c8SMatthias Ringwald #ifdef ENABLE_CLASSIC
300563168530SMatthias Ringwald     // classic name
300663168530SMatthias Ringwald     hci_stack->local_name = default_classic_name;
3007c4c88f1bSJakob Krantz 
3008c4c88f1bSJakob Krantz     // Master slave policy
3009c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = 1;
3010170fafaeSMatthias Ringwald 
3011b4eb4420SMatthias Ringwald     // Allow Role Switch
3012b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = 1;
3013b4eb4420SMatthias Ringwald 
301478315a58SMatthias Ringwald     // Default / minimum security level = 2
301578315a58SMatthias Ringwald     hci_stack->gap_security_level = LEVEL_2;
301678315a58SMatthias Ringwald 
3017170fafaeSMatthias Ringwald     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3, we use 16 as default
3018170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = 16;
3019e9f343c8SMatthias Ringwald #endif
302063168530SMatthias Ringwald 
302163048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
30223a9fb326S[email protected]     hci_stack->ssp_enable = 1;
30233a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
30243a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
30253a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
302669a97523S[email protected] 
30275d23aae8SMatthias Ringwald     // Secure Connections: enable (requires support from Controller)
30285d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = true;
30295d23aae8SMatthias Ringwald 
3030fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
3031fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
3032d950d659SMatthias Ringwald 
3033831711daSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3034831711daSMatthias Ringwald     // connection parameter to use for outgoing connections
3035cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
3036cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
3037831711daSMatthias Ringwald     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
3038831711daSMatthias Ringwald     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
3039831711daSMatthias Ringwald     hci_stack->le_connection_latency      = 4;         // 4
3040831711daSMatthias Ringwald     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
3041831711daSMatthias Ringwald     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
3042831711daSMatthias Ringwald     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
30437261e5d8SMatthias Ringwald 
30447261e5d8SMatthias Ringwald     // default LE Scanning
30457261e5d8SMatthias Ringwald     hci_stack->le_scan_interval = 0x1e0;
30467261e5d8SMatthias Ringwald     hci_stack->le_scan_window   =  0x30;
3047831711daSMatthias Ringwald #endif
3048831711daSMatthias Ringwald 
30492b6ab3e6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30502b6ab3e6SMatthias Ringwald     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
30512b6ab3e6SMatthias Ringwald #endif
30522b6ab3e6SMatthias Ringwald 
3053831711daSMatthias Ringwald     // connection parameter range used to answer connection parameter update requests in l2cap
3054831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
3055831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
3056831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
3057831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
3058831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
3059831711daSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
3060831711daSMatthias Ringwald 
3061595bdbfbS[email protected]     hci_state_reset();
3062475c8125Smatthias.ringwald }
3063475c8125Smatthias.ringwald 
30643fb36a29SMatthias Ringwald /**
30653fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
30663fb36a29SMatthias Ringwald  */
30673fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
30683fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
30693fb36a29SMatthias Ringwald 
30703fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
30713fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
30723fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
30733fb36a29SMatthias Ringwald     }
30743fb36a29SMatthias Ringwald }
30753fb36a29SMatthias Ringwald 
3076fb55bd0aSMatthias Ringwald /**
3077d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
3078fb55bd0aSMatthias Ringwald  */
3079fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
3080fb55bd0aSMatthias Ringwald     // references to used control implementation
3081fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
3082d0b87befSMatthias Ringwald     // init with transport config
3083d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
3084fb55bd0aSMatthias Ringwald }
3085fb55bd0aSMatthias Ringwald 
308671de195eSMatthias Ringwald void hci_close(void){
3087404843c1Smatthias.ringwald     // close remote device db
3088a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
3089a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
3090404843c1Smatthias.ringwald     }
30917224be7eSMatthias Ringwald 
30927224be7eSMatthias Ringwald     btstack_linked_list_iterator_t lit;
30937224be7eSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
30947224be7eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
30957224be7eSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
30967224be7eSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
30977224be7eSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
30987224be7eSMatthias Ringwald         hci_shutdown_connection(connection);
3099f5454fc6Smatthias.ringwald     }
31007224be7eSMatthias Ringwald 
3101f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
31023a9fb326S[email protected] 
31033a9fb326S[email protected] #ifdef HAVE_MALLOC
31043a9fb326S[email protected]     free(hci_stack);
31053a9fb326S[email protected] #endif
31063a9fb326S[email protected]     hci_stack = NULL;
3107404843c1Smatthias.ringwald }
3108404843c1Smatthias.ringwald 
310935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3110170fafaeSMatthias Ringwald void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
3111170fafaeSMatthias Ringwald     // validate ranage and set
3112170fafaeSMatthias Ringwald     if (encryption_key_size < 7)  return;
3113170fafaeSMatthias Ringwald     if (encryption_key_size > 16) return;
3114170fafaeSMatthias Ringwald     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
3115170fafaeSMatthias Ringwald }
311678315a58SMatthias Ringwald 
311778315a58SMatthias Ringwald void gap_set_security_level(gap_security_level_t security_level){
311878315a58SMatthias Ringwald     hci_stack->gap_security_level = security_level;
311978315a58SMatthias Ringwald }
312078315a58SMatthias Ringwald 
312178315a58SMatthias Ringwald gap_security_level_t gap_get_security_level(void){
312278315a58SMatthias Ringwald     return hci_stack->gap_security_level;
312378315a58SMatthias Ringwald }
3124170fafaeSMatthias Ringwald #endif
3125170fafaeSMatthias Ringwald 
3126170fafaeSMatthias Ringwald #ifdef ENABLE_CLASSIC
312760b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
31289e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
31299e61646fS[email protected] }
313076f27cffSMatthias Ringwald 
3131c33e56d3SMatthias Ringwald void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
3132c33e56d3SMatthias Ringwald     hci_stack->default_link_policy_settings = default_link_policy_settings;
3133c33e56d3SMatthias Ringwald }
3134c33e56d3SMatthias Ringwald 
3135b4eb4420SMatthias Ringwald void gap_set_allow_role_switch(bool allow_role_switch){
3136b4eb4420SMatthias Ringwald     hci_stack->allow_role_switch = allow_role_switch ? 1 : 0;
3137b4eb4420SMatthias Ringwald }
3138b4eb4420SMatthias Ringwald 
3139b4eb4420SMatthias Ringwald uint8_t hci_get_allow_role_switch(void){
3140b4eb4420SMatthias Ringwald     return  hci_stack->allow_role_switch;
3141b4eb4420SMatthias Ringwald }
3142b4eb4420SMatthias Ringwald 
31430c3eb48dSMatthias Ringwald void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){
31440c3eb48dSMatthias Ringwald     hci_stack->link_supervision_timeout = link_supervision_timeout;
31450c3eb48dSMatthias Ringwald }
31460c3eb48dSMatthias Ringwald 
314776f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
314876f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
314976f27cffSMatthias Ringwald }
315035454696SMatthias Ringwald #endif
31519e61646fS[email protected] 
315276f27cffSMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
3153f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
3154f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
31556535961aSMatthias Ringwald     (void)memcpy(hci_stack->custom_bd_addr, addr, 6);
3156f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
3157f456b2d0S[email protected] }
315876f27cffSMatthias Ringwald #endif
3159f456b2d0S[email protected] 
31608d213e1aSmatthias.ringwald // State-Module-Driver overview
31618d213e1aSmatthias.ringwald // state                    module  low-level
31628d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
31638d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
31648d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
31658d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
3166d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
3167d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
3168c7e0c5f6Smatthias.ringwald 
316940d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
31707301ad89Smatthias.ringwald 
3171038bc64cSmatthias.ringwald     // power on
3172f9a30166Smatthias.ringwald     int err = 0;
31733a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
3174d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
3175f9a30166Smatthias.ringwald     }
3176038bc64cSmatthias.ringwald     if (err){
31779da54300S[email protected]         log_error( "POWER_ON failed");
3178038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3179038bc64cSmatthias.ringwald         return err;
3180038bc64cSmatthias.ringwald     }
3181038bc64cSmatthias.ringwald 
318224b3c629SMatthias Ringwald     // int chipset driver
31833fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
31843fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
31853fb36a29SMatthias Ringwald     }
31863fb36a29SMatthias Ringwald 
318724b3c629SMatthias Ringwald     // init transport
318824b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
318924b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
319024b3c629SMatthias Ringwald     }
319124b3c629SMatthias Ringwald 
319224b3c629SMatthias Ringwald     // open transport
319324b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
3194038bc64cSmatthias.ringwald     if (err){
31959da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
31963a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3197d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3198f9a30166Smatthias.ringwald         }
3199038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
3200038bc64cSmatthias.ringwald         return err;
3201038bc64cSmatthias.ringwald     }
32028d213e1aSmatthias.ringwald     return 0;
32038d213e1aSmatthias.ringwald }
3204038bc64cSmatthias.ringwald 
320540d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
32068d213e1aSmatthias.ringwald 
32079da54300S[email protected]     log_info("hci_power_control_off");
32089418f9c9Smatthias.ringwald 
32098d213e1aSmatthias.ringwald     // close low-level device
321024b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
32118d213e1aSmatthias.ringwald 
32129da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
32139418f9c9Smatthias.ringwald 
32148d213e1aSmatthias.ringwald     // power off
32153a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
3216d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
32178d213e1aSmatthias.ringwald     }
32189418f9c9Smatthias.ringwald 
32199da54300S[email protected]     log_info("hci_power_control_off - control closed");
32209418f9c9Smatthias.ringwald 
32213a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
322272ea5239Smatthias.ringwald }
322372ea5239Smatthias.ringwald 
322440d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
322572ea5239Smatthias.ringwald 
32269da54300S[email protected]     log_info("hci_power_control_sleep");
32273144bce4Smatthias.ringwald 
3228b429b9b7Smatthias.ringwald #if 0
3229b429b9b7Smatthias.ringwald     // don't close serial port during sleep
3230b429b9b7Smatthias.ringwald 
323172ea5239Smatthias.ringwald     // close low-level device
32323a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
3233b429b9b7Smatthias.ringwald #endif
323472ea5239Smatthias.ringwald 
323572ea5239Smatthias.ringwald     // sleep mode
32363a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
3237d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
323872ea5239Smatthias.ringwald     }
3239b429b9b7Smatthias.ringwald 
32403a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
32418d213e1aSmatthias.ringwald }
32428d213e1aSmatthias.ringwald 
324340d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
3244b429b9b7Smatthias.ringwald 
32459da54300S[email protected]     log_info("hci_power_control_wake");
3246b429b9b7Smatthias.ringwald 
3247b429b9b7Smatthias.ringwald     // wake on
32483a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
3249d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
3250b429b9b7Smatthias.ringwald     }
3251b429b9b7Smatthias.ringwald 
3252b429b9b7Smatthias.ringwald #if 0
3253b429b9b7Smatthias.ringwald     // open low-level device
32543a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
3255b429b9b7Smatthias.ringwald     if (err){
32569da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
32573a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
3258d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
3259b429b9b7Smatthias.ringwald         }
3260b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
3261b429b9b7Smatthias.ringwald         return err;
3262b429b9b7Smatthias.ringwald     }
3263b429b9b7Smatthias.ringwald #endif
3264b429b9b7Smatthias.ringwald 
3265b429b9b7Smatthias.ringwald     return 0;
3266b429b9b7Smatthias.ringwald }
3267b429b9b7Smatthias.ringwald 
326844935e40S[email protected] static void hci_power_transition_to_initializing(void){
326944935e40S[email protected]     // set up state machine
327044935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
327144935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
327244935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
32735c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
327444935e40S[email protected] }
3275b429b9b7Smatthias.ringwald 
32768d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
3277d661ed19Smatthias.ringwald 
3278f04a0c31SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3279d661ed19Smatthias.ringwald 
32808d213e1aSmatthias.ringwald     int err = 0;
32813a9fb326S[email protected]     switch (hci_stack->state){
32828d213e1aSmatthias.ringwald 
32838d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
32848d213e1aSmatthias.ringwald             switch (power_mode){
32858d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
32868d213e1aSmatthias.ringwald                     err = hci_power_control_on();
328797b61c7bS[email protected]                     if (err) {
3288f04a0c31SMatthias Ringwald                         log_error("hci_power_control_on() error %d", err);
328997b61c7bS[email protected]                         return err;
329097b61c7bS[email protected]                     }
329144935e40S[email protected]                     hci_power_transition_to_initializing();
32928d213e1aSmatthias.ringwald                     break;
32938d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
32948d213e1aSmatthias.ringwald                     // do nothing
32958d213e1aSmatthias.ringwald                     break;
32968d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3297b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
32988d213e1aSmatthias.ringwald                     break;
32998d213e1aSmatthias.ringwald             }
33008d213e1aSmatthias.ringwald             break;
33017301ad89Smatthias.ringwald 
33028d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
33038d213e1aSmatthias.ringwald             switch (power_mode){
33048d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
33058d213e1aSmatthias.ringwald                     // do nothing
33068d213e1aSmatthias.ringwald                     break;
33078d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
33088d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
33098d213e1aSmatthias.ringwald                     hci_power_control_off();
33108d213e1aSmatthias.ringwald                     break;
33118d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3312b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
331372ea5239Smatthias.ringwald                     hci_power_control_sleep();
33148d213e1aSmatthias.ringwald                     break;
33158d213e1aSmatthias.ringwald             }
33168d213e1aSmatthias.ringwald             break;
33177301ad89Smatthias.ringwald 
33188d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
33198d213e1aSmatthias.ringwald             switch (power_mode){
33208d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
33218d213e1aSmatthias.ringwald                     // do nothing
33228d213e1aSmatthias.ringwald                     break;
33238d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
3324c7e0c5f6Smatthias.ringwald                     // see hci_run
33253a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
3326beceeddeSMatthias Ringwald                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
33278d213e1aSmatthias.ringwald                     break;
33288d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3329b546ac54Smatthias.ringwald                     // see hci_run
33303a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
333174b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
33328d213e1aSmatthias.ringwald                     break;
33338d213e1aSmatthias.ringwald             }
33348d213e1aSmatthias.ringwald             break;
33357301ad89Smatthias.ringwald 
33368d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
33378d213e1aSmatthias.ringwald             switch (power_mode){
33388d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
333944935e40S[email protected]                     hci_power_transition_to_initializing();
33408d213e1aSmatthias.ringwald                     break;
33418d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
33428d213e1aSmatthias.ringwald                     // do nothing
33438d213e1aSmatthias.ringwald                     break;
33448d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3345b546ac54Smatthias.ringwald                     // see hci_run
33463a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
334774b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
33488d213e1aSmatthias.ringwald                     break;
33498d213e1aSmatthias.ringwald             }
33508d213e1aSmatthias.ringwald             break;
33518d213e1aSmatthias.ringwald 
33528d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
33538d213e1aSmatthias.ringwald             switch (power_mode){
33548d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
335528171530Smatthias.ringwald 
3356423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
335728171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
3358d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
33593a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
336074b323a9SMatthias Ringwald                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
336128171530Smatthias.ringwald                         break;
336228171530Smatthias.ringwald                     }
336328171530Smatthias.ringwald #endif
336444935e40S[email protected]                     hci_power_transition_to_initializing();
33658d213e1aSmatthias.ringwald                     break;
33668d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
3367b546ac54Smatthias.ringwald                     // see hci_run
33683a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
3369beceeddeSMatthias Ringwald                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
33708d213e1aSmatthias.ringwald                     break;
33718d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3372b546ac54Smatthias.ringwald                     // do nothing
33738d213e1aSmatthias.ringwald                     break;
33748d213e1aSmatthias.ringwald             }
33758d213e1aSmatthias.ringwald             break;
33768d213e1aSmatthias.ringwald 
33778d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
33788d213e1aSmatthias.ringwald             switch (power_mode){
33798d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
338028171530Smatthias.ringwald 
3381423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
338228171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
3383d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
33843a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
33855c363727SMatthias Ringwald                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3386758b46ceSmatthias.ringwald                         hci_update_scan_enable();
338728171530Smatthias.ringwald                         break;
338828171530Smatthias.ringwald                     }
338928171530Smatthias.ringwald #endif
33903144bce4Smatthias.ringwald                     err = hci_power_control_wake();
33913144bce4Smatthias.ringwald                     if (err) return err;
339244935e40S[email protected]                     hci_power_transition_to_initializing();
33938d213e1aSmatthias.ringwald                     break;
33948d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
33953a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
3396beceeddeSMatthias Ringwald                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
33978d213e1aSmatthias.ringwald                     break;
33988d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
3399b546ac54Smatthias.ringwald                     // do nothing
34008d213e1aSmatthias.ringwald                     break;
34018d213e1aSmatthias.ringwald             }
34028d213e1aSmatthias.ringwald             break;
340311e23e5fSmatthias.ringwald     }
340468d92d03Smatthias.ringwald 
3405038bc64cSmatthias.ringwald     // create internal event
3406ee8bf225Smatthias.ringwald 	hci_emit_state();
3407ee8bf225Smatthias.ringwald 
340868d92d03Smatthias.ringwald 	// trigger next/first action
340968d92d03Smatthias.ringwald 	hci_run();
341068d92d03Smatthias.ringwald 
3411475c8125Smatthias.ringwald     return 0;
3412475c8125Smatthias.ringwald }
3413475c8125Smatthias.ringwald 
341435454696SMatthias Ringwald 
341535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
341635454696SMatthias Ringwald 
3417758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
3418758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
3419a1df452eSMatthias Ringwald     hci_stack->new_scan_enable_value  = (hci_stack->connectable << 1) | hci_stack->discoverable;
3420758b46ceSmatthias.ringwald     hci_run();
3421758b46ceSmatthias.ringwald }
3422758b46ceSmatthias.ringwald 
342315a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
3424381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
3425381fbed8Smatthias.ringwald 
34263a9fb326S[email protected]     if (hci_stack->discoverable == enable){
34273a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
3428381fbed8Smatthias.ringwald         return;
3429381fbed8Smatthias.ringwald     }
3430381fbed8Smatthias.ringwald 
34313a9fb326S[email protected]     hci_stack->discoverable = enable;
3432758b46ceSmatthias.ringwald     hci_update_scan_enable();
3433758b46ceSmatthias.ringwald }
3434b031bebbSmatthias.ringwald 
343515a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
3436758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
3437758b46ceSmatthias.ringwald 
3438758b46ceSmatthias.ringwald     // don't emit event
34393a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
3440758b46ceSmatthias.ringwald 
34413a9fb326S[email protected]     hci_stack->connectable = enable;
3442758b46ceSmatthias.ringwald     hci_update_scan_enable();
3443381fbed8Smatthias.ringwald }
344435454696SMatthias Ringwald #endif
3445381fbed8Smatthias.ringwald 
344615a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
34476535961aSMatthias Ringwald     (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6);
34485061f3afS[email protected] }
34495061f3afS[email protected] 
34502b838201SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
34512b838201SMatthias Ringwald static void hci_host_num_completed_packets(void){
34522b838201SMatthias Ringwald 
34532b838201SMatthias Ringwald     // create packet manually as arrays are not supported and num_commands should not get reduced
34542b838201SMatthias Ringwald     hci_reserve_packet_buffer();
34552b838201SMatthias Ringwald     uint8_t * packet = hci_get_outgoing_packet_buffer();
34562b838201SMatthias Ringwald 
34572b838201SMatthias Ringwald     uint16_t size = 0;
34582b838201SMatthias Ringwald     uint16_t num_handles = 0;
34592b838201SMatthias Ringwald     packet[size++] = 0x35;
34602b838201SMatthias Ringwald     packet[size++] = 0x0c;
34612b838201SMatthias Ringwald     size++;  // skip param len
34622b838201SMatthias Ringwald     size++;  // skip num handles
34632b838201SMatthias Ringwald 
34642b838201SMatthias Ringwald     // add { handle, packets } entries
34652b838201SMatthias Ringwald     btstack_linked_item_t * it;
34662b838201SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
34672b838201SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
34682b838201SMatthias Ringwald         if (connection->num_packets_completed){
34692b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->con_handle);
34702b838201SMatthias Ringwald             size += 2;
34712b838201SMatthias Ringwald             little_endian_store_16(packet, size, connection->num_packets_completed);
34722b838201SMatthias Ringwald             size += 2;
34732b838201SMatthias Ringwald             //
34742b838201SMatthias Ringwald             num_handles++;
34752b838201SMatthias Ringwald             connection->num_packets_completed = 0;
34762b838201SMatthias Ringwald         }
34772b838201SMatthias Ringwald     }
34782b838201SMatthias Ringwald 
34792b838201SMatthias Ringwald     packet[2] = size - 3;
34802b838201SMatthias Ringwald     packet[3] = num_handles;
34812b838201SMatthias Ringwald 
34822b838201SMatthias Ringwald     hci_stack->host_completed_packets = 0;
34832b838201SMatthias Ringwald 
34842b838201SMatthias Ringwald     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
34852b838201SMatthias Ringwald     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
34862b838201SMatthias Ringwald 
34872b838201SMatthias Ringwald     // release packet buffer for synchronous transport implementations
34882b838201SMatthias Ringwald     if (hci_transport_synchronous()){
3489e2d22487SMatthias Ringwald         hci_release_packet_buffer();
3490068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
34912b838201SMatthias Ringwald     }
34922b838201SMatthias Ringwald }
34932b838201SMatthias Ringwald #endif
34942b838201SMatthias Ringwald 
349526fe9592SMatthias Ringwald static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
349626fe9592SMatthias Ringwald     UNUSED(ds);
349726fe9592SMatthias Ringwald     hci_stack->substate = HCI_HALTING_CLOSE;
3498beceeddeSMatthias Ringwald     // allow packet handlers to defer final shutdown
3499beceeddeSMatthias Ringwald     hci_emit_state();
350026fe9592SMatthias Ringwald     hci_run();
350126fe9592SMatthias Ringwald }
350226fe9592SMatthias Ringwald 
3503f30077b7SMatthias Ringwald static bool hci_run_acl_fragments(void){
3504b5d8b22bS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
3505b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3506b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3507b5d8b22bS[email protected]         if (connection) {
350828a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3509b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
3510f30077b7SMatthias Ringwald                 return true;
3511b5d8b22bS[email protected]             }
351228a0332dSMatthias Ringwald         } else {
3513b5d8b22bS[email protected]             // connection gone -> discard further fragments
351428a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3515b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
3516b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
3517b5d8b22bS[email protected]         }
3518b5d8b22bS[email protected]     }
3519f30077b7SMatthias Ringwald     return false;
35202b838201SMatthias Ringwald }
3521b031bebbSmatthias.ringwald 
352235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3523f30077b7SMatthias Ringwald static bool hci_run_general_gap_classic(void){
3524f30077b7SMatthias Ringwald 
3525b031bebbSmatthias.ringwald     // decline incoming connections
35263a9fb326S[email protected]     if (hci_stack->decline_reason){
35273a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
35283a9fb326S[email protected]         hci_stack->decline_reason = 0;
35293a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3530f30077b7SMatthias Ringwald         return true;
3531ce4c8fabSmatthias.ringwald     }
3532b031bebbSmatthias.ringwald     // send scan enable
35330e588213SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){
35343a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
35353a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
3536f30077b7SMatthias Ringwald         return true;
3537b031bebbSmatthias.ringwald     }
3538f5875de5SMatthias Ringwald     // start/stop inquiry
3539a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){
3540f5875de5SMatthias Ringwald         uint8_t duration = hci_stack->inquiry_state;
3541f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
35428aee7be2SMilanka Ringwald         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3543f30077b7SMatthias Ringwald         return true;
3544f5875de5SMatthias Ringwald     }
3545f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3546f5875de5SMatthias Ringwald         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3547f5875de5SMatthias Ringwald         hci_send_cmd(&hci_inquiry_cancel);
3548f30077b7SMatthias Ringwald         return true;
3549f5875de5SMatthias Ringwald     }
3550b7f1ee76SMatthias Ringwald     // remote name request
3551b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3552b7f1ee76SMatthias Ringwald         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3553b7f1ee76SMatthias Ringwald         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3554ee8a36c8SMatthias Ringwald                      hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3555f30077b7SMatthias Ringwald         return true;
3556b7f1ee76SMatthias Ringwald     }
35570a51f88bSMatthias Ringwald     // pairing
35580a51f88bSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
35590a51f88bSMatthias Ringwald         uint8_t state = hci_stack->gap_pairing_state;
35600a51f88bSMatthias Ringwald         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
35610a51f88bSMatthias Ringwald         switch (state){
35620a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN:
3563d504181aSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_input.gap_pairing_pin), hci_stack->gap_pairing_input.gap_pairing_pin);
35640a51f88bSMatthias Ringwald                 break;
35650a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
35660a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
35670a51f88bSMatthias Ringwald                 break;
35680a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY:
3569d504181aSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
35700a51f88bSMatthias Ringwald                 break;
35710a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
35720a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
35730a51f88bSMatthias Ringwald                 break;
35740a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
35750a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
35760a51f88bSMatthias Ringwald                 break;
35770a51f88bSMatthias Ringwald             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
35780a51f88bSMatthias Ringwald                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
35790a51f88bSMatthias Ringwald                 break;
35800a51f88bSMatthias Ringwald             default:
35810a51f88bSMatthias Ringwald                 break;
35820a51f88bSMatthias Ringwald         }
3583f30077b7SMatthias Ringwald         return true;
3584f30077b7SMatthias Ringwald     }
3585f30077b7SMatthias Ringwald     return false;
35860a51f88bSMatthias Ringwald }
358735454696SMatthias Ringwald #endif
3588b031bebbSmatthias.ringwald 
3589a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
3590f30077b7SMatthias Ringwald static bool hci_run_general_gap_le(void){
3591f30077b7SMatthias Ringwald 
3592f30077b7SMatthias Ringwald     // advertisements, active scanning, and creating connections requires random address to be set if using private address
3593f30077b7SMatthias Ringwald 
3594f30077b7SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return false;
3595f30077b7SMatthias Ringwald     if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0) ) return false;
3596d70217a2SMatthias Ringwald 
3597d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
35983251a108SMatthias Ringwald     // parameter change requires scanning to be stopped first
3599e2602ea2Smatthias.ringwald     if (hci_stack->le_scan_type != 0xff) {
36003251a108SMatthias Ringwald         if (hci_stack->le_scanning_active){
36013251a108SMatthias Ringwald             hci_stack->le_scanning_active = 0;
36023251a108SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
36033251a108SMatthias Ringwald         } else {
36043251a108SMatthias Ringwald             int scan_type = (int) hci_stack->le_scan_type;
3605e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
3606b95a5a35SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0);
36073251a108SMatthias Ringwald         }
3608f30077b7SMatthias Ringwald         return true;
36093251a108SMatthias Ringwald     }
36103251a108SMatthias Ringwald     // finally, we can enable/disable le scan
3611787e73a5SMatthias Ringwald     if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
36123251a108SMatthias Ringwald         hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
36133251a108SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3614f30077b7SMatthias Ringwald         return true;
3615e2602ea2Smatthias.ringwald     }
3616d70217a2SMatthias Ringwald #endif
3617d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
361845c102fdSMatthias Ringwald     // le advertisement control
36199a2e4658SMatthias Ringwald     if (hci_stack->le_advertisements_todo){
36209a2e4658SMatthias Ringwald         log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
36219a2e4658SMatthias Ringwald     }
362245c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
362345c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
362445c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 0);
3625f30077b7SMatthias Ringwald         return true;
362645c102fdSMatthias Ringwald     }
362745c102fdSMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
362845c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
362945c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_parameters,
363045c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_min,
363145c102fdSMatthias Ringwald                      hci_stack->le_advertisements_interval_max,
363245c102fdSMatthias Ringwald                      hci_stack->le_advertisements_type,
3633b95a5a35SMatthias Ringwald                      hci_stack->le_own_addr_type,
363445c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address_type,
363545c102fdSMatthias Ringwald                      hci_stack->le_advertisements_direct_address,
363645c102fdSMatthias Ringwald                      hci_stack->le_advertisements_channel_map,
363745c102fdSMatthias Ringwald                      hci_stack->le_advertisements_filter_policy);
3638f30077b7SMatthias Ringwald         return true;
363945c102fdSMatthias Ringwald     }
3640501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3641501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
36427a85e4f5SMatthias Ringwald         uint8_t adv_data_clean[31];
36437a85e4f5SMatthias Ringwald         memset(adv_data_clean, 0, sizeof(adv_data_clean));
36446535961aSMatthias Ringwald         (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data,
36456535961aSMatthias Ringwald                      hci_stack->le_advertisements_data_len);
36463c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr);
36477a85e4f5SMatthias Ringwald         hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3648f30077b7SMatthias Ringwald         return true;
364945c102fdSMatthias Ringwald     }
3650501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3651501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3652f868b059SMatthias Ringwald         uint8_t scan_data_clean[31];
3653f868b059SMatthias Ringwald         memset(scan_data_clean, 0, sizeof(scan_data_clean));
36546535961aSMatthias Ringwald         (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data,
36556535961aSMatthias Ringwald                      hci_stack->le_scan_response_data_len);
36563c9da642SMatthias Ringwald         btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr);
3657214bfd60SMatthias Ringwald         hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
3658f30077b7SMatthias Ringwald         return true;
3659501f56b3SMatthias Ringwald     }
3660b95a5a35SMatthias Ringwald     if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
366145c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
366245c102fdSMatthias Ringwald         hci_send_cmd(&hci_le_set_advertise_enable, 1);
3663f30077b7SMatthias Ringwald         return true;
366445c102fdSMatthias Ringwald     }
3665d70217a2SMatthias Ringwald #endif
36669956955bSMatthias Ringwald 
3667d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
36689956955bSMatthias Ringwald     //
36699956955bSMatthias Ringwald     // LE Whitelist Management
36709956955bSMatthias Ringwald     //
36719956955bSMatthias Ringwald 
36729956955bSMatthias Ringwald     // check if whitelist needs modification
3673665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t lit;
36749956955bSMatthias Ringwald     int modification_pending = 0;
3675665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3676665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
3677665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
36789956955bSMatthias Ringwald         if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
36799956955bSMatthias Ringwald             modification_pending = 1;
36809956955bSMatthias Ringwald             break;
36819956955bSMatthias Ringwald         }
36829956955bSMatthias Ringwald     }
368391915b0bSMatthias Ringwald 
36849956955bSMatthias Ringwald     if (modification_pending){
368591915b0bSMatthias Ringwald         // stop connnecting if modification pending
36869956955bSMatthias Ringwald         if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
36879956955bSMatthias Ringwald             hci_send_cmd(&hci_le_create_connection_cancel);
3688f30077b7SMatthias Ringwald             return true;
36899956955bSMatthias Ringwald         }
36909956955bSMatthias Ringwald 
36919956955bSMatthias Ringwald         // add/remove entries
3692665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3693665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
3694665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
36959956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
36969956955bSMatthias Ringwald                 entry->state = LE_WHITELIST_ON_CONTROLLER;
36979956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3698f30077b7SMatthias Ringwald                 return true;
36999956955bSMatthias Ringwald             }
37009956955bSMatthias Ringwald             if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
37019ecbe201SMatthias Ringwald                 bd_addr_t address;
37029ecbe201SMatthias Ringwald                 bd_addr_type_t address_type = entry->address_type;
37036535961aSMatthias Ringwald                 (void)memcpy(address, entry->address, 6);
3704665d90f2SMatthias Ringwald                 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
37059956955bSMatthias Ringwald                 btstack_memory_whitelist_entry_free(entry);
37069ecbe201SMatthias Ringwald                 hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3707f30077b7SMatthias Ringwald                 return true;
37089956955bSMatthias Ringwald             }
37099956955bSMatthias Ringwald         }
371091915b0bSMatthias Ringwald     }
37119956955bSMatthias Ringwald 
37129956955bSMatthias Ringwald     // start connecting
3713a1df452eSMatthias Ringwald     if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) &&
3714665d90f2SMatthias Ringwald          !btstack_linked_list_empty(&hci_stack->le_whitelist)){
37159956955bSMatthias Ringwald         bd_addr_t null_addr;
37169956955bSMatthias Ringwald         memset(null_addr, 0, 6);
37179956955bSMatthias Ringwald         hci_send_cmd(&hci_le_create_connection,
3718cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3719cbe54ab2SJakob Krantz                      hci_stack->le_connection_scan_window,    // scan interval: 30 ms
37209956955bSMatthias Ringwald                      1,         // use whitelist
37219956955bSMatthias Ringwald                      0,         // peer address type
37229956955bSMatthias Ringwald                      null_addr, // peer bd addr
3723b95a5a35SMatthias Ringwald                      hci_stack->le_own_addr_type, // our addr type:
372473044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_min,    // conn interval min
372573044eb2SMatthias Ringwald                      hci_stack->le_connection_interval_max,    // conn interval max
372673044eb2SMatthias Ringwald                      hci_stack->le_connection_latency,         // conn latency
372773044eb2SMatthias Ringwald                      hci_stack->le_supervision_timeout,        // conn latency
372873044eb2SMatthias Ringwald                      hci_stack->le_minimum_ce_length,          // min ce length
372973044eb2SMatthias Ringwald                      hci_stack->le_maximum_ce_length           // max ce length
37309956955bSMatthias Ringwald         );
3731f30077b7SMatthias Ringwald         return true;
37329956955bSMatthias Ringwald     }
3733d70217a2SMatthias Ringwald #endif
3734f30077b7SMatthias Ringwald     return false;
37357bdc6798S[email protected] }
3736b2f949feS[email protected] #endif
37377bdc6798S[email protected] 
3738f30077b7SMatthias Ringwald static bool hci_run_general_pending_commmands(void){
3739f30077b7SMatthias Ringwald     btstack_linked_item_t * it;
3740a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
374105ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
374232ab9390Smatthias.ringwald 
37430bf6344aS[email protected]         switch(connection->state){
37440bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
37454f3229d8S[email protected]                 switch(connection->address_type){
374635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3747f16129ceSMatthias Ringwald                     case BD_ADDR_TYPE_ACL:
37489da54300S[email protected]                         log_info("sending hci_create_connection");
3749b4eb4420SMatthias Ringwald                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch);
37504f3229d8S[email protected]                         break;
375135454696SMatthias Ringwald #endif
37524f3229d8S[email protected]                     default:
3753a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
3754d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3755229331c6SMatthias Ringwald                         // track outgoing connection
3756229331c6SMatthias Ringwald                         hci_stack->outgoing_addr_type = connection->address_type;
37576535961aSMatthias Ringwald                         (void)memcpy(hci_stack->outgoing_addr,
37586535961aSMatthias Ringwald                                      connection->address, 6);
37599da54300S[email protected]                         log_info("sending hci_le_create_connection");
37604f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
3761cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_interval,    // conn scan interval
3762cbe54ab2SJakob Krantz                                      hci_stack->le_connection_scan_window,      // conn scan windows
37634f3229d8S[email protected]                                      0,         // don't use whitelist
37644f3229d8S[email protected]                                      connection->address_type, // peer address type
37654f3229d8S[email protected]                                      connection->address,      // peer bd addr
3766b95a5a35SMatthias Ringwald                                      hci_stack->le_own_addr_type, // our addr type:
376773044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_min,    // conn interval min
376873044eb2SMatthias Ringwald                                      hci_stack->le_connection_interval_max,    // conn interval max
376973044eb2SMatthias Ringwald                                      hci_stack->le_connection_latency,         // conn latency
377073044eb2SMatthias Ringwald                                      hci_stack->le_supervision_timeout,        // conn latency
377173044eb2SMatthias Ringwald                                      hci_stack->le_minimum_ce_length,          // min ce length
377273044eb2SMatthias Ringwald                                      hci_stack->le_maximum_ce_length          // max ce length
37734f3229d8S[email protected]                         );
37744f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
3775b2f949feS[email protected] #endif
3776d70217a2SMatthias Ringwald #endif
37774f3229d8S[email protected]                         break;
37784f3229d8S[email protected]                 }
3779f30077b7SMatthias Ringwald                 return true;
3780ad83dc6aS[email protected] 
378135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
37820bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
37835cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
3784f16129ceSMatthias Ringwald                 if (connection->address_type == BD_ADDR_TYPE_ACL){
378576ccfb2aSMatthias Ringwald                     log_info("sending hci_accept_connection_request");
3786895f6685SMilanka Ringwald                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3787c4c88f1bSJakob Krantz                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3788e35edcc1S[email protected]                 }
3789f30077b7SMatthias Ringwald                 return true;
379035454696SMatthias Ringwald #endif
37910bf6344aS[email protected] 
3792a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
3793d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
37940bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
37950bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
37960bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
3797f30077b7SMatthias Ringwald                 return true;
3798a6725849S[email protected] #endif
3799d70217a2SMatthias Ringwald #endif
38000bf6344aS[email protected]             case SEND_DISCONNECT:
38010bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
38026ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3803f30077b7SMatthias Ringwald                 return true;
38040bf6344aS[email protected] 
38050bf6344aS[email protected]             default:
38060bf6344aS[email protected]                 break;
3807c7e0c5f6Smatthias.ringwald         }
3808c7e0c5f6Smatthias.ringwald 
3809cabf004eSMatthias Ringwald         // no further commands if connection is about to get shut down
3810cabf004eSMatthias Ringwald         if (connection->state == SENT_DISCONNECT) continue;
3811cabf004eSMatthias Ringwald 
3812891b9fc2SMatthias Ringwald         if (connection->authentication_flags & READ_RSSI){
3813891b9fc2SMatthias Ringwald             connectionClearAuthenticationFlags(connection, READ_RSSI);
3814891b9fc2SMatthias Ringwald             hci_send_cmd(&hci_read_rssi, connection->con_handle);
3815f30077b7SMatthias Ringwald             return true;
3816891b9fc2SMatthias Ringwald         }
3817891b9fc2SMatthias Ringwald 
381894418890SMatthias Ringwald #ifdef ENABLE_CLASSIC
381994418890SMatthias Ringwald 
38206909f064SMatthias Ringwald         if (connection->authentication_flags & WRITE_SUPERVISION_TIMEOUT){
38216909f064SMatthias Ringwald             connectionClearAuthenticationFlags(connection, WRITE_SUPERVISION_TIMEOUT);
38226909f064SMatthias Ringwald             hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout);
3823f30077b7SMatthias Ringwald             return true;
38246909f064SMatthias Ringwald         }
38256909f064SMatthias Ringwald 
382632ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
38279da54300S[email protected]             log_info("responding to link key request");
382834d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
382930e72d78SMatthias Ringwald 
383032ab9390Smatthias.ringwald             link_key_t link_key;
3831c77e8838S[email protected]             link_key_type_t link_key_type;
383230e72d78SMatthias Ringwald             bool have_link_key = hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type);
383330e72d78SMatthias Ringwald 
383430e72d78SMatthias Ringwald             const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER;
383530e72d78SMatthias Ringwald             bool sc_enabled_remote = (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask;
383630e72d78SMatthias Ringwald             bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(link_key_type) == 1) && !sc_enabled_remote;
383730e72d78SMatthias Ringwald             if (sc_downgrade){
383830e72d78SMatthias Ringwald                 log_info("Link key based on SC, but remote does not support SC -> disconnect");
383930e72d78SMatthias Ringwald                 connection->state = SENT_DISCONNECT;
384030e72d78SMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
384130e72d78SMatthias Ringwald                 return true;
384230e72d78SMatthias Ringwald             }
384330e72d78SMatthias Ringwald 
384430e72d78SMatthias Ringwald             bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level);
384530e72d78SMatthias Ringwald             if (have_link_key && security_level_sufficient){
38469ab95c90S[email protected]                 connection->link_key_type = link_key_type;
384732ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
384832ab9390Smatthias.ringwald             } else {
384932ab9390Smatthias.ringwald                 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
385032ab9390Smatthias.ringwald             }
3851f30077b7SMatthias Ringwald             return true;
385232ab9390Smatthias.ringwald         }
38531d6b20aeS[email protected] 
3854899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
38559da54300S[email protected]             log_info("denying to pin request");
3856899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
385734d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3858f30077b7SMatthias Ringwald             return true;
38594c57c146S[email protected]         }
38604c57c146S[email protected] 
3861dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
386234d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
386382d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
386482d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3865106d6d11S[email protected]                 // tweak authentication requirements
38663a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3867106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
38689faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
38699faad3abS[email protected]                 }
38709faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
38719faad3abS[email protected]                     authreq |= 1;
3872106d6d11S[email protected]                 }
38733a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3874f8fb5f6eS[email protected]             } else {
3875f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3876f8fb5f6eS[email protected]             }
3877f30077b7SMatthias Ringwald             return true;
387832ab9390Smatthias.ringwald         }
387932ab9390Smatthias.ringwald 
3880dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3881dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
388234d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3883f30077b7SMatthias Ringwald             return true;
3884dbe1a790S[email protected]         }
3885dbe1a790S[email protected] 
3886dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3887dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
388834d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3889f30077b7SMatthias Ringwald             return true;
3890dbe1a790S[email protected]         }
3891afd4e962S[email protected] 
3892ba018746SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){
3893ba018746SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0;
389434d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3895f30077b7SMatthias Ringwald             return true;
38962bd8b7e7S[email protected]         }
38972bd8b7e7S[email protected] 
38985ccef624SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){
38995ccef624SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1;
39005ccef624SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1);
39015ccef624SMatthias Ringwald             return true;
39025ccef624SMatthias Ringwald         }
39035ccef624SMatthias Ringwald 
390482721f83SMatthias Ringwald         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){
390582721f83SMatthias Ringwald             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2;
390682721f83SMatthias Ringwald             hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2);
390782721f83SMatthias Ringwald             return true;
390882721f83SMatthias Ringwald         }
390982721f83SMatthias Ringwald 
3910ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3911ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
39121bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
39136ef3696aSMatthias Ringwald             connection->state = SENT_DISCONNECT;
39146ef3696aSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
3915f30077b7SMatthias Ringwald             return true;
3916ad83dc6aS[email protected]         }
391776f27cffSMatthias Ringwald 
391834d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
391934d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3920abdad579SMatthias Ringwald             connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST;
392134d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3922f30077b7SMatthias Ringwald             return true;
3923afd4e962S[email protected]         }
392476f27cffSMatthias Ringwald 
3925dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3926dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3927dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3928f30077b7SMatthias Ringwald             return true;
3929dce78009S[email protected]         }
3930573897a0SMatthias Ringwald         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
3931573897a0SMatthias Ringwald             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3932573897a0SMatthias Ringwald             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
3933f30077b7SMatthias Ringwald             return true;
3934573897a0SMatthias Ringwald         }
393576f27cffSMatthias Ringwald #endif
393676f27cffSMatthias Ringwald 
393776f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
393876f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
39396ef3696aSMatthias Ringwald             if (connection->state != SENT_DISCONNECT){
39406ef3696aSMatthias Ringwald                 connection->state = SENT_DISCONNECT;
39416ef3696aSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE);
3942f30077b7SMatthias Ringwald                 return true;
394376f27cffSMatthias Ringwald             }
39446ef3696aSMatthias Ringwald         }
3945da886c03S[email protected] 
39466cdc2862SMatthias Ringwald #ifdef ENABLE_CLASSIC
3947f8ee3071SMatthias Ringwald         uint16_t sniff_min_interval;
3948f8ee3071SMatthias Ringwald         switch (connection->sniff_min_interval){
3949f8ee3071SMatthias Ringwald             case 0:
3950f8ee3071SMatthias Ringwald                 break;
3951f8ee3071SMatthias Ringwald             case 0xffff:
3952f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
3953f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3954f30077b7SMatthias Ringwald                 return true;
3955f8ee3071SMatthias Ringwald             default:
3956f8ee3071SMatthias Ringwald                 sniff_min_interval = connection->sniff_min_interval;
3957f8ee3071SMatthias Ringwald                 connection->sniff_min_interval = 0;
3958f8ee3071SMatthias Ringwald                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3959f30077b7SMatthias Ringwald                 return true;
3960f8ee3071SMatthias Ringwald         }
39616cdc2862SMatthias Ringwald #endif
3962f8ee3071SMatthias Ringwald 
3963a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
396473cd8a2aSMatthias Ringwald         switch (connection->le_con_parameter_update_state){
396573cd8a2aSMatthias Ringwald             // response to L2CAP CON PARAMETER UPDATE REQUEST
396673cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3967da886c03S[email protected]                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
396873cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3969c37a3166S[email protected]                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3970c37a3166S[email protected]                              0x0000, 0xffff);
3971f30077b7SMatthias Ringwald                 return true;
397273cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_REPLY:
397373cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
397473cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
397573cd8a2aSMatthias Ringwald                              connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
397673cd8a2aSMatthias Ringwald                              0x0000, 0xffff);
3977f30077b7SMatthias Ringwald                 return true;
397873cd8a2aSMatthias Ringwald             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
397973cd8a2aSMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
398073cd8a2aSMatthias Ringwald                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3981f30077b7SMatthias Ringwald                 return true;
398273cd8a2aSMatthias Ringwald             default:
398373cd8a2aSMatthias Ringwald                 break;
3984c37a3166S[email protected]         }
3985b90f6e0aSMatthias Ringwald         if (connection->le_phy_update_all_phys != 0xff){
3986b90f6e0aSMatthias Ringwald             uint8_t all_phys = connection->le_phy_update_all_phys;
3987b90f6e0aSMatthias Ringwald             connection->le_phy_update_all_phys = 0xff;
3988b90f6e0aSMatthias 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);
3989f30077b7SMatthias Ringwald             return true;
3990b90f6e0aSMatthias Ringwald         }
3991c37a3166S[email protected] #endif
3992dbe1a790S[email protected]     }
3993f30077b7SMatthias Ringwald     return false;
3994f30077b7SMatthias Ringwald }
3995c7e0c5f6Smatthias.ringwald 
3996f30077b7SMatthias Ringwald static void hci_run(void){
3997f30077b7SMatthias Ringwald 
3998f30077b7SMatthias Ringwald     bool done;
3999f30077b7SMatthias Ringwald 
4000f30077b7SMatthias Ringwald     // send continuation fragments first, as they block the prepared packet buffer
4001f30077b7SMatthias Ringwald     done = hci_run_acl_fragments();
4002f30077b7SMatthias Ringwald     if (done) return;
4003f30077b7SMatthias Ringwald 
4004f30077b7SMatthias Ringwald #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
4005f30077b7SMatthias Ringwald     // send host num completed packets next as they don't require num_cmd_packets > 0
4006f30077b7SMatthias Ringwald     if (!hci_can_send_comand_packet_transport()) return;
4007f30077b7SMatthias Ringwald     if (hci_stack->host_completed_packets){
4008f30077b7SMatthias Ringwald         hci_host_num_completed_packets();
4009f30077b7SMatthias Ringwald         return;
4010f30077b7SMatthias Ringwald     }
4011f30077b7SMatthias Ringwald #endif
4012f30077b7SMatthias Ringwald 
4013f30077b7SMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
4014f30077b7SMatthias Ringwald 
4015f30077b7SMatthias Ringwald     // global/non-connection oriented commands
4016f30077b7SMatthias Ringwald 
4017f30077b7SMatthias Ringwald 
4018f30077b7SMatthias Ringwald #ifdef ENABLE_CLASSIC
4019f30077b7SMatthias Ringwald     // general gap classic
4020f30077b7SMatthias Ringwald     done = hci_run_general_gap_classic();
4021f30077b7SMatthias Ringwald     if (done) return;
4022f30077b7SMatthias Ringwald #endif
4023f30077b7SMatthias Ringwald 
4024f30077b7SMatthias Ringwald #ifdef ENABLE_BLE
4025f30077b7SMatthias Ringwald     // general gap le
4026f30077b7SMatthias Ringwald     done = hci_run_general_gap_le();
4027f30077b7SMatthias Ringwald     if (done) return;
4028f30077b7SMatthias Ringwald #endif
4029f30077b7SMatthias Ringwald 
4030f30077b7SMatthias Ringwald     // send pending HCI commands
4031f30077b7SMatthias Ringwald     done = hci_run_general_pending_commmands();
4032f30077b7SMatthias Ringwald     if (done) return;
4033f30077b7SMatthias Ringwald 
4034f30077b7SMatthias Ringwald     // stack state sub statemachines
403505ae8de3SMatthias Ringwald     hci_connection_t * connection;
40363a9fb326S[email protected]     switch (hci_stack->state){
40373429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
403874b323a9SMatthias Ringwald             hci_initializing_run();
40393429f56bSmatthias.ringwald             break;
4040c7e0c5f6Smatthias.ringwald 
4041c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
4042c7e0c5f6Smatthias.ringwald 
404326fe9592SMatthias Ringwald             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
404426fe9592SMatthias Ringwald             switch (hci_stack->substate){
4045beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
4046beceeddeSMatthias Ringwald                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
4047beceeddeSMatthias Ringwald 
4048a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
4049d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4050beceeddeSMatthias Ringwald                     // free whitelist entries
40519956955bSMatthias Ringwald                     {
4052665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_t lit;
4053665d90f2SMatthias Ringwald                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
4054665d90f2SMatthias Ringwald                         while (btstack_linked_list_iterator_has_next(&lit)){
4055665d90f2SMatthias Ringwald                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
4056665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
40579956955bSMatthias Ringwald                             btstack_memory_whitelist_entry_free(entry);
40589956955bSMatthias Ringwald                         }
40599956955bSMatthias Ringwald                     }
40609956955bSMatthias Ringwald #endif
4061d70217a2SMatthias Ringwald #endif
4062c7e0c5f6Smatthias.ringwald                     // close all open connections
40633a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
4064c7e0c5f6Smatthias.ringwald                     if (connection){
4065711e6c80SMatthias Ringwald                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
4066d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
406732ab9390Smatthias.ringwald 
40688fca890eSMatthias Ringwald                         // check state
40698fca890eSMatthias Ringwald                         if (connection->state == SENT_DISCONNECT) return;
40708fca890eSMatthias Ringwald                         connection->state = SENT_DISCONNECT;
40718fca890eSMatthias Ringwald 
40728837e9efSMatthias Ringwald                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
4073c7e0c5f6Smatthias.ringwald 
40748837e9efSMatthias Ringwald                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
40758837e9efSMatthias Ringwald                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
40768837e9efSMatthias Ringwald 
40778837e9efSMatthias Ringwald                         // ... which would be ignored anyway as we shutdown (free) the connection now
4078c7e0c5f6Smatthias.ringwald                         hci_shutdown_connection(connection);
40798837e9efSMatthias Ringwald 
40808837e9efSMatthias Ringwald                         // finally, send the disconnect command
40816ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4082c7e0c5f6Smatthias.ringwald                         return;
4083c7e0c5f6Smatthias.ringwald                     }
408426fe9592SMatthias Ringwald 
4085beceeddeSMatthias Ringwald                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
4086beceeddeSMatthias Ringwald                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
4087beceeddeSMatthias Ringwald                         log_info("HCI_STATE_HALTING: wait 50 ms");
408826fe9592SMatthias Ringwald                         hci_stack->substate = HCI_HALTING_W4_TIMER;
4089beceeddeSMatthias Ringwald                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
409026fe9592SMatthias Ringwald                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
409126fe9592SMatthias Ringwald                         btstack_run_loop_add_timer(&hci_stack->timeout);
409226fe9592SMatthias Ringwald                         break;
4093beceeddeSMatthias Ringwald                     }
409426fe9592SMatthias Ringwald 
4095cf373d3aSMatthias Ringwald                     /* fall through */
409626fe9592SMatthias Ringwald 
409726fe9592SMatthias Ringwald                 case HCI_HALTING_CLOSE:
40989da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling off");
4099c7e0c5f6Smatthias.ringwald 
410072ea5239Smatthias.ringwald                     // switch mode
4101c7e0c5f6Smatthias.ringwald                     hci_power_control_off();
41029418f9c9Smatthias.ringwald 
41039da54300S[email protected]                     log_info("HCI_STATE_HALTING, emitting state");
410472ea5239Smatthias.ringwald                     hci_emit_state();
41059da54300S[email protected]                     log_info("HCI_STATE_HALTING, done");
410672ea5239Smatthias.ringwald                     break;
4107beceeddeSMatthias Ringwald 
4108beceeddeSMatthias Ringwald                 case HCI_HALTING_W4_TIMER:
4109beceeddeSMatthias Ringwald                     // keep waiting
4110beceeddeSMatthias Ringwald 
4111beceeddeSMatthias Ringwald                     break;
411226fe9592SMatthias Ringwald                 default:
411326fe9592SMatthias Ringwald                     break;
411426fe9592SMatthias Ringwald             }
411526fe9592SMatthias Ringwald 
411626fe9592SMatthias Ringwald             break;
4117c7e0c5f6Smatthias.ringwald 
411872ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
41193a9fb326S[email protected]             switch(hci_stack->substate) {
412074b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_DISCONNECT:
41219da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
412272ea5239Smatthias.ringwald                     // close all open connections
41233a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
412466da7044Smatthias.ringwald 
4125423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
412666da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
4127d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
412866da7044Smatthias.ringwald                         connection = NULL;
412966da7044Smatthias.ringwald                     }
413066da7044Smatthias.ringwald #endif
413172ea5239Smatthias.ringwald                     if (connection){
413232ab9390Smatthias.ringwald 
413372ea5239Smatthias.ringwald                         // send disconnect
4134d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
413532ab9390Smatthias.ringwald 
41369da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
41376ef3696aSMatthias Ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
413872ea5239Smatthias.ringwald 
413972ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
414072ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
414172ea5239Smatthias.ringwald                         return;
414272ea5239Smatthias.ringwald                     }
414372ea5239Smatthias.ringwald 
414492368cd3S[email protected]                     if (hci_classic_supported()){
414589db417bSmatthias.ringwald                         // disable page and inquiry scan
4146d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
414732ab9390Smatthias.ringwald 
41489da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
41493a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
415089db417bSmatthias.ringwald 
415189db417bSmatthias.ringwald                         // continue in next sub state
415274b323a9SMatthias Ringwald                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
415389db417bSmatthias.ringwald                         break;
415492368cd3S[email protected]                     }
4155cf373d3aSMatthias Ringwald 
4156cf373d3aSMatthias Ringwald                     /* fall through */
415792368cd3S[email protected] 
415874b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_COMPLETE:
41599da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
4160423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
416128171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
4162d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
416328171530Smatthias.ringwald                         // SLEEP MODE reached
41643a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
416528171530Smatthias.ringwald                         hci_emit_state();
416628171530Smatthias.ringwald                         break;
416728171530Smatthias.ringwald                     }
416828171530Smatthias.ringwald #endif
416972ea5239Smatthias.ringwald                     // switch mode
41703a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
4171c7e0c5f6Smatthias.ringwald                     hci_emit_state();
417228171530Smatthias.ringwald                     break;
417328171530Smatthias.ringwald 
417489db417bSmatthias.ringwald                 default:
417589db417bSmatthias.ringwald                     break;
417689db417bSmatthias.ringwald             }
4177c7e0c5f6Smatthias.ringwald             break;
4178c7e0c5f6Smatthias.ringwald 
41793429f56bSmatthias.ringwald         default:
41803429f56bSmatthias.ringwald             break;
41811f504dbdSmatthias.ringwald     }
41823429f56bSmatthias.ringwald }
418316833f0aSmatthias.ringwald 
418431452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
418535454696SMatthias Ringwald     // house-keeping
418635454696SMatthias Ringwald 
418735454696SMatthias Ringwald     if (IS_COMMAND(packet, hci_write_loopback_mode)){
418835454696SMatthias Ringwald         hci_stack->loopback_mode = packet[3];
418935454696SMatthias Ringwald     }
419035454696SMatthias Ringwald 
419135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4192c8e4258aSmatthias.ringwald     bd_addr_t addr;
4193c8e4258aSmatthias.ringwald     hci_connection_t * conn;
4194c8e4258aSmatthias.ringwald 
4195c8e4258aSmatthias.ringwald     // create_connection?
4196c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
4197724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
41989da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
4199c8e4258aSmatthias.ringwald 
4200f16129ceSMatthias Ringwald         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
4201ad83dc6aS[email protected]         if (!conn){
4202f16129ceSMatthias Ringwald             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
420317f1ba2aSmatthias.ringwald             if (!conn){
420417f1ba2aSmatthias.ringwald                 // notify client that alloc failed
42052deddeceSMatthias Ringwald                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4206f5e5741dSMatthias Ringwald                 return -1; // packet not sent to controller
420717f1ba2aSmatthias.ringwald             }
4208ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
4209ad83dc6aS[email protected]         }
4210ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
4211ad83dc6aS[email protected]         switch (conn->state){
4212ad83dc6aS[email protected]             // if connection active exists
4213ad83dc6aS[email protected]             case OPEN:
4214f5e5741dSMatthias Ringwald                 // and OPEN, emit connection complete command
4215274dad91SMatthias Ringwald                 hci_emit_connection_complete(addr, conn->con_handle, 0);
4216f5e5741dSMatthias Ringwald                 return -1; // packet not sent to controller
4217672e36abSMatthias Ringwald             case RECEIVED_DISCONNECTION_COMPLETE:
4218672e36abSMatthias Ringwald                 // create connection triggered in disconnect complete event, let's do it now
4219672e36abSMatthias Ringwald                 break;
4220ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
4221532f91a5SMatthias Ringwald                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
4222532f91a5SMatthias Ringwald                 break;
4223ad83dc6aS[email protected]             default:
4224ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
4225f5e5741dSMatthias Ringwald                 return -1; // packet not sent to controller
4226ad83dc6aS[email protected]         }
4227c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
4228229331c6SMatthias Ringwald 
4229229331c6SMatthias Ringwald         // track outgoing connection
4230f16129ceSMatthias Ringwald         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL;
42316535961aSMatthias Ringwald         (void)memcpy(hci_stack->outgoing_addr, addr, 6);
4232c8e4258aSmatthias.ringwald     }
423335454696SMatthias Ringwald 
423455573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_link_key_request_reply)){
42357fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
42367fde4af9Smatthias.ringwald     }
423755573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
42387fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
42397fde4af9Smatthias.ringwald     }
42407fde4af9Smatthias.ringwald 
424155573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_delete_stored_link_key)){
4242a98592bcSMatthias Ringwald         if (hci_stack->link_key_db){
4243724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
4244a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
42458ef73945Smatthias.ringwald         }
42468ef73945Smatthias.ringwald     }
4247c8e4258aSmatthias.ringwald 
424855573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
42496724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
4250724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
4251f16129ceSMatthias Ringwald         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
42526724cd9eS[email protected]         if (conn){
42536724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
42546724cd9eS[email protected]         }
42556724cd9eS[email protected]     }
42566724cd9eS[email protected] 
425755573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
42586724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
42596724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
42606724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
4261724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
4262f16129ceSMatthias Ringwald         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
42636724cd9eS[email protected]         if (conn){
42646724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
42656724cd9eS[email protected]         }
42666724cd9eS[email protected]     }
4267ee752bb8SMatthias Ringwald 
4268ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
4269ee752bb8SMatthias Ringwald     // setup_synchronous_connection? Voice setting at offset 22
427055573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
4271ee752bb8SMatthias Ringwald         // TODO: compare to current setting if sco connection already active
4272ee752bb8SMatthias Ringwald         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
4273ee752bb8SMatthias Ringwald     }
4274ee752bb8SMatthias Ringwald     // accept_synchronus_connection? Voice setting at offset 18
427555573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
4276ee752bb8SMatthias Ringwald         // TODO: compare to current setting if sco connection already active
4277ee752bb8SMatthias Ringwald         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
4278ee752bb8SMatthias Ringwald     }
4279ee752bb8SMatthias Ringwald #endif
428035454696SMatthias Ringwald #endif
42814b3e1e19SMatthias Ringwald 
4282a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
428355573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_le_set_random_address)){
4284b95a5a35SMatthias Ringwald         hci_stack->le_random_address_set = 1;
4285b95a5a35SMatthias Ringwald         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
4286d70217a2SMatthias Ringwald     }
42877e8d8b1dSMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
428855573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
4289171293d3SMatthias Ringwald         hci_stack->le_advertisements_active = packet[3];
4290171293d3SMatthias Ringwald     }
4291d70217a2SMatthias Ringwald #endif
4292d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
429355573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_le_create_connection)){
4294b04dfa37SMatthias Ringwald         // white list used?
4295b04dfa37SMatthias Ringwald         uint8_t initiator_filter_policy = packet[7];
4296b04dfa37SMatthias Ringwald         switch (initiator_filter_policy){
4297b04dfa37SMatthias Ringwald             case 0:
4298b04dfa37SMatthias Ringwald                 // whitelist not used
4299b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
4300b04dfa37SMatthias Ringwald                 break;
4301b04dfa37SMatthias Ringwald             case 1:
4302b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
4303b04dfa37SMatthias Ringwald                 break;
4304b04dfa37SMatthias Ringwald             default:
4305b04dfa37SMatthias Ringwald                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
4306b04dfa37SMatthias Ringwald                 break;
4307b04dfa37SMatthias Ringwald         }
4308b04dfa37SMatthias Ringwald     }
430955573af2SMatthias Ringwald     else if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
4310b04dfa37SMatthias Ringwald         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4311b04dfa37SMatthias Ringwald     }
431269a97523S[email protected] #endif
4313d70217a2SMatthias Ringwald #endif
431469a97523S[email protected] 
43153a9fb326S[email protected]     hci_stack->num_cmd_packets--;
43165bb5bc3eS[email protected] 
43175bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4318bfea0222SMatthias Ringwald     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
431931452debSmatthias.ringwald }
43208adf0ddaSmatthias.ringwald 
43212bd8b7e7S[email protected] // disconnect because of security block
43222bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
43232bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
43242bd8b7e7S[email protected]     if (!connection) return;
43252bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
43262bd8b7e7S[email protected] }
43272bd8b7e7S[email protected] 
43282bd8b7e7S[email protected] 
4329dbe1a790S[email protected] // Configure Secure Simple Pairing
4330dbe1a790S[email protected] 
433135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
433235454696SMatthias Ringwald 
4333dbe1a790S[email protected] // enable will enable SSP during init
433415a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
43353a9fb326S[email protected]     hci_stack->ssp_enable = enable;
4336dbe1a790S[email protected] }
4337dbe1a790S[email protected] 
433895d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
433915a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
43402bd8b7e7S[email protected] }
43412bd8b7e7S[email protected] 
4342dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
434315a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
43443a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
4345dbe1a790S[email protected] }
434615a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
43473a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
4348dbe1a790S[email protected] }
4349dbe1a790S[email protected] 
4350dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
435115a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
43523a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
4353dbe1a790S[email protected] }
43545d23aae8SMatthias Ringwald 
43555d23aae8SMatthias Ringwald void gap_secure_connections_enable(bool enable){
43565d23aae8SMatthias Ringwald     hci_stack->secure_connections_enable = enable;
43575d23aae8SMatthias Ringwald }
43585d23aae8SMatthias Ringwald 
435935454696SMatthias Ringwald #endif
4360dbe1a790S[email protected] 
436194be1a66SMatthias Ringwald // va_list part of hci_send_cmd
436294be1a66SMatthias Ringwald int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
4363d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
43649d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
43659d14b626S[email protected]         return 0;
43669d14b626S[email protected]     }
43679d14b626S[email protected] 
43685127cc62S[email protected]     // for HCI INITIALIZATION
43699da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
43705127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
43715127cc62S[email protected] 
43729d14b626S[email protected]     hci_reserve_packet_buffer();
43739d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
437494be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
4375bfea0222SMatthias Ringwald     int err = hci_send_cmd_packet(packet, size);
4376bfea0222SMatthias Ringwald 
4377593702caSMatthias Ringwald     // release packet buffer on error or for synchronous transport implementations
4378593702caSMatthias Ringwald     if ((err < 0) || hci_transport_synchronous()){
4379e2d22487SMatthias Ringwald         hci_release_packet_buffer();
4380068b8592SMatthias Ringwald         hci_emit_transport_packet_sent();
4381bfea0222SMatthias Ringwald     }
4382bfea0222SMatthias Ringwald 
4383bfea0222SMatthias Ringwald     return err;
438494be1a66SMatthias Ringwald }
43859d14b626S[email protected] 
438694be1a66SMatthias Ringwald /**
438794be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
438894be1a66SMatthias Ringwald  */
438994be1a66SMatthias Ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
43901cd208adSmatthias.ringwald     va_list argptr;
43911cd208adSmatthias.ringwald     va_start(argptr, cmd);
439294be1a66SMatthias Ringwald     int res = hci_send_cmd_va_arg(cmd, argptr);
43931cd208adSmatthias.ringwald     va_end(argptr);
439494be1a66SMatthias Ringwald     return res;
439593b8dc03Smatthias.ringwald }
4396c8e4258aSmatthias.ringwald 
4397ee091cf1Smatthias.ringwald // Create various non-HCI events.
4398ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
4399ee091cf1Smatthias.ringwald 
4400d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
4401fb37a842SMatthias Ringwald     // dump packet
4402d6b06661SMatthias Ringwald     if (dump) {
4403300c1ba4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
4404d6b06661SMatthias Ringwald     }
44051ef6bb52SMatthias Ringwald 
4406fb37a842SMatthias Ringwald     // dispatch to all event handlers
44071ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
44081ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
44091ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
44101ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
4411d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
44121ef6bb52SMatthias Ringwald     }
4413d6b06661SMatthias Ringwald }
4414d6b06661SMatthias Ringwald 
4415d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
4416fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
44173d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
4418d6b06661SMatthias Ringwald }
4419d6b06661SMatthias Ringwald 
442035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
4421701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
44223bc639ceSMatthias Ringwald     // notify SCO sender if waiting
4423701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
4424701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
44253bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
4426701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
4427701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
44283d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
44293bc639ceSMatthias Ringwald     }
44303bc639ceSMatthias Ringwald }
44311cfb383eSMatthias Ringwald 
44321cfb383eSMatthias Ringwald // parsing end emitting has been merged to reduce code size
44339784dac1SMatthias Ringwald static void gap_inquiry_explode(uint8_t *packet, uint16_t size) {
4434e4f5dd75SMatthias Ringwald     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
44351cfb383eSMatthias Ringwald 
44361cfb383eSMatthias Ringwald     uint8_t * eir_data;
44371cfb383eSMatthias Ringwald     ad_context_t context;
44381cfb383eSMatthias Ringwald     const uint8_t * name;
44391cfb383eSMatthias Ringwald     uint8_t         name_len;
44401cfb383eSMatthias Ringwald 
44419784dac1SMatthias Ringwald     if (size < 3) return;
44429784dac1SMatthias Ringwald 
44431cfb383eSMatthias Ringwald     int event_type = hci_event_packet_get_type(packet);
4444a1df452eSMatthias Ringwald     int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1;    // 2 for old event, 1 otherwise
44451cfb383eSMatthias Ringwald     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
44461cfb383eSMatthias Ringwald 
44479784dac1SMatthias Ringwald     switch (event_type){
44489784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT:
44499784dac1SMatthias Ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
44509784dac1SMatthias Ringwald             if (size != (3 + (num_responses * 14))) return;
44519784dac1SMatthias Ringwald             break;
44529784dac1SMatthias Ringwald         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
44539784dac1SMatthias Ringwald             if (size != 257) return;
44549784dac1SMatthias Ringwald             if (num_responses != 1) return;
44559784dac1SMatthias Ringwald             break;
44569784dac1SMatthias Ringwald         default:
44579784dac1SMatthias Ringwald             return;
44589784dac1SMatthias Ringwald     }
44599784dac1SMatthias Ringwald 
44601cfb383eSMatthias Ringwald     // event[1] is set at the end
44611cfb383eSMatthias Ringwald     int i;
44621cfb383eSMatthias Ringwald     for (i=0; i<num_responses;i++){
44631cfb383eSMatthias Ringwald         memset(event, 0, sizeof(event));
44641cfb383eSMatthias Ringwald         event[0] = GAP_EVENT_INQUIRY_RESULT;
44651cfb383eSMatthias Ringwald         uint8_t event_size = 18;    // if name is not set by EIR
44661cfb383eSMatthias Ringwald 
44676535961aSMatthias Ringwald         (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr
44680e588213SMatthias Ringwald         event[8] =          packet[3 + (num_responses*(6))                         + (i*1)];     // page_scan_repetition_mode
44696535961aSMatthias Ringwald         (void)memcpy(&event[9],
44706535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)],
44716535961aSMatthias Ringwald                      3); // class of device
44726535961aSMatthias Ringwald         (void)memcpy(&event[12],
44736535961aSMatthias Ringwald                      &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)],
44746535961aSMatthias Ringwald                      2); // clock offset
44751cfb383eSMatthias Ringwald 
44761cfb383eSMatthias Ringwald         switch (event_type){
44771cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT:
44781cfb383eSMatthias Ringwald                 // 14,15,16,17 = 0, size 18
44791cfb383eSMatthias Ringwald                 break;
44801cfb383eSMatthias Ringwald             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
44811cfb383eSMatthias Ringwald                 event[14] = 1;
4482a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
44831cfb383eSMatthias Ringwald                 // 16,17 = 0, size 18
44841cfb383eSMatthias Ringwald                 break;
44851cfb383eSMatthias Ringwald             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
44861cfb383eSMatthias Ringwald                 event[14] = 1;
4487a1df452eSMatthias Ringwald                 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi
448879186815SMatthias Ringwald                 // EIR packets only contain a single inquiry response
44891cfb383eSMatthias Ringwald                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
44901cfb383eSMatthias Ringwald                 name = NULL;
4491a8c4e5adSMatthias Ringwald                 // Iterate over EIR data
4492a8c4e5adSMatthias Ringwald                 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
44931cfb383eSMatthias Ringwald                     uint8_t data_type    = ad_iterator_get_data_type(&context);
44941cfb383eSMatthias Ringwald                     uint8_t data_size    = ad_iterator_get_data_len(&context);
44951cfb383eSMatthias Ringwald                     const uint8_t * data = ad_iterator_get_data(&context);
44961cfb383eSMatthias Ringwald                     // Prefer Complete Local Name over Shortend Local Name
44971cfb383eSMatthias Ringwald                     switch (data_type){
44981cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
44991cfb383eSMatthias Ringwald                             if (name) continue;
4500cf373d3aSMatthias Ringwald                             /* fall through */
45011cfb383eSMatthias Ringwald                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
45021cfb383eSMatthias Ringwald                             name = data;
45031cfb383eSMatthias Ringwald                             name_len = data_size;
45041cfb383eSMatthias Ringwald                             break;
45051cfb383eSMatthias Ringwald                         default:
45061cfb383eSMatthias Ringwald                             break;
45071cfb383eSMatthias Ringwald                     }
45081cfb383eSMatthias Ringwald                 }
45091cfb383eSMatthias Ringwald                 if (name){
45101cfb383eSMatthias Ringwald                     event[16] = 1;
45111cfb383eSMatthias Ringwald                     // truncate name if needed
45121cfb383eSMatthias Ringwald                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
45131cfb383eSMatthias Ringwald                     event[17] = len;
45146535961aSMatthias Ringwald                     (void)memcpy(&event[18], name, len);
45151cfb383eSMatthias Ringwald                     event_size += len;
45161cfb383eSMatthias Ringwald                 }
45171cfb383eSMatthias Ringwald                 break;
45181cfb383eSMatthias Ringwald         }
45191cfb383eSMatthias Ringwald         event[1] = event_size - 2;
45201cfb383eSMatthias Ringwald         hci_emit_event(event, event_size, 1);
45211cfb383eSMatthias Ringwald     }
45221cfb383eSMatthias Ringwald }
452335454696SMatthias Ringwald #endif
45243bc639ceSMatthias Ringwald 
452571de195eSMatthias Ringwald void hci_emit_state(void){
45263a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
4527425d1371Smatthias.ringwald     uint8_t event[3];
452880d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
4529425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
45303a9fb326S[email protected]     event[2] = hci_stack->state;
4531d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4532c8e4258aSmatthias.ringwald }
4533c8e4258aSmatthias.ringwald 
453435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
45352deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4536425d1371Smatthias.ringwald     uint8_t event[13];
4537c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
4538425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
453917f1ba2aSmatthias.ringwald     event[2] = status;
45402deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
45412deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
4542c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
4543c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
4544d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4545c8e4258aSmatthias.ringwald }
454652db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
454752db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
454852db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
454952db98b2SMatthias Ringwald     uint8_t event[4];
455052db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
455152db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
455252db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
455352db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
455452db98b2SMatthias Ringwald }
455535454696SMatthias Ringwald #endif
4556c8e4258aSmatthias.ringwald 
455735454696SMatthias Ringwald #ifdef ENABLE_BLE
4558d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4559fc64f94aSMatthias Ringwald static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
45604f3229d8S[email protected]     uint8_t event[21];
45614f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
45624f3229d8S[email protected]     event[1] = sizeof(event) - 2;
45634f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
45644f3229d8S[email protected]     event[3] = status;
4565fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
45664f3229d8S[email protected]     event[6] = 0; // TODO: role
45676e2e9a6bS[email protected]     event[7] = address_type;
4568724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
4569f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
4570f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
4571f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
45724f3229d8S[email protected]     event[20] = 0; // master clock accuracy
4573d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
45744f3229d8S[email protected] }
457535454696SMatthias Ringwald #endif
4576d70217a2SMatthias Ringwald #endif
45774f3229d8S[email protected] 
4578fd43c0e0SMatthias Ringwald static void hci_emit_transport_packet_sent(void){
4579fd43c0e0SMatthias Ringwald     // notify upper stack that it might be possible to send again
4580fd43c0e0SMatthias Ringwald     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4581fd43c0e0SMatthias Ringwald     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4582fd43c0e0SMatthias Ringwald }
4583fd43c0e0SMatthias Ringwald 
4584fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4585425d1371Smatthias.ringwald     uint8_t event[6];
45863c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4587e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
45883c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
4589fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
45903c4d4b90Smatthias.ringwald     event[5] = reason;
4591d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
45923c4d4b90Smatthias.ringwald }
45933c4d4b90Smatthias.ringwald 
4594b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
4595e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4596425d1371Smatthias.ringwald     uint8_t event[3];
459780d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4598425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
459943bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
4600d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
460143bfb1bdSmatthias.ringwald }
4602038bc64cSmatthias.ringwald 
4603b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
4604e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
4605425d1371Smatthias.ringwald     uint8_t event[2];
460680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4607425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
4608d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4609038bc64cSmatthias.ringwald }
46101b0e3922Smatthias.ringwald 
461135454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
461235454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
461335454696SMatthias Ringwald     uint8_t event[9];
461435454696SMatthias Ringwald     int pos = 0;
461535454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
461635454696SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
461735454696SMatthias Ringwald     event[pos++] = status;
461835454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
4619d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4620381fbed8Smatthias.ringwald }
4621458bf4e8S[email protected] 
462235454696SMatthias Ringwald 
462335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
462435454696SMatthias Ringwald 
4625b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4626df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4627a00031e2S[email protected]     uint8_t event[5];
4628e00caf9cS[email protected]     int pos = 0;
46295611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4630e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
4631f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
4632e00caf9cS[email protected]     pos += 2;
4633e00caf9cS[email protected]     event[pos++] = level;
4634d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4635e00caf9cS[email protected] }
4636e00caf9cS[email protected] 
463735454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
463835454696SMatthias Ringwald     if (!connection) return LEVEL_0;
463935454696SMatthias Ringwald     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4640abdad579SMatthias Ringwald     if ((connection->authentication_flags & CONNECTION_AUTHENTICATED) == 0) return LEVEL_0;
4641170fafaeSMatthias Ringwald     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
46424051b7ffSMatthias Ringwald     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
4643170fafaeSMatthias Ringwald     // LEVEL 4 always requires 128 bit encrytion key size
46440e588213SMatthias Ringwald     if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){
4645170fafaeSMatthias Ringwald         security_level = LEVEL_3;
4646170fafaeSMatthias Ringwald     }
4647170fafaeSMatthias Ringwald     return security_level;
464835454696SMatthias Ringwald }
464935454696SMatthias Ringwald 
465035454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled){
465135454696SMatthias Ringwald     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
465235454696SMatthias Ringwald     uint8_t event[3];
465335454696SMatthias Ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
465435454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
465535454696SMatthias Ringwald     event[2] = enabled;
4656d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
4657ad83dc6aS[email protected] }
4658ad83dc6aS[email protected] 
465998a2fd1cSMatthias Ringwald // query if remote side supports eSCO
4660073bd0faSMatthias Ringwald int hci_remote_esco_supported(hci_con_handle_t con_handle){
466198a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
466298a2fd1cSMatthias Ringwald     if (!connection) return 0;
466376ccfb2aSMatthias Ringwald     return (connection->remote_supported_features[0] & 1) != 0;
466498a2fd1cSMatthias Ringwald }
466598a2fd1cSMatthias Ringwald 
466667aae551SMatthias Ringwald static bool hci_ssp_supported(hci_connection_t * connection){
466767aae551SMatthias Ringwald     const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST;
466867aae551SMatthias Ringwald     return (connection->bonding_flags & mask) == mask;
466967aae551SMatthias Ringwald }
467067aae551SMatthias Ringwald 
46712bd8b7e7S[email protected] // query if remote side supports SSP
46722bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
46732bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
46742bd8b7e7S[email protected]     if (!connection) return 0;
467567aae551SMatthias Ringwald     return hci_ssp_supported(connection) ? 1 : 0;
46762bd8b7e7S[email protected] }
46772bd8b7e7S[email protected] 
467815a95bd5SMatthias Ringwald int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4679df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4680df3354fcS[email protected] }
4681df3354fcS[email protected] 
4682458bf4e8S[email protected] // GAP API
4683458bf4e8S[email protected] /**
4684458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
4685458bf4e8S[email protected]  * @praram enabled
4686458bf4e8S[email protected]  */
46874c57c146S[email protected] void gap_set_bondable_mode(int enable){
46883a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
4689458bf4e8S[email protected] }
46904ef6443cSMatthias Ringwald /**
46914ef6443cSMatthias Ringwald  * @brief Get bondable mode.
46924ef6443cSMatthias Ringwald  * @return 1 if bondable
46934ef6443cSMatthias Ringwald  */
46944ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
46954ef6443cSMatthias Ringwald     return hci_stack->bondable;
46964ef6443cSMatthias Ringwald }
4697cb230b9dS[email protected] 
4698cb230b9dS[email protected] /**
469934d2123cS[email protected]  * @brief map link keys to security levels
4700cb230b9dS[email protected]  */
470134d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
470234d2123cS[email protected]     switch (link_key_type){
47033c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
47043c68dfa9S[email protected]             return LEVEL_4;
47053c68dfa9S[email protected]         case COMBINATION_KEY:
47063c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
47073c68dfa9S[email protected]             return LEVEL_3;
47083c68dfa9S[email protected]         default:
47093c68dfa9S[email protected]             return LEVEL_2;
47103c68dfa9S[email protected]     }
4711cb230b9dS[email protected] }
4712cb230b9dS[email protected] 
47138b35e16aSMatthias Ringwald /**
47148b35e16aSMatthias Ringwald  * @brief map link keys to secure connection yes/no
47158b35e16aSMatthias Ringwald  */
47168b35e16aSMatthias Ringwald int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
47178b35e16aSMatthias Ringwald     switch (link_key_type){
47188b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
47198b35e16aSMatthias Ringwald         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
47208b35e16aSMatthias Ringwald             return 1;
47218b35e16aSMatthias Ringwald         default:
47228b35e16aSMatthias Ringwald             return 0;
47238b35e16aSMatthias Ringwald     }
47248b35e16aSMatthias Ringwald }
47258b35e16aSMatthias Ringwald 
47268b35e16aSMatthias Ringwald /**
47278b35e16aSMatthias Ringwald  * @brief map link keys to authenticated
47288b35e16aSMatthias Ringwald  */
47298b35e16aSMatthias Ringwald int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
47308b35e16aSMatthias Ringwald     switch (link_key_type){
47318b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
47328b35e16aSMatthias Ringwald         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
47338b35e16aSMatthias Ringwald             return 1;
47348b35e16aSMatthias Ringwald         default:
47358b35e16aSMatthias Ringwald             return 0;
47368b35e16aSMatthias Ringwald     }
47378b35e16aSMatthias Ringwald }
47388b35e16aSMatthias Ringwald 
4739106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
47405127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
4741106d6d11S[email protected]     return level > LEVEL_2;
4742106d6d11S[email protected] }
4743106d6d11S[email protected] 
474434d2123cS[email protected] /**
474534d2123cS[email protected]  * @brief get current security level
474634d2123cS[email protected]  */
474734d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
474834d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
474934d2123cS[email protected]     if (!connection) return LEVEL_0;
475034d2123cS[email protected]     return gap_security_level_for_connection(connection);
475134d2123cS[email protected] }
475234d2123cS[email protected] 
4753cb230b9dS[email protected] /**
4754cb230b9dS[email protected]  * @brief request connection to device to
4755cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
4756cb230b9dS[email protected]  */
475734d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
475834d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
475934d2123cS[email protected]     if (!connection){
4760a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
476134d2123cS[email protected]         return;
476234d2123cS[email protected]     }
476334d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
476483d08d7cSMatthias Ringwald     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
476583d08d7cSMatthias Ringwald         requested_level, connection->requested_security_level, current_level);
476683d08d7cSMatthias Ringwald 
476783d08d7cSMatthias Ringwald     // assumption: earlier requested security higher than current level => security request is active
476883d08d7cSMatthias Ringwald     if (current_level < connection->requested_security_level){
476983d08d7cSMatthias Ringwald         if (connection->requested_security_level < requested_level){
477083d08d7cSMatthias Ringwald             // increase requested level as new level is higher
477183d08d7cSMatthias Ringwald 
477283d08d7cSMatthias Ringwald             // TODO: handle re-authentication when done
477383d08d7cSMatthias Ringwald 
477483d08d7cSMatthias Ringwald             connection->requested_security_level = requested_level;
477583d08d7cSMatthias Ringwald         }
477683d08d7cSMatthias Ringwald         return;
477783d08d7cSMatthias Ringwald     }
477883d08d7cSMatthias Ringwald 
477983d08d7cSMatthias Ringwald     // no request active, notify if security sufficient
478083d08d7cSMatthias Ringwald     if (requested_level <= current_level){
4781a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
478234d2123cS[email protected]         return;
478334d2123cS[email protected]     }
4784a00031e2S[email protected] 
478583d08d7cSMatthias Ringwald     // start pairing to increase security level
478634d2123cS[email protected]     connection->requested_security_level = requested_level;
4787a00031e2S[email protected] 
478825bf5872S[email protected] #if 0
478925bf5872S[email protected]     // sending encryption request without a link key results in an error.
479025bf5872S[email protected]     // TODO: figure out how to use it properly
479125bf5872S[email protected] 
4792fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
4793a98592bcSMatthias Ringwald     if (hci_stack->link_key_db){
4794a00031e2S[email protected]         link_key_type_t link_key_type;
4795a00031e2S[email protected]         link_key_t      link_key;
4796a98592bcSMatthias Ringwald         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4797a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4798a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4799a00031e2S[email protected]                 return;
4800a00031e2S[email protected]             }
4801a00031e2S[email protected]         }
4802a00031e2S[email protected]     }
480325bf5872S[email protected] #endif
4804a00031e2S[email protected] 
4805abdad579SMatthias Ringwald     // start to authenticate connection if not already active
4806abdad579SMatthias Ringwald     if ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return;
48071eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4808e80b2cf9S[email protected]     hci_run();
4809e00caf9cS[email protected] }
4810ad83dc6aS[email protected] 
4811ad83dc6aS[email protected] /**
4812ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
4813ad83dc6aS[email protected]  * @param device
4814ad83dc6aS[email protected]  * @param request MITM protection
4815ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
4816ad83dc6aS[email protected]  */
4817ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4818ad83dc6aS[email protected] 
4819ad83dc6aS[email protected]     // create connection state machine
4820f16129ceSMatthias Ringwald     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL);
4821ad83dc6aS[email protected] 
4822ad83dc6aS[email protected]     if (!connection){
4823ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
4824ad83dc6aS[email protected]     }
4825ad83dc6aS[email protected] 
4826ad83dc6aS[email protected]     // delete linkn key
482715a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
4828ad83dc6aS[email protected] 
4829ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
4830ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
4831ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4832f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4833ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
4834ad83dc6aS[email protected] 
4835ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4836ad83dc6aS[email protected] 
4837ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
4838ad83dc6aS[email protected]     // handle: authentication failure
4839ad83dc6aS[email protected]     // handle: disconnect on done
4840ad83dc6aS[email protected] 
4841ad83dc6aS[email protected]     hci_run();
4842ad83dc6aS[email protected] 
4843ad83dc6aS[email protected]     return 0;
4844ad83dc6aS[email protected] }
484535454696SMatthias Ringwald #endif
48468e618f72S[email protected] 
48478e618f72S[email protected] void gap_set_local_name(const char * local_name){
48488e618f72S[email protected]     hci_stack->local_name = local_name;
48498e618f72S[email protected] }
48508e618f72S[email protected] 
485135454696SMatthias Ringwald 
485235454696SMatthias Ringwald #ifdef ENABLE_BLE
485335454696SMatthias Ringwald 
4854d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4855d8e8f12aSMatthias Ringwald void gap_start_scan(void){
48566fab74dbSMatthias Ringwald     hci_stack->le_scanning_enabled = 1;
48577bdc6798S[email protected]     hci_run();
48587bdc6798S[email protected] }
48598e618f72S[email protected] 
4860d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
48616fab74dbSMatthias Ringwald     hci_stack->le_scanning_enabled = 0;
48627bdc6798S[email protected]     hci_run();
48637bdc6798S[email protected] }
48644f3229d8S[email protected] 
4865d8e8f12aSMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4866ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
4867ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
4868ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
4869ef11999fSmatthias.ringwald     hci_run();
4870ef11999fSmatthias.ringwald }
48714f3229d8S[email protected] 
4872d8e8f12aSMatthias Ringwald uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
48734f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
48744f3229d8S[email protected]     if (!conn){
4875d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
48762e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
48774f3229d8S[email protected]         if (!conn){
48784f3229d8S[email protected]             // notify client that alloc failed
48796e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4880d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
4881472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
48824f3229d8S[email protected]         }
48834f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
4884d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
4885564fca32S[email protected]         hci_run();
4886b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
48874f3229d8S[email protected]     }
48880bf6344aS[email protected] 
48890bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
4890a1df452eSMatthias Ringwald         (conn->state == SEND_CREATE_CONNECTION) ||
48910e588213SMatthias Ringwald         (conn->state == SENT_CREATE_CONNECTION)) {
48922e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4893d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
4894616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
48950bf6344aS[email protected]     }
48960bf6344aS[email protected] 
4897b0136355SMatthias Ringwald     // check if connection was just disconnected
4898b0136355SMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4899b0136355SMatthias Ringwald         log_info("gap_connect: send create connection (again)");
4900b0136355SMatthias Ringwald         conn->state = SEND_CREATE_CONNECTION;
4901b0136355SMatthias Ringwald         hci_run();
4902b0136355SMatthias Ringwald         return ERROR_CODE_SUCCESS;
4903b0136355SMatthias Ringwald     }
4904b0136355SMatthias Ringwald 
4905d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
49062e77e513S[email protected]     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
49074f3229d8S[email protected]     hci_run();
4908b0136355SMatthias Ringwald     return ERROR_CODE_SUCCESS;
49094f3229d8S[email protected] }
49104f3229d8S[email protected] 
49117851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
4912d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
4913665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
4914a0da043fSMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){
49150bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
49160bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
49170bf6344aS[email protected]         switch (conn->state){
4918a6725849S[email protected]             case SEND_CREATE_CONNECTION:
49197851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
49209c77c9dbSMatthias Ringwald             case SENT_CANCEL_CONNECTION:
49217851196eSmatthias.ringwald                 return conn;
49227851196eSmatthias.ringwald             default:
49237851196eSmatthias.ringwald                 break;
49247851196eSmatthias.ringwald         };
49257851196eSmatthias.ringwald     }
49267851196eSmatthias.ringwald     return NULL;
49277851196eSmatthias.ringwald }
49287851196eSmatthias.ringwald 
4929d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
4930d8e8f12aSMatthias Ringwald     hci_connection_t * conn = gap_get_outgoing_connection();
4931616edd56SMatthias Ringwald     if (!conn) return 0;
49327851196eSmatthias.ringwald     switch (conn->state){
49337851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
49347851196eSmatthias.ringwald             // skip sending create connection and emit event instead
49352e77e513S[email protected]             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4936665d90f2SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
49377851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
49380bf6344aS[email protected]             break;
4939a6725849S[email protected]         case SENT_CREATE_CONNECTION:
49407851196eSmatthias.ringwald             // request to send cancel connection
49410bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
49420bf6344aS[email protected]             hci_run();
49430bf6344aS[email protected]             break;
49440bf6344aS[email protected]         default:
49450bf6344aS[email protected]             break;
49460bf6344aS[email protected]     }
4947616edd56SMatthias Ringwald     return 0;
4948e31f89a7S[email protected] }
4949d70217a2SMatthias Ringwald #endif
49504f3229d8S[email protected] 
495113e645d2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
4952c37a3166S[email protected] /**
49536012052bSMatthias Ringwald  * @brief Set connection parameters for outgoing connections
4954cbe54ab2SJakob Krantz  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4955cbe54ab2SJakob Krantz  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
49566012052bSMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
49576012052bSMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
49586012052bSMatthias Ringwald  * @param conn_latency, default: 4
49596012052bSMatthias Ringwald  * @param supervision_timeout (unit: 10ms), default: 720 ms
49606012052bSMatthias Ringwald  * @param min_ce_length (unit: 0.625ms), default: 10 ms
49616012052bSMatthias Ringwald  * @param max_ce_length (unit: 0.625ms), default: 30 ms
49626012052bSMatthias Ringwald  */
49636012052bSMatthias Ringwald 
4964cbe54ab2SJakob Krantz void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4965cbe54ab2SJakob Krantz     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4966cbe54ab2SJakob Krantz     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4967cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_interval = conn_scan_interval;
4968cbe54ab2SJakob Krantz     hci_stack->le_connection_scan_window = conn_scan_window;
49696012052bSMatthias Ringwald     hci_stack->le_connection_interval_min = conn_interval_min;
49706012052bSMatthias Ringwald     hci_stack->le_connection_interval_max = conn_interval_max;
49716012052bSMatthias Ringwald     hci_stack->le_connection_latency = conn_latency;
49726012052bSMatthias Ringwald     hci_stack->le_supervision_timeout = supervision_timeout;
49736012052bSMatthias Ringwald     hci_stack->le_minimum_ce_length = min_ce_length;
49746012052bSMatthias Ringwald     hci_stack->le_maximum_ce_length = max_ce_length;
49756012052bSMatthias Ringwald }
497613e645d2SMatthias Ringwald #endif
49776012052bSMatthias Ringwald 
49786012052bSMatthias Ringwald /**
4979c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
4980c37a3166S[email protected]  * @param handle
4981c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
4982c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
4983c37a3166S[email protected]  * @param conn_latency
4984c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
4985c37a3166S[email protected]  * @returns 0 if ok
4986c37a3166S[email protected]  */
4987c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4988c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4989c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4990c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4991c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
4992c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
4993c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
4994c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
499584cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4996cfc59f1bSMatthias Ringwald     hci_run();
4997c37a3166S[email protected]     return 0;
4998c37a3166S[email protected] }
4999c37a3166S[email protected] 
500045c102fdSMatthias Ringwald /**
5001b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
5002b68d7bc3SMatthias Ringwald  * @param handle
5003b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
5004b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
5005b68d7bc3SMatthias Ringwald  * @param conn_latency
5006b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
5007b68d7bc3SMatthias Ringwald  * @returns 0 if ok
5008b68d7bc3SMatthias Ringwald  */
5009b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
5010b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
5011b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5012b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5013b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
5014b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
5015b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
5016b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
5017b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
501809c9c963SMatthias Ringwald     uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0};
501909c9c963SMatthias Ringwald     hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0);
5020b68d7bc3SMatthias Ringwald     return 0;
5021b68d7bc3SMatthias Ringwald }
5022b68d7bc3SMatthias Ringwald 
5023d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
5024d70217a2SMatthias Ringwald 
5025501f56b3SMatthias Ringwald static void gap_advertisments_changed(void){
5026501f56b3SMatthias Ringwald     // disable advertisements before updating adv, scan data, or adv params
5027501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_active){
5028501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
5029501f56b3SMatthias Ringwald     }
5030501f56b3SMatthias Ringwald     hci_run();
5031501f56b3SMatthias Ringwald }
5032501f56b3SMatthias Ringwald 
5033b68d7bc3SMatthias Ringwald /**
503445c102fdSMatthias Ringwald  * @brief Set Advertisement Data
503545c102fdSMatthias Ringwald  * @param advertising_data_length
503645c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
503745c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
503845c102fdSMatthias Ringwald  */
503945c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
504045c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
504145c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
5042501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
5043501f56b3SMatthias Ringwald     gap_advertisments_changed();
504445c102fdSMatthias Ringwald }
5045501f56b3SMatthias Ringwald 
5046501f56b3SMatthias Ringwald /**
5047501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
5048501f56b3SMatthias Ringwald  * @param advertising_data_length
5049501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
5050501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
5051501f56b3SMatthias Ringwald  */
5052501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
5053501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
5054501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
5055501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
5056501f56b3SMatthias Ringwald     gap_advertisments_changed();
505745c102fdSMatthias Ringwald }
505845c102fdSMatthias Ringwald 
505945c102fdSMatthias Ringwald /**
506045c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
506145c102fdSMatthias Ringwald  * @param adv_int_min
506245c102fdSMatthias Ringwald  * @param adv_int_max
506345c102fdSMatthias Ringwald  * @param adv_type
506445c102fdSMatthias Ringwald  * @param direct_address_type
506545c102fdSMatthias Ringwald  * @param direct_address
506645c102fdSMatthias Ringwald  * @param channel_map
506745c102fdSMatthias Ringwald  * @param filter_policy
506845c102fdSMatthias Ringwald  *
506945c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
507045c102fdSMatthias Ringwald  */
507145c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5072b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
507345c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
507445c102fdSMatthias Ringwald 
507545c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
507645c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
507745c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
507845c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
507945c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
508045c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
50816535961aSMatthias Ringwald     (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address,
50826535961aSMatthias Ringwald                  6);
508345c102fdSMatthias Ringwald 
508445c102fdSMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
5085501f56b3SMatthias Ringwald     gap_advertisments_changed();
508645c102fdSMatthias Ringwald  }
508745c102fdSMatthias Ringwald 
508845c102fdSMatthias Ringwald /**
508945c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
509045c102fdSMatthias Ringwald  * @param enabled
509145c102fdSMatthias Ringwald  */
509245c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
509345c102fdSMatthias Ringwald     hci_stack->le_advertisements_enabled = enabled;
509445c102fdSMatthias Ringwald     if (enabled && !hci_stack->le_advertisements_active){
509545c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
509645c102fdSMatthias Ringwald     }
509745c102fdSMatthias Ringwald     if (!enabled && hci_stack->le_advertisements_active){
509845c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
509945c102fdSMatthias Ringwald     }
5100cfc59f1bSMatthias Ringwald     hci_run();
510145c102fdSMatthias Ringwald }
510245c102fdSMatthias Ringwald 
510335454696SMatthias Ringwald #endif
510406e5cf96SMatthias Ringwald 
510506e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
510606e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
510706e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
510806e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
510906e5cf96SMatthias Ringwald 
511064068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
511106e5cf96SMatthias Ringwald     // update advertisement parameters, too
511206e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
511306e5cf96SMatthias Ringwald     gap_advertisments_changed();
511464068776SMatthias Ringwald #endif
511564068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
511606e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
511764068776SMatthias Ringwald #endif
511806e5cf96SMatthias Ringwald }
511906e5cf96SMatthias Ringwald 
5120d70217a2SMatthias Ringwald #endif
512145c102fdSMatthias Ringwald 
5122616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
51235917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
51245917a5c5S[email protected]     if (!conn){
51257851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
5126616edd56SMatthias Ringwald         return 0;
51275917a5c5S[email protected]     }
51287fd7aa6fSMatthias Ringwald     // ignore if already disconnected
51297fd7aa6fSMatthias Ringwald     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
51307fd7aa6fSMatthias Ringwald         return 0;
51317fd7aa6fSMatthias Ringwald     }
51325917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
51335917a5c5S[email protected]     hci_run();
5134616edd56SMatthias Ringwald     return 0;
51354f3229d8S[email protected] }
513604a6ef8cSmatthias.ringwald 
5137228e430cSMatthias Ringwald int gap_read_rssi(hci_con_handle_t con_handle){
5138228e430cSMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5139228e430cSMatthias Ringwald     if (hci_connection == NULL) return 0;
5140228e430cSMatthias Ringwald     connectionSetAuthenticationFlags(hci_connection, READ_RSSI);
5141228e430cSMatthias Ringwald     hci_run();
5142228e430cSMatthias Ringwald     return 1;
5143228e430cSMatthias Ringwald }
5144228e430cSMatthias Ringwald 
5145a1bf5ae7SMatthias Ringwald /**
5146a1bf5ae7SMatthias Ringwald  * @brief Get connection type
5147a1bf5ae7SMatthias Ringwald  * @param con_handle
5148a1bf5ae7SMatthias Ringwald  * @result connection_type
5149a1bf5ae7SMatthias Ringwald  */
5150a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
5151a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5152a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
5153a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
5154a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
5155a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
5156a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
5157a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
5158a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
5159f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
5160a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
5161a1bf5ae7SMatthias Ringwald         default:
5162a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
5163a1bf5ae7SMatthias Ringwald     }
5164a1bf5ae7SMatthias Ringwald }
5165a1bf5ae7SMatthias Ringwald 
5166a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
51674f551432SMatthias Ringwald 
5168b90f6e0aSMatthias Ringwald uint8_t gap_le_set_phy(hci_con_handle_t connection_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
5169b90f6e0aSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5170b90f6e0aSMatthias Ringwald     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5171b90f6e0aSMatthias Ringwald 
5172b90f6e0aSMatthias Ringwald     conn->le_phy_update_all_phys    = all_phys;
5173b90f6e0aSMatthias Ringwald     conn->le_phy_update_tx_phys     = tx_phys;
5174b90f6e0aSMatthias Ringwald     conn->le_phy_update_rx_phys     = rx_phys;
5175b90f6e0aSMatthias Ringwald     conn->le_phy_update_phy_options = phy_options;
5176b90f6e0aSMatthias Ringwald 
5177b90f6e0aSMatthias Ringwald     hci_run();
5178b90f6e0aSMatthias Ringwald 
5179b90f6e0aSMatthias Ringwald     return 0;
5180b90f6e0aSMatthias Ringwald }
5181b90f6e0aSMatthias Ringwald 
5182d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
5183d23838ecSMatthias Ringwald /**
5184ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
5185ac9c45e0SMatthias Ringwald  * @param address_typ
5186ac9c45e0SMatthias Ringwald  * @param address
5187ac9c45e0SMatthias Ringwald  * @returns 0 if ok
5188ac9c45e0SMatthias Ringwald  */
51894f551432SMatthias Ringwald int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
5190e83201bcSMatthias Ringwald     // check capacity
5191665d90f2SMatthias Ringwald     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
519291915b0bSMatthias Ringwald     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
5193e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
5194e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
5195e83201bcSMatthias Ringwald     entry->address_type = address_type;
51966535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
5197e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
5198665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
5199e83201bcSMatthias Ringwald     hci_run();
5200e83201bcSMatthias Ringwald     return 0;
5201ac9c45e0SMatthias Ringwald }
5202ac9c45e0SMatthias Ringwald 
520342ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
5204665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
5205665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5206665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5207665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5208e83201bcSMatthias Ringwald         if (entry->address_type != address_type) continue;
5209e83201bcSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) continue;
5210e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5211e83201bcSMatthias Ringwald             // remove from controller if already present
5212e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5213e83201bcSMatthias Ringwald             continue;
5214e83201bcSMatthias Ringwald         }
5215e83201bcSMatthias Ringwald         // direclty remove entry from whitelist
5216665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
5217e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
5218e83201bcSMatthias Ringwald     }
521942ff5ba1SMatthias Ringwald }
522042ff5ba1SMatthias Ringwald 
522142ff5ba1SMatthias Ringwald /**
522242ff5ba1SMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
522342ff5ba1SMatthias Ringwald  * @param address_typ
522442ff5ba1SMatthias Ringwald  * @param address
522542ff5ba1SMatthias Ringwald  * @returns 0 if ok
522642ff5ba1SMatthias Ringwald  */
522742ff5ba1SMatthias Ringwald int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
522842ff5ba1SMatthias Ringwald     hci_remove_from_whitelist(address_type, address);
5229e83201bcSMatthias Ringwald     hci_run();
5230e83201bcSMatthias Ringwald     return 0;
5231ac9c45e0SMatthias Ringwald }
5232ac9c45e0SMatthias Ringwald 
5233ac9c45e0SMatthias Ringwald /**
5234ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
5235ac9c45e0SMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
5236ac9c45e0SMatthias Ringwald  */
5237ac9c45e0SMatthias Ringwald void gap_auto_connection_stop_all(void){
5238665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
5239665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
5240665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5241665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
5242e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
5243e83201bcSMatthias Ringwald             // remove from controller if already present
5244e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
5245e83201bcSMatthias Ringwald             continue;
5246e83201bcSMatthias Ringwald         }
524791915b0bSMatthias Ringwald         // directly remove entry from whitelist
5248665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
5249e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
5250e83201bcSMatthias Ringwald     }
5251e83201bcSMatthias Ringwald     hci_run();
5252ac9c45e0SMatthias Ringwald }
5253c9db5c21SMilanka Ringwald 
5254c9db5c21SMilanka Ringwald uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
5255c9db5c21SMilanka Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
5256c9db5c21SMilanka Ringwald     if (!conn) return 0;
5257c9db5c21SMilanka Ringwald     return conn->le_connection_interval;
5258c9db5c21SMilanka Ringwald }
5259d70217a2SMatthias Ringwald #endif
52604f551432SMatthias Ringwald #endif
52614f551432SMatthias Ringwald 
526235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
5263ac9c45e0SMatthias Ringwald /**
5264ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
5265a8c4e5adSMatthias Ringwald  * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup
5266ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
5267ff00ed1cSMatthias Ringwald  */
5268ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
5269ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
5270ff00ed1cSMatthias Ringwald }
5271ff00ed1cSMatthias Ringwald 
5272ff00ed1cSMatthias Ringwald /**
5273f5875de5SMatthias Ringwald  * @brief Start GAP Classic Inquiry
5274f5875de5SMatthias Ringwald  * @param duration in 1.28s units
5275f5875de5SMatthias Ringwald  * @return 0 if ok
5276f5875de5SMatthias Ringwald  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
5277f5875de5SMatthias Ringwald  */
5278f5875de5SMatthias Ringwald int gap_inquiry_start(uint8_t duration_in_1280ms_units){
527999449554SMatthias Ringwald     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
5280f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5281a1df452eSMatthias Ringwald     if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){
5282f5875de5SMatthias Ringwald         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
5283f5875de5SMatthias Ringwald     }
5284f5875de5SMatthias Ringwald     hci_stack->inquiry_state = duration_in_1280ms_units;
5285f5875de5SMatthias Ringwald     hci_run();
5286f5875de5SMatthias Ringwald     return 0;
5287f5875de5SMatthias Ringwald }
5288f5875de5SMatthias Ringwald 
5289f5875de5SMatthias Ringwald /**
5290f5875de5SMatthias Ringwald  * @brief Stop GAP Classic Inquiry
5291f5875de5SMatthias Ringwald  * @returns 0 if ok
5292f5875de5SMatthias Ringwald  */
5293f5875de5SMatthias Ringwald int gap_inquiry_stop(void){
5294a1df452eSMatthias Ringwald     if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) {
5295f5875de5SMatthias Ringwald         // emit inquiry complete event, before it even started
5296f5875de5SMatthias Ringwald         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
5297f5875de5SMatthias Ringwald         hci_emit_event(event, sizeof(event), 1);
5298f5875de5SMatthias Ringwald         return 0;
5299f5875de5SMatthias Ringwald     }
5300f5875de5SMatthias Ringwald     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
5301f5875de5SMatthias Ringwald     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
5302f5875de5SMatthias Ringwald     hci_run();
5303f5875de5SMatthias Ringwald     return 0;
5304f5875de5SMatthias Ringwald }
5305f5875de5SMatthias Ringwald 
5306b7f1ee76SMatthias Ringwald 
5307b7f1ee76SMatthias Ringwald /**
5308b7f1ee76SMatthias Ringwald  * @brief Remote Name Request
5309b7f1ee76SMatthias Ringwald  * @param addr
5310b7f1ee76SMatthias Ringwald  * @param page_scan_repetition_mode
5311b7f1ee76SMatthias Ringwald  * @param clock_offset only used when bit 15 is set
5312b7f1ee76SMatthias Ringwald  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
5313b7f1ee76SMatthias Ringwald  */
5314b7f1ee76SMatthias Ringwald int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
5315b7f1ee76SMatthias Ringwald     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
53166535961aSMatthias Ringwald     (void)memcpy(hci_stack->remote_name_addr, addr, 6);
5317b7f1ee76SMatthias Ringwald     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
5318b7f1ee76SMatthias Ringwald     hci_stack->remote_name_clock_offset = clock_offset;
5319b7f1ee76SMatthias Ringwald     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
5320b7f1ee76SMatthias Ringwald     hci_run();
5321b7f1ee76SMatthias Ringwald     return 0;
5322b7f1ee76SMatthias Ringwald }
5323b7f1ee76SMatthias Ringwald 
53240a51f88bSMatthias Ringwald static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
53250a51f88bSMatthias Ringwald     hci_stack->gap_pairing_state = state;
53266535961aSMatthias Ringwald     (void)memcpy(hci_stack->gap_pairing_addr, addr, 6);
53270a51f88bSMatthias Ringwald     hci_run();
53280a51f88bSMatthias Ringwald     return 0;
53290a51f88bSMatthias Ringwald }
53300a51f88bSMatthias Ringwald 
53310a51f88bSMatthias Ringwald /**
53320a51f88bSMatthias Ringwald  * @brief Legacy Pairing Pin Code Response
53330a51f88bSMatthias Ringwald  * @param addr
53340a51f88bSMatthias Ringwald  * @param pin
53350a51f88bSMatthias Ringwald  * @return 0 if ok
53360a51f88bSMatthias Ringwald  */
53370a51f88bSMatthias Ringwald int gap_pin_code_response(bd_addr_t addr, const char * pin){
5338cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5339d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
53400a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
53410a51f88bSMatthias Ringwald }
53420a51f88bSMatthias Ringwald 
53430a51f88bSMatthias Ringwald /**
53440a51f88bSMatthias Ringwald  * @brief Abort Legacy Pairing
53450a51f88bSMatthias Ringwald  * @param addr
53460a51f88bSMatthias Ringwald  * @param pin
53470a51f88bSMatthias Ringwald  * @return 0 if ok
53480a51f88bSMatthias Ringwald  */
53490a51f88bSMatthias Ringwald int gap_pin_code_negative(bd_addr_t addr){
5350cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
53510a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
53520a51f88bSMatthias Ringwald }
53530a51f88bSMatthias Ringwald 
53540a51f88bSMatthias Ringwald /**
53550a51f88bSMatthias Ringwald  * @brief SSP Passkey Response
53560a51f88bSMatthias Ringwald  * @param addr
53570a51f88bSMatthias Ringwald  * @param passkey
53580a51f88bSMatthias Ringwald  * @return 0 if ok
53590a51f88bSMatthias Ringwald  */
53600a51f88bSMatthias Ringwald int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
5361cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5362d504181aSMatthias Ringwald     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
53630a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
53640a51f88bSMatthias Ringwald }
53650a51f88bSMatthias Ringwald 
53660a51f88bSMatthias Ringwald /**
53670a51f88bSMatthias Ringwald  * @brief Abort SSP Passkey Entry/Pairing
53680a51f88bSMatthias Ringwald  * @param addr
53690a51f88bSMatthias Ringwald  * @param pin
53700a51f88bSMatthias Ringwald  * @return 0 if ok
53710a51f88bSMatthias Ringwald  */
53720a51f88bSMatthias Ringwald int gap_ssp_passkey_negative(bd_addr_t addr){
5373cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
53740a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
53750a51f88bSMatthias Ringwald }
53760a51f88bSMatthias Ringwald 
53770a51f88bSMatthias Ringwald /**
53780a51f88bSMatthias Ringwald  * @brief Accept SSP Numeric Comparison
53790a51f88bSMatthias Ringwald  * @param addr
53800a51f88bSMatthias Ringwald  * @param passkey
53810a51f88bSMatthias Ringwald  * @return 0 if ok
53820a51f88bSMatthias Ringwald  */
53830a51f88bSMatthias Ringwald int gap_ssp_confirmation_response(bd_addr_t addr){
5384cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
53850a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
53860a51f88bSMatthias Ringwald }
53870a51f88bSMatthias Ringwald 
53880a51f88bSMatthias Ringwald /**
53890a51f88bSMatthias Ringwald  * @brief Abort SSP Numeric Comparison/Pairing
53900a51f88bSMatthias Ringwald  * @param addr
53910a51f88bSMatthias Ringwald  * @param pin
53920a51f88bSMatthias Ringwald  * @return 0 if ok
53930a51f88bSMatthias Ringwald  */
53940a51f88bSMatthias Ringwald int gap_ssp_confirmation_negative(bd_addr_t addr){
5395cd74063aSMatthias Ringwald     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
53960a51f88bSMatthias Ringwald     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
53970a51f88bSMatthias Ringwald }
53980a51f88bSMatthias Ringwald 
5399f5875de5SMatthias Ringwald /**
5400f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
5401f5875de5SMatthias Ringwald  * @param inquiry_mode see bluetooth_defines.h
5402f6858d14SMatthias Ringwald  */
5403f6858d14SMatthias Ringwald void hci_set_inquiry_mode(inquiry_mode_t mode){
5404f6858d14SMatthias Ringwald     hci_stack->inquiry_mode = mode;
5405f6858d14SMatthias Ringwald }
5406f6858d14SMatthias Ringwald 
5407f6858d14SMatthias Ringwald /**
5408d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
5409d950d659SMatthias Ringwald  */
5410d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
5411d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
5412d950d659SMatthias Ringwald }
5413d950d659SMatthias Ringwald 
5414d950d659SMatthias Ringwald /**
5415d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
5416d950d659SMatthias Ringwald  * @return current voice setting
5417d950d659SMatthias Ringwald  */
54180cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
5419d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
5420d950d659SMatthias Ringwald }
5421d950d659SMatthias Ringwald 
5422400ff5abSMatthias Ringwald static int hci_have_usb_transport(void){
5423400ff5abSMatthias Ringwald     if (!hci_stack->hci_transport) return 0;
5424400ff5abSMatthias Ringwald     const char * transport_name = hci_stack->hci_transport->name;
5425400ff5abSMatthias Ringwald     if (!transport_name) return 0;
5426400ff5abSMatthias Ringwald     return (transport_name[0] == 'H') && (transport_name[1] == '2');
5427400ff5abSMatthias Ringwald }
5428400ff5abSMatthias Ringwald 
5429b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
5430b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
5431b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
5432b3aad8daSMatthias Ringwald  */
5433b3aad8daSMatthias Ringwald int hci_get_sco_packet_length(void){
5434a3069afeSMatthias Ringwald     int sco_packet_length = 0;
5435a3069afeSMatthias Ringwald 
5436a3069afeSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
5437cf119f3bSMatthias Ringwald 
54386f28d2eeSMatthias Ringwald     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
54396f28d2eeSMatthias Ringwald     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
5440cf119f3bSMatthias Ringwald 
5441400ff5abSMatthias Ringwald     if (hci_have_usb_transport()){
5442400ff5abSMatthias Ringwald         // see Core Spec for H2 USB Transfer.
5443cf119f3bSMatthias Ringwald         // 3 byte SCO header + 24 bytes per connection
544452e46257SMatthias Ringwald         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
544552e46257SMatthias Ringwald         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
5446400ff5abSMatthias Ringwald     } else {
5447400ff5abSMatthias Ringwald         // 3 byte SCO header + SCO packet size over the air (60 bytes)
5448400ff5abSMatthias Ringwald         sco_packet_length = 3 + 60 * multiplier;
5449d966a453SMatthias Ringwald         // assert that it still fits inside an SCO buffer
5450d966a453SMatthias Ringwald         if (sco_packet_length > hci_stack->sco_data_packet_length){
5451d966a453SMatthias Ringwald             sco_packet_length = 3 + 60;
5452d966a453SMatthias Ringwald         }
5453400ff5abSMatthias Ringwald     }
5454a3069afeSMatthias Ringwald #endif
5455a3069afeSMatthias Ringwald     return sco_packet_length;
5456b3aad8daSMatthias Ringwald }
5457b3aad8daSMatthias Ringwald 
5458c4c88f1bSJakob Krantz /**
5459c4c88f1bSJakob Krantz * @brief Sets the master/slave policy
5460c4c88f1bSJakob Krantz * @param policy (0: attempt to become master, 1: let connecting device decide)
5461c4c88f1bSJakob Krantz */
5462c4c88f1bSJakob Krantz void hci_set_master_slave_policy(uint8_t policy){
5463c4c88f1bSJakob Krantz     hci_stack->master_slave_policy = policy;
5464c4c88f1bSJakob Krantz }
5465c4c88f1bSJakob Krantz 
5466c4c88f1bSJakob Krantz #endif
5467ec111c8bSMatthias Ringwald 
5468ec111c8bSMatthias Ringwald HCI_STATE hci_get_state(void){
5469ec111c8bSMatthias Ringwald     return hci_stack->state;
5470ec111c8bSMatthias Ringwald }
5471ec111c8bSMatthias Ringwald 
547207e010b6SMilanka Ringwald #ifdef ENABLE_CLASSIC
547307e010b6SMilanka Ringwald void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr)){
547407e010b6SMilanka Ringwald     hci_stack->gap_classic_accept_callback = accept_callback;
547507e010b6SMilanka Ringwald }
547607e010b6SMilanka Ringwald #endif
5477ec111c8bSMatthias Ringwald 
5478d950d659SMatthias Ringwald /**
5479d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
5480d23838ecSMatthias Ringwald  */
5481c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
5482d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
5483d23838ecSMatthias Ringwald }
5484d23838ecSMatthias Ringwald 
548571de195eSMatthias Ringwald void hci_disconnect_all(void){
5486665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
5487665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5488665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5489665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
549004a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
549104a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
549204a6ef8cSmatthias.ringwald     }
5493d31fba26S[email protected]     hci_run();
549404a6ef8cSmatthias.ringwald }
549533373e40SMatthias Ringwald 
549633373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
549733373e40SMatthias Ringwald     return hci_stack->manufacturer;
549833373e40SMatthias Ringwald }
54999c6e867eSMatthias Ringwald 
55003e329ddfSandryblack #ifdef ENABLE_BLE
55013e329ddfSandryblack 
55029c6e867eSMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
55039c6e867eSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
55049c6e867eSMatthias Ringwald     if (!hci_con) return NULL;
55059c6e867eSMatthias Ringwald     return &hci_con->sm_connection;
55069c6e867eSMatthias Ringwald }
55079c6e867eSMatthias Ringwald 
55089c6e867eSMatthias Ringwald // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
55099c6e867eSMatthias Ringwald // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
55109c6e867eSMatthias Ringwald 
55119c6e867eSMatthias Ringwald int gap_encryption_key_size(hci_con_handle_t con_handle){
5512c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5513c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
5514c5fb5ca4SMatthias Ringwald     if (hci_is_le_connection(hci_connection)){
5515c5fb5ca4SMatthias Ringwald         sm_connection_t * sm_conn = &hci_connection->sm_connection;
5516c5fb5ca4SMatthias Ringwald         if (sm_conn->sm_connection_encrypted) {
55179c6e867eSMatthias Ringwald             return sm_conn->sm_actual_encryption_key_size;
55189c6e867eSMatthias Ringwald         }
5519c5fb5ca4SMatthias Ringwald     }
5520c5fb5ca4SMatthias Ringwald #ifdef ENABLE_CLASSIC
5521c5fb5ca4SMatthias Ringwald     else {
5522c5fb5ca4SMatthias Ringwald         if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){
5523c5fb5ca4SMatthias Ringwald             return hci_connection->encryption_key_size;
5524c5fb5ca4SMatthias Ringwald         }
5525c5fb5ca4SMatthias Ringwald     }
5526c5fb5ca4SMatthias Ringwald #endif
5527c5fb5ca4SMatthias Ringwald     return 0;
5528c5fb5ca4SMatthias Ringwald }
55299c6e867eSMatthias Ringwald 
55309c6e867eSMatthias Ringwald int gap_authenticated(hci_con_handle_t con_handle){
5531c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5532c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
55335f3981bfSMatthias Ringwald 
5534c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
55355f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
55365f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
5537c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
5538c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_authenticated;
553959a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
55405f3981bfSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
5541f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
5542c5fb5ca4SMatthias Ringwald             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
554359a1a47aSMatthias Ringwald #endif
55445f3981bfSMatthias Ringwald         default:
55455f3981bfSMatthias Ringwald             return 0;
55465f3981bfSMatthias Ringwald     }
55479c6e867eSMatthias Ringwald }
55489c6e867eSMatthias Ringwald 
5549f1dfbe18SMatthias Ringwald int gap_secure_connection(hci_con_handle_t con_handle){
5550c5fb5ca4SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5551c5fb5ca4SMatthias Ringwald     if (hci_connection == NULL) return 0;
55528b35e16aSMatthias Ringwald 
5553c5fb5ca4SMatthias Ringwald     switch (hci_connection->address_type){
55548b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
55558b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
5556c5fb5ca4SMatthias Ringwald             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
5557c5fb5ca4SMatthias Ringwald             return hci_connection->sm_connection.sm_connection_sc;
555859a1a47aSMatthias Ringwald #ifdef ENABLE_CLASSIC
55598b35e16aSMatthias Ringwald         case BD_ADDR_TYPE_SCO:
5560f16129ceSMatthias Ringwald         case BD_ADDR_TYPE_ACL:
5561c5fb5ca4SMatthias Ringwald             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
556259a1a47aSMatthias Ringwald #endif
55638b35e16aSMatthias Ringwald         default:
55648b35e16aSMatthias Ringwald             return 0;
55658b35e16aSMatthias Ringwald     }
5566f1dfbe18SMatthias Ringwald }
5567f1dfbe18SMatthias Ringwald 
55689c6e867eSMatthias Ringwald authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
55699c6e867eSMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
55709c6e867eSMatthias Ringwald     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
55719c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
55729c6e867eSMatthias Ringwald     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
55739c6e867eSMatthias Ringwald     return sm_conn->sm_connection_authorization_state;
55749c6e867eSMatthias Ringwald }
55759c6e867eSMatthias Ringwald #endif
5576f8ee3071SMatthias Ringwald 
5577f8ee3071SMatthias Ringwald #ifdef ENABLE_CLASSIC
5578f8ee3071SMatthias 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){
5579f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5580f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
5581f8ee3071SMatthias Ringwald     conn->sniff_min_interval = sniff_min_interval;
5582f8ee3071SMatthias Ringwald     conn->sniff_max_interval = sniff_max_interval;
5583f8ee3071SMatthias Ringwald     conn->sniff_attempt = sniff_attempt;
5584f8ee3071SMatthias Ringwald     conn->sniff_timeout = sniff_timeout;
5585f8ee3071SMatthias Ringwald     hci_run();
5586f8ee3071SMatthias Ringwald     return 0;
5587f8ee3071SMatthias Ringwald }
5588f8ee3071SMatthias Ringwald 
5589f8ee3071SMatthias Ringwald /**
5590f8ee3071SMatthias Ringwald  * @brief Exit Sniff mode
5591f8ee3071SMatthias Ringwald  * @param con_handle
5592f8ee3071SMatthias Ringwald  @ @return 0 if ok
5593f8ee3071SMatthias Ringwald  */
5594f8ee3071SMatthias Ringwald uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
5595f8ee3071SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5596f8ee3071SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
5597f8ee3071SMatthias Ringwald     conn->sniff_min_interval = 0xffff;
5598f8ee3071SMatthias Ringwald     hci_run();
5599f8ee3071SMatthias Ringwald     return 0;
5600f8ee3071SMatthias Ringwald }
5601f8ee3071SMatthias Ringwald #endif
5602beceeddeSMatthias Ringwald 
5603beceeddeSMatthias Ringwald void hci_halting_defer(void){
5604beceeddeSMatthias Ringwald     if (hci_stack->state != HCI_STATE_HALTING) return;
5605beceeddeSMatthias Ringwald     switch (hci_stack->substate){
5606beceeddeSMatthias Ringwald         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5607beceeddeSMatthias Ringwald         case HCI_HALTING_CLOSE:
5608beceeddeSMatthias Ringwald             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
5609beceeddeSMatthias Ringwald             break;
5610beceeddeSMatthias Ringwald         default:
5611beceeddeSMatthias Ringwald             break;
5612beceeddeSMatthias Ringwald     }
5613beceeddeSMatthias Ringwald }
5614eddac615SMatthias Ringwald 
5615eddac615SMatthias Ringwald #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
561618976c74SMatthias Ringwald void hci_setup_test_connections_fuzz(void){
561718976c74SMatthias Ringwald     hci_connection_t * conn;
561818976c74SMatthias Ringwald 
561918976c74SMatthias Ringwald     // default address: 66:55:44:33:00:01
562018976c74SMatthias Ringwald     bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00};
562118976c74SMatthias Ringwald 
56227d33cb26SMilanka Ringwald     // setup Controller info
56237d33cb26SMilanka Ringwald     hci_stack->num_cmd_packets = 255;
56247d33cb26SMilanka Ringwald     hci_stack->acl_packets_total_num = 255;
56257d33cb26SMilanka Ringwald 
562618976c74SMatthias Ringwald     // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01
562718976c74SMatthias Ringwald     addr[5] = 0x01;
562818976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
562918976c74SMatthias Ringwald     conn->con_handle = addr[5];
563018976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
563118976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
56327d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
563318976c74SMatthias Ringwald 
563418976c74SMatthias Ringwald     // setup incoming Classic SCO connection with con handle 0x0002
563518976c74SMatthias Ringwald     addr[5] = 0x02;
563618976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
563718976c74SMatthias Ringwald     conn->con_handle = addr[5];
563818976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
563918976c74SMatthias Ringwald     conn->state = RECEIVED_CONNECTION_REQUEST;
56407d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
564118976c74SMatthias Ringwald 
564218976c74SMatthias Ringwald     // setup ready Classic ACL connection with con handle 0x0003
564318976c74SMatthias Ringwald     addr[5] = 0x03;
564418976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
564518976c74SMatthias Ringwald     conn->con_handle = addr[5];
564618976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
564718976c74SMatthias Ringwald     conn->state = OPEN;
56487d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
564918976c74SMatthias Ringwald 
565018976c74SMatthias Ringwald     // setup ready Classic SCO connection with con handle 0x0004
565118976c74SMatthias Ringwald     addr[5] = 0x04;
565218976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
565318976c74SMatthias Ringwald     conn->con_handle = addr[5];
565418976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
565518976c74SMatthias Ringwald     conn->state = OPEN;
56567d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
565718976c74SMatthias Ringwald 
565818976c74SMatthias Ringwald     // setup ready LE ACL connection with con handle 0x005 and public address
565918976c74SMatthias Ringwald     addr[5] = 0x05;
566018976c74SMatthias Ringwald     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC);
566118976c74SMatthias Ringwald     conn->con_handle = addr[5];
566218976c74SMatthias Ringwald     conn->role  = HCI_ROLE_SLAVE;
566318976c74SMatthias Ringwald     conn->state = OPEN;
56647d33cb26SMilanka Ringwald     conn->sm_connection.sm_role = HCI_ROLE_SLAVE;
566518976c74SMatthias Ringwald }
566618976c74SMatthias Ringwald 
5667eddac615SMatthias Ringwald void hci_free_connections_fuzz(void){
5668eddac615SMatthias Ringwald     btstack_linked_list_iterator_t it;
5669eddac615SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5670eddac615SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
5671eddac615SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5672eddac615SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
5673eddac615SMatthias Ringwald         btstack_memory_hci_connection_free(con);
5674eddac615SMatthias Ringwald     }
5675eddac615SMatthias Ringwald }
56761470db0cSMatthias Ringwald void hci_simulate_working_fuzz(void){
56771470db0cSMatthias Ringwald     hci_init_done();
56781470db0cSMatthias Ringwald     hci_stack->num_cmd_packets = 255;
56791470db0cSMatthias Ringwald }
5680eddac615SMatthias Ringwald #endif
5681