xref: /btstack/src/hci.c (revision 429122cc1045c1a4046608040721680faa8dd579)
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 
381713bceaSmatthias.ringwald /*
391f504dbdSmatthias.ringwald  *  hci.c
401f504dbdSmatthias.ringwald  *
411f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
421f504dbdSmatthias.ringwald  *
431f504dbdSmatthias.ringwald  */
441f504dbdSmatthias.ringwald 
457907f069SMatthias Ringwald #include "btstack_config.h"
4628171530Smatthias.ringwald 
477f2435e6Smatthias.ringwald 
4806b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
49aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
508f2a52f4SMatthias Ringwald #include "btstack_run_loop_embedded.h"
51a484130cSMatthias Ringwald #endif
5206b9e820SMatthias Ringwald #endif
53a484130cSMatthias Ringwald 
544a3574a1SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
55d0b87befSMatthias Ringwald #include "../port/ios/src/btstack_control_iphone.h"
564a3574a1SMatthias Ringwald #endif
574a3574a1SMatthias Ringwald 
58a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
59472a5742SMatthias Ringwald #include "gap.h"
6045c102fdSMatthias Ringwald #endif
6145c102fdSMatthias Ringwald 
6293b8dc03Smatthias.ringwald #include <stdarg.h>
6393b8dc03Smatthias.ringwald #include <string.h>
6456fe0872Smatthias.ringwald #include <stdio.h>
655838a2edSMatthias Ringwald #include <inttypes.h>
667f2435e6Smatthias.ringwald 
6716ece135SMatthias Ringwald #include "btstack_debug.h"
680e2df43fSMatthias Ringwald #include "btstack_event.h"
694a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
704a3574a1SMatthias Ringwald #include "btstack_memory.h"
714a3574a1SMatthias Ringwald #include "gap.h"
724a3574a1SMatthias Ringwald #include "hci.h"
734a3574a1SMatthias Ringwald #include "hci_cmd.h"
74d8905019Smatthias.ringwald #include "hci_dump.h"
7593b8dc03Smatthias.ringwald 
761b0e3922Smatthias.ringwald 
77169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
78659d758cSMatthias Ringwald #define HCI_RESET_RESEND_TIMEOUT_MS 200
79ee091cf1Smatthias.ringwald 
80b83d5eabSMatthias Ringwald // prototypes
8135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
82758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
8335454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled);
8435454696SMatthias Ringwald static int  hci_local_ssp_activated(void);
8535454696SMatthias Ringwald static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
8635454696SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
8735454696SMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
88a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
8935454696SMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
90ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
9196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
9252db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
9352db98b2SMatthias Ringwald #endif
947586ee35S[email protected] static int  hci_power_control_on(void);
957586ee35S[email protected] static void hci_power_control_off(void);
966da48142SSean Wilson static void hci_state_reset(void);
97fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
98b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
99b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
100b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
101b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
102b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
10395d71764SMatthias Ringwald static void hci_run(void);
10495d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
10595d71764SMatthias Ringwald static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
1065d509858SMatthias Ringwald 
107a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
108e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
10939677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
11039677e66SMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, int size);
11142ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
1125d509858SMatthias Ringwald #endif
113d70217a2SMatthias Ringwald #endif
114758b46ceSmatthias.ringwald 
11506b35ec0Smatthias.ringwald // the STACK is here
1163a9fb326S[email protected] #ifndef HAVE_MALLOC
1173a9fb326S[email protected] static hci_stack_t   hci_stack_static;
1183a9fb326S[email protected] #endif
1193a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
12016833f0aSmatthias.ringwald 
1211c9e5e9dSMatthias Ringwald #ifdef ENABLE_CLASSIC
12266fb9560S[email protected] // test helper
12366fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
1241c9e5e9dSMatthias Ringwald #endif
12566fb9560S[email protected] 
12696a45072S[email protected] /**
12796a45072S[email protected]  * create connection for given address
12896a45072S[email protected]  *
12996a45072S[email protected]  * @return connection OR NULL, if no memory left
13096a45072S[email protected]  */
13196a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
1321a06f663S[email protected]     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
133bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
13496a45072S[email protected]     if (!conn) return NULL;
135c91d150bS[email protected]     memset(conn, 0, sizeof(hci_connection_t));
136058e3d6bSMatthias Ringwald     bd_addr_copy(conn->address, addr);
13796a45072S[email protected]     conn->address_type = addr_type;
13896a45072S[email protected]     conn->con_handle = 0xffff;
13996a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
14096a45072S[email protected]     conn->bonding_flags = 0;
14196a45072S[email protected]     conn->requested_security_level = LEVEL_0;
14252db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
14391a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
14491a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
14596a45072S[email protected]     hci_connection_timestamp(conn);
14652db98b2SMatthias Ringwald #endif
14796a45072S[email protected]     conn->acl_recombination_length = 0;
14896a45072S[email protected]     conn->acl_recombination_pos = 0;
14996a45072S[email protected]     conn->num_acl_packets_sent = 0;
1501a06f663S[email protected]     conn->num_sco_packets_sent = 0;
151da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
152665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
15396a45072S[email protected]     return conn;
15496a45072S[email protected] }
15566fb9560S[email protected] 
156da886c03S[email protected] 
157da886c03S[email protected] /**
158da886c03S[email protected]  * get le connection parameter range
159da886c03S[email protected] *
160da886c03S[email protected]  * @return le connection parameter range struct
161da886c03S[email protected]  */
1624ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
1634ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
164da886c03S[email protected] }
165da886c03S[email protected] 
166da886c03S[email protected] /**
167da886c03S[email protected]  * set le connection parameter range
168da886c03S[email protected]  *
169da886c03S[email protected]  */
170da886c03S[email protected] 
1714ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
1724ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
173da886c03S[email protected] }
174da886c03S[email protected] 
175da886c03S[email protected] /**
176da886c03S[email protected]  * get hci connections iterator
177da886c03S[email protected]  *
178da886c03S[email protected]  * @return hci connections iterator
179da886c03S[email protected]  */
180da886c03S[email protected] 
181665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
182665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
183da886c03S[email protected] }
184da886c03S[email protected] 
18597addcc5Smatthias.ringwald /**
186ee091cf1Smatthias.ringwald  * get connection for a given handle
187ee091cf1Smatthias.ringwald  *
188ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
189ee091cf1Smatthias.ringwald  */
1905061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
191665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
192665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
193665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
194665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1953ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
196da886c03S[email protected]             return item;
197ee091cf1Smatthias.ringwald         }
198ee091cf1Smatthias.ringwald     }
199ee091cf1Smatthias.ringwald     return NULL;
200ee091cf1Smatthias.ringwald }
201ee091cf1Smatthias.ringwald 
20296a45072S[email protected] /**
20396a45072S[email protected]  * get connection for given address
20496a45072S[email protected]  *
20596a45072S[email protected]  * @return connection OR NULL, if not found
20696a45072S[email protected]  */
2072e77e513S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
208665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
209665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
210665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
211665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21296a45072S[email protected]         if (connection->address_type != addr_type)  continue;
21396a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
21462bda3fbS[email protected]         return connection;
21562bda3fbS[email protected]     }
21662bda3fbS[email protected]     return NULL;
21762bda3fbS[email protected] }
21862bda3fbS[email protected] 
21952db98b2SMatthias Ringwald 
22052db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
22152db98b2SMatthias Ringwald 
222ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
223ee752bb8SMatthias Ringwald static int hci_number_sco_connections(void){
224ee752bb8SMatthias Ringwald     int connections = 0;
225ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_t it;
226ee752bb8SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
227ee752bb8SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
228ee752bb8SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
229ee752bb8SMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
230ee752bb8SMatthias Ringwald         connections++;
231ee752bb8SMatthias Ringwald     }
232ee752bb8SMatthias Ringwald     return connections;
233ee752bb8SMatthias Ringwald }
234ee752bb8SMatthias Ringwald #endif
235ee752bb8SMatthias Ringwald 
236ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
23791a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
238aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
239528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
240c785ef68Smatthias.ringwald         // connections might be timed out
241c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
242c785ef68Smatthias.ringwald     }
243f316a845SMatthias Ringwald #else
244528a4a3bSMatthias Ringwald     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
2455f26aadcSMatthias Ringwald         // connections might be timed out
2465f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
2475f26aadcSMatthias Ringwald     }
2485f26aadcSMatthias Ringwald #endif
249c785ef68Smatthias.ringwald }
250ee091cf1Smatthias.ringwald 
251ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
252aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
253528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
254f316a845SMatthias Ringwald #else
255528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
2565f26aadcSMatthias Ringwald #endif
257ee091cf1Smatthias.ringwald }
258ee091cf1Smatthias.ringwald 
25928ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
26028ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
26128ca2b46S[email protected] }
26228ca2b46S[email protected] 
26335454696SMatthias Ringwald 
26428ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
26528ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
26628ca2b46S[email protected] }
26728ca2b46S[email protected] 
26843bfb1bdSmatthias.ringwald /**
26980ca58a0Smatthias.ringwald  * add authentication flags and reset timer
27096a45072S[email protected]  * @note: assumes classic connection
2712e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
2727fde4af9Smatthias.ringwald  */
2737fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
2747fde4af9Smatthias.ringwald     bd_addr_t addr;
275724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
2762e77e513S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2777fde4af9Smatthias.ringwald     if (conn) {
27828ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
27980ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
2807fde4af9Smatthias.ringwald     }
2817fde4af9Smatthias.ringwald }
2827fde4af9Smatthias.ringwald 
28380ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
2845061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
28580ca58a0Smatthias.ringwald     if (!conn) return 0;
2866724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2876724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2886724cd9eS[email protected]     return 0;
28980ca58a0Smatthias.ringwald }
29080ca58a0Smatthias.ringwald 
29115a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
29255597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
2932bacf595SMatthias Ringwald     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
294a98592bcSMatthias Ringwald     hci_stack->link_key_db->delete_link_key(addr);
295c12e46e7Smatthias.ringwald }
29655597469SMatthias Ringwald 
29755597469SMatthias Ringwald void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
29855597469SMatthias Ringwald     if (!hci_stack->link_key_db) return;
2992bacf595SMatthias Ringwald     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
30055597469SMatthias Ringwald     hci_stack->link_key_db->put_link_key(addr, link_key, type);
301c12e46e7Smatthias.ringwald }
30235454696SMatthias Ringwald #endif
303c12e46e7Smatthias.ringwald 
30495d71764SMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
3050bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
3060bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
3070bf6344aS[email protected] }
3080bf6344aS[email protected] 
3097fde4af9Smatthias.ringwald /**
31043bfb1bdSmatthias.ringwald  * count connections
31143bfb1bdSmatthias.ringwald  */
31240d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
31356c253c9Smatthias.ringwald     int count = 0;
314665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
315665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
31643bfb1bdSmatthias.ringwald     return count;
31743bfb1bdSmatthias.ringwald }
318c8e4258aSmatthias.ringwald 
31995d71764SMatthias Ringwald static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
320ee303eddS[email protected] 
321f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_classic = 0;
322f04a0c31SMatthias Ringwald     unsigned int num_packets_sent_le = 0;
323ee303eddS[email protected] 
324665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
325665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
326998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
327ee303eddS[email protected]         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
328ee303eddS[email protected]             num_packets_sent_classic += connection->num_acl_packets_sent;
329ee303eddS[email protected]         } else {
330ee303eddS[email protected]             num_packets_sent_le += connection->num_acl_packets_sent;
331ee303eddS[email protected]         }
332ee303eddS[email protected]     }
333d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
334ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
335ee303eddS[email protected]     int free_slots_le = 0;
336ee303eddS[email protected] 
337ee303eddS[email protected]     if (free_slots_classic < 0){
3389da54300S[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);
339998906cdSmatthias.ringwald         return 0;
340998906cdSmatthias.ringwald     }
341ee303eddS[email protected] 
342ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
343ee303eddS[email protected]         // if we have LE slots, they are used
344ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
345ee303eddS[email protected]         if (free_slots_le < 0){
3469da54300S[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);
347ee303eddS[email protected]             return 0;
348998906cdSmatthias.ringwald         }
349ee303eddS[email protected]     } else {
350ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
351ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
352ee303eddS[email protected]         if (free_slots_classic < 0){
3539da54300S[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);
354ee303eddS[email protected]             return 0;
355ee303eddS[email protected]         }
356ee303eddS[email protected]     }
357ee303eddS[email protected] 
358ee303eddS[email protected]     switch (address_type){
359ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
3602125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
361ee303eddS[email protected]             return 0;
362ee303eddS[email protected] 
363ee303eddS[email protected]         case BD_ADDR_TYPE_CLASSIC:
364ee303eddS[email protected]             return free_slots_classic;
365ee303eddS[email protected] 
366ee303eddS[email protected]         default:
367cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
368ee303eddS[email protected]                return free_slots_le;
369ee303eddS[email protected]            }
370cb00d3aaS[email protected]            return free_slots_classic;
371cb00d3aaS[email protected]     }
372998906cdSmatthias.ringwald }
373998906cdSmatthias.ringwald 
3742125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
3752125de09SMatthias Ringwald     // get connection type
3762125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3772125de09SMatthias Ringwald     if (!connection){
3782125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
3792125de09SMatthias Ringwald         return 0;
3802125de09SMatthias Ringwald     }
3812125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
3822125de09SMatthias Ringwald }
3832125de09SMatthias Ringwald 
38435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
385701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
386f04a0c31SMatthias Ringwald     unsigned int num_sco_packets_sent  = 0;
387665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
388665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
389e35edcc1S[email protected]         hci_connection_t * connection = (hci_connection_t *) it;
390e35edcc1S[email protected]         num_sco_packets_sent += connection->num_sco_packets_sent;
391e35edcc1S[email protected]     }
392e35edcc1S[email protected]     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
393701e3307SMatthias Ringwald         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
39444d0e3d5S[email protected]         return 0;
39544d0e3d5S[email protected]     }
396701e3307SMatthias Ringwald     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
397e35edcc1S[email protected]     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
398e35edcc1S[email protected] }
39935454696SMatthias Ringwald #endif
40044d0e3d5S[email protected] 
401ac928cc2S[email protected] // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
402ac928cc2S[email protected] int hci_can_send_command_packet_now(void){
403ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
404ac928cc2S[email protected] 
405ac928cc2S[email protected]     // check for async hci transport implementations
406ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
407ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
408ac928cc2S[email protected]             return 0;
409ac928cc2S[email protected]         }
410ac928cc2S[email protected]     }
411ac928cc2S[email protected] 
412ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
413ac928cc2S[email protected] }
414ac928cc2S[email protected] 
4159d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
416ac928cc2S[email protected]     // check for async hci transport implementations
4179d04d3a7SMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
4189d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
419ac928cc2S[email protected] }
4209d04d3a7SMatthias Ringwald 
4219d04d3a7SMatthias Ringwald static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
4229d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
4239d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
424ac928cc2S[email protected] }
4259d04d3a7SMatthias Ringwald 
4269d04d3a7SMatthias Ringwald int hci_can_send_acl_le_packet_now(void){
4279d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
4289d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
4299d04d3a7SMatthias Ringwald }
4309d04d3a7SMatthias Ringwald 
4319d04d3a7SMatthias Ringwald int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
4329d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
433e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
434ac928cc2S[email protected] }
435ac928cc2S[email protected] 
436ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
437ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
438ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
4396b4af23dS[email protected] }
4406b4af23dS[email protected] 
44135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
44235454696SMatthias Ringwald int hci_can_send_acl_classic_packet_now(void){
44335454696SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
44435454696SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
44535454696SMatthias Ringwald }
44635454696SMatthias Ringwald 
447701e3307SMatthias Ringwald int hci_can_send_prepared_sco_packet_now(void){
448d057580eSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
449ed361f5fSMatthias Ringwald     if (!hci_stack->synchronous_flow_control_enabled) return 1;
450701e3307SMatthias Ringwald     return hci_number_free_sco_slots() > 0;
45144d0e3d5S[email protected] }
45244d0e3d5S[email protected] 
453701e3307SMatthias Ringwald int hci_can_send_sco_packet_now(void){
454d057580eSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
455701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
45644d0e3d5S[email protected] }
45744d0e3d5S[email protected] 
458d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
459d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
460d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
461d057580eSMatthias Ringwald }
46235454696SMatthias Ringwald #endif
463d057580eSMatthias Ringwald 
46495d71764SMatthias Ringwald // used for internal checks in l2cap.c
465c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
466c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
467c8b9416aS[email protected] }
468c8b9416aS[email protected] 
4696b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
4706b4af23dS[email protected] int hci_reserve_packet_buffer(void){
4719d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
4729d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
4739d14b626S[email protected]         return 0;
4749d14b626S[email protected]     }
4756b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
4766b4af23dS[email protected]     return 1;
4776b4af23dS[email protected] }
4786b4af23dS[email protected] 
47968a0fcf7S[email protected] void hci_release_packet_buffer(void){
48068a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
48168a0fcf7S[email protected] }
48268a0fcf7S[email protected] 
4836b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
4847f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
4856b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
4866b4af23dS[email protected] }
4876b4af23dS[email protected] 
488452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
489452cf3bbS[email protected] 
490452cf3bbS[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);
491452cf3bbS[email protected] 
492452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
493452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
494452cf3bbS[email protected]     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
495452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
496452cf3bbS[email protected]     }
497452cf3bbS[email protected] 
498452cf3bbS[email protected]     // testing: reduce buffer to minimum
499452cf3bbS[email protected]     // max_acl_data_packet_length = 52;
500452cf3bbS[email protected] 
501d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
502d999b54eSMatthias Ringwald 
503452cf3bbS[email protected]     int err;
504452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
505452cf3bbS[email protected]     while (1){
506452cf3bbS[email protected] 
507d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
508d999b54eSMatthias Ringwald 
509452cf3bbS[email protected]         // get current data
510452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
511452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
512452cf3bbS[email protected]         int more_fragments = 0;
513452cf3bbS[email protected] 
514452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
515452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
516452cf3bbS[email protected]             more_fragments = 1;
517452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
518452cf3bbS[email protected]         }
519452cf3bbS[email protected] 
520452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
521452cf3bbS[email protected]         if (acl_header_pos > 0){
522f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
523452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
524f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
525452cf3bbS[email protected]         }
526452cf3bbS[email protected] 
527452cf3bbS[email protected]         // update header len
528f8fbdce0SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
529452cf3bbS[email protected] 
530452cf3bbS[email protected]         // count packet
531452cf3bbS[email protected]         connection->num_acl_packets_sent++;
532f04a0c31SMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
533d999b54eSMatthias Ringwald 
534d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
535d999b54eSMatthias Ringwald         if (more_fragments){
536d999b54eSMatthias Ringwald             // update start of next fragment to send
537d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
538d999b54eSMatthias Ringwald         } else {
539d999b54eSMatthias Ringwald             // done
540d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
541d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
542d999b54eSMatthias Ringwald         }
543452cf3bbS[email protected] 
544452cf3bbS[email protected]         // send packet
545452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
546452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
5475bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
548452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
549452cf3bbS[email protected] 
550f04a0c31SMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
551d999b54eSMatthias Ringwald 
552452cf3bbS[email protected]         // done yet?
553452cf3bbS[email protected]         if (!more_fragments) break;
554452cf3bbS[email protected] 
555452cf3bbS[email protected]         // can send more?
556452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
557452cf3bbS[email protected]     }
558452cf3bbS[email protected] 
559d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
560452cf3bbS[email protected] 
561d051460cS[email protected]     // release buffer now for synchronous transport
562203bace6S[email protected]     if (hci_transport_synchronous()){
563452cf3bbS[email protected]         hci_release_packet_buffer();
56463fa3374SMatthias Ringwald         // notify upper stack that it might be possible to send again
56563fa3374SMatthias Ringwald         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
566d6b06661SMatthias Ringwald         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
567452cf3bbS[email protected]     }
568452cf3bbS[email protected] 
569452cf3bbS[email protected]     return err;
570452cf3bbS[email protected] }
571452cf3bbS[email protected] 
572826f7347S[email protected] // pre: caller has reserved the packet buffer
573826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
5747856c818Smatthias.ringwald 
575452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
576452cf3bbS[email protected] 
577826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
578826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
579826f7347S[email protected]         return 0;
580826f7347S[email protected]     }
581826f7347S[email protected] 
582d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
583d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
584d713a683S[email protected] 
585826f7347S[email protected]     // check for free places on Bluetooth module
586d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
587826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
58897b61c7bS[email protected]         hci_release_packet_buffer();
58997b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
59097b61c7bS[email protected]     }
5916218e6f1Smatthias.ringwald 
5925061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
59397b61c7bS[email protected]     if (!connection) {
5945fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
59597b61c7bS[email protected]         hci_release_packet_buffer();
59697b61c7bS[email protected]         return 0;
59797b61c7bS[email protected]     }
59852db98b2SMatthias Ringwald 
59952db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
60056cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
60152db98b2SMatthias Ringwald #endif
60256cf178bSmatthias.ringwald 
603452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
6047856c818Smatthias.ringwald 
605452cf3bbS[email protected]     // setup data
606452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
607452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
6086218e6f1Smatthias.ringwald 
609452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
610ee091cf1Smatthias.ringwald }
611ee091cf1Smatthias.ringwald 
61235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
61344d0e3d5S[email protected] // pre: caller has reserved the packet buffer
61444d0e3d5S[email protected] int hci_send_sco_packet_buffer(int size){
61544d0e3d5S[email protected] 
61644d0e3d5S[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
61744d0e3d5S[email protected] 
61844d0e3d5S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
61944d0e3d5S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
62044d0e3d5S[email protected]         return 0;
62144d0e3d5S[email protected]     }
62244d0e3d5S[email protected] 
62344d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
6244b3e1e19SMatthias Ringwald 
6254b3e1e19SMatthias Ringwald     // skip checks in loopback mode
6264b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
62744d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
62844d0e3d5S[email protected] 
62944d0e3d5S[email protected]         // check for free places on Bluetooth module
630701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
63144d0e3d5S[email protected]             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
63244d0e3d5S[email protected]             hci_release_packet_buffer();
63344d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
63444d0e3d5S[email protected]         }
63544d0e3d5S[email protected] 
636e35edcc1S[email protected]         // track send packet in connection struct
637e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
638e35edcc1S[email protected]         if (!connection) {
639e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
640e35edcc1S[email protected]             hci_release_packet_buffer();
641e35edcc1S[email protected]             return 0;
642e35edcc1S[email protected]         }
643e35edcc1S[email protected]         connection->num_sco_packets_sent++;
6444b3e1e19SMatthias Ringwald     }
64544d0e3d5S[email protected] 
64644d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
647543e835cSMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
648543e835cSMatthias Ringwald 
649543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
650543e835cSMatthias Ringwald         hci_release_packet_buffer();
65163fa3374SMatthias Ringwald         // notify upper stack that it might be possible to send again
65263fa3374SMatthias Ringwald         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
653d6b06661SMatthias Ringwald         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
654543e835cSMatthias Ringwald     }
655543e835cSMatthias Ringwald 
656543e835cSMatthias Ringwald     return err;
65744d0e3d5S[email protected] }
65835454696SMatthias Ringwald #endif
65944d0e3d5S[email protected] 
66016833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
6617856c818Smatthias.ringwald 
662e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
663e76a89eeS[email protected] 
6647856c818Smatthias.ringwald     // get info
6657856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
6665061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
6677856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
6687856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
6697856c818Smatthias.ringwald 
6707856c818Smatthias.ringwald     // ignore non-registered handle
6717856c818Smatthias.ringwald     if (!conn){
6729da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
6737856c818Smatthias.ringwald         return;
6747856c818Smatthias.ringwald     }
6757856c818Smatthias.ringwald 
676e76a89eeS[email protected]     // assert packet is complete
6779ecc3e17S[email protected]     if (acl_length + 4 != size){
678f04a0c31SMatthias Ringwald         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
679e76a89eeS[email protected]         return;
680e76a89eeS[email protected]     }
681e76a89eeS[email protected] 
68252db98b2SMatthias Ringwald #ifdef ENABLE_CLASSIC
6837856c818Smatthias.ringwald     // update idle timestamp
6847856c818Smatthias.ringwald     hci_connection_timestamp(conn);
68552db98b2SMatthias Ringwald #endif
6867856c818Smatthias.ringwald 
6877856c818Smatthias.ringwald     // handle different packet types
6887856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
6897856c818Smatthias.ringwald 
6907856c818Smatthias.ringwald         case 0x01: // continuation fragment
6917856c818Smatthias.ringwald 
6920ca847afS[email protected]             // sanity checks
6937856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
6949da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
6957856c818Smatthias.ringwald                 return;
6967856c818Smatthias.ringwald             }
6970ca847afS[email protected]             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
6980ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
6990ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
7000ca847afS[email protected]                 conn->acl_recombination_pos = 0;
7010ca847afS[email protected]                 return;
7020ca847afS[email protected]             }
7037856c818Smatthias.ringwald 
7047856c818Smatthias.ringwald             // append fragment payload (header already stored)
705ec6321eeS[email protected]             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
7067856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
7077856c818Smatthias.ringwald 
7089da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
709decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
7107856c818Smatthias.ringwald 
7117856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
7127856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
713d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
7147856c818Smatthias.ringwald                 // reset recombination buffer
7157856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
7167856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
7177856c818Smatthias.ringwald             }
7187856c818Smatthias.ringwald             break;
7197856c818Smatthias.ringwald 
7207856c818Smatthias.ringwald         case 0x02: { // first fragment
7217856c818Smatthias.ringwald 
72223a77e1aS[email protected]             // sanity check
72323a77e1aS[email protected]             if (conn->acl_recombination_pos) {
72423a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
72523a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
72623a77e1aS[email protected]             }
72723a77e1aS[email protected] 
7287856c818Smatthias.ringwald             // peek into L2CAP packet!
7297856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
7307856c818Smatthias.ringwald 
7319da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
732decc01a8Smatthias.ringwald 
7337856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
7347856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
7357856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
736d6b06661SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4);
7377856c818Smatthias.ringwald             } else {
7380ca847afS[email protected] 
7390ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
7400ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
7410ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
7420ca847afS[email protected]                     return;
7430ca847afS[email protected]                 }
7440ca847afS[email protected] 
7457856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
746ec6321eeS[email protected]                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
7477856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
7487856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
749f8fbdce0SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
7507856c818Smatthias.ringwald             }
7517856c818Smatthias.ringwald             break;
7527856c818Smatthias.ringwald 
7537856c818Smatthias.ringwald         }
7547856c818Smatthias.ringwald         default:
7559da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
7567856c818Smatthias.ringwald             return;
7577856c818Smatthias.ringwald     }
75894ab26f8Smatthias.ringwald 
75994ab26f8Smatthias.ringwald     // execute main loop
76094ab26f8Smatthias.ringwald     hci_run();
76116833f0aSmatthias.ringwald }
76222909952Smatthias.ringwald 
76367a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
7649da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
7653c4d4b90Smatthias.ringwald 
766ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
767ee752bb8SMatthias Ringwald     int addr_type = conn->address_type;
768ee752bb8SMatthias Ringwald #endif
769ee752bb8SMatthias Ringwald 
770528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
771c785ef68Smatthias.ringwald 
772665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
773a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
7743c4d4b90Smatthias.ringwald 
7753c4d4b90Smatthias.ringwald     // now it's gone
776c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
777ee752bb8SMatthias Ringwald 
778034e9b53SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
779ee752bb8SMatthias Ringwald     // update SCO
780ee752bb8SMatthias Ringwald     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
781ee752bb8SMatthias Ringwald         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
782ee752bb8SMatthias Ringwald     }
783034e9b53SMatthias Ringwald #endif
784c7e0c5f6Smatthias.ringwald }
785c7e0c5f6Smatthias.ringwald 
78635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
78735454696SMatthias Ringwald 
7880c042179S[email protected] static const uint16_t packet_type_sizes[] = {
7898f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
7908f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
7918f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
7928f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
7938f8108aaSmatthias.ringwald };
79465389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
79565389bfcS[email protected]      0, // 3 slot packets
79665389bfcS[email protected]      1, // 5 slot packets
79765389bfcS[email protected]     25, // EDR 2 mpbs
79865389bfcS[email protected]     26, // EDR 3 mbps
79965389bfcS[email protected]     39, // 3 slot EDR packts
80065389bfcS[email protected]     40, // 5 slot EDR packet
80165389bfcS[email protected] };
80265389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
80365389bfcS[email protected]     0x0f00, // 3 slot packets
80465389bfcS[email protected]     0xf000, // 5 slot packets
80565389bfcS[email protected]     0x1102, // EDR 2 mpbs
80665389bfcS[email protected]     0x2204, // EDR 3 mbps
80765389bfcS[email protected]     0x0300, // 3 slot EDR packts
80865389bfcS[email protected]     0x3000, // 5 slot EDR packet
80965389bfcS[email protected] };
8108f8108aaSmatthias.ringwald 
81165389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
81265389bfcS[email protected]     // enable packet types based on size
8138f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
814f16a69bbS[email protected]     unsigned int i;
8158f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
8168f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
8178f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
8188f8108aaSmatthias.ringwald             packet_types |= 1 << i;
8198f8108aaSmatthias.ringwald         }
8208f8108aaSmatthias.ringwald     }
82165389bfcS[email protected]     // disable packet types due to missing local supported features
82265389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
823f04a0c31SMatthias Ringwald         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
82465389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
82565389bfcS[email protected]         if (feature_set) continue;
82665389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
82765389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
82865389bfcS[email protected]     }
8298f8108aaSmatthias.ringwald     // flip bits for "may not be used"
8308f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
8318f8108aaSmatthias.ringwald     return packet_types;
8328f8108aaSmatthias.ringwald }
8338f8108aaSmatthias.ringwald 
8348f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
8353a9fb326S[email protected]     return hci_stack->packet_types;
8368f8108aaSmatthias.ringwald }
83735454696SMatthias Ringwald #endif
8388f8108aaSmatthias.ringwald 
839facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
8407dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
8413a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
8427dc17943Smatthias.ringwald }
8437dc17943Smatthias.ringwald 
844f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
8453a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
8467dc17943Smatthias.ringwald }
8477dc17943Smatthias.ringwald 
84806b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
8493e68d23dSMatthias Ringwald int hci_extended_sco_link_supported(void){
8503e68d23dSMatthias Ringwald     // No. 31, byte 3, bit 7
8513e68d23dSMatthias Ringwald     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
8523e68d23dSMatthias Ringwald }
85306b9e820SMatthias Ringwald #endif
8543e68d23dSMatthias Ringwald 
8556ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
8566ac9a97eS[email protected]     // No. 54, byte 6, bit 6
8576ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
8586ac9a97eS[email protected] }
8596ac9a97eS[email protected] 
86015a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
8616ac9a97eS[email protected]     // No. 51, byte 6, bit 3
8623a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
863f5d8d141S[email protected] }
864f5d8d141S[email protected] 
8657f02f414SMatthias Ringwald static int hci_classic_supported(void){
86635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
8676ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
8683a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
86935454696SMatthias Ringwald #else
87035454696SMatthias Ringwald     return 0;
87135454696SMatthias Ringwald #endif
872f5d8d141S[email protected] }
873f5d8d141S[email protected] 
8747f02f414SMatthias Ringwald static int hci_le_supported(void){
875a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
8766ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
8773a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
878f5d8d141S[email protected] #else
879f5d8d141S[email protected]     return 0;
880f5d8d141S[email protected] #endif
881f5d8d141S[email protected] }
882f5d8d141S[email protected] 
883b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
884b95a5a35SMatthias Ringwald 
885b95a5a35SMatthias Ringwald /**
886b95a5a35SMatthias Ringwald  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
887b95a5a35SMatthias Ringwald  */
888b95a5a35SMatthias Ringwald void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
889b95a5a35SMatthias Ringwald     *addr_type = hci_stack->le_own_addr_type;
890b95a5a35SMatthias Ringwald     if (hci_stack->le_own_addr_type){
891b95a5a35SMatthias Ringwald         memcpy(addr, hci_stack->le_random_address, 6);
89269a97523S[email protected]     } else {
8933a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
89469a97523S[email protected]     }
89569a97523S[email protected] }
89669a97523S[email protected] 
897e8c8828eSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
89839677e66SMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, int size){
8999ec2630cSMatthias Ringwald 
9009ec2630cSMatthias Ringwald     UNUSED(size);
9019ec2630cSMatthias Ringwald 
902d1dc057bS[email protected]     int offset = 3;
903d1dc057bS[email protected]     int num_reports = packet[offset];
904d1dc057bS[email protected]     offset += 1;
905d1dc057bS[email protected] 
90657c9da5bS[email protected]     int i;
9074f4e0224SMatthias Ringwald     // log_info("HCI: handle adv report with num reports: %d", num_reports);
90803fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
90957c9da5bS[email protected]     for (i=0; i<num_reports;i++){
910210c6774S[email protected]         uint8_t data_length = packet[offset + 8];
911a0aac9c4S[email protected]         uint8_t event_size = 10 + data_length;
912d1dc057bS[email protected]         int pos = 0;
913045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
91457c9da5bS[email protected]         event[pos++] = event_size;
915210c6774S[email protected]         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
916d1dc057bS[email protected]         offset += 8;
917d1dc057bS[email protected]         pos += 8;
918d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
919d1dc057bS[email protected]         event[pos++] = packet[offset++]; //data_length;
920d1dc057bS[email protected]         memcpy(&event[pos], &packet[offset], data_length);
92157c9da5bS[email protected]         pos += data_length;
922d1dc057bS[email protected]         offset += data_length + 1; // rssi
923d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
92457c9da5bS[email protected]     }
92557c9da5bS[email protected] }
926b2f949feS[email protected] #endif
927e8c8828eSMatthias Ringwald #endif
92857c9da5bS[email protected] 
929cd77dd38SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
93006b9e820SMatthias Ringwald 
93196b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
93296b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
9339796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
93496b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
935c6d1dbedSMatthias Ringwald     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
93696b53536SMatthias Ringwald         baud_rate = 3000000;
93796b53536SMatthias Ringwald     }
93896b53536SMatthias Ringwald     return baud_rate;
93996b53536SMatthias Ringwald }
94096b53536SMatthias Ringwald 
941ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
9429ec2630cSMatthias Ringwald     UNUSED(ds);
9439ec2630cSMatthias Ringwald 
9440305bdeaSMatthias Ringwald     switch (hci_stack->substate){
9450305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
9467b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
9470305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
9487b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
9490305bdeaSMatthias Ringwald             hci_run();
9500305bdeaSMatthias Ringwald             break;
9519f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
9529f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
9539f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
9549f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
9559f007422SMatthias Ringwald             }
956202c8a4cSMatthias Ringwald             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
957e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
958e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
959e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
960e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
961e47e68c7SMatthias Ringwald             hci_run();
962688c2635SMatthias Ringwald             break;
9637224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
9647224be7eSMatthias Ringwald             if (hci_stack->hci_transport->set_baudrate){
96596b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
966cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
9677dd9d0ecSMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
9687224be7eSMatthias Ringwald             }
969772a36d3SMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate
9702caefae9SMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
971772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
972772a36d3SMatthias Ringwald                 hci_run();
973772a36d3SMatthias Ringwald             }
9744696bddbSMatthias Ringwald             break;
975559961d0SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
976559961d0SMatthias Ringwald             // otherwise continue
977559961d0SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
978559961d0SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
979559961d0SMatthias Ringwald             break;
9800305bdeaSMatthias Ringwald         default:
9810305bdeaSMatthias Ringwald             break;
9820305bdeaSMatthias Ringwald     }
9830305bdeaSMatthias Ringwald }
98406b9e820SMatthias Ringwald #endif
9850305bdeaSMatthias Ringwald 
98671de195eSMatthias Ringwald static void hci_initializing_next_state(void){
98774b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
98874b323a9SMatthias Ringwald }
98974b323a9SMatthias Ringwald 
99074b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
99171de195eSMatthias Ringwald static void hci_initializing_run(void){
992148ca237SMatthias Ringwald     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
99374b323a9SMatthias Ringwald     switch (hci_stack->substate){
99474b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
99574b323a9SMatthias Ringwald             hci_state_reset();
996a0cf2f3fSMatthias Ringwald 
99706b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
9980305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
999659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1000528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1001528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1002a0cf2f3fSMatthias Ringwald #endif
10030305bdeaSMatthias Ringwald             // send command
100474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
10050305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
100674b323a9SMatthias Ringwald             break;
100776fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
100876fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
100976fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
101076fcb19bSMatthias Ringwald             break;
1011e90bae01SMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_NAME:
1012e90bae01SMatthias Ringwald             hci_send_cmd(&hci_read_local_name);
1013e90bae01SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1014e90bae01SMatthias Ringwald             break;
101506b9e820SMatthias Ringwald 
101606b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1017e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1018e47e68c7SMatthias Ringwald             hci_state_reset();
1019e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
1020659d758cSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1021528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1022528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
1023e47e68c7SMatthias Ringwald             // send command
1024e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1025e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
1026e47e68c7SMatthias Ringwald             break;
10278d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
10288d29070eSMatthias Ringwald             hci_state_reset();
10298d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
10308d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
10318d29070eSMatthias Ringwald             break;
1032fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE: {
103396b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
10343fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1035f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
103674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
10370305bdeaSMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
10384696bddbSMatthias Ringwald             // STLC25000D: baudrate change happens within 0.5 s after command was send,
10394696bddbSMatthias Ringwald             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1040c6d1dbedSMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1041659d758cSMatthias Ringwald                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1042528a4a3bSMatthias Ringwald                 btstack_run_loop_add_timer(&hci_stack->timeout);
10434696bddbSMatthias Ringwald             }
104474b323a9SMatthias Ringwald             break;
1045fab26ab3SMatthias Ringwald         }
1046fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
104796b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
10483fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1049f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1050eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1051eb3a5314SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1052eb3a5314SMatthias Ringwald             break;
1053fab26ab3SMatthias Ringwald         }
105474b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
105574b323a9SMatthias Ringwald             // Custom initialization
10563fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
10573fb36a29SMatthias Ringwald                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
105874b323a9SMatthias Ringwald                 if (valid_cmd){
105974b323a9SMatthias Ringwald                     int size = 3 + hci_stack->hci_packet_buffer[2];
1060f8fbdce0SMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
106174b323a9SMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1062e47e68c7SMatthias Ringwald                     switch (valid_cmd) {
1063e47e68c7SMatthias Ringwald                         case 1:
1064e47e68c7SMatthias Ringwald                         default:
1065e47e68c7SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1066e47e68c7SMatthias Ringwald                             break;
1067e47e68c7SMatthias Ringwald                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1068e47e68c7SMatthias Ringwald                             log_info("CSR Warm Boot");
1069659d758cSMatthias Ringwald                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1070528a4a3bSMatthias Ringwald                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1071528a4a3bSMatthias Ringwald                             btstack_run_loop_add_timer(&hci_stack->timeout);
10722caefae9SMatthias Ringwald                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1073772a36d3SMatthias Ringwald                                 && hci_stack->config
10743fb36a29SMatthias Ringwald                                 && hci_stack->chipset
10753fb36a29SMatthias Ringwald                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1076772a36d3SMatthias Ringwald                                 && hci_stack->hci_transport->set_baudrate
10772caefae9SMatthias Ringwald                                 && hci_transport_uart_get_main_baud_rate()){
1078772a36d3SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1079772a36d3SMatthias Ringwald                             } else {
10809f007422SMatthias Ringwald                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1081772a36d3SMatthias Ringwald                             }
1082e47e68c7SMatthias Ringwald                             break;
1083e47e68c7SMatthias Ringwald                     }
10840305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
108574b323a9SMatthias Ringwald                     break;
108674b323a9SMatthias Ringwald                 }
1087148ca237SMatthias Ringwald                 log_info("Init script done");
108892a0d36dSMatthias Ringwald 
1089559961d0SMatthias Ringwald                 // Init script download on Broadcom chipsets causes:
1090c6d1dbedSMatthias Ringwald                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1091559961d0SMatthias Ringwald                     // - baud rate to reset, restore UART baud rate if needed
109292a0d36dSMatthias Ringwald                     int need_baud_change = hci_stack->config
10933fb36a29SMatthias Ringwald                         && hci_stack->chipset
10943fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
109592a0d36dSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
10969796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
109792a0d36dSMatthias Ringwald                     if (need_baud_change) {
10989796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1099cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
110092a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
110192a0d36dSMatthias Ringwald                     }
1102559961d0SMatthias Ringwald 
1103559961d0SMatthias Ringwald                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1104559961d0SMatthias Ringwald                     //   -> Work around: wait a few milliseconds here.
1105559961d0SMatthias Ringwald                     log_info("BCM delay after init script");
1106559961d0SMatthias Ringwald                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1107559961d0SMatthias Ringwald                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1108559961d0SMatthias Ringwald                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1109559961d0SMatthias Ringwald                     btstack_run_loop_add_timer(&hci_stack->timeout);
1110559961d0SMatthias Ringwald                     break;
111192a0d36dSMatthias Ringwald                 }
111274b323a9SMatthias Ringwald                         }
111374b323a9SMatthias Ringwald             // otherwise continue
1114a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1115a828a756SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1116a828a756SMatthias Ringwald             break;
111753860077SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
111853860077SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
11193fb36a29SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1120f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
112153860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
112253860077SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
112353860077SMatthias Ringwald             break;
112406b9e820SMatthias Ringwald #endif
112506b9e820SMatthias Ringwald 
112606b9e820SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
112706b9e820SMatthias Ringwald             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
112806b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
112906b9e820SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
113006b9e820SMatthias Ringwald             break;
113153860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
113253860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
113353860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
113453860077SMatthias Ringwald             break;
113574b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
113674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
11370305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_buffer_size);
113874b323a9SMatthias Ringwald             break;
113953860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
114053860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
11410305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
114274b323a9SMatthias Ringwald             break;
114374b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
11440305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
114574b323a9SMatthias Ringwald             if (hci_le_supported()){
114674b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
114774b323a9SMatthias Ringwald             } else {
114874b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
114974b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
115074b323a9SMatthias Ringwald             }
115174b323a9SMatthias Ringwald             break;
115235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
115374b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
115474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
11550305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
115674b323a9SMatthias Ringwald             break;
115774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_PAGE_TIMEOUT:
115874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
11590305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
116074b323a9SMatthias Ringwald             break;
116174b323a9SMatthias Ringwald         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
116274b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
11630305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
116474b323a9SMatthias Ringwald             break;
116574b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LOCAL_NAME:
11660305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
116774b323a9SMatthias Ringwald             if (hci_stack->local_name){
116874b323a9SMatthias Ringwald                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
116974b323a9SMatthias Ringwald             } else {
11707224be7eSMatthias Ringwald                 char local_name[8+17+1];
11717224be7eSMatthias Ringwald                 // BTstack 11:22:33:44:55:66
11727224be7eSMatthias Ringwald                 memcpy(local_name, "BTstack ", 8);
11737224be7eSMatthias Ringwald                 memcpy(&local_name[8], bd_addr_to_str(hci_stack->local_bd_addr), 17);   // strlen(bd_addr_to_str(...)) = 17
11747224be7eSMatthias Ringwald                 local_name[8+17] = '\0';
117593bcd4d0SMatthias Ringwald                 log_info("---> Name %s", local_name);
117693bcd4d0SMatthias Ringwald                 hci_send_cmd(&hci_write_local_name, local_name);
117774b323a9SMatthias Ringwald             }
117874b323a9SMatthias Ringwald             break;
1179ff00ed1cSMatthias Ringwald         case HCI_INIT_WRITE_EIR_DATA:
11808a114470SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1181ff00ed1cSMatthias Ringwald             hci_send_cmd(&hci_write_extended_inquiry_response, 0, hci_stack->eir_data);
1182ff00ed1cSMatthias Ringwald             break;
1183f6858d14SMatthias Ringwald         case HCI_INIT_WRITE_INQUIRY_MODE:
1184f6858d14SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
11858a114470SMatthias Ringwald             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1186f6858d14SMatthias Ringwald             break;
118774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SCAN_ENABLE:
118874b323a9SMatthias Ringwald             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
118974b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
119074b323a9SMatthias Ringwald             break;
1191483c5078SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI is defined
1192729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1193729ed62eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1194729ed62eSMatthias Ringwald             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1195729ed62eSMatthias Ringwald             break;
1196483c5078SMatthias Ringwald         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1197483c5078SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1198483c5078SMatthias Ringwald             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1199483c5078SMatthias Ringwald             break;
1200a42798c3SMatthias Ringwald         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1201a42798c3SMatthias Ringwald         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1202a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1203a42798c3SMatthias Ringwald             log_info("BCM: Route SCO data via HCI transport");
1204a42798c3SMatthias Ringwald             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1205a42798c3SMatthias Ringwald             break;
1206a42798c3SMatthias Ringwald 
120735454696SMatthias Ringwald #endif
1208a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
120974b323a9SMatthias Ringwald         // LE INIT
121074b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
121174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
12120305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_read_buffer_size);
121374b323a9SMatthias Ringwald             break;
121474b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
121574b323a9SMatthias Ringwald             // LE Supported Host = 1, Simultaneous Host = 0
121674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
12170305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
121874b323a9SMatthias Ringwald             break;
1219b95a5a35SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12203b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
12213b6d4121SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
12223b6d4121SMatthias Ringwald             hci_send_cmd(&hci_le_read_white_list_size);
12233b6d4121SMatthias Ringwald             break;
122474b323a9SMatthias Ringwald         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1225b95a5a35SMatthias Ringwald             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
122674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1227b95a5a35SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
122874b323a9SMatthias Ringwald             break;
122974b323a9SMatthias Ringwald #endif
1230b95a5a35SMatthias Ringwald #endif
123174b323a9SMatthias Ringwald         default:
123274b323a9SMatthias Ringwald             return;
123374b323a9SMatthias Ringwald     }
123455975f88SMatthias Ringwald }
123555975f88SMatthias Ringwald 
1236a650ba4dSMatthias Ringwald static void hci_init_done(void){
1237a650ba4dSMatthias Ringwald     // done. tell the app
1238a650ba4dSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1239a650ba4dSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1240a650ba4dSMatthias Ringwald     hci_emit_state();
1241a650ba4dSMatthias Ringwald     hci_run();
1242a650ba4dSMatthias Ringwald }
1243a650ba4dSMatthias Ringwald 
12446155b3d3S[email protected] static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
12459ec2630cSMatthias Ringwald     UNUSED(size);
12469ec2630cSMatthias Ringwald 
1247a2481739S[email protected]     uint8_t command_completed = 0;
1248c4633093SMatthias Ringwald 
12490e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1250f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
12516155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
1252a2481739S[email protected]             command_completed = 1;
1253148ca237SMatthias Ringwald             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
12546155b3d3S[email protected]         } else {
1255d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
12566155b3d3S[email protected]         }
12576155b3d3S[email protected]     }
12580f97eae7SMatthias Ringwald 
12590e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
12606155b3d3S[email protected]         uint8_t  status = packet[2];
1261f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
12626155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
12636155b3d3S[email protected]             if (status){
1264a2481739S[email protected]                 command_completed = 1;
1265148ca237SMatthias Ringwald                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
12666155b3d3S[email protected]             } else {
12676155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
12686155b3d3S[email protected]             }
12696155b3d3S[email protected]         } else {
1270148ca237SMatthias Ringwald             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
12716155b3d3S[email protected]         }
12726155b3d3S[email protected]     }
12730f97eae7SMatthias Ringwald 
127406b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
127506b9e820SMatthias Ringwald 
1276e47e68c7SMatthias Ringwald     // Vendor == CSR
12770e2df43fSMatthias Ringwald     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1278e47e68c7SMatthias Ringwald         // TODO: track actual command
1279e47e68c7SMatthias Ringwald         command_completed = 1;
1280e47e68c7SMatthias Ringwald     }
1281a2481739S[email protected] 
12824e9daa6fSMatthias Ringwald     // Vendor == Toshiba
12830e2df43fSMatthias Ringwald     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
12844e9daa6fSMatthias Ringwald         // TODO: track actual command
12854e9daa6fSMatthias Ringwald         command_completed = 1;
12864e9daa6fSMatthias Ringwald     }
12874e9daa6fSMatthias Ringwald 
12880f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
12890f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
12900f97eae7SMatthias Ringwald     //
12910f97eae7SMatthias Ringwald     // HCI Reset
12920f97eae7SMatthias Ringwald     // Timeout 100 ms
12930f97eae7SMatthias Ringwald     // HCI Reset
12940f97eae7SMatthias Ringwald     // Command Complete Reset
12950f97eae7SMatthias Ringwald     // HCI Read Local Version Information
12960f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
12970f97eae7SMatthias Ringwald     // hang...
12980f97eae7SMatthias Ringwald     //
12990f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
13000f97eae7SMatthias Ringwald     if (!command_completed
13010e2df43fSMatthias Ringwald             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
13020f97eae7SMatthias Ringwald             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
13030f97eae7SMatthias Ringwald 
1304f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
13050f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
13060f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
13070f97eae7SMatthias Ringwald             return;
13080f97eae7SMatthias Ringwald         }
13090f97eae7SMatthias Ringwald     }
13100f97eae7SMatthias Ringwald 
13119f007422SMatthias Ringwald     // CSR & H5
13129f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
13139f007422SMatthias Ringwald     if (!command_completed
13149f007422SMatthias Ringwald             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
13159f007422SMatthias Ringwald             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
13169f007422SMatthias Ringwald 
13179f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
13189f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
13199f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
13209f007422SMatthias Ringwald             return;
13219f007422SMatthias Ringwald         }
13229f007422SMatthias Ringwald     }
13239f007422SMatthias Ringwald 
13249f007422SMatthias 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
13259f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
13269f007422SMatthias Ringwald     if (command_completed){
13279f007422SMatthias Ringwald         switch (hci_stack->substate){
13289f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
13299f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
13309f007422SMatthias Ringwald                 break;
13319f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
13329f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
13339f007422SMatthias Ringwald                 break;
13349f007422SMatthias Ringwald             default:
13359f007422SMatthias Ringwald                 break;
13369f007422SMatthias Ringwald         }
13379f007422SMatthias Ringwald     }
13380f97eae7SMatthias Ringwald 
133906b9e820SMatthias Ringwald #endif
13400f97eae7SMatthias Ringwald 
1341a2481739S[email protected]     if (!command_completed) return;
1342a2481739S[email protected] 
134306b9e820SMatthias Ringwald     int need_baud_change = 0;
134406b9e820SMatthias Ringwald     int need_addr_change = 0;
134506b9e820SMatthias Ringwald 
134606b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
134706b9e820SMatthias Ringwald     need_baud_change = hci_stack->config
13483fb36a29SMatthias Ringwald                         && hci_stack->chipset
13493fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
1350db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
13519796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1352db8bc6ffSMatthias Ringwald 
135306b9e820SMatthias Ringwald     need_addr_change = hci_stack->custom_bd_addr_set
13543fb36a29SMatthias Ringwald                         && hci_stack->chipset
13553fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
135606b9e820SMatthias Ringwald #endif
1357a80162e9SMatthias Ringwald 
13585c363727SMatthias Ringwald     switch(hci_stack->substate){
135906b9e820SMatthias Ringwald 
136006b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
13619f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
1362d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
13639f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
13649f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
13659f007422SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
13669f007422SMatthias Ringwald             break;
136774b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
1368528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
136976fcb19bSMatthias Ringwald             break;
1370e90bae01SMatthias Ringwald         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1371e90bae01SMatthias Ringwald             log_info("Received local name, need baud change %d", need_baud_change);
13722f48d920SMatthias Ringwald             if (need_baud_change){
13732f48d920SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
13742f48d920SMatthias Ringwald                 return;
13752f48d920SMatthias Ringwald             }
137653860077SMatthias Ringwald             // skip baud change
137774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
137874b323a9SMatthias Ringwald             return;
1379a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
13804696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
1381fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
13827224be7eSMatthias Ringwald             if ((hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
138396b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1384cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1385fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
13864696bddbSMatthias Ringwald             }
138774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
138874b323a9SMatthias Ringwald             return;
1389a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1390528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
1391a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1392a80162e9SMatthias Ringwald             return;
139374b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
139474b323a9SMatthias Ringwald             // repeat custom init
139574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
139674b323a9SMatthias Ringwald             return;
139706b9e820SMatthias Ringwald #else
139806b9e820SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
139906b9e820SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
140006b9e820SMatthias Ringwald             return ;
140106b9e820SMatthias Ringwald #endif
140206b9e820SMatthias Ringwald 
1403a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1404c6d1dbedSMatthias Ringwald             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1405eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1406eb3a5314SMatthias Ringwald                 return;
1407eb3a5314SMatthias Ringwald             }
140853860077SMatthias Ringwald             if (need_addr_change){
140953860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
141053860077SMatthias Ringwald                 return;
141153860077SMatthias Ringwald             }
141253860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
141353860077SMatthias Ringwald             return;
141406b9e820SMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
14157224be7eSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
14167224be7eSMatthias Ringwald             if (need_baud_change){
141796b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1418cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1419fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
14207224be7eSMatthias Ringwald             }
1421eb3a5314SMatthias Ringwald             if (need_addr_change){
1422eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1423eb3a5314SMatthias Ringwald                 return;
1424eb3a5314SMatthias Ringwald             }
1425eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1426eb3a5314SMatthias Ringwald             return;
142753860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
142853860077SMatthias Ringwald             // for STLC2500D, bd addr change only gets active after sending reset command
1429c6d1dbedSMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
143053860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
143153860077SMatthias Ringwald                 return;
143253860077SMatthias Ringwald             }
143353860077SMatthias Ringwald             // skipping st warm boot
143453860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
143553860077SMatthias Ringwald             return;
143653860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
143753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
143853860077SMatthias Ringwald             return;
143906b9e820SMatthias Ringwald #endif
144053860077SMatthias Ringwald         case HCI_INIT_W4_READ_BD_ADDR:
144153860077SMatthias Ringwald             // only read buffer size if supported
144253860077SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x01) {
144353860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
144453860077SMatthias Ringwald                 return;
144553860077SMatthias Ringwald             }
144653860077SMatthias Ringwald             // skipping read buffer size
144753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1448a828a756SMatthias Ringwald             return;
144974b323a9SMatthias Ringwald         case HCI_INIT_W4_SET_EVENT_MASK:
14506155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
14516155b3d3S[email protected]             if (!hci_classic_supported()){
14522c68f164SMatthias Ringwald #ifdef ENABLE_BLE
14536155b3d3S[email protected]                 if (hci_le_supported()){
145474b323a9SMatthias Ringwald                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
145574b323a9SMatthias Ringwald                     return;
14562c68f164SMatthias Ringwald                 }
14572c68f164SMatthias Ringwald #endif
14586155b3d3S[email protected]                 log_error("Neither BR/EDR nor LE supported");
1459a650ba4dSMatthias Ringwald                 hci_init_done();
146074b323a9SMatthias Ringwald                 return;
14616155b3d3S[email protected]             }
146215a95bd5SMatthias Ringwald             if (!gap_ssp_supported()){
14635c363727SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
146474b323a9SMatthias Ringwald                 return;
14656155b3d3S[email protected]             }
14666155b3d3S[email protected]             break;
1467903ea03aSMatthias Ringwald #ifdef ENABLE_BLE
1468a828a756SMatthias Ringwald         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1469a828a756SMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
1470a828a756SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x02) break;
1471903ea03aSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1472903ea03aSMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1473903ea03aSMatthias Ringwald #else
1474903ea03aSMatthias Ringwald             hci_init_done();
1475903ea03aSMatthias Ringwald #endif
1476a828a756SMatthias Ringwald             return;
1477903ea03aSMatthias Ringwald #endif
1478ff00ed1cSMatthias Ringwald         case HCI_INIT_W4_WRITE_LOCAL_NAME:
1479ff00ed1cSMatthias Ringwald             // skip write eir data if no eir data set
1480ff00ed1cSMatthias Ringwald             if (hci_stack->eir_data) break;
1481ff00ed1cSMatthias Ringwald             hci_stack->substate = HCI_INIT_WRITE_INQUIRY_MODE;
1482ff00ed1cSMatthias Ringwald             return;
1483729ed62eSMatthias Ringwald 
148471c4de7aSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1485729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
14863905afbfSMatthias Ringwald             // skip write synchronous flow control if not supported
14873905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x04) break;
14883905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
14893905afbfSMatthias Ringwald             // explicit fall through to reduce repetitions
14903905afbfSMatthias Ringwald 
1491729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
14923905afbfSMatthias Ringwald             // skip write default erroneous data reporting if not supported
14933905afbfSMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x08) break;
14943905afbfSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
14953905afbfSMatthias Ringwald             // explicit fall through to reduce repetitions
14963905afbfSMatthias Ringwald 
1497f064e0bbSMatthias Ringwald         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1498a42798c3SMatthias Ringwald             // skip bcm set sco pcm config on non-Broadcom chipsets
1499a42798c3SMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION) break;
1500a42798c3SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1501a42798c3SMatthias Ringwald             // explicit fall through to reduce repetitions
1502a42798c3SMatthias Ringwald 
1503a42798c3SMatthias Ringwald         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1504729ed62eSMatthias Ringwald             if (!hci_le_supported()){
1505729ed62eSMatthias Ringwald                 // SKIP LE init for Classic only configuration
1506a650ba4dSMatthias Ringwald                 hci_init_done();
1507729ed62eSMatthias Ringwald                 return;
1508729ed62eSMatthias Ringwald             }
1509729ed62eSMatthias Ringwald             break;
1510f3b012f9SMatthias Ringwald 
1511f3b012f9SMatthias Ringwald #else /* !ENABLE_SCO_OVER_HCI */
1512f3b012f9SMatthias Ringwald 
151374b323a9SMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1514f3b012f9SMatthias Ringwald #ifdef ENABLE_BLE
1515f3b012f9SMatthias Ringwald             if (hci_le_supported()){
1516f3b012f9SMatthias Ringwald                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
151774b323a9SMatthias Ringwald                 return;
15186155b3d3S[email protected]             }
1519729ed62eSMatthias Ringwald #endif
1520f3b012f9SMatthias Ringwald             // SKIP LE init for Classic only configuration
1521f3b012f9SMatthias Ringwald             hci_init_done();
1522f3b012f9SMatthias Ringwald             return;
1523f3b012f9SMatthias Ringwald #endif /* ENABLE_SCO_OVER_HCI */
1524f3b012f9SMatthias Ringwald 
1525a650ba4dSMatthias Ringwald         // Response to command before init done state -> init done
1526a650ba4dSMatthias Ringwald         case (HCI_INIT_DONE-1):
1527a650ba4dSMatthias Ringwald             hci_init_done();
1528a650ba4dSMatthias Ringwald             return;
1529a650ba4dSMatthias Ringwald 
15306155b3d3S[email protected]         default:
153174b323a9SMatthias Ringwald             break;
15326155b3d3S[email protected]     }
153355975f88SMatthias Ringwald     hci_initializing_next_state();
15346155b3d3S[email protected] }
15356155b3d3S[email protected] 
153616833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
1537e76a89eeS[email protected] 
1538e76a89eeS[email protected]     uint16_t event_length = packet[1];
1539e76a89eeS[email protected] 
1540e76a89eeS[email protected]     // assert packet is complete
1541e76a89eeS[email protected]     if (size != event_length + 2){
1542f04a0c31SMatthias Ringwald         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1543e76a89eeS[email protected]         return;
1544e76a89eeS[email protected]     }
1545e76a89eeS[email protected] 
15461281a47eSmatthias.ringwald     bd_addr_t addr;
154796a45072S[email protected]     bd_addr_type_t addr_type;
15482d00edd4Smatthias.ringwald     uint8_t link_type;
1549fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
15501f7b95a1Smatthias.ringwald     hci_connection_t * conn;
155156cf178bSmatthias.ringwald     int i;
155222909952Smatthias.ringwald 
155335454696SMatthias Ringwald     // warnings
155435454696SMatthias Ringwald     (void) link_type;
155535454696SMatthias Ringwald 
15560e2df43fSMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
15575909f7f2Smatthias.ringwald 
15580e2df43fSMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
155922909952Smatthias.ringwald 
15606772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
15616bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
15626bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
15637ec5eeaaSmatthias.ringwald 
15649e263bd7SMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
156506b9e820SMatthias Ringwald                 if (packet[5]) break;
15669e263bd7SMatthias Ringwald                 // terminate, name 248 chars
15679e263bd7SMatthias Ringwald                 packet[6+248] = 0;
15689e263bd7SMatthias Ringwald                 log_info("local name: %s", &packet[6]);
15699e263bd7SMatthias Ringwald             }
1570073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
15711d279b20Smatthias.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"
1572*429122ccSMatthias Ringwald                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1573*429122ccSMatthias Ringwald                     uint16_t acl_len = little_endian_read_16(packet, 6);
1574*429122ccSMatthias Ringwald                     uint16_t sco_len = packet[8];
1575*429122ccSMatthias Ringwald 
1576*429122ccSMatthias Ringwald                     // determine usable ACL/SCO payload size
1577*429122ccSMatthias Ringwald                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1578*429122ccSMatthias Ringwald                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1579*429122ccSMatthias Ringwald 
1580f8fbdce0SMatthias Ringwald                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1581f8fbdce0SMatthias Ringwald                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1582a8b12447S[email protected] 
1583*429122ccSMatthias Ringwald                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1584*429122ccSMatthias Ringwald                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
15851a06f663S[email protected]                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1586e2edc0c3Smatthias.ringwald                 }
158756cf178bSmatthias.ringwald             }
1588a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
1589073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1590f8fbdce0SMatthias Ringwald                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1591ee303eddS[email protected]                 hci_stack->le_acl_packets_total_num  = packet[8];
15926c26b087S[email protected]                     // determine usable ACL payload size
15936c26b087S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
15946c26b087S[email protected]                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
15956c26b087S[email protected]                     }
15969da54300S[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);
159765a46ef3S[email protected]             }
1598d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
1599073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1600e691bb38SMatthias Ringwald                 hci_stack->le_whitelist_capacity = packet[6];
160115d0a15bSMatthias Ringwald                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
16023b6d4121SMatthias Ringwald             }
160365a46ef3S[email protected] #endif
1604d70217a2SMatthias Ringwald #endif
1605073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1606724d70a2SMatthias Ringwald                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1607724d70a2SMatthias Ringwald 				hci_stack->local_bd_addr);
16089da54300S[email protected]                 log_info("Local Address, Status: 0x%02x: Addr: %s",
16093a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
161033373e40SMatthias Ringwald #ifdef ENABLE_CLASSIC
16111624665aSMatthias Ringwald                 if (hci_stack->link_key_db){
16121624665aSMatthias Ringwald                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
16131624665aSMatthias Ringwald                 }
161433373e40SMatthias Ringwald #endif
1615188981d2Smatthias.ringwald             }
161635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
1617073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
16183a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1619381fbed8Smatthias.ringwald             }
162035454696SMatthias Ringwald #endif
162135454696SMatthias Ringwald 
162265389bfcS[email protected]             // Note: HCI init checks
1623073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
16243a9fb326S[email protected]                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
162565389bfcS[email protected] 
162635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
1627a5a23fc2S[email protected]                 // determine usable ACL packet types based on host buffer size and supported features
1628a5a23fc2S[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]);
16298b96126aSMatthias Ringwald                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
163035454696SMatthias Ringwald #endif
1631f5d8d141S[email protected]                 // Classic/LE
1632f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1633559e517eS[email protected]             }
1634073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1635f8fbdce0SMatthias Ringwald                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1636f8fbdce0SMatthias Ringwald                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1637f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1638f8fbdce0SMatthias Ringwald                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1639f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
16404696bddbSMatthias Ringwald                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
16414696bddbSMatthias Ringwald             }
1642073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1643a828a756SMatthias Ringwald                 hci_stack->local_supported_commands[0] =
16443905afbfSMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
16453905afbfSMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
16463905afbfSMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
16473905afbfSMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08);        // bit 3 = Octet 18, bit 3
16483905afbfSMatthias Ringwald                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1649a828a756SMatthias Ringwald             }
1650e8c8828eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1651073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
16525b9b590fSMatthias Ringwald                 if (packet[5] == 0){
16535b9b590fSMatthias Ringwald                     hci_stack->synchronous_flow_control_enabled = 1;
16545b9b590fSMatthias Ringwald                 }
16555b9b590fSMatthias Ringwald             }
1656e8c8828eSMatthias Ringwald #endif
165756cf178bSmatthias.ringwald             break;
165856cf178bSmatthias.ringwald 
16597ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
16606bef4003SMatthias Ringwald             // get num cmd packets - limit to 1 to reduce complexity
16616bef4003SMatthias Ringwald             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
16627ec5eeaaSmatthias.ringwald             break;
16637ec5eeaaSmatthias.ringwald 
16642e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
16652e440c8aS[email protected]             int offset = 3;
166656cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
1667f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, offset);
16682e440c8aS[email protected]                 offset += 2;
1669f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
16702e440c8aS[email protected]                 offset += 2;
16712e440c8aS[email protected] 
16725061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
167356cf178bSmatthias.ringwald                 if (!conn){
16749da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
167556cf178bSmatthias.ringwald                     continue;
167656cf178bSmatthias.ringwald                 }
167723bed257S[email protected] 
1678e35edcc1S[email protected]                 if (conn->address_type == BD_ADDR_TYPE_SCO){
167935454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
1680e35edcc1S[email protected]                     if (conn->num_sco_packets_sent >= num_packets){
1681e35edcc1S[email protected]                         conn->num_sco_packets_sent -= num_packets;
1682e35edcc1S[email protected]                     } else {
1683e35edcc1S[email protected]                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1684e35edcc1S[email protected]                         conn->num_sco_packets_sent = 0;
1685e35edcc1S[email protected]                     }
1686701e3307SMatthias Ringwald                     hci_notify_if_sco_can_send_now();
168735454696SMatthias Ringwald #endif
1688e35edcc1S[email protected]                 } else {
168923bed257S[email protected]                     if (conn->num_acl_packets_sent >= num_packets){
169056cf178bSmatthias.ringwald                         conn->num_acl_packets_sent -= num_packets;
169123bed257S[email protected]                     } else {
1692e35edcc1S[email protected]                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
169323bed257S[email protected]                         conn->num_acl_packets_sent = 0;
169423bed257S[email protected]                     }
1695e35edcc1S[email protected]                 }
16969da54300S[email protected]                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
169756cf178bSmatthias.ringwald             }
16986772a24cSmatthias.ringwald             break;
16992e440c8aS[email protected]         }
170035454696SMatthias Ringwald 
170135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
17021f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
1703724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
170437eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
17052d00edd4Smatthias.ringwald             link_type = packet[11];
17069da54300S[email protected]             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1707e35edcc1S[email protected]             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
17082e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
17091f7b95a1Smatthias.ringwald             if (!conn) {
17105293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
17111f7b95a1Smatthias.ringwald             }
1712ce4c8fabSmatthias.ringwald             if (!conn) {
1713ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
17143a9fb326S[email protected]                 hci_stack->decline_reason = 0x0d;
1715058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
1716ce4c8fabSmatthias.ringwald                 break;
1717ce4c8fabSmatthias.ringwald             }
17185cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
171932ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
1720f3a16b9aSMatthias Ringwald             // store info about eSCO
1721f3a16b9aSMatthias Ringwald             if (link_type == 0x02){
1722f3a16b9aSMatthias Ringwald                 conn->remote_supported_feature_eSCO = 1;
1723f3a16b9aSMatthias Ringwald             }
172432ab9390Smatthias.ringwald             hci_run();
17251f7b95a1Smatthias.ringwald             break;
17261f7b95a1Smatthias.ringwald 
17276772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1728fe1ed1b8Smatthias.ringwald             // Connection management
1729724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
17309da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
173196a45072S[email protected]             addr_type = BD_ADDR_TYPE_CLASSIC;
17322e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1733fe1ed1b8Smatthias.ringwald             if (conn) {
1734b448a0e7Smatthias.ringwald                 if (!packet[2]){
1735c8e4258aSmatthias.ringwald                     conn->state = OPEN;
1736f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
1737ad83dc6aS[email protected]                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1738ee091cf1Smatthias.ringwald 
1739c785ef68Smatthias.ringwald                     // restart timer
1740528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1741528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
1742c785ef68Smatthias.ringwald 
17439da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
174443bfb1bdSmatthias.ringwald 
174543bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
1746b448a0e7Smatthias.ringwald                 } else {
17471bd5283dS[email protected]                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
17481bd5283dS[email protected]                     uint8_t status = packet[2];
17491bd5283dS[email protected]                     bd_addr_t bd_address;
17501bd5283dS[email protected]                     memcpy(&bd_address, conn->address, 6);
1751ad83dc6aS[email protected] 
1752b448a0e7Smatthias.ringwald                     // connection failed, remove entry
1753665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1754a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
1755c12e46e7Smatthias.ringwald 
17561bd5283dS[email protected]                     // notify client if dedicated bonding
17571bd5283dS[email protected]                     if (notify_dedicated_bonding_failed){
17581bd5283dS[email protected]                         log_info("hci notify_dedicated_bonding_failed");
17591bd5283dS[email protected]                         hci_emit_dedicated_bonding_result(bd_address, status);
17601bd5283dS[email protected]                     }
17611bd5283dS[email protected] 
1762c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
1763c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
176415a95bd5SMatthias Ringwald                         gap_drop_link_key_for_bd_addr(addr);
1765c12e46e7Smatthias.ringwald                     }
1766fe1ed1b8Smatthias.ringwald                 }
1767fe1ed1b8Smatthias.ringwald             }
17686772a24cSmatthias.ringwald             break;
1769fe1ed1b8Smatthias.ringwald 
177044d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1771724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
177244d0e3d5S[email protected]             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
17731a06f663S[email protected]             if (packet[2]){
177444d0e3d5S[email protected]                 // connection failed
177544d0e3d5S[email protected]                 break;
177644d0e3d5S[email protected]             }
17772e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1778e35edcc1S[email protected]             if (!conn) {
1779e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1780e35edcc1S[email protected]             }
1781e35edcc1S[email protected]             if (!conn) {
1782e35edcc1S[email protected]                 break;
1783e35edcc1S[email protected]             }
17841a06f663S[email protected]             conn->state = OPEN;
1785f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
1786ee752bb8SMatthias Ringwald 
1787ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1788ee752bb8SMatthias Ringwald             // update SCO
1789ee752bb8SMatthias Ringwald             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1790ee752bb8SMatthias Ringwald                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1791ee752bb8SMatthias Ringwald             }
1792ee752bb8SMatthias Ringwald #endif
179344d0e3d5S[email protected]             break;
179444d0e3d5S[email protected] 
1795afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1796f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1797afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
1798afd4e962S[email protected]             if (!conn) break;
1799afd4e962S[email protected]             if (!packet[2]){
1800afd4e962S[email protected]                 uint8_t * features = &packet[5];
1801afd4e962S[email protected]                 if (features[6] & (1 << 3)){
1802afd4e962S[email protected]                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1803afd4e962S[email protected]                 }
180498a2fd1cSMatthias Ringwald                 if (features[3] & (1<<7)){
180598a2fd1cSMatthias Ringwald                     conn->remote_supported_feature_eSCO = 1;
180698a2fd1cSMatthias Ringwald                 }
1807afd4e962S[email protected]             }
1808afd4e962S[email protected]             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
180998a2fd1cSMatthias Ringwald             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1810ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1811ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1812ad83dc6aS[email protected]             }
1813afd4e962S[email protected]             break;
1814afd4e962S[email protected] 
18157fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
18169da54300S[email protected]             log_info("HCI_EVENT_LINK_KEY_REQUEST");
18177fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
181874d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1819a98592bcSMatthias Ringwald             if (hci_stack->bondable && !hci_stack->link_key_db) break;
182032ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
182164472d52Smatthias.ringwald             hci_run();
1822d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
182329d53098Smatthias.ringwald             return;
18247fde4af9Smatthias.ringwald 
18259ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1826724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
18272e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
18289ab95c90S[email protected]             if (!conn) break;
18299ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
18307bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
18319ab95c90S[email protected]             // Change Connection Encryption keeps link key type
18329ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
18339ab95c90S[email protected]                 conn->link_key_type = link_key_type;
18349ab95c90S[email protected]             }
183555597469SMatthias Ringwald             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
183629d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
18377fde4af9Smatthias.ringwald             break;
18389ab95c90S[email protected]         }
18397fde4af9Smatthias.ringwald 
18407fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
18416724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
18424c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
18433a9fb326S[email protected]             if (!hci_stack->bondable){
1844899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1845f8fb5f6eS[email protected]                 hci_run();
1846f8fb5f6eS[email protected]                 return;
18474c57c146S[email protected]             }
1848d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1849a98592bcSMatthias Ringwald             if (!hci_stack->link_key_db) break;
1850a6ef64baSMilanka Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
1851a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
18527fde4af9Smatthias.ringwald             break;
18537fde4af9Smatthias.ringwald 
18541d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
18551d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1856dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1857dbe1a790S[email protected]             break;
1858dbe1a790S[email protected] 
1859dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
18606724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
18613a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1862dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1863dbe1a790S[email protected]             break;
1864dbe1a790S[email protected] 
1865dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
18666724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
18673a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1868dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
18691d6b20aeS[email protected]             break;
187035454696SMatthias Ringwald #endif
18711d6b20aeS[email protected] 
1872f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
1873f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1874f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
1875f0944df2S[email protected]             if (!conn) break;
1876ad83dc6aS[email protected]             if (packet[2] == 0) {
1877f0944df2S[email protected]                 if (packet[5]){
1878f0944df2S[email protected]                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1879f0944df2S[email protected]                 } else {
1880536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1881f0944df2S[email protected]                 }
1882ad83dc6aS[email protected]             }
188335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
1884a00031e2S[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
188535454696SMatthias Ringwald #endif
1886f0944df2S[email protected]             break;
1887f0944df2S[email protected] 
188835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
18891eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1890f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
18911eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
18921eb2563eS[email protected]             if (!conn) break;
1893ad83dc6aS[email protected] 
1894ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
1895ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1896ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
1897ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
18981bd5283dS[email protected]                 conn->bonding_status = packet[2];
1899ad83dc6aS[email protected]                 break;
1900ad83dc6aS[email protected]             }
1901ad83dc6aS[email protected] 
1902b5cb6874S[email protected]             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
19031eb2563eS[email protected]                 // link key sufficient for requested security
19041eb2563eS[email protected]                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1905ad83dc6aS[email protected]                 break;
1906ad83dc6aS[email protected]             }
19071eb2563eS[email protected]             // not enough
19081eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
19091eb2563eS[email protected]             break;
191035454696SMatthias Ringwald #endif
191134d2123cS[email protected] 
191286805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
1913ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
1914ccda6e14S[email protected]         // see end of function, too.
1915a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
1916a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
1917f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1918c6a37cfdSMatthias Ringwald             // drop outgoing ACL fragments if it is for closed connection
1919c6a37cfdSMatthias Ringwald             if (hci_stack->acl_fragmentation_total_size > 0) {
1920c6a37cfdSMatthias Ringwald                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
1921c6a37cfdSMatthias Ringwald                     log_info("hci: drop fragmented ACL data for closed connection");
1922c6a37cfdSMatthias Ringwald                      hci_stack->acl_fragmentation_total_size = 0;
1923c6a37cfdSMatthias Ringwald                      hci_stack->acl_fragmentation_pos = 0;
1924c6a37cfdSMatthias Ringwald                 }
1925c6a37cfdSMatthias Ringwald             }
192635454696SMatthias Ringwald 
19279a2e4658SMatthias Ringwald             // re-enable advertisements for le connections if active
1928c6a37cfdSMatthias Ringwald             conn = hci_connection_for_handle(handle);
1929c6a37cfdSMatthias Ringwald             if (!conn) break;
193035454696SMatthias Ringwald #ifdef ENABLE_BLE
1931d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
19329a2e4658SMatthias Ringwald             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
19339a2e4658SMatthias Ringwald                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
19349a2e4658SMatthias Ringwald             }
193535454696SMatthias Ringwald #endif
1936d70217a2SMatthias Ringwald #endif
1937ccda6e14S[email protected]             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1938ccda6e14S[email protected]             break;
19396772a24cSmatthias.ringwald 
1940c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
1941313e5f9cSMatthias Ringwald             log_error("Hardware Error: 0x%02x", packet[2]);
1942d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
1943c2e1fa60SMatthias Ringwald                 (*hci_stack->hardware_error_callback)(packet[2]);
19447586ee35S[email protected]             } else {
19457586ee35S[email protected]                 // if no special requests, just reboot stack
19467586ee35S[email protected]                 hci_power_control_off();
19477586ee35S[email protected]                 hci_power_control_on();
1948c68bdf90Smatthias.ringwald             }
1949c68bdf90Smatthias.ringwald             break;
1950c68bdf90Smatthias.ringwald 
19510e6f3837SMatthias Ringwald #ifdef ENABLE_CLASSIC
19525cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
19535cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
1954f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
19555cf766e8SMatthias Ringwald             conn = hci_connection_for_handle(handle);
19565cf766e8SMatthias Ringwald             if (!conn) break;       // no conn
19575cf766e8SMatthias Ringwald             conn->role = packet[9];
19585cf766e8SMatthias Ringwald             break;
19590e6f3837SMatthias Ringwald #endif
19605cf766e8SMatthias Ringwald 
196163fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1962d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
19634fa24b5fS[email protected]             if (hci_transport_synchronous()) {
196463fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
19654fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
19664fa24b5fS[email protected]             }
1967d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
1968d051460cS[email protected]             hci_release_packet_buffer();
1969701e3307SMatthias Ringwald 
197063fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
197163fa3374SMatthias Ringwald 
197235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
197363fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
1974701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
197535454696SMatthias Ringwald #endif
19766b4af23dS[email protected]             break;
19776b4af23dS[email protected] 
197835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
197963fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
198063fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
198163fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
198263fa3374SMatthias Ringwald             return;
198335454696SMatthias Ringwald #endif
198463fa3374SMatthias Ringwald 
1985a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
19865909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
19875909f7f2Smatthias.ringwald             switch (packet[2]){
1988d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
198957c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
19904f4e0224SMatthias Ringwald                     // log_info("advertising report received");
19917bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
199257c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
19937bdc6798S[email protected]                     break;
1994d70217a2SMatthias Ringwald #endif
19955909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
19965909f7f2Smatthias.ringwald                     // Connection management
1997724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[8], addr);
19987bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
19999da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
20002e77e513S[email protected]                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2001d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
200242ff5ba1SMatthias Ringwald                     // if auto-connect, remove from whitelist in both roles
200342ff5ba1SMatthias Ringwald                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
200442ff5ba1SMatthias Ringwald                         hci_remove_from_whitelist(addr_type, addr);
200542ff5ba1SMatthias Ringwald                     }
200642ff5ba1SMatthias Ringwald                     // handle error: error is reported only to the initiator -> outgoing connection
20075909f7f2Smatthias.ringwald                     if (packet[3]){
200842ff5ba1SMatthias Ringwald                         // outgoing connection establishment is done
200942ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
201042ff5ba1SMatthias Ringwald                         // remove entry
20115909f7f2Smatthias.ringwald                         if (conn){
2012665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
20135909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
20145909f7f2Smatthias.ringwald                         }
20155909f7f2Smatthias.ringwald                         break;
20165909f7f2Smatthias.ringwald                     }
2017d70217a2SMatthias Ringwald #endif
201842ff5ba1SMatthias Ringwald                     // on success, both hosts receive connection complete event
20195cf766e8SMatthias Ringwald                     if (packet[6] == HCI_ROLE_MASTER){
2020d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
202142ff5ba1SMatthias Ringwald                         // if we're master, it was an outgoing connection and we're done with it
202242ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2023d70217a2SMatthias Ringwald #endif
202442ff5ba1SMatthias Ringwald                     } else {
2025d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
202642ff5ba1SMatthias Ringwald                         // if we're slave, it was an incoming connection, advertisements have stopped
2027171293d3SMatthias Ringwald                         hci_stack->le_advertisements_active = 0;
20285106e6dcSMatthias Ringwald                         // try to re-enable them
20295106e6dcSMatthias Ringwald                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2030d70217a2SMatthias Ringwald #endif
203142ff5ba1SMatthias Ringwald                     }
2032171293d3SMatthias Ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
203342ff5ba1SMatthias Ringwald                     if (!conn){
203496a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
20355909f7f2Smatthias.ringwald                     }
203642ff5ba1SMatthias Ringwald                     // no memory, sorry.
20375909f7f2Smatthias.ringwald                     if (!conn){
20385909f7f2Smatthias.ringwald                         break;
20395909f7f2Smatthias.ringwald                     }
20405909f7f2Smatthias.ringwald 
20415909f7f2Smatthias.ringwald                     conn->state = OPEN;
20425cf766e8SMatthias Ringwald                     conn->role  = packet[6];
2043f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 4);
20445909f7f2Smatthias.ringwald 
20455909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
20465909f7f2Smatthias.ringwald 
20475909f7f2Smatthias.ringwald                     // restart timer
2048528a4a3bSMatthias Ringwald                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2049528a4a3bSMatthias Ringwald                     // btstack_run_loop_add_timer(&conn->timeout);
20505909f7f2Smatthias.ringwald 
20519da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
20525909f7f2Smatthias.ringwald 
20535909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
20545909f7f2Smatthias.ringwald                     break;
20555909f7f2Smatthias.ringwald 
2056f8fbdce0SMatthias Ringwald             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
205765a46ef3S[email protected] 
20585909f7f2Smatthias.ringwald                 default:
20595909f7f2Smatthias.ringwald                     break;
20605909f7f2Smatthias.ringwald             }
20615909f7f2Smatthias.ringwald             break;
20625909f7f2Smatthias.ringwald #endif
20636772a24cSmatthias.ringwald         default:
20646772a24cSmatthias.ringwald             break;
2065fe1ed1b8Smatthias.ringwald     }
2066fe1ed1b8Smatthias.ringwald 
20673429f56bSmatthias.ringwald     // handle BT initialization
20683a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
20696155b3d3S[email protected]         hci_initializing_event_handler(packet, size);
2070c9af4d3fS[email protected]     }
207122909952Smatthias.ringwald 
207289db417bSmatthias.ringwald     // help with BT sleep
20733a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
207474b323a9SMatthias Ringwald         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2075073bd0faSMatthias Ringwald         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
207655975f88SMatthias Ringwald         hci_initializing_next_state();
207789db417bSmatthias.ringwald     }
207889db417bSmatthias.ringwald 
207986805605S[email protected]     // notify upper stack
2080d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
208194ab26f8Smatthias.ringwald 
208286805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
20830e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
208486805605S[email protected]         if (!packet[2]){
2085f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
208605ae8de3SMatthias Ringwald             hci_connection_t * aConn = hci_connection_for_handle(handle);
208705ae8de3SMatthias Ringwald             if (aConn) {
208805ae8de3SMatthias Ringwald                 uint8_t status = aConn->bonding_status;
208905ae8de3SMatthias Ringwald                 uint16_t flags = aConn->bonding_flags;
209086805605S[email protected]                 bd_addr_t bd_address;
209105ae8de3SMatthias Ringwald                 memcpy(&bd_address, aConn->address, 6);
209205ae8de3SMatthias Ringwald                 hci_shutdown_connection(aConn);
2093bb820044S[email protected]                 // connection struct is gone, don't access anymore
2094bb820044S[email protected]                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
209586805605S[email protected]                     hci_emit_dedicated_bonding_result(bd_address, status);
209686805605S[email protected]                 }
209786805605S[email protected]             }
209886805605S[email protected]         }
209986805605S[email protected]     }
210086805605S[email protected] 
210194ab26f8Smatthias.ringwald 	// execute main loop
210294ab26f8Smatthias.ringwald 	hci_run();
210316833f0aSmatthias.ringwald }
210416833f0aSmatthias.ringwald 
210535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2106c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
21078abbe8b5SMatthias Ringwald     if (!hci_stack->sco_packet_handler) return;
21083d50b4baSMatthias Ringwald     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2109c91d150bS[email protected] }
211035454696SMatthias Ringwald #endif
2111c91d150bS[email protected] 
21120a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
21135bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
211410e830c9Smatthias.ringwald     switch (packet_type) {
211510e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
211610e830c9Smatthias.ringwald             event_handler(packet, size);
211710e830c9Smatthias.ringwald             break;
211810e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
211910e830c9Smatthias.ringwald             acl_handler(packet, size);
212010e830c9Smatthias.ringwald             break;
212135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2122c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
2123c91d150bS[email protected]             sco_handler(packet, size);
2124202c8a4cSMatthias Ringwald             break;
212535454696SMatthias Ringwald #endif
212610e830c9Smatthias.ringwald         default:
212710e830c9Smatthias.ringwald             break;
212810e830c9Smatthias.ringwald     }
212910e830c9Smatthias.ringwald }
213010e830c9Smatthias.ringwald 
2131d6b06661SMatthias Ringwald /**
2132d6b06661SMatthias Ringwald  * @brief Add event packet handler.
2133d6b06661SMatthias Ringwald  */
2134d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2135d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2136d6b06661SMatthias Ringwald }
2137d6b06661SMatthias Ringwald 
2138d6b06661SMatthias Ringwald 
2139fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
21403d50b4baSMatthias Ringwald void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2141fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
214216833f0aSmatthias.ringwald }
214316833f0aSmatthias.ringwald 
214435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
21458abbe8b5SMatthias Ringwald /**
21468abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
21478abbe8b5SMatthias Ringwald  */
21483d50b4baSMatthias Ringwald void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
21498abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
21508abbe8b5SMatthias Ringwald }
215135454696SMatthias Ringwald #endif
21528abbe8b5SMatthias Ringwald 
215371de195eSMatthias Ringwald static void hci_state_reset(void){
2154595bdbfbS[email protected]     // no connections yet
2155595bdbfbS[email protected]     hci_stack->connections = NULL;
215674308b23Smatthias.ringwald 
215774308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
215874308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
215974308b23Smatthias.ringwald     // hci_stack->connectable = 0;
216074308b23Smatthias.ringwald     // hci_stack->bondable = 1;
2161b95a5a35SMatthias Ringwald     // hci_stack->own_addr_type = 0;
2162595bdbfbS[email protected] 
216344935e40S[email protected]     // buffer is free
216444935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
216544935e40S[email protected] 
2166595bdbfbS[email protected]     // no pending cmds
2167595bdbfbS[email protected]     hci_stack->decline_reason = 0;
2168595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
2169595bdbfbS[email protected] 
2170595bdbfbS[email protected]     // LE
2171b95a5a35SMatthias Ringwald #ifdef ENABLE_BLE
2172b95a5a35SMatthias Ringwald     memset(hci_stack->le_random_address, 0, 6);
2173b95a5a35SMatthias Ringwald     hci_stack->le_random_address_set = 0;
2174d70217a2SMatthias Ringwald #endif
2175d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
2176595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2177e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
2178b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2179e83201bcSMatthias Ringwald     hci_stack->le_whitelist = 0;
2180e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
2181d70217a2SMatthias Ringwald #endif
2182d70217a2SMatthias Ringwald 
2183e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2184e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2185e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2186e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2187e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2188e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2189595bdbfbS[email protected] }
2190595bdbfbS[email protected] 
219135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
21922d5e09d6SMatthias Ringwald /**
21932d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
21942d5e09d6SMatthias Ringwald  */
21952d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
21962d5e09d6SMatthias Ringwald     // store and open remote device db
21972d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
21982d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
21992d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
22002d5e09d6SMatthias Ringwald     }
22012d5e09d6SMatthias Ringwald }
220235454696SMatthias Ringwald #endif
22032d5e09d6SMatthias Ringwald 
22042d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
2205475c8125Smatthias.ringwald 
22063a9fb326S[email protected] #ifdef HAVE_MALLOC
22073a9fb326S[email protected]     if (!hci_stack) {
22083a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
22093a9fb326S[email protected]     }
22103a9fb326S[email protected] #else
22113a9fb326S[email protected]     hci_stack = &hci_stack_static;
22123a9fb326S[email protected] #endif
221366fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
22143a9fb326S[email protected] 
2215475c8125Smatthias.ringwald     // reference to use transport layer implementation
22163a9fb326S[email protected]     hci_stack->hci_transport = transport;
2217475c8125Smatthias.ringwald 
221811e23e5fSmatthias.ringwald     // reference to used config
22193a9fb326S[email protected]     hci_stack->config = config;
222011e23e5fSmatthias.ringwald 
222126a9b6daSMatthias Ringwald     // setup pointer for outgoing packet buffer
222226a9b6daSMatthias Ringwald     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
222326a9b6daSMatthias Ringwald 
22248fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
22253a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
22268fcba05dSmatthias.ringwald 
222716833f0aSmatthias.ringwald     // register packet handlers with transport
222810e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
2229f5454fc6Smatthias.ringwald 
22303a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
2231e2386ba1S[email protected] 
2232e2386ba1S[email protected]     // class of device
22333a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
2234a45d6b9fS[email protected] 
2235f20168b8Smatthias.ringwald     // bondable by default
2236f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
2237f20168b8Smatthias.ringwald 
223863048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
22393a9fb326S[email protected]     hci_stack->ssp_enable = 1;
22403a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
22413a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
22423a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
224369a97523S[email protected] 
2244fac2e2feSMatthias Ringwald     // voice setting - signed 16 bit pcm data with CVSD over the air
2245fac2e2feSMatthias Ringwald     hci_stack->sco_voice_setting = 0x60;
2246d950d659SMatthias Ringwald 
2247595bdbfbS[email protected]     hci_state_reset();
2248475c8125Smatthias.ringwald }
2249475c8125Smatthias.ringwald 
22503fb36a29SMatthias Ringwald /**
22513fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
22523fb36a29SMatthias Ringwald  */
22533fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
22543fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
22553fb36a29SMatthias Ringwald 
22563fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
22573fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
22583fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
22593fb36a29SMatthias Ringwald     }
22603fb36a29SMatthias Ringwald }
22613fb36a29SMatthias Ringwald 
2262fb55bd0aSMatthias Ringwald /**
2263d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2264fb55bd0aSMatthias Ringwald  */
2265fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
2266fb55bd0aSMatthias Ringwald     // references to used control implementation
2267fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
2268d0b87befSMatthias Ringwald     // init with transport config
2269d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
2270fb55bd0aSMatthias Ringwald }
2271fb55bd0aSMatthias Ringwald 
227271de195eSMatthias Ringwald void hci_close(void){
2273404843c1Smatthias.ringwald     // close remote device db
2274a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
2275a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
2276404843c1Smatthias.ringwald     }
22777224be7eSMatthias Ringwald 
22787224be7eSMatthias Ringwald     btstack_linked_list_iterator_t lit;
22797224be7eSMatthias Ringwald     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
22807224be7eSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&lit)){
22817224be7eSMatthias Ringwald         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
22827224be7eSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
22837224be7eSMatthias Ringwald         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
22847224be7eSMatthias Ringwald         hci_shutdown_connection(connection);
2285f5454fc6Smatthias.ringwald     }
22867224be7eSMatthias Ringwald 
2287f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
22883a9fb326S[email protected] 
22893a9fb326S[email protected] #ifdef HAVE_MALLOC
22903a9fb326S[email protected]     free(hci_stack);
22913a9fb326S[email protected] #endif
22923a9fb326S[email protected]     hci_stack = NULL;
2293404843c1Smatthias.ringwald }
2294404843c1Smatthias.ringwald 
229535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
229660b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
22979e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
22989e61646fS[email protected] }
229976f27cffSMatthias Ringwald 
230076f27cffSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
230176f27cffSMatthias Ringwald     disable_l2cap_timeouts = 1;
230276f27cffSMatthias Ringwald }
230335454696SMatthias Ringwald #endif
23049e61646fS[email protected] 
230576f27cffSMatthias Ringwald #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2306f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2307f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
2308f456b2d0S[email protected]     memcpy(hci_stack->custom_bd_addr, addr, 6);
2309f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
2310f456b2d0S[email protected] }
231176f27cffSMatthias Ringwald #endif
2312f456b2d0S[email protected] 
23138d213e1aSmatthias.ringwald // State-Module-Driver overview
23148d213e1aSmatthias.ringwald // state                    module  low-level
23158d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
23168d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
23178d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
23188d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
2319d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
2320d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
2321c7e0c5f6Smatthias.ringwald 
232240d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
23237301ad89Smatthias.ringwald 
2324038bc64cSmatthias.ringwald     // power on
2325f9a30166Smatthias.ringwald     int err = 0;
23263a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
2327d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
2328f9a30166Smatthias.ringwald     }
2329038bc64cSmatthias.ringwald     if (err){
23309da54300S[email protected]         log_error( "POWER_ON failed");
2331038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
2332038bc64cSmatthias.ringwald         return err;
2333038bc64cSmatthias.ringwald     }
2334038bc64cSmatthias.ringwald 
233524b3c629SMatthias Ringwald     // int chipset driver
23363fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
23373fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
23383fb36a29SMatthias Ringwald     }
23393fb36a29SMatthias Ringwald 
234024b3c629SMatthias Ringwald     // init transport
234124b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
234224b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
234324b3c629SMatthias Ringwald     }
234424b3c629SMatthias Ringwald 
234524b3c629SMatthias Ringwald     // open transport
234624b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
2347038bc64cSmatthias.ringwald     if (err){
23489da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
23493a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
2350d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
2351f9a30166Smatthias.ringwald         }
2352038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
2353038bc64cSmatthias.ringwald         return err;
2354038bc64cSmatthias.ringwald     }
23558d213e1aSmatthias.ringwald     return 0;
23568d213e1aSmatthias.ringwald }
2357038bc64cSmatthias.ringwald 
235840d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
23598d213e1aSmatthias.ringwald 
23609da54300S[email protected]     log_info("hci_power_control_off");
23619418f9c9Smatthias.ringwald 
23628d213e1aSmatthias.ringwald     // close low-level device
236324b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
23648d213e1aSmatthias.ringwald 
23659da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
23669418f9c9Smatthias.ringwald 
23678d213e1aSmatthias.ringwald     // power off
23683a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
2369d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
23708d213e1aSmatthias.ringwald     }
23719418f9c9Smatthias.ringwald 
23729da54300S[email protected]     log_info("hci_power_control_off - control closed");
23739418f9c9Smatthias.ringwald 
23743a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
237572ea5239Smatthias.ringwald }
237672ea5239Smatthias.ringwald 
237740d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
237872ea5239Smatthias.ringwald 
23799da54300S[email protected]     log_info("hci_power_control_sleep");
23803144bce4Smatthias.ringwald 
2381b429b9b7Smatthias.ringwald #if 0
2382b429b9b7Smatthias.ringwald     // don't close serial port during sleep
2383b429b9b7Smatthias.ringwald 
238472ea5239Smatthias.ringwald     // close low-level device
23853a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
2386b429b9b7Smatthias.ringwald #endif
238772ea5239Smatthias.ringwald 
238872ea5239Smatthias.ringwald     // sleep mode
23893a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
2390d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
239172ea5239Smatthias.ringwald     }
2392b429b9b7Smatthias.ringwald 
23933a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
23948d213e1aSmatthias.ringwald }
23958d213e1aSmatthias.ringwald 
239640d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
2397b429b9b7Smatthias.ringwald 
23989da54300S[email protected]     log_info("hci_power_control_wake");
2399b429b9b7Smatthias.ringwald 
2400b429b9b7Smatthias.ringwald     // wake on
24013a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
2402d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
2403b429b9b7Smatthias.ringwald     }
2404b429b9b7Smatthias.ringwald 
2405b429b9b7Smatthias.ringwald #if 0
2406b429b9b7Smatthias.ringwald     // open low-level device
24073a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
2408b429b9b7Smatthias.ringwald     if (err){
24099da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
24103a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
2411d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
2412b429b9b7Smatthias.ringwald         }
2413b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
2414b429b9b7Smatthias.ringwald         return err;
2415b429b9b7Smatthias.ringwald     }
2416b429b9b7Smatthias.ringwald #endif
2417b429b9b7Smatthias.ringwald 
2418b429b9b7Smatthias.ringwald     return 0;
2419b429b9b7Smatthias.ringwald }
2420b429b9b7Smatthias.ringwald 
242144935e40S[email protected] static void hci_power_transition_to_initializing(void){
242244935e40S[email protected]     // set up state machine
242344935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
242444935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
242544935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
24265c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
242744935e40S[email protected] }
2428b429b9b7Smatthias.ringwald 
24298d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
2430d661ed19Smatthias.ringwald 
2431f04a0c31SMatthias Ringwald     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2432d661ed19Smatthias.ringwald 
24338d213e1aSmatthias.ringwald     int err = 0;
24343a9fb326S[email protected]     switch (hci_stack->state){
24358d213e1aSmatthias.ringwald 
24368d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
24378d213e1aSmatthias.ringwald             switch (power_mode){
24388d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
24398d213e1aSmatthias.ringwald                     err = hci_power_control_on();
244097b61c7bS[email protected]                     if (err) {
2441f04a0c31SMatthias Ringwald                         log_error("hci_power_control_on() error %d", err);
244297b61c7bS[email protected]                         return err;
244397b61c7bS[email protected]                     }
244444935e40S[email protected]                     hci_power_transition_to_initializing();
24458d213e1aSmatthias.ringwald                     break;
24468d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
24478d213e1aSmatthias.ringwald                     // do nothing
24488d213e1aSmatthias.ringwald                     break;
24498d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2450b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
24518d213e1aSmatthias.ringwald                     break;
24528d213e1aSmatthias.ringwald             }
24538d213e1aSmatthias.ringwald             break;
24547301ad89Smatthias.ringwald 
24558d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
24568d213e1aSmatthias.ringwald             switch (power_mode){
24578d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
24588d213e1aSmatthias.ringwald                     // do nothing
24598d213e1aSmatthias.ringwald                     break;
24608d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
24618d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
24628d213e1aSmatthias.ringwald                     hci_power_control_off();
24638d213e1aSmatthias.ringwald                     break;
24648d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2465b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
246672ea5239Smatthias.ringwald                     hci_power_control_sleep();
24678d213e1aSmatthias.ringwald                     break;
24688d213e1aSmatthias.ringwald             }
24698d213e1aSmatthias.ringwald             break;
24707301ad89Smatthias.ringwald 
24718d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
24728d213e1aSmatthias.ringwald             switch (power_mode){
24738d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
24748d213e1aSmatthias.ringwald                     // do nothing
24758d213e1aSmatthias.ringwald                     break;
24768d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
2477c7e0c5f6Smatthias.ringwald                     // see hci_run
24783a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
24798d213e1aSmatthias.ringwald                     break;
24808d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2481b546ac54Smatthias.ringwald                     // see hci_run
24823a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
248374b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
24848d213e1aSmatthias.ringwald                     break;
24858d213e1aSmatthias.ringwald             }
24868d213e1aSmatthias.ringwald             break;
24877301ad89Smatthias.ringwald 
24888d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
24898d213e1aSmatthias.ringwald             switch (power_mode){
24908d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
249144935e40S[email protected]                     hci_power_transition_to_initializing();
24928d213e1aSmatthias.ringwald                     break;
24938d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
24948d213e1aSmatthias.ringwald                     // do nothing
24958d213e1aSmatthias.ringwald                     break;
24968d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2497b546ac54Smatthias.ringwald                     // see hci_run
24983a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
249974b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
25008d213e1aSmatthias.ringwald                     break;
25018d213e1aSmatthias.ringwald             }
25028d213e1aSmatthias.ringwald             break;
25038d213e1aSmatthias.ringwald 
25048d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
25058d213e1aSmatthias.ringwald             switch (power_mode){
25068d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
250728171530Smatthias.ringwald 
2508423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
250928171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
2510d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
25113a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
251274b323a9SMatthias Ringwald                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
251328171530Smatthias.ringwald                         break;
251428171530Smatthias.ringwald                     }
251528171530Smatthias.ringwald #endif
251644935e40S[email protected]                     hci_power_transition_to_initializing();
25178d213e1aSmatthias.ringwald                     break;
25188d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
2519b546ac54Smatthias.ringwald                     // see hci_run
25203a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
25218d213e1aSmatthias.ringwald                     break;
25228d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2523b546ac54Smatthias.ringwald                     // do nothing
25248d213e1aSmatthias.ringwald                     break;
25258d213e1aSmatthias.ringwald             }
25268d213e1aSmatthias.ringwald             break;
25278d213e1aSmatthias.ringwald 
25288d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
25298d213e1aSmatthias.ringwald             switch (power_mode){
25308d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
253128171530Smatthias.ringwald 
2532423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
253328171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
2534d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
25353a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
25365c363727SMatthias Ringwald                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2537758b46ceSmatthias.ringwald                         hci_update_scan_enable();
253828171530Smatthias.ringwald                         break;
253928171530Smatthias.ringwald                     }
254028171530Smatthias.ringwald #endif
25413144bce4Smatthias.ringwald                     err = hci_power_control_wake();
25423144bce4Smatthias.ringwald                     if (err) return err;
254344935e40S[email protected]                     hci_power_transition_to_initializing();
25448d213e1aSmatthias.ringwald                     break;
25458d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
25463a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
25478d213e1aSmatthias.ringwald                     break;
25488d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2549b546ac54Smatthias.ringwald                     // do nothing
25508d213e1aSmatthias.ringwald                     break;
25518d213e1aSmatthias.ringwald             }
25528d213e1aSmatthias.ringwald             break;
255311e23e5fSmatthias.ringwald     }
255468d92d03Smatthias.ringwald 
2555038bc64cSmatthias.ringwald     // create internal event
2556ee8bf225Smatthias.ringwald 	hci_emit_state();
2557ee8bf225Smatthias.ringwald 
255868d92d03Smatthias.ringwald 	// trigger next/first action
255968d92d03Smatthias.ringwald 	hci_run();
256068d92d03Smatthias.ringwald 
2561475c8125Smatthias.ringwald     return 0;
2562475c8125Smatthias.ringwald }
2563475c8125Smatthias.ringwald 
256435454696SMatthias Ringwald 
256535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
256635454696SMatthias Ringwald 
2567758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
2568758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
25693a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2570758b46ceSmatthias.ringwald     hci_run();
2571758b46ceSmatthias.ringwald }
2572758b46ceSmatthias.ringwald 
257315a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
2574381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
2575381fbed8Smatthias.ringwald 
25763a9fb326S[email protected]     if (hci_stack->discoverable == enable){
25773a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
2578381fbed8Smatthias.ringwald         return;
2579381fbed8Smatthias.ringwald     }
2580381fbed8Smatthias.ringwald 
25813a9fb326S[email protected]     hci_stack->discoverable = enable;
2582758b46ceSmatthias.ringwald     hci_update_scan_enable();
2583758b46ceSmatthias.ringwald }
2584b031bebbSmatthias.ringwald 
258515a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
2586758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
2587758b46ceSmatthias.ringwald 
2588758b46ceSmatthias.ringwald     // don't emit event
25893a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
2590758b46ceSmatthias.ringwald 
25913a9fb326S[email protected]     hci_stack->connectable = enable;
2592758b46ceSmatthias.ringwald     hci_update_scan_enable();
2593381fbed8Smatthias.ringwald }
259435454696SMatthias Ringwald #endif
2595381fbed8Smatthias.ringwald 
259615a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
2597690bd0baS[email protected]     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
25985061f3afS[email protected] }
25995061f3afS[email protected] 
260095d71764SMatthias Ringwald static void hci_run(void){
26018a485f27Smatthias.ringwald 
2602db8bc6ffSMatthias Ringwald     // log_info("hci_run: entered");
2603665d90f2SMatthias Ringwald     btstack_linked_item_t * it;
260432ab9390Smatthias.ringwald 
2605b5d8b22bS[email protected]     // send continuation fragments first, as they block the prepared packet buffer
2606b5d8b22bS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
2607b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2608b5d8b22bS[email protected]         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2609b5d8b22bS[email protected]         if (connection) {
261028a0332dSMatthias Ringwald             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2611b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
2612b5d8b22bS[email protected]                 return;
2613b5d8b22bS[email protected]             }
261428a0332dSMatthias Ringwald         } else {
2615b5d8b22bS[email protected]             // connection gone -> discard further fragments
261628a0332dSMatthias Ringwald             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2617b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
2618b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
2619b5d8b22bS[email protected]         }
2620b5d8b22bS[email protected]     }
2621b5d8b22bS[email protected] 
2622d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()) return;
2623ce4c8fabSmatthias.ringwald 
2624b031bebbSmatthias.ringwald     // global/non-connection oriented commands
2625b031bebbSmatthias.ringwald 
262635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
2627b031bebbSmatthias.ringwald     // decline incoming connections
26283a9fb326S[email protected]     if (hci_stack->decline_reason){
26293a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
26303a9fb326S[email protected]         hci_stack->decline_reason = 0;
26313a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2632dbe1a790S[email protected]         return;
2633ce4c8fabSmatthias.ringwald     }
2634ce4c8fabSmatthias.ringwald 
2635b031bebbSmatthias.ringwald     // send scan enable
26363a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
26373a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
26383a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
2639dbe1a790S[email protected]         return;
2640b031bebbSmatthias.ringwald     }
264135454696SMatthias Ringwald #endif
2642b031bebbSmatthias.ringwald 
2643a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2644b95a5a35SMatthias Ringwald     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2645b95a5a35SMatthias Ringwald     if ((hci_stack->state == HCI_STATE_WORKING)
2646b95a5a35SMatthias Ringwald     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2647d70217a2SMatthias Ringwald 
2648d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
264945c102fdSMatthias Ringwald         // handle le scan
26507bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
26517bdc6798S[email protected]             case LE_START_SCAN:
26527bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
26537bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
26547bdc6798S[email protected]                 return;
26557bdc6798S[email protected] 
26567bdc6798S[email protected]             case LE_STOP_SCAN:
26577bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
26587bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
26597bdc6798S[email protected]                 return;
26607bdc6798S[email protected]             default:
26617bdc6798S[email protected]                 break;
26627bdc6798S[email protected]         }
2663e2602ea2Smatthias.ringwald         if (hci_stack->le_scan_type != 0xff){
2664e2602ea2Smatthias.ringwald             // defaults: active scanning, accept all advertisement packets
2665e2602ea2Smatthias.ringwald             int scan_type = hci_stack->le_scan_type;
2666e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
2667b95a5a35SMatthias 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);
2668e2602ea2Smatthias.ringwald             return;
2669e2602ea2Smatthias.ringwald         }
2670d70217a2SMatthias Ringwald #endif
2671d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
267245c102fdSMatthias Ringwald         // le advertisement control
26739a2e4658SMatthias Ringwald         if (hci_stack->le_advertisements_todo){
26749a2e4658SMatthias Ringwald             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
26759a2e4658SMatthias Ringwald         }
267645c102fdSMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
267745c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
267845c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
267945c102fdSMatthias Ringwald             return;
268045c102fdSMatthias Ringwald         }
268145c102fdSMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
268245c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
268345c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
268445c102fdSMatthias Ringwald                  hci_stack->le_advertisements_interval_min,
268545c102fdSMatthias Ringwald                  hci_stack->le_advertisements_interval_max,
268645c102fdSMatthias Ringwald                  hci_stack->le_advertisements_type,
2687b95a5a35SMatthias Ringwald                  hci_stack->le_own_addr_type,
268845c102fdSMatthias Ringwald                  hci_stack->le_advertisements_direct_address_type,
268945c102fdSMatthias Ringwald                  hci_stack->le_advertisements_direct_address,
269045c102fdSMatthias Ringwald                  hci_stack->le_advertisements_channel_map,
269145c102fdSMatthias Ringwald                  hci_stack->le_advertisements_filter_policy);
269245c102fdSMatthias Ringwald             return;
269345c102fdSMatthias Ringwald         }
2694501f56b3SMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2695501f56b3SMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2696b95a5a35SMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, hci_stack->le_advertisements_data);
269745c102fdSMatthias Ringwald             return;
269845c102fdSMatthias Ringwald         }
2699501f56b3SMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2700501f56b3SMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2701501f56b3SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2702501f56b3SMatthias Ringwald                 hci_stack->le_scan_response_data);
2703501f56b3SMatthias Ringwald             return;
2704501f56b3SMatthias Ringwald         }
2705b95a5a35SMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
270645c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
270745c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
270845c102fdSMatthias Ringwald             return;
270945c102fdSMatthias Ringwald         }
2710d70217a2SMatthias Ringwald #endif
27119956955bSMatthias Ringwald 
2712d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
27139956955bSMatthias Ringwald         //
27149956955bSMatthias Ringwald         // LE Whitelist Management
27159956955bSMatthias Ringwald         //
27169956955bSMatthias Ringwald 
27179956955bSMatthias Ringwald         // check if whitelist needs modification
2718665d90f2SMatthias Ringwald         btstack_linked_list_iterator_t lit;
27199956955bSMatthias Ringwald         int modification_pending = 0;
2720665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2721665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
2722665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
27239956955bSMatthias Ringwald             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
27249956955bSMatthias Ringwald                 modification_pending = 1;
27259956955bSMatthias Ringwald                 break;
27269956955bSMatthias Ringwald             }
27279956955bSMatthias Ringwald         }
272891915b0bSMatthias Ringwald 
27299956955bSMatthias Ringwald         if (modification_pending){
273091915b0bSMatthias Ringwald             // stop connnecting if modification pending
27319956955bSMatthias Ringwald             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
27329956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_create_connection_cancel);
27339956955bSMatthias Ringwald                 return;
27349956955bSMatthias Ringwald             }
27359956955bSMatthias Ringwald 
27369956955bSMatthias Ringwald             // add/remove entries
2737665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2738665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&lit)){
2739665d90f2SMatthias Ringwald                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
27409956955bSMatthias Ringwald                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
27419956955bSMatthias Ringwald                     entry->state = LE_WHITELIST_ON_CONTROLLER;
27429956955bSMatthias Ringwald                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
27439956955bSMatthias Ringwald                     return;
27449956955bSMatthias Ringwald 
27459956955bSMatthias Ringwald                 }
27469956955bSMatthias Ringwald                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
27479ecbe201SMatthias Ringwald                     bd_addr_t address;
27489ecbe201SMatthias Ringwald                     bd_addr_type_t address_type = entry->address_type;
27499ecbe201SMatthias Ringwald                     memcpy(address, entry->address, 6);
2750665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
27519956955bSMatthias Ringwald                     btstack_memory_whitelist_entry_free(entry);
27529ecbe201SMatthias Ringwald                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
27539956955bSMatthias Ringwald                     return;
27549956955bSMatthias Ringwald                 }
27559956955bSMatthias Ringwald             }
275691915b0bSMatthias Ringwald         }
27579956955bSMatthias Ringwald 
27589956955bSMatthias Ringwald         // start connecting
275991915b0bSMatthias Ringwald         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2760665d90f2SMatthias Ringwald             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
27619956955bSMatthias Ringwald             bd_addr_t null_addr;
27629956955bSMatthias Ringwald             memset(null_addr, 0, 6);
27639956955bSMatthias Ringwald             hci_send_cmd(&hci_le_create_connection,
27649956955bSMatthias Ringwald                  0x0060,    // scan interval: 60 ms
27659956955bSMatthias Ringwald                  0x0030,    // scan interval: 30 ms
27669956955bSMatthias Ringwald                  1,         // use whitelist
27679956955bSMatthias Ringwald                  0,         // peer address type
27689956955bSMatthias Ringwald                  null_addr, // peer bd addr
2769b95a5a35SMatthias Ringwald                  hci_stack->le_own_addr_type, // our addr type:
27709956955bSMatthias Ringwald                  0x0008,    // conn interval min
27719956955bSMatthias Ringwald                  0x0018,    // conn interval max
27729956955bSMatthias Ringwald                  0,         // conn latency
27739956955bSMatthias Ringwald                  0x0048,    // supervision timeout
27749956955bSMatthias Ringwald                  0x0001,    // min ce length
27759956955bSMatthias Ringwald                  0x0001     // max ce length
27769956955bSMatthias Ringwald                  );
27779956955bSMatthias Ringwald             return;
27789956955bSMatthias Ringwald         }
2779d70217a2SMatthias Ringwald #endif
27807bdc6798S[email protected]     }
2781b2f949feS[email protected] #endif
27827bdc6798S[email protected] 
278332ab9390Smatthias.ringwald     // send pending HCI commands
2784665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
278505ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
278632ab9390Smatthias.ringwald 
27870bf6344aS[email protected]         switch(connection->state){
27880bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
27894f3229d8S[email protected]                 switch(connection->address_type){
279035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
27914f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
27929da54300S[email protected]                         log_info("sending hci_create_connection");
2793ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
27944f3229d8S[email protected]                         break;
279535454696SMatthias Ringwald #endif
27964f3229d8S[email protected]                     default:
2797a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2798d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
27999da54300S[email protected]                         log_info("sending hci_le_create_connection");
28004f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
2801b2571179Smatthias.ringwald                                      0x0060,    // scan interval: 60 ms
2802b2571179Smatthias.ringwald                                      0x0030,    // scan interval: 30 ms
28034f3229d8S[email protected]                                      0,         // don't use whitelist
28044f3229d8S[email protected]                                      connection->address_type, // peer address type
28054f3229d8S[email protected]                                      connection->address,      // peer bd addr
2806b95a5a35SMatthias Ringwald                                      hci_stack->le_own_addr_type,  // our addr type:
2807b2571179Smatthias.ringwald                                      0x0008,    // conn interval min
2808b2571179Smatthias.ringwald                                      0x0018,    // conn interval max
28094f3229d8S[email protected]                                      0,         // conn latency
2810b2571179Smatthias.ringwald                                      0x0048,    // supervision timeout
2811b2571179Smatthias.ringwald                                      0x0001,    // min ce length
2812b2571179Smatthias.ringwald                                      0x0001     // max ce length
28134f3229d8S[email protected]                                      );
28144f3229d8S[email protected] 
28154f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
2816b2f949feS[email protected] #endif
2817d70217a2SMatthias Ringwald #endif
28184f3229d8S[email protected]                         break;
28194f3229d8S[email protected]                 }
2820ad83dc6aS[email protected]                 return;
2821ad83dc6aS[email protected] 
282235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
28230bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
282494e4aaa2SMatthias Ringwald                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
282532ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
28265cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
2827e35edcc1S[email protected]                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
282834d2123cS[email protected]                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2829e35edcc1S[email protected]                 }
2830dbe1a790S[email protected]                 return;
283135454696SMatthias Ringwald #endif
28320bf6344aS[email protected] 
2833a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2834d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
28350bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
28360bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
28370bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
28380bf6344aS[email protected]                 return;
2839a6725849S[email protected] #endif
2840d70217a2SMatthias Ringwald #endif
28410bf6344aS[email protected]             case SEND_DISCONNECT:
28420bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
28437851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
28440bf6344aS[email protected]                 return;
28450bf6344aS[email protected] 
28460bf6344aS[email protected]             default:
28470bf6344aS[email protected]                 break;
2848c7e0c5f6Smatthias.ringwald         }
2849c7e0c5f6Smatthias.ringwald 
285035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
285132ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
28529da54300S[email protected]             log_info("responding to link key request");
285334d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
285432ab9390Smatthias.ringwald             link_key_t link_key;
2855c77e8838S[email protected]             link_key_type_t link_key_type;
2856a98592bcSMatthias Ringwald             if ( hci_stack->link_key_db
2857a98592bcSMatthias Ringwald               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
285834d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
28599ab95c90S[email protected]                connection->link_key_type = link_key_type;
286032ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
286132ab9390Smatthias.ringwald             } else {
286232ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
286332ab9390Smatthias.ringwald             }
2864dbe1a790S[email protected]             return;
286532ab9390Smatthias.ringwald         }
28661d6b20aeS[email protected] 
2867899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
28689da54300S[email protected]             log_info("denying to pin request");
2869899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
287034d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
28714c57c146S[email protected]             return;
28724c57c146S[email protected]         }
28734c57c146S[email protected] 
2874dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
287534d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
287682d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
287782d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2878106d6d11S[email protected]                 // tweak authentication requirements
28793a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2880106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
28819faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
28829faad3abS[email protected]                 }
28839faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
28849faad3abS[email protected]                     authreq |= 1;
2885106d6d11S[email protected]                 }
28863a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2887f8fb5f6eS[email protected]             } else {
2888f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2889f8fb5f6eS[email protected]             }
2890dbe1a790S[email protected]             return;
289132ab9390Smatthias.ringwald         }
289232ab9390Smatthias.ringwald 
2893dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2894dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
289534d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2896dbe1a790S[email protected]             return;
2897dbe1a790S[email protected]         }
2898dbe1a790S[email protected] 
2899dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2900dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
290134d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2902dbe1a790S[email protected]             return;
2903dbe1a790S[email protected]         }
2904afd4e962S[email protected] 
2905afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2906afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
290734d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
29082bd8b7e7S[email protected]             return;
29092bd8b7e7S[email protected]         }
29102bd8b7e7S[email protected] 
2911ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2912ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
29131bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
291452d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2915ad83dc6aS[email protected]             return;
2916ad83dc6aS[email protected]         }
291776f27cffSMatthias Ringwald 
291834d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
291934d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
292034d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
29212bd8b7e7S[email protected]             return;
2922afd4e962S[email protected]         }
292376f27cffSMatthias Ringwald 
2924dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2925dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2926dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2927dce78009S[email protected]             return;
2928dce78009S[email protected]         }
292976f27cffSMatthias Ringwald #endif
293076f27cffSMatthias Ringwald 
293176f27cffSMatthias Ringwald         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
293276f27cffSMatthias Ringwald             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
293376f27cffSMatthias Ringwald             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
293476f27cffSMatthias Ringwald             return;
293576f27cffSMatthias Ringwald         }
2936da886c03S[email protected] 
2937a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2938da886c03S[email protected]         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2939da886c03S[email protected]             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2940da886c03S[email protected] 
2941c37a3166S[email protected]             uint16_t connection_interval_min = connection->le_conn_interval_min;
2942c37a3166S[email protected]             connection->le_conn_interval_min = 0;
2943c37a3166S[email protected]             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2944c37a3166S[email protected]                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2945c37a3166S[email protected]                 0x0000, 0xffff);
2946c37a3166S[email protected]         }
2947c37a3166S[email protected] #endif
2948dbe1a790S[email protected]     }
2949c7e0c5f6Smatthias.ringwald 
295005ae8de3SMatthias Ringwald     hci_connection_t * connection;
29513a9fb326S[email protected]     switch (hci_stack->state){
29523429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
295374b323a9SMatthias Ringwald             hci_initializing_run();
29543429f56bSmatthias.ringwald             break;
2955c7e0c5f6Smatthias.ringwald 
2956c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
2957c7e0c5f6Smatthias.ringwald 
29589da54300S[email protected]             log_info("HCI_STATE_HALTING");
29599956955bSMatthias Ringwald 
29609956955bSMatthias Ringwald             // free whitelist entries
2961a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2962d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
29639956955bSMatthias Ringwald             {
2964665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_t lit;
2965665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2966665d90f2SMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&lit)){
2967665d90f2SMatthias Ringwald                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2968665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
29699956955bSMatthias Ringwald                     btstack_memory_whitelist_entry_free(entry);
29709956955bSMatthias Ringwald                 }
29719956955bSMatthias Ringwald             }
29729956955bSMatthias Ringwald #endif
2973d70217a2SMatthias Ringwald #endif
2974c7e0c5f6Smatthias.ringwald             // close all open connections
29753a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
2976c7e0c5f6Smatthias.ringwald             if (connection){
2977711e6c80SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2978d94d3cafS[email protected]                 if (!hci_can_send_command_packet_now()) return;
297932ab9390Smatthias.ringwald 
29808837e9efSMatthias Ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2981c7e0c5f6Smatthias.ringwald 
29828837e9efSMatthias Ringwald                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
29838837e9efSMatthias Ringwald                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
29848837e9efSMatthias Ringwald 
29858837e9efSMatthias Ringwald                 // ... which would be ignored anyway as we shutdown (free) the connection now
2986c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
29878837e9efSMatthias Ringwald 
29888837e9efSMatthias Ringwald                 // finally, send the disconnect command
29898837e9efSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2990c7e0c5f6Smatthias.ringwald                 return;
2991c7e0c5f6Smatthias.ringwald             }
29929da54300S[email protected]             log_info("HCI_STATE_HALTING, calling off");
2993c7e0c5f6Smatthias.ringwald 
299472ea5239Smatthias.ringwald             // switch mode
2995c7e0c5f6Smatthias.ringwald             hci_power_control_off();
29969418f9c9Smatthias.ringwald 
29979da54300S[email protected]             log_info("HCI_STATE_HALTING, emitting state");
299872ea5239Smatthias.ringwald             hci_emit_state();
29999da54300S[email protected]             log_info("HCI_STATE_HALTING, done");
300072ea5239Smatthias.ringwald             break;
3001c7e0c5f6Smatthias.ringwald 
300272ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
30033a9fb326S[email protected]             switch(hci_stack->substate) {
300474b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_DISCONNECT:
30059da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
300672ea5239Smatthias.ringwald                     // close all open connections
30073a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
300866da7044Smatthias.ringwald 
3009423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
301066da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
3011d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
301266da7044Smatthias.ringwald                         connection = NULL;
301366da7044Smatthias.ringwald                     }
301466da7044Smatthias.ringwald #endif
301572ea5239Smatthias.ringwald                     if (connection){
301632ab9390Smatthias.ringwald 
301772ea5239Smatthias.ringwald                         // send disconnect
3018d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
301932ab9390Smatthias.ringwald 
30209da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
30216ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
302272ea5239Smatthias.ringwald 
302372ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
302472ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
302572ea5239Smatthias.ringwald                         return;
302672ea5239Smatthias.ringwald                     }
302772ea5239Smatthias.ringwald 
302892368cd3S[email protected]                     if (hci_classic_supported()){
302989db417bSmatthias.ringwald                         // disable page and inquiry scan
3030d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
303132ab9390Smatthias.ringwald 
30329da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
30333a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
303489db417bSmatthias.ringwald 
303589db417bSmatthias.ringwald                         // continue in next sub state
303674b323a9SMatthias Ringwald                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
303789db417bSmatthias.ringwald                         break;
303892368cd3S[email protected]                     }
3039202c8a4cSMatthias Ringwald                     // no break - fall through for ble-only chips
304092368cd3S[email protected] 
304174b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_COMPLETE:
30429da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
3043423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
304428171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
3045d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
304628171530Smatthias.ringwald                         // SLEEP MODE reached
30473a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
304828171530Smatthias.ringwald                         hci_emit_state();
304928171530Smatthias.ringwald                         break;
305028171530Smatthias.ringwald                     }
305128171530Smatthias.ringwald #endif
305272ea5239Smatthias.ringwald                     // switch mode
30533a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3054c7e0c5f6Smatthias.ringwald                     hci_emit_state();
305528171530Smatthias.ringwald                     break;
305628171530Smatthias.ringwald 
305789db417bSmatthias.ringwald                 default:
305889db417bSmatthias.ringwald                     break;
305989db417bSmatthias.ringwald             }
3060c7e0c5f6Smatthias.ringwald             break;
3061c7e0c5f6Smatthias.ringwald 
30623429f56bSmatthias.ringwald         default:
30633429f56bSmatthias.ringwald             break;
30641f504dbdSmatthias.ringwald     }
30653429f56bSmatthias.ringwald }
306616833f0aSmatthias.ringwald 
306731452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
306835454696SMatthias Ringwald     // house-keeping
306935454696SMatthias Ringwald 
307035454696SMatthias Ringwald     if (IS_COMMAND(packet, hci_write_loopback_mode)){
307135454696SMatthias Ringwald         hci_stack->loopback_mode = packet[3];
307235454696SMatthias Ringwald     }
307335454696SMatthias Ringwald 
307435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3075c8e4258aSmatthias.ringwald     bd_addr_t addr;
3076c8e4258aSmatthias.ringwald     hci_connection_t * conn;
3077c8e4258aSmatthias.ringwald 
3078c8e4258aSmatthias.ringwald     // create_connection?
3079c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
3080724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
30819da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
3082c8e4258aSmatthias.ringwald 
30832e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3084ad83dc6aS[email protected]         if (!conn){
308596a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
308617f1ba2aSmatthias.ringwald             if (!conn){
308717f1ba2aSmatthias.ringwald                 // notify client that alloc failed
30882deddeceSMatthias Ringwald                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
308917f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
309017f1ba2aSmatthias.ringwald             }
3091ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
3092ad83dc6aS[email protected]         }
3093ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
3094ad83dc6aS[email protected]         switch (conn->state){
3095ad83dc6aS[email protected]             // if connection active exists
3096ad83dc6aS[email protected]             case OPEN:
309762bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
3098274dad91SMatthias Ringwald                 hci_emit_connection_complete(addr, conn->con_handle, 0);
309962bda3fbS[email protected]                 return 0;
3100ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
3101ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
3102ad83dc6aS[email protected]                 break;
3103ad83dc6aS[email protected]             default:
3104ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
3105ad83dc6aS[email protected]                 return 0;
3106ad83dc6aS[email protected]         }
3107c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
3108c8e4258aSmatthias.ringwald     }
310935454696SMatthias Ringwald 
31107fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
31117fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
31127fde4af9Smatthias.ringwald     }
31137fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
31147fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
31157fde4af9Smatthias.ringwald     }
31167fde4af9Smatthias.ringwald 
31178ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3118a98592bcSMatthias Ringwald         if (hci_stack->link_key_db){
3119724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
3120a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
31218ef73945Smatthias.ringwald         }
31228ef73945Smatthias.ringwald     }
3123c8e4258aSmatthias.ringwald 
31246724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
31256724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3126724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
31272e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
31286724cd9eS[email protected]         if (conn){
31296724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
31306724cd9eS[email protected]         }
31316724cd9eS[email protected]     }
31326724cd9eS[email protected] 
31336724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
31346724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
31356724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
31366724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3137724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
31382e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
31396724cd9eS[email protected]         if (conn){
31406724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
31416724cd9eS[email protected]         }
31426724cd9eS[email protected]     }
3143ee752bb8SMatthias Ringwald 
3144ee752bb8SMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
3145ee752bb8SMatthias Ringwald     // setup_synchronous_connection? Voice setting at offset 22
3146ee752bb8SMatthias Ringwald     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3147ee752bb8SMatthias Ringwald         // TODO: compare to current setting if sco connection already active
3148ee752bb8SMatthias Ringwald         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3149ee752bb8SMatthias Ringwald     }
3150ee752bb8SMatthias Ringwald     // accept_synchronus_connection? Voice setting at offset 18
3151ee752bb8SMatthias Ringwald     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3152ee752bb8SMatthias Ringwald         // TODO: compare to current setting if sco connection already active
3153ee752bb8SMatthias Ringwald         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3154ee752bb8SMatthias Ringwald     }
3155ee752bb8SMatthias Ringwald #endif
315635454696SMatthias Ringwald #endif
31574b3e1e19SMatthias Ringwald 
3158a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
3159d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
316069a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
3161b95a5a35SMatthias Ringwald         hci_stack->le_random_address_set = 1;
3162b95a5a35SMatthias Ringwald         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3163d70217a2SMatthias Ringwald     }
3164171293d3SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3165171293d3SMatthias Ringwald         hci_stack->le_advertisements_active = packet[3];
3166171293d3SMatthias Ringwald     }
3167d70217a2SMatthias Ringwald #endif
3168d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3169b04dfa37SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_create_connection)){
3170b04dfa37SMatthias Ringwald         // white list used?
3171b04dfa37SMatthias Ringwald         uint8_t initiator_filter_policy = packet[7];
3172b04dfa37SMatthias Ringwald         switch (initiator_filter_policy){
3173b04dfa37SMatthias Ringwald             case 0:
3174b04dfa37SMatthias Ringwald                 // whitelist not used
3175b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3176b04dfa37SMatthias Ringwald                 break;
3177b04dfa37SMatthias Ringwald             case 1:
3178b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3179b04dfa37SMatthias Ringwald                 break;
3180b04dfa37SMatthias Ringwald             default:
3181b04dfa37SMatthias Ringwald                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3182b04dfa37SMatthias Ringwald                 break;
3183b04dfa37SMatthias Ringwald         }
3184b04dfa37SMatthias Ringwald     }
3185b04dfa37SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3186b04dfa37SMatthias Ringwald         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3187b04dfa37SMatthias Ringwald     }
318869a97523S[email protected] #endif
3189d70217a2SMatthias Ringwald #endif
319069a97523S[email protected] 
31913a9fb326S[email protected]     hci_stack->num_cmd_packets--;
31925bb5bc3eS[email protected] 
31935bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
31946b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
31956b4af23dS[email protected] 
3196d051460cS[email protected]     // release packet buffer for synchronous transport implementations
3197c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
31986b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
31996b4af23dS[email protected]     }
32006b4af23dS[email protected] 
32016b4af23dS[email protected]     return err;
320231452debSmatthias.ringwald }
32038adf0ddaSmatthias.ringwald 
32042bd8b7e7S[email protected] // disconnect because of security block
32052bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
32062bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
32072bd8b7e7S[email protected]     if (!connection) return;
32082bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
32092bd8b7e7S[email protected] }
32102bd8b7e7S[email protected] 
32112bd8b7e7S[email protected] 
3212dbe1a790S[email protected] // Configure Secure Simple Pairing
3213dbe1a790S[email protected] 
321435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
321535454696SMatthias Ringwald 
3216dbe1a790S[email protected] // enable will enable SSP during init
321715a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
32183a9fb326S[email protected]     hci_stack->ssp_enable = enable;
3219dbe1a790S[email protected] }
3220dbe1a790S[email protected] 
322195d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
322215a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
32232bd8b7e7S[email protected] }
32242bd8b7e7S[email protected] 
3225dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
322615a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
32273a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
3228dbe1a790S[email protected] }
322915a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
32303a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
3231dbe1a790S[email protected] }
3232dbe1a790S[email protected] 
3233dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
323415a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
32353a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
3236dbe1a790S[email protected] }
323735454696SMatthias Ringwald #endif
3238dbe1a790S[email protected] 
323994be1a66SMatthias Ringwald // va_list part of hci_send_cmd
324094be1a66SMatthias Ringwald int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3241d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
32429d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
32439d14b626S[email protected]         return 0;
32449d14b626S[email protected]     }
32459d14b626S[email protected] 
32465127cc62S[email protected]     // for HCI INITIALIZATION
32479da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
32485127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
32495127cc62S[email protected] 
32509d14b626S[email protected]     hci_reserve_packet_buffer();
32519d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
325294be1a66SMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
325394be1a66SMatthias Ringwald     return hci_send_cmd_packet(packet, size);
325494be1a66SMatthias Ringwald }
32559d14b626S[email protected] 
325694be1a66SMatthias Ringwald /**
325794be1a66SMatthias Ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
325894be1a66SMatthias Ringwald  */
325994be1a66SMatthias Ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
32601cd208adSmatthias.ringwald     va_list argptr;
32611cd208adSmatthias.ringwald     va_start(argptr, cmd);
326294be1a66SMatthias Ringwald     int res = hci_send_cmd_va_arg(cmd, argptr);
32631cd208adSmatthias.ringwald     va_end(argptr);
326494be1a66SMatthias Ringwald     return res;
326593b8dc03Smatthias.ringwald }
3266c8e4258aSmatthias.ringwald 
3267ee091cf1Smatthias.ringwald // Create various non-HCI events.
3268ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
3269ee091cf1Smatthias.ringwald 
3270d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3271fb37a842SMatthias Ringwald     // dump packet
3272d6b06661SMatthias Ringwald     if (dump) {
3273300c1ba4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3274d6b06661SMatthias Ringwald     }
32751ef6bb52SMatthias Ringwald 
3276fb37a842SMatthias Ringwald     // dispatch to all event handlers
32771ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
32781ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
32791ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
32801ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3281d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
32821ef6bb52SMatthias Ringwald     }
3283d6b06661SMatthias Ringwald }
3284d6b06661SMatthias Ringwald 
3285d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3286fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
32873d50b4baSMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3288d6b06661SMatthias Ringwald }
3289d6b06661SMatthias Ringwald 
329035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3291701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
32923bc639ceSMatthias Ringwald     // notify SCO sender if waiting
3293701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
3294701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
32953bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
3296701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3297701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
32983d50b4baSMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
32993bc639ceSMatthias Ringwald     }
33003bc639ceSMatthias Ringwald }
330135454696SMatthias Ringwald #endif
33023bc639ceSMatthias Ringwald 
330371de195eSMatthias Ringwald void hci_emit_state(void){
33043a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3305425d1371Smatthias.ringwald     uint8_t event[3];
330680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
3307425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
33083a9fb326S[email protected]     event[2] = hci_stack->state;
3309d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3310c8e4258aSmatthias.ringwald }
3311c8e4258aSmatthias.ringwald 
331235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
33132deddeceSMatthias Ringwald static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3314425d1371Smatthias.ringwald     uint8_t event[13];
3315c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3316425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
331717f1ba2aSmatthias.ringwald     event[2] = status;
33182deddeceSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
33192deddeceSMatthias Ringwald     reverse_bd_addr(address, &event[5]);
3320c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
3321c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
3322d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3323c8e4258aSmatthias.ringwald }
332452db98b2SMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
332552db98b2SMatthias Ringwald     if (disable_l2cap_timeouts) return;
332652db98b2SMatthias Ringwald     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
332752db98b2SMatthias Ringwald     uint8_t event[4];
332852db98b2SMatthias Ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
332952db98b2SMatthias Ringwald     event[1] = sizeof(event) - 2;
333052db98b2SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
333152db98b2SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
333252db98b2SMatthias Ringwald }
333335454696SMatthias Ringwald #endif
3334c8e4258aSmatthias.ringwald 
333535454696SMatthias Ringwald #ifdef ENABLE_BLE
3336d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3337fc64f94aSMatthias 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){
33384f3229d8S[email protected]     uint8_t event[21];
33394f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
33404f3229d8S[email protected]     event[1] = sizeof(event) - 2;
33414f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
33424f3229d8S[email protected]     event[3] = status;
3343fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
33444f3229d8S[email protected]     event[6] = 0; // TODO: role
33456e2e9a6bS[email protected]     event[7] = address_type;
3346724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
3347f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
3348f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
3349f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
33504f3229d8S[email protected]     event[20] = 0; // master clock accuracy
3351d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
33524f3229d8S[email protected] }
335335454696SMatthias Ringwald #endif
3354d70217a2SMatthias Ringwald #endif
33554f3229d8S[email protected] 
3356fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3357425d1371Smatthias.ringwald     uint8_t event[6];
33583c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3359e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
33603c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
3361fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
33623c4d4b90Smatthias.ringwald     event[5] = reason;
3363d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
33643c4d4b90Smatthias.ringwald }
33653c4d4b90Smatthias.ringwald 
3366b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
3367e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3368425d1371Smatthias.ringwald     uint8_t event[3];
336980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3370425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
337143bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
3372d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
337343bfb1bdSmatthias.ringwald }
3374038bc64cSmatthias.ringwald 
3375b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
3376e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
3377425d1371Smatthias.ringwald     uint8_t event[2];
337880d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3379425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
3380d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3381038bc64cSmatthias.ringwald }
33821b0e3922Smatthias.ringwald 
338335454696SMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
338435454696SMatthias Ringwald     log_info("hci_emit_dedicated_bonding_result %u ", status);
338535454696SMatthias Ringwald     uint8_t event[9];
338635454696SMatthias Ringwald     int pos = 0;
338735454696SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
338835454696SMatthias Ringwald     event[pos++] = sizeof(event) - 2;
338935454696SMatthias Ringwald     event[pos++] = status;
339035454696SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
3391d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3392381fbed8Smatthias.ringwald }
3393458bf4e8S[email protected] 
339435454696SMatthias Ringwald 
339535454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
339635454696SMatthias Ringwald 
3397b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3398df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3399a00031e2S[email protected]     uint8_t event[5];
3400e00caf9cS[email protected]     int pos = 0;
34015611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3402e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
3403f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
3404e00caf9cS[email protected]     pos += 2;
3405e00caf9cS[email protected]     event[pos++] = level;
3406d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3407e00caf9cS[email protected] }
3408e00caf9cS[email protected] 
340935454696SMatthias Ringwald static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
341035454696SMatthias Ringwald     if (!connection) return LEVEL_0;
341135454696SMatthias Ringwald     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
341235454696SMatthias Ringwald     return gap_security_level_for_link_key_type(connection->link_key_type);
341335454696SMatthias Ringwald }
341435454696SMatthias Ringwald 
341535454696SMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled){
341635454696SMatthias Ringwald     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
341735454696SMatthias Ringwald     uint8_t event[3];
341835454696SMatthias Ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
341935454696SMatthias Ringwald     event[1] = sizeof(event) - 2;
342035454696SMatthias Ringwald     event[2] = enabled;
3421d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3422ad83dc6aS[email protected] }
3423ad83dc6aS[email protected] 
342406b9e820SMatthias Ringwald #ifdef ENABLE_CLASSIC
342598a2fd1cSMatthias Ringwald // query if remote side supports eSCO
3426073bd0faSMatthias Ringwald int hci_remote_esco_supported(hci_con_handle_t con_handle){
342798a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
342898a2fd1cSMatthias Ringwald     if (!connection) return 0;
342998a2fd1cSMatthias Ringwald     return connection->remote_supported_feature_eSCO;
343098a2fd1cSMatthias Ringwald }
343198a2fd1cSMatthias Ringwald 
34322bd8b7e7S[email protected] // query if remote side supports SSP
34332bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
34342bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
34352bd8b7e7S[email protected]     if (!connection) return 0;
34362bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
34372bd8b7e7S[email protected] }
34382bd8b7e7S[email protected] 
343915a95bd5SMatthias Ringwald int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3440df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3441df3354fcS[email protected] }
344206b9e820SMatthias Ringwald #endif
3443df3354fcS[email protected] 
3444458bf4e8S[email protected] // GAP API
3445458bf4e8S[email protected] /**
3446458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
3447458bf4e8S[email protected]  * @praram enabled
3448458bf4e8S[email protected]  */
34494c57c146S[email protected] void gap_set_bondable_mode(int enable){
34503a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
3451458bf4e8S[email protected] }
34524ef6443cSMatthias Ringwald /**
34534ef6443cSMatthias Ringwald  * @brief Get bondable mode.
34544ef6443cSMatthias Ringwald  * @return 1 if bondable
34554ef6443cSMatthias Ringwald  */
34564ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
34574ef6443cSMatthias Ringwald     return hci_stack->bondable;
34584ef6443cSMatthias Ringwald }
3459cb230b9dS[email protected] 
3460cb230b9dS[email protected] /**
346134d2123cS[email protected]  * @brief map link keys to security levels
3462cb230b9dS[email protected]  */
346334d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
346434d2123cS[email protected]     switch (link_key_type){
34653c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
34663c68dfa9S[email protected]             return LEVEL_4;
34673c68dfa9S[email protected]         case COMBINATION_KEY:
34683c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
34693c68dfa9S[email protected]             return LEVEL_3;
34703c68dfa9S[email protected]         default:
34713c68dfa9S[email protected]             return LEVEL_2;
34723c68dfa9S[email protected]     }
3473cb230b9dS[email protected] }
3474cb230b9dS[email protected] 
3475106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
34765127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
3477106d6d11S[email protected]     return level > LEVEL_2;
3478106d6d11S[email protected] }
3479106d6d11S[email protected] 
348034d2123cS[email protected] /**
348134d2123cS[email protected]  * @brief get current security level
348234d2123cS[email protected]  */
348334d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
348434d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
348534d2123cS[email protected]     if (!connection) return LEVEL_0;
348634d2123cS[email protected]     return gap_security_level_for_connection(connection);
348734d2123cS[email protected] }
348834d2123cS[email protected] 
3489cb230b9dS[email protected] /**
3490cb230b9dS[email protected]  * @brief request connection to device to
3491cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
3492cb230b9dS[email protected]  */
349334d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
349434d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
349534d2123cS[email protected]     if (!connection){
3496a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
349734d2123cS[email protected]         return;
349834d2123cS[email protected]     }
349934d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
350034d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
350134d2123cS[email protected]     if (current_level >= requested_level){
3502a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
350334d2123cS[email protected]         return;
350434d2123cS[email protected]     }
3505a00031e2S[email protected] 
350634d2123cS[email protected]     connection->requested_security_level = requested_level;
3507a00031e2S[email protected] 
350825bf5872S[email protected] #if 0
350925bf5872S[email protected]     // sending encryption request without a link key results in an error.
351025bf5872S[email protected]     // TODO: figure out how to use it properly
351125bf5872S[email protected] 
3512fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
3513a98592bcSMatthias Ringwald     if (hci_stack->link_key_db){
3514a00031e2S[email protected]         link_key_type_t link_key_type;
3515a00031e2S[email protected]         link_key_t      link_key;
3516a98592bcSMatthias Ringwald         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3517a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3518a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3519a00031e2S[email protected]                 return;
3520a00031e2S[email protected]             }
3521a00031e2S[email protected]         }
3522a00031e2S[email protected]     }
352325bf5872S[email protected] #endif
3524a00031e2S[email protected] 
35251eb2563eS[email protected]     // try to authenticate connection
35261eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3527e80b2cf9S[email protected]     hci_run();
3528e00caf9cS[email protected] }
3529ad83dc6aS[email protected] 
3530ad83dc6aS[email protected] /**
3531ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
3532ad83dc6aS[email protected]  * @param device
3533ad83dc6aS[email protected]  * @param request MITM protection
3534ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
3535ad83dc6aS[email protected]  */
3536ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3537ad83dc6aS[email protected] 
3538ad83dc6aS[email protected]     // create connection state machine
353996a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3540ad83dc6aS[email protected] 
3541ad83dc6aS[email protected]     if (!connection){
3542ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
3543ad83dc6aS[email protected]     }
3544ad83dc6aS[email protected] 
3545ad83dc6aS[email protected]     // delete linkn key
354615a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
3547ad83dc6aS[email protected] 
3548ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
3549ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
3550ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3551f04a0c31SMatthias Ringwald     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3552ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
3553ad83dc6aS[email protected] 
3554ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3555ad83dc6aS[email protected] 
3556ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
3557ad83dc6aS[email protected]     // handle: authentication failure
3558ad83dc6aS[email protected]     // handle: disconnect on done
3559ad83dc6aS[email protected] 
3560ad83dc6aS[email protected]     hci_run();
3561ad83dc6aS[email protected] 
3562ad83dc6aS[email protected]     return 0;
3563ad83dc6aS[email protected] }
356435454696SMatthias Ringwald #endif
35658e618f72S[email protected] 
35668e618f72S[email protected] void gap_set_local_name(const char * local_name){
35678e618f72S[email protected]     hci_stack->local_name = local_name;
35688e618f72S[email protected] }
35698e618f72S[email protected] 
357035454696SMatthias Ringwald 
357135454696SMatthias Ringwald #ifdef ENABLE_BLE
357235454696SMatthias Ringwald 
3573d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3574d8e8f12aSMatthias Ringwald void gap_start_scan(void){
3575d8e8f12aSMatthias Ringwald     if (hci_stack->le_scanning_state == LE_SCANNING) return;
35767bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
35777bdc6798S[email protected]     hci_run();
35787bdc6798S[email protected] }
35798e618f72S[email protected] 
3580d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
3581d8e8f12aSMatthias Ringwald     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
35827bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
35837bdc6798S[email protected]     hci_run();
35847bdc6798S[email protected] }
35854f3229d8S[email protected] 
3586d8e8f12aSMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3587ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
3588ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
3589ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
3590ef11999fSmatthias.ringwald     hci_run();
3591ef11999fSmatthias.ringwald }
35924f3229d8S[email protected] 
3593d8e8f12aSMatthias Ringwald uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
35944f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
35954f3229d8S[email protected]     if (!conn){
3596d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
35972e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
35984f3229d8S[email protected]         if (!conn){
35994f3229d8S[email protected]             // notify client that alloc failed
36006e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3601d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
3602472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
36034f3229d8S[email protected]         }
36044f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
3605d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
3606564fca32S[email protected]         hci_run();
3607616edd56SMatthias Ringwald         return 0;
36084f3229d8S[email protected]     }
36090bf6344aS[email protected] 
36100bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
36110bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
36120bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
36132e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3614d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
3615616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
36160bf6344aS[email protected]     }
36170bf6344aS[email protected] 
3618d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
36192e77e513S[email protected]     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
36204f3229d8S[email protected]     hci_run();
3621616edd56SMatthias Ringwald     return 0;
36224f3229d8S[email protected] }
36234f3229d8S[email protected] 
36247851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
3625d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
3626665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
3627665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
36280bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
36290bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
36300bf6344aS[email protected]         switch (conn->state){
3631a6725849S[email protected]             case SEND_CREATE_CONNECTION:
36327851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
36337851196eSmatthias.ringwald                 return conn;
36347851196eSmatthias.ringwald             default:
36357851196eSmatthias.ringwald                 break;
36367851196eSmatthias.ringwald         };
36377851196eSmatthias.ringwald     }
36387851196eSmatthias.ringwald     return NULL;
36397851196eSmatthias.ringwald }
36407851196eSmatthias.ringwald 
3641d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
3642d8e8f12aSMatthias Ringwald     hci_connection_t * conn = gap_get_outgoing_connection();
3643616edd56SMatthias Ringwald     if (!conn) return 0;
36447851196eSmatthias.ringwald     switch (conn->state){
36457851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
36467851196eSmatthias.ringwald             // skip sending create connection and emit event instead
36472e77e513S[email protected]             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3648665d90f2SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
36497851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
36500bf6344aS[email protected]             break;
3651a6725849S[email protected]         case SENT_CREATE_CONNECTION:
36527851196eSmatthias.ringwald             // request to send cancel connection
36530bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
36540bf6344aS[email protected]             hci_run();
36550bf6344aS[email protected]             break;
36560bf6344aS[email protected]         default:
36570bf6344aS[email protected]             break;
36580bf6344aS[email protected]     }
3659616edd56SMatthias Ringwald     return 0;
3660e31f89a7S[email protected] }
3661d70217a2SMatthias Ringwald #endif
36624f3229d8S[email protected] 
3663c37a3166S[email protected] /**
3664c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
3665c37a3166S[email protected]  * @param handle
3666c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
3667c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
3668c37a3166S[email protected]  * @param conn_latency
3669c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
3670c37a3166S[email protected]  * @returns 0 if ok
3671c37a3166S[email protected]  */
3672c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3673c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3674c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3675c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3676c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
3677c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
3678c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
3679c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
368084cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3681cfc59f1bSMatthias Ringwald     hci_run();
3682c37a3166S[email protected]     return 0;
3683c37a3166S[email protected] }
3684c37a3166S[email protected] 
368545c102fdSMatthias Ringwald /**
3686b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
3687b68d7bc3SMatthias Ringwald  * @param handle
3688b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
3689b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
3690b68d7bc3SMatthias Ringwald  * @param conn_latency
3691b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
3692b68d7bc3SMatthias Ringwald  * @returns 0 if ok
3693b68d7bc3SMatthias Ringwald  */
3694b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3695b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3696b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3697b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3698b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
3699b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
3700b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
3701b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
3702b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3703b68d7bc3SMatthias Ringwald     hci_run();
3704b68d7bc3SMatthias Ringwald     return 0;
3705b68d7bc3SMatthias Ringwald }
3706b68d7bc3SMatthias Ringwald 
3707d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3708d70217a2SMatthias Ringwald 
3709501f56b3SMatthias Ringwald static void gap_advertisments_changed(void){
3710501f56b3SMatthias Ringwald     // disable advertisements before updating adv, scan data, or adv params
3711501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_active){
3712501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3713501f56b3SMatthias Ringwald     }
3714501f56b3SMatthias Ringwald     hci_run();
3715501f56b3SMatthias Ringwald }
3716501f56b3SMatthias Ringwald 
3717b68d7bc3SMatthias Ringwald /**
371845c102fdSMatthias Ringwald  * @brief Set Advertisement Data
371945c102fdSMatthias Ringwald  * @param advertising_data_length
372045c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
372145c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
372245c102fdSMatthias Ringwald  */
372345c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
372445c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
372545c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
3726501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3727501f56b3SMatthias Ringwald     gap_advertisments_changed();
372845c102fdSMatthias Ringwald }
3729501f56b3SMatthias Ringwald 
3730501f56b3SMatthias Ringwald /**
3731501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
3732501f56b3SMatthias Ringwald  * @param advertising_data_length
3733501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
3734501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
3735501f56b3SMatthias Ringwald  */
3736501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3737501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
3738501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
3739501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3740501f56b3SMatthias Ringwald     gap_advertisments_changed();
374145c102fdSMatthias Ringwald }
374245c102fdSMatthias Ringwald 
374345c102fdSMatthias Ringwald /**
374445c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
374545c102fdSMatthias Ringwald  * @param adv_int_min
374645c102fdSMatthias Ringwald  * @param adv_int_max
374745c102fdSMatthias Ringwald  * @param adv_type
374845c102fdSMatthias Ringwald  * @param direct_address_type
374945c102fdSMatthias Ringwald  * @param direct_address
375045c102fdSMatthias Ringwald  * @param channel_map
375145c102fdSMatthias Ringwald  * @param filter_policy
375245c102fdSMatthias Ringwald  *
375345c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
375445c102fdSMatthias Ringwald  */
375545c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3756b95a5a35SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address,
375745c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
375845c102fdSMatthias Ringwald 
375945c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
376045c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
376145c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
376245c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
376345c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
376445c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
376545c102fdSMatthias Ringwald     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
376645c102fdSMatthias Ringwald 
376745c102fdSMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3768501f56b3SMatthias Ringwald     gap_advertisments_changed();
376945c102fdSMatthias Ringwald  }
377045c102fdSMatthias Ringwald 
377145c102fdSMatthias Ringwald /**
377245c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
377345c102fdSMatthias Ringwald  * @param enabled
377445c102fdSMatthias Ringwald  */
377545c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
377645c102fdSMatthias Ringwald     hci_stack->le_advertisements_enabled = enabled;
377745c102fdSMatthias Ringwald     if (enabled && !hci_stack->le_advertisements_active){
377845c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
377945c102fdSMatthias Ringwald     }
378045c102fdSMatthias Ringwald     if (!enabled && hci_stack->le_advertisements_active){
378145c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
378245c102fdSMatthias Ringwald     }
3783cfc59f1bSMatthias Ringwald     hci_run();
378445c102fdSMatthias Ringwald }
378545c102fdSMatthias Ringwald 
378635454696SMatthias Ringwald #endif
378706e5cf96SMatthias Ringwald 
378806e5cf96SMatthias Ringwald void hci_le_set_own_address_type(uint8_t own_address_type){
378906e5cf96SMatthias Ringwald     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
379006e5cf96SMatthias Ringwald     if (own_address_type == hci_stack->le_own_addr_type) return;
379106e5cf96SMatthias Ringwald     hci_stack->le_own_addr_type = own_address_type;
379206e5cf96SMatthias Ringwald 
379364068776SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
379406e5cf96SMatthias Ringwald     // update advertisement parameters, too
379506e5cf96SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
379606e5cf96SMatthias Ringwald     gap_advertisments_changed();
379764068776SMatthias Ringwald #endif
379864068776SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
379906e5cf96SMatthias Ringwald     // note: we don't update scan parameters or modify ongoing connection attempts
380064068776SMatthias Ringwald #endif
380106e5cf96SMatthias Ringwald }
380206e5cf96SMatthias Ringwald 
3803d70217a2SMatthias Ringwald #endif
380445c102fdSMatthias Ringwald 
3805616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
38065917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
38075917a5c5S[email protected]     if (!conn){
38087851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
3809616edd56SMatthias Ringwald         return 0;
38105917a5c5S[email protected]     }
38115917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
38125917a5c5S[email protected]     hci_run();
3813616edd56SMatthias Ringwald     return 0;
38144f3229d8S[email protected] }
381504a6ef8cSmatthias.ringwald 
3816a1bf5ae7SMatthias Ringwald /**
3817a1bf5ae7SMatthias Ringwald  * @brief Get connection type
3818a1bf5ae7SMatthias Ringwald  * @param con_handle
3819a1bf5ae7SMatthias Ringwald  * @result connection_type
3820a1bf5ae7SMatthias Ringwald  */
3821a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3822a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3823a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
3824a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
3825a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
3826a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
3827a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
3828a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
3829a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
3830a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_CLASSIC:
3831a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
3832a1bf5ae7SMatthias Ringwald         default:
3833a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
3834a1bf5ae7SMatthias Ringwald     }
3835a1bf5ae7SMatthias Ringwald }
3836a1bf5ae7SMatthias Ringwald 
3837a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
38384f551432SMatthias Ringwald 
3839d70217a2SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3840d23838ecSMatthias Ringwald /**
3841ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
3842ac9c45e0SMatthias Ringwald  * @param address_typ
3843ac9c45e0SMatthias Ringwald  * @param address
3844ac9c45e0SMatthias Ringwald  * @returns 0 if ok
3845ac9c45e0SMatthias Ringwald  */
38464f551432SMatthias Ringwald int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3847e83201bcSMatthias Ringwald     // check capacity
3848665d90f2SMatthias Ringwald     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
384991915b0bSMatthias Ringwald     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3850e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3851e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3852e83201bcSMatthias Ringwald     entry->address_type = address_type;
3853e83201bcSMatthias Ringwald     memcpy(entry->address, address, 6);
3854e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3855665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3856e83201bcSMatthias Ringwald     hci_run();
3857e83201bcSMatthias Ringwald     return 0;
3858ac9c45e0SMatthias Ringwald }
3859ac9c45e0SMatthias Ringwald 
386042ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3861665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3862665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3863665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3864665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3865e83201bcSMatthias Ringwald         if (entry->address_type != address_type) continue;
3866e83201bcSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) continue;
3867e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3868e83201bcSMatthias Ringwald             // remove from controller if already present
3869e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3870e83201bcSMatthias Ringwald             continue;
3871e83201bcSMatthias Ringwald         }
3872e83201bcSMatthias Ringwald         // direclty remove entry from whitelist
3873665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
3874e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
3875e83201bcSMatthias Ringwald     }
387642ff5ba1SMatthias Ringwald }
387742ff5ba1SMatthias Ringwald 
387842ff5ba1SMatthias Ringwald /**
387942ff5ba1SMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
388042ff5ba1SMatthias Ringwald  * @param address_typ
388142ff5ba1SMatthias Ringwald  * @param address
388242ff5ba1SMatthias Ringwald  * @returns 0 if ok
388342ff5ba1SMatthias Ringwald  */
388442ff5ba1SMatthias Ringwald int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
388542ff5ba1SMatthias Ringwald     hci_remove_from_whitelist(address_type, address);
3886e83201bcSMatthias Ringwald     hci_run();
3887e83201bcSMatthias Ringwald     return 0;
3888ac9c45e0SMatthias Ringwald }
3889ac9c45e0SMatthias Ringwald 
3890ac9c45e0SMatthias Ringwald /**
3891ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
3892ac9c45e0SMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
3893ac9c45e0SMatthias Ringwald  */
3894ac9c45e0SMatthias Ringwald void gap_auto_connection_stop_all(void){
3895665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3896665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3897665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3898665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3899e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3900e83201bcSMatthias Ringwald             // remove from controller if already present
3901e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3902e83201bcSMatthias Ringwald             continue;
3903e83201bcSMatthias Ringwald         }
390491915b0bSMatthias Ringwald         // directly remove entry from whitelist
3905665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
3906e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
3907e83201bcSMatthias Ringwald     }
3908e83201bcSMatthias Ringwald     hci_run();
3909ac9c45e0SMatthias Ringwald }
3910d70217a2SMatthias Ringwald #endif
39114f551432SMatthias Ringwald #endif
39124f551432SMatthias Ringwald 
391335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
3914ac9c45e0SMatthias Ringwald /**
3915ff00ed1cSMatthias Ringwald  * @brief Set Extended Inquiry Response data
3916ff00ed1cSMatthias Ringwald  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
3917ff00ed1cSMatthias Ringwald  * @note has to be done before stack starts up
3918ff00ed1cSMatthias Ringwald  */
3919ff00ed1cSMatthias Ringwald void gap_set_extended_inquiry_response(const uint8_t * data){
3920ff00ed1cSMatthias Ringwald     hci_stack->eir_data = data;
3921ff00ed1cSMatthias Ringwald }
3922ff00ed1cSMatthias Ringwald 
3923ff00ed1cSMatthias Ringwald /**
3924f6858d14SMatthias Ringwald  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
3925f6858d14SMatthias Ringwald  * @param inquriy_mode see bluetooth_defines.h
3926f6858d14SMatthias Ringwald  */
3927f6858d14SMatthias Ringwald void hci_set_inquiry_mode(inquiry_mode_t mode){
3928f6858d14SMatthias Ringwald     hci_stack->inquiry_mode = mode;
3929f6858d14SMatthias Ringwald }
3930f6858d14SMatthias Ringwald 
3931f6858d14SMatthias Ringwald /**
3932d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3933d950d659SMatthias Ringwald  */
3934d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
3935d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
3936d950d659SMatthias Ringwald }
3937d950d659SMatthias Ringwald 
3938d950d659SMatthias Ringwald /**
3939d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
3940d950d659SMatthias Ringwald  * @return current voice setting
3941d950d659SMatthias Ringwald  */
39420cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
3943d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
3944d950d659SMatthias Ringwald }
3945d950d659SMatthias Ringwald 
3946b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
3947b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
3948b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
3949b3aad8daSMatthias Ringwald  */
3950b3aad8daSMatthias Ringwald int hci_get_sco_packet_length(void){
3951b3aad8daSMatthias Ringwald     // see Core Spec for H2 USB Transfer.
3952b3aad8daSMatthias Ringwald     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3953b3aad8daSMatthias Ringwald     return 27;
3954b3aad8daSMatthias Ringwald }
395535454696SMatthias Ringwald #endif
3956b3aad8daSMatthias Ringwald 
3957d950d659SMatthias Ringwald /**
3958d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
3959d23838ecSMatthias Ringwald  */
3960c2e1fa60SMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
3961d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
3962d23838ecSMatthias Ringwald }
3963d23838ecSMatthias Ringwald 
396471de195eSMatthias Ringwald void hci_disconnect_all(void){
3965665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3966665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3967665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3968665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
396904a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
397004a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
397104a6ef8cSmatthias.ringwald     }
3972d31fba26S[email protected]     hci_run();
397304a6ef8cSmatthias.ringwald }
397433373e40SMatthias Ringwald 
397533373e40SMatthias Ringwald uint16_t hci_get_manufacturer(void){
397633373e40SMatthias Ringwald     return hci_stack->manufacturer;
397733373e40SMatthias Ringwald }
3978